#include "../src/shader_directory.h" // A Vulkan-backed ID3D12Device (PC ABI) for the Xbox-ABI device proxy (d3d12_xs_device.cpp) to forward to. // Implemented: queues, allocators, command lists, fences, descriptor heaps, render-target and depth-stencil views, // committed buffers and textures (1D, 1D arrays, 2D, multisampled 2D, 3D) and their 1/2/3 variants, allocation // info, CPU texture copies (WriteToSubresource/ReadFromSubresource), query heaps, a few feature queries. Everything else is a // generated stub that reports itself once. See docs/d3d12_vulkan.md section 4.1/4.2 for what each answer means and // what is still open. #ifndef VK_USE_PLATFORM_WIN32_KHR #define VK_USE_PLATFORM_WIN32_KHR #endif #include "../src/vulkan_graphics_shader_modules.h" #include "d3d12_com.h" #include "d3d12_compile_exit.h" #include "d3d12_pipeline_compile.h" #include "d3d12_precompile.h" #include "d3d12_compile_helper.h" #include "d3d12_pipeline_checkpoint.h" #include "d3d12_feature_compat.h" #include "d3d12_stubs.h" // generated #include "d3d12_com_object.h" #include "d3d12_trace.h" #include "d3d12_xs_device.h" #include "d3d12_xs_pso_stream.h" #include "xg_xs_layout.h" #include "d3d12_title_image_upload.h" #include "d3d12_title_buffer_windows.h" #include "d3d12_geometry_views.h" #include "placed_image_map_note.h" #include "d3d12_title_image_census.h" #include "d3d12_xs_native_pso.h" #include "dxgi_com.h" #include "../src/arena_size.h" #include "../src/arena_staging.h" #include "../src/command_list_epochs.h" #include "../src/value_write_sink.h" #include "../src/address_guard.h" #include "../src/address_guard_buffer.h" #include "../src/arena_backing.h" #include "../src/arena_blocks.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" #include "../src/rgba4_fragment.h" #include "../src/dual_source_fragment.h" #include "../src/sample_mask_fragment.h" #include "../src/rect_list_geometry.h" #include "../src/stub_pipeline.h" #include "../src/uav_clear.h" #include "../src/vulkan_bindless.h" #include "../src/vulkan_memory.h" #include "../src/vulkan_mesh_limits.h" #include "../src/resource_tiling.h" #include "../src/cached_pso.h" #include "../src/compile_gate_calibration.h" #include "../src/pipeline_cache_file.h" #include "../src/pipeline_profile.h" #include "../src/submit_phases.h" #include "../src/heavy_pipeline_cache.h" #include "../src/pipeline_cache_store.h" #include "../src/pipeline_cache_journal.h" #include "../src/pipeline_order.h" #include "../src/pipeline_prewarm.h" #include "../src/large_module_gate.h" #include "../src/dev_status.h" #include "../src/conservative_raster.h" #include "../src/resource_detile.h" #include "../src/console_texture_layout.h" #include "../src/shader_library.h" #include "../src/literal_sampler_spec.h" #include "../src/shadow_keep.h" #include "../src/dstorage_trace.h" #include "../src/title_page_watch.h" #include "../src/title_mirror.h" #include "../src/title_mirror_space.h" #include "../src/title_mirror_tracking.h" #include "../src/title_mirror_hot_cold.h" #include "../src/guarded_copy.h" #include "../src/title_geometry_watch.h" #include "../src/title_texture_memory.h" #include "../src/title_texture_refresh.h" #include "../src/title_texture_watch.h" #include "title_gpu_placements.h" #include "../src/spirv_f16_halves.h" #include "../src/spirv_stage_link.h" #include "../src/spirv_stores.h" #include "../src/title_va_alias.h" #include "../src/console_heap_slot_records.h" #include "../src/title_window_plan.h" #include "../src/vulkan_present.h" #include "../src/vulkan_device_filter.h" #include "../src/host_image_copy_policy.h" #include "../src/vulkan13_features.h" #include "../src/vulkan_index_view.h" #include "d3d12_compute_input_probe.h" #include "../src/fsdraw_probe.h" // LOCAL DIAGNOSTIC #include "../src/local_diagnostics.h" #include "../src/mem_probe.h" // LOCAL DIAGNOSTIC #include "../src/vulkan_aftermath.h" #include "../src/console_heap_gpu.h" #include #ifdef _MSC_VER #pragma comment(lib, "advapi32.lib") #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(__AVX2__) #include #endif #include namespace rt::d3d12 { namespace { // CBV/SRV/UAV, RTV and DSV slots are 32 bytes (`kDescriptorSize`); an RTV or DSV slot holds a leonida::TargetView. // SAMPLER slots are 16 bytes (`sampler_descriptor_size`, one hardware 4-dword S#), matching Xbox Series shaders. constexpr UINT kDescriptorSize = descriptor_size; constexpr UINT kSamplerDescriptorSize = sampler_descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read constexpr auto kQuadIndicesPerQuad = std::uint32_t(leonida::quad_triangle_indices.size()); constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); // LEONIDA_ADDRESS_GUARD's header and sinks follow the quad indices (src/address_guard.h). static_assert(kArenaReserved <= leonida::address_guard::kGuardHeader); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); static_assert(sizeof(leonida::gfx10::SamplerWords) == kSamplerDescriptorSize); // pipeline_cache_store.h reads this layout without vulkan.h (D3D-704); remember the two. static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == leonida::pipeline_cache_store::header_bytes); // Saturates at the last multiple of `to` instead of wrapping, as the PC runtime's totals do. UINT64 align_up(UINT64 value, UINT64 to) { return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; } // The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the // game's shaders arrive as SPIR-V from the offline translator, and the only DXIL path (the BVH builder) is lowered // to standard DXIL, whose baseline is 6.0. Answering the driver's own maximum would tell the game it can hand this // layer shaders it has no front end for, which section 4.1 of docs/d3d12_vulkan.md calls worse than a false // "unsupported" at boot. Raise these when a front end for the higher version lands. constexpr D3D_SHADER_MODEL kHighestShaderModel = D3D_SHADER_MODEL_6_0; constexpr D3D_ROOT_SIGNATURE_VERSION kHighestRootSignatureVersion = D3D_ROOT_SIGNATURE_VERSION_1_1; std::atomic g_global_realtime_privilege_override{-1}; bool first_diagnostic(const char* what, int value) { static std::mutex mutex; static std::set> seen; std::lock_guard lock(mutex); return seen.insert({what, value}).second; } enum class TitleImageOrigin { ordinary, placed, streamed, pending_stream }; void log_once(const char* what, int value) { if (first_diagnostic(what, value)) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); } // LEONIDA_ADDRESS_GUARD=1: the address guard (docs/d3d12_vulkan.md, "Address guard"). The arena keeps its guard // header and sinks at heap_base + 0x70000..0x80000 and a page table of every backing outside it is kept current // before each submission, so shaders translated with `rdna2spirv.py --address-guard` read 0 from, and drop stores // to, an address nothing backs. Without it those shaders find no header and check nothing. bool address_guard_enabled() { static const bool on = [] { wchar_t value[2]{}; return GetEnvironmentVariableW(L"LEONIDA_ADDRESS_GUARD", value, 2) == 1 && value[0] == L'1'; }(); return on; } // LEONIDA_IMPORT_BELOW_ARENA=1: an import of title memory that the driver put below the arena is kept (and V# bases // are read as signed offsets whatever the shader pack says). bool import_below_arena() { static const bool on = [] { wchar_t value[2]{}; return GetEnvironmentVariableW(L"LEONIDA_IMPORT_BELOW_ARENA", value, 2) == 1 && value[0] == L'1'; }(); return on; } // Set by the device from its shader library (create_arena): every loaded module sign-extends a V#'s 48-bit base // (leonida::VsharpBaseCensus), so a buffer below heap_base is named by its negative offset. std::atomic g_pack_signed_vsharp_offsets{false}; // Matches the offset interpretation of the selected shader pack: a V# base is a signed 48-bit offset from heap_base // (any buffer within 2^47 of it, on either side) or an unsigned one (only buffers above it). bool signed_vsharp_offsets() { return import_below_arena() || g_pack_signed_vsharp_offsets.load(std::memory_order_relaxed); } // The CBV/SRV/UAV slots a descriptor table declares: the end of its furthest range (D3D12 appends a range at // D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND), an unbounded range limited by the registered heap. 0 for a sampler table or no table. std::uint32_t table_view_descriptors(const rt::rootsig::RootParameter& param) { if (param.type != rt::rootsig::ParamType::Table) return 0; constexpr std::uint32_t kUnbounded = UINT_MAX; std::uint64_t next = 0, end = 0; for (const auto& range : param.ranges) { const std::uint64_t start = range.offset_in_table == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND ? next : range.offset_in_table; next = start + range.num_descriptors; if (range.range_type != D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) end = std::max(end, next); } return std::uint32_t(std::min(end, kUnbounded)); } // The streaming copy of copy_guarded, in a frame of its own so that a fault in it reaches copy_guarded's __except // (src/guarded_copy.h: not in the CRT, which Wine's unwinding does not get out of, and not inline, which clang-cl does // not cover without /EHa). MOVNTDQA, for write-combined pages: ordinary loads from them are not cached, and memcpy // read 64 MiB of them in 253 ms on a Core i9-13900K (253 MiB/s), MOVNTDQA in 13 to 17 ms (4 to 5 GiB/s). #if defined(__clang__) && defined(_M_X64) __attribute__((target("sse4.1"))) #endif __declspec(noinline) LEONIDA_GUARDED_NO_BUILTIN void copy_streaming(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { const std::size_t head = std::min(bytes, (0 - reinterpret_cast(from)) & 63); __movsb(to, from, head); to += head, from += head, bytes -= head; for (; bytes >= 64; to += 64, from += 64, bytes -= 64) { const auto* in = reinterpret_cast(from); const __m128i a = _mm_stream_load_si128(in), b = _mm_stream_load_si128(in + 1); const __m128i c = _mm_stream_load_si128(in + 2), d = _mm_stream_load_si128(in + 3); auto* out = reinterpret_cast<__m128i*>(to); _mm_storeu_si128(out, a), _mm_storeu_si128(out + 1, b); _mm_storeu_si128(out + 2, c), _mm_storeu_si128(out + 3, d); } __movsb(to, from, bytes); } // A copy that a page fault ends instead of killing the process: the title may decommit or remap a page between the // VirtualQuery that saw it committed and the read. No C++ objects here: it is a __try frame. `streaming`: for // write-combined pages (copy_streaming). Paid at every submission. bool copy_guarded_host(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { __try { if (streaming) copy_streaming(to, from, bytes); else leonida::guarded::copy(to, from, bytes); return true; } __except (EXCEPTION_EXECUTE_HANDLER) { return false; } } // Fused guarded copy + 256-byte piece hashing for cached (non-WC) pages: one __try per 16 KiB strip, single read pass // from `from` into `to` + in-register AVX2 hash. Intentionally NOT noexcept (SEH under /EHsc). bool copy_and_sum_guarded_host(std::uint8_t* to, const std::uint8_t* from, std::size_t pieces, std::uint64_t* sums) { __try { leonida::guarded::copy_and_sum_256(to, from, pieces, sums); return true; } __except (EXCEPTION_EXECUTE_HANDLER) { return false; } } // The same, reading the title's pages that xmem's frame table holds through their frames: a stream pool's GPU-only // pages and their CPU twins after queue slot 31's copies have no host view (src/title_frames.h). A frame is a section's // scratch view, cached memory, so it is not read streaming. bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { const auto at = reinterpret_cast(from); if (!leonida::title_frames::may_hold(at, at + bytes)) return copy_guarded_host(to, from, bytes, streaming); return leonida::title_frames::for_each_part(at, bytes, [&](std::uintptr_t part, std::size_t n, std::uint8_t* frame) { return copy_guarded_host(to + (part - at), frame ? frame : reinterpret_cast(part), n, streaming && !frame); }); } // Set while this thread is inside the title-texture registry (it holds title_texture_mutex): a staged copy it makes // submits through a queue, whose before-submission refresh must then not take the registry again. thread_local bool t_in_title_textures = false; struct InTitleTextures { bool was = std::exchange(t_in_title_textures, true); ~InTitleTextures() { t_in_title_textures = was; } }; // Copies a run of the title's pages that VirtualQuery saw committed and readable. A page decommitted since then reads // as zeros, and only that page: the run is redone page by page, so the rest of it keeps its bytes. void copy_run(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { if (copy_guarded(to, from, bytes, streaming)) return; for (std::size_t off = 0; off < bytes;) { const std::size_t in_page = reinterpret_cast(from + off) & 4095; const std::size_t n = std::min(bytes - off, 4096 - in_page); if (!copy_guarded(to + off, from + off, n, streaming)) std::memset(to + off, 0, n); off += n; } } // The title's pages behind slot-133 shadow buffers and title windows, and which of them the title wrote since the // copies were last brought up to date. Nothing says which pages a title writes, so the pages say it themselves: once // copied, a read-write page is made read-only (its cache attribute kept: PAGE_READONLY | PAGE_WRITECOMBINE for a // write-combined one), and the title's next write to it faults. The fault handler (shadow_write_fault) makes the // 64 KiB around it writable again and the write goes on; reopening the page clears its watched state. Each refresh() // walks the range with VirtualQuery, passing over pages still known clean when the title memory map hasn't changed: // - read-write pages were written (or newly committed, or newly mapped by xmem): made read-only, then copied. A // write landing between the two faults again, so it reaches the next refresh at the latest; // - pages this tracker made read-only weren't written: skipped; // - other readable pages (read-only or copy-on-write pages of the title's own, pages another tracker protected) // can't be watched: copied every time, as before; // - pages not committed, or not readable, are zero in the copies (written once); // - pages xmem reports mapped at another address too (title_page_watch.h): a write through the other address // doesn't fault here, so their 64 KiB blocks are guarded at every address by the geometry watch's cells // (update_aliased) and copied when a cell's version moved. Without the other addresses (no xmem), or while a // cell can't be armed, they are copied every time; // - pages a file shim pinned for a kernel write (ReadFile into title memory, which fails with ERROR_NOACCESS on a // read-only page instead of faulting) are left writable and copied every time until the pin ends. // If the protection can't be changed (VirtualProtect refuses, or the fault handler couldn't be installed), those // pages stay read-write and are copied at every submission: the whole-range copy this replaces. // // One tracker serves every copy of the pages it covers (its targets). A page has one owner that may make it // read-only, so copies of the same 4 KiB page must share a tracker: the title places many slot-133 buffers of a few // KiB back to back, off page boundaries (measured on Windows 11: 3,172 of 3,267 placements shared a page with // another), and with a tracker each every buffer but one found its shared pages read-only, not its own, and queried // and copied them again at every submission (3,045 VirtualQuery calls, 57 of 62 ms per refresh). DeviceState:: // add_shadow keeps one tracker per run of pages that overlap or touch, and a written page reaches every target over // it. A page no target covers any more (its buffer went) is left writable and passed over. // // Pages xmem reserved with MEM_WRITE_WATCH (leonida::title_write_watch: the title's ordinary memory, not its // physical-page views) start guarded like the rest. A write fault on one makes its 64 KiB block hot: never made // read-only again, it is asked about instead. Each refresh first asks the kernel which hot pages were written since // the last asking (GetWriteWatch, which clears its bits), through the journal that keeps the answer for every other // tracker over the same pages; then those, and pages not known yet, are copied, and the rest passed over. A write // after the asking is in the next one. No fault, no VirtualProtect, and a kernel write needs no opening: hot pages // stay writable. A block not found written for kCool refreshes is guarded again. Asking costs about 3 ns per page per // refresh and a fault about three orders more, so the pages written often are asked about and the rest wait for their // write (measured natively: asking about all 242 MiB of write-watched pages at every submission cost 2.4 ms per // refresh, against 0.14 ms for the guards with their faults). A file shim's pin still marks a hot page written // (reopen_range) and keeps it copied until the pin ends: a device's write into locked pages need not set the kernel's // bit. // // The fault handler waits for g_shadow_pages_lock and a tracker's lock_, and the faulting thread may hold the process // heap's lock (the title's XMemAlloc memory is _aligned_malloc's, whose headers HeapAlloc and HeapFree write on pages a // tracker may guard). So nothing that holds either lock, or a lock taken under them (title_page_aliases, // kernel_writes' pins, title_write_watch's record and journal), touches the process heap: their containers allocate // from leonida::host_heap, a heap of the runtime's own, and logging waits until the lock is released. class ShadowPages { template using Vector = leonida::host_heap::vector; public: static constexpr std::uintptr_t kPage = 0x1000; static constexpr std::uintptr_t kBlock = 0x10000; // what one write fault makes writable again // LEONIDA_SHADOW_GPU (DeviceState::gpu_copy_shadow): takes a copy of [from, from + bytes) to `to` for the GPU, or // returns false and the CPU copies it. Set once by the device. using GpuCopy = bool (*)(void* context, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes); static inline GpuCopy gpu_copy = nullptr; static inline void* gpu_copy_context = nullptr; // RT-ARENA-DEVICE-LOCAL-STAGED: notifies the device when the CPU writes into a target mapped in the staged arena. // Must only be called when lock_ is NOT held (ArenaStaging::mark uses the process heap). using DirtyFn = void (*)(void* context, const void* ptr, std::size_t bytes); void set_dirty_hook(void* context, DirtyFn fn) { dirty_context_ = context; dirty_fn_ = fn; } // Collects the arena byte spans of every target overlapping `ranges` so a staged DEVICE_LOCAL arena can read // GPU-written bytes back into the host staging buffer before write_back() inspects them. Runs under shadow_mutex. template void for_each_target_range(const std::pair* ranges, std::size_t count, const std::uint8_t* only, Fn&& fn) const { if (!count) return; for (std::size_t r = 0; r < count; ++r) { const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_); if (from >= to) continue; for_each_target(from, to, [&](const Target& t, std::uintptr_t a, std::uintptr_t b) { if (!t.shadow || (only && t.retired && t.shadow != only)) return; fn(t.shadow + (a - t.begin), b - a); }); } } void collect_arena_ranges(const std::pair* ranges, std::size_t count, const std::uint8_t* only, const std::uint8_t* arena_mapped, VkDeviceSize arena_size, std::vector& out) const { if (!arena_mapped || !arena_size || !count) return; const auto arena_lo = reinterpret_cast(arena_mapped); const auto arena_hi = arena_lo + static_cast(arena_size); for_each_target_range(ranges, count, only, [&](const std::uint8_t* ptr, std::size_t len) { const auto dst = reinterpret_cast(ptr); if (dst >= arena_lo && dst < arena_hi && len <= arena_hi - dst) { const VkDeviceSize off = static_cast(dst - arena_lo); out.push_back({off, off, static_cast(len)}); } }); } // Bytes this tracker's refreshes handed to gpu_copy so far. std::uint64_t gpu_bytes() const { return gpu_bytes_; } ShadowPages(const std::uint8_t* pages, std::uint8_t* shadow, std::size_t size, bool watch) : watch_(watch) { begin_ = reinterpret_cast(pages); end_ = begin_ + size; first_ = begin_ & ~(kPage - 1); last_ = (end_ + kPage - 1) & ~(kPage - 1); state_.assign((last_ - first_) / kPage, 0); idle_.assign(state_.size(), 0); sums_.assign(state_.size() * kPieces, 0); cover_.assign(state_.size(), 1); targets_.push_back({begin_, end_, shadow}); index_targets(); } ~ShadowPages() { if (reader_) leonida::title_write_watch::close_reader(reader_); } // Every page made read-only here is read-write again: the title's pages outlive the buffer. void reopen_all() { AcquireSRWLockExclusive(&lock_); if (std::any_of(state_.begin(), state_.end(), [](std::uint16_t s) { return s & kProtected; })) reopen_locked(first_, last_); ReleaseSRWLockExclusive(&lock_); for (auto& [va, block] : aliased_blocks_) release_cells(va, block); aliased_blocks_.clear(); } ShadowPages(const ShadowPages&) = delete; ShadowPages& operator=(const ShadowPages&) = delete; // What the GPU writes into the copies of the ranges [first, second) goes back to the title's pages: `count` of // them, sorted by start. Returns the bytes written, and in `reached` (when given) how many of the ranges wrote // any. Called before the next refresh, so a page the title writes again is copied forward over the result, as on // a GPU that shares the memory. // // Only the bytes a copy holds differently from the title's page go back, and only on a page known unchanged since // it was copied: guarded (read-only since that copy), or write-watched and found unwritten by an asking made here. // The asking comes first because write_back runs before refresh() asks: a hot page still carried kClean from the // last asking, so the title's writes since then were copied over with the older copy. Comparing first leaves a // read-only binding's pages alone (guarded, so a write the title makes meanwhile faults and waits on the lock), // where opening them for a whole copy lost a write made between the opening and the copy; and of two copies of // the same bytes only the one that differs is written, where the last one won. // // All the finished ranges over this tracker come in one call, and which pages are held is decided once for all of // them, before the first copy. One call per range made the first range that differed reopen its page (kProtected // gone), and every later range on that page then read as written by the title and was dropped, though only this // write-back had written there (73N1X, #1608: of 130 four-byte ranges 256 bytes apart, 9 went back). A page // opened here is open to the title until the next refresh guards it again, as it was for the pieces of one range // after the first. // // `only` (a retired window's copy, when it is freed): that copy alone goes back, where no live copy changed the // bytes; the live copies' own results wait for their submissions' batches. struct ReadbackLookup { struct Entry { std::uintptr_t src_lo = 0; std::uintptr_t src_hi = 0; const std::uint8_t* cached = nullptr; }; const Entry* entries = nullptr; std::size_t count = 0; const std::uint8_t* map(const std::uint8_t* ptr, std::size_t len) const { if (!entries || !count || !ptr || !len) return ptr; const auto p = reinterpret_cast(ptr); std::size_t lo = 0, hi = count; while (lo < hi) { const std::size_t mid = lo + (hi - lo) / 2; if (entries[mid].src_lo <= p) lo = mid + 1; else hi = mid; } if (lo == 0) return ptr; const Entry& e = entries[lo - 1]; if (p >= e.src_lo && p < e.src_hi && len <= e.src_hi - p) return e.cached + (p - e.src_lo); return ptr; } }; std::size_t write_back(const std::pair* ranges, std::size_t count, std::size_t* reached = nullptr, const std::uint8_t* only = nullptr, const ReadbackLookup* readback = nullptr) { if (reached) *reached = 0; std::uintptr_t lo = last_, hi = first_; // the pages the ranges cover for (std::size_t r = 0; r < count; ++r) { const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_); if (from >= to) continue; lo = std::min(lo, from & ~(kPage - 1)); hi = std::max(hi, (to + kPage - 1) & ~(kPage - 1)); } if (lo >= hi) return 0; // Sized before lock_ is taken: a thread that faults on a guarded page waits on lock_ in reopen(), and may hold // the heap's lock while it does. Only write_back uses it, and one write_back runs at a time (shadow_mutex). held_pages_.resize((hi - lo) / kPage); AcquireSRWLockExclusive(&lock_); // The copies below can fault on a page another guard (the geometry watch, another view's shadow) keeps // read-only. The fault handler asks this tracker too (reopen), and must not take lock_ again on this thread: // SRW locks are not recursive, and a title thread hung there for good (621.40, a submission's write-back). writer_.store(GetCurrentThreadId(), std::memory_order_relaxed); // What changed since the last refresh, as refresh() learns it: mappings (the journal), kernel-write pins, and // the write watch. A journal that no longer reaches back makes nothing known: nothing goes back. std::uint64_t map_generation = leonida::title_memory_map::generation(); bool known = map_generation_ != ~std::uint64_t(0); if (known && map_generation != map_generation_) known = leonida::title_memory_map::changes_since( map_generation_, map_generation, first_, last_, [&](std::uintptr_t a, std::uintptr_t b) { for (std::size_t i = (a - first_) / kPage, i1 = (b - first_ + kPage - 1) / kPage; i < i1 && i < state_.size(); ++i) state_[i] |= kRequery; }); if (!known) { writer_.store(0, std::memory_order_relaxed); ReleaseSRWLockExclusive(&lock_); return 0; } for (std::size_t r = 0; r < count; ++r) { const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_); if (from >= to) continue; leonida::kernel_writes::for_each_pin(from, to, [&](std::uintptr_t a, std::uintptr_t b) { for (std::uintptr_t p = std::max(a, from) & ~(kPage - 1); p < std::min(b, to); p += kPage) state_[(p - first_) / kPage] |= kPinned; pinned_ = true; }); } ask_written_locked(); // A page the title wrote since it was last copied holds the newer bytes already: its GPU result is dropped and // the refresh's own copy carries the title's. So is a page whose mapping changed, one a kernel write may be // filling, and one xmem maps at another address too (a write there is seen by no guard and no watch here). // Decided for every page of every range before the first copy (#2468, RT-WRITEBACK-TILE-REOPEN, and this // call's other ranges): a copy below can fault on another guard, and the handler then reopens the whole 64 KiB // tile here on this thread (reopen_range), which clears kClean and kProtected there; and a range that differs // reopens its pages itself. Read live, either made the later runs on those pages count as written by the // title, and their GPU results were dropped from a batch already taken off the queue. A page the title wrote // before this point is held still. const std::size_t p0 = (lo - first_) / kPage; for (std::size_t r = 0; r < count; ++r) { const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_); if (from >= to) continue; for (std::size_t i = (from - first_) / kPage, i1 = (to - first_ + kPage - 1) / kPage; i < i1; ++i) { const std::uint16_t s = state_[i]; held_pages_[i - p0] = (s & (kZero | kRequery | kPinned | kAliased)) || (!(s & kProtected) && !(s & kClean)); } } const auto held = [&](std::size_t i) { return held_pages_[i - p0] != 0; }; constexpr std::uintptr_t kPiece = 256; // compared and copied in pieces this size std::size_t written = 0; Vector> dirty_targets; for (std::size_t r = 0; r < count; ++r) { const std::uintptr_t from = std::max(ranges[r].first, first_), to = std::min(ranges[r].second, last_); if (from >= to) continue; const std::size_t range_written = written; const std::uintptr_t end = (to + kPage - 1) & ~(kPage - 1); for (std::uintptr_t at = from & ~(kPage - 1); at < end;) { std::size_t pages = 0; while (at + (pages + 1) * kPage <= end && held((at - first_) / kPage + pages) == held((at - first_) / kPage)) ++pages; if (!held((at - first_) / kPage)) { const std::uintptr_t a = std::max(at, from), b = std::min(at + pages * kPage, to); bool opened = false; Vector over; // the targets with bytes in [a, b) for (const Target& t : targets_) if (t.shadow && std::max(a, t.begin) < std::min(b, t.end)) over.push_back(&t); // Piece by piece, against the title's bytes as they were before any copy went back here: a copy goes // back on the bytes it holds differently from those, so one that still holds them is not written over // another's result. A retired window's copy (retire_target) goes back only on bytes no live copy // changed: what a submission wrote in it is older than what a live copy holds (the range that // replaced it serves every submission recorded since). Byte by byte, as two copies can share a piece // with disjoint bytes each. for (std::uintptr_t c = a; c < b && !over.empty();) { const std::uintptr_t e = std::min(b, (c + kPiece) & ~(kPiece - 1)); std::uint8_t before[kPiece]; bool live[kPiece]; // the bytes a live copy changed, once `saved` bool saved = false; for (int pass = 0; pass < 2; ++pass) for (const Target* t : over) { if (t->retired != (pass == 1) || (only && pass == 1 && t->shadow != only)) continue; const std::uintptr_t x = std::max(c, t->begin), y = std::min(e, t->end); if (x >= y) continue; const std::uint8_t* raw_copy = t->shadow + (x - t->begin); const std::uint8_t* copy = readback ? readback->map(raw_copy, y - x) : raw_copy; const void* now = saved ? static_cast(before + (x - c)) : reinterpret_cast(x); if (std::memcmp(now, copy, y - x) == 0) continue; if (!saved) { std::memcpy(before, reinterpret_cast(c), e - c); std::fill_n(live, e - c, false); saved = true; } const auto goes = [&](std::uintptr_t v) { return copy[v - x] != before[v - c] && !(pass == 1 && live[v - c]); }; for (std::uintptr_t i = x; i < y;) { if (!goes(i)) { ++i; continue; } std::uintptr_t j = i + 1; while (j < y && goes(j)) ++j; if (pass == 0) std::fill(live + (i - c), live + (j - c), true); if (pass == 1 || !only) { // `only`: the live copies' results wait for their batches if (!opened) { // An earlier range on these pages may have reopened them already. const std::size_t i0 = (at - first_) / kPage; if (std::any_of(state_.begin() + i0, state_.begin() + i0 + pages, [](std::uint16_t page) { return page & kProtected; })) reopen_locked(at, at + pages * kPage); opened = true; } std::memcpy(reinterpret_cast(i), copy + (i - x), j - i); written += j - i; } // A retired copy's bytes are the title's now: the copies that held the older ones // take them too, as the next refresh would, so one read before it (the range that // replaced the window, when the window is freed after this submission's refresh) // is not behind the title. A copy that changed a byte keeps its own. if (pass == 1) for (const Target* o : over) { if (o == t) continue; const std::uintptr_t lo = std::max(i, o->begin); const std::uintptr_t hi = std::min(j, o->end); const std::uint8_t* o_read = readback && lo < hi ? readback->map(o->shadow + (lo - o->begin), hi - lo) : (o->shadow + (lo - o->begin)); std::uintptr_t run_start = hi; for (std::uintptr_t v = lo; v < hi; ++v) { if (o_read[v - lo] == before[v - c]) { o->shadow[v - o->begin] = copy[v - x]; if (dirty_fn_ && run_start == hi) run_start = v; } else if (dirty_fn_ && run_start < v) { dirty_targets.push_back( {o->shadow + (run_start - o->begin), v - run_start}); run_start = hi; } } if (dirty_fn_ && run_start < hi) dirty_targets.push_back( {o->shadow + (run_start - o->begin), hi - run_start}); } i = j; } } c = e; } } at += pages * kPage; } if (reached && written != range_written) ++*reached; } writer_.store(0, std::memory_order_relaxed); ReleaseSRWLockExclusive(&lock_); for (const auto& [ptr, len] : dirty_targets) note_dirty(ptr, len); return written; } // The bytes of all targets, and how many there are. std::size_t size() const { return target_bytes_; } std::size_t targets() const { return targets_.size(); } // The pages covered: [first(), last()), 4 KiB aligned. std::uintptr_t first() const { return first_; } std::uintptr_t last() const { return last_; } bool contains(std::uintptr_t address) const { return address >= first_ && address < last_; } std::uint64_t faults() const { return faults_.load(std::memory_order_relaxed); } std::uint64_t refresh_queries() const { return refresh_queries_; } std::uint64_t refresh_protects() const { return refresh_protects_; } bool refresh_walked_all() const { return refresh_walked_all_; } // GetWriteWatch calls of the last refresh(), the write-watched pages it found written, and the bytes of the // covered pages that are write-watched, and of those asked about (hot). std::uint64_t refresh_asks() const { return refresh_asks_; } std::uint64_t refresh_written() const { return refresh_written_; } std::size_t watched_bytes() const { return watched_pages_ * kPage; } std::size_t hot_bytes() const { return hot_pages_ * kPage; } // The ranges the last refresh() copied from the pages, as (offset from the first target's start, bytes). Pages it // zeroed are not among them. Only between refreshes, under the lock that serializes them. For a tracker with one // target (a console descriptor heap's), whose offsets are the buffer's. template void for_each_copied(F&& f) const { for (const Job& job : jobs_) f(job.offset, job.bytes); } // The ranges the last refresh() zeroed in the copies (pages no longer committed or readable), likewise. template void for_each_zeroed(F&& f) const { for (const Job& job : zeroed_) f(job.offset, job.bytes); } // Brings every target up to date with the pages. Returns the bytes copied into them. With copy_aliased false, pages // xmem maps at another address too are left as they are this time (DeviceState::refresh_shadows throttles them). std::size_t refresh(bool copy_aliased = true) { const auto walk_start = std::chrono::steady_clock::now(); pieces_ = {}; copy_aliased_ = copy_aliased; update_aliased(); jobs_.clear(); zeroed_.clear(); copy_bytes_ = {}; std::uint64_t queries = 0; // LEONIDA_SHADOW_FULL_WALK=1 queries every page at every refresh, as before the generation skip. static const bool always_full_walk = [] { char value[8] = {}; std::size_t length = 0; return getenv_s(&length, value, sizeof(value), "LEONIDA_SHADOW_FULL_WALK") == 0 && length > 1 && value[0] != '0'; }(); AcquireSRWLockExclusive(&lock_); // Pages whose mapping, commitment or protection changed since the last walk are queried again (kRequery); the // rest keep what is known of them. A tracker that never walked, or whose changes the journal no longer holds, // walks everything. std::uint64_t map_generation = leonida::title_memory_map::generation(); bool full_walk = always_full_walk || map_generation_ == ~std::uint64_t(0); if (!full_walk && map_generation != map_generation_ && !leonida::title_memory_map::changes_since( map_generation_, map_generation, first_, last_, [&](std::uintptr_t from, std::uintptr_t to) { for (std::size_t i = (from - first_) / kPage, i1 = (to - first_ + kPage - 1) / kPage; i < i1 && i < state_.size(); ++i) state_[i] |= kRequery; })) full_walk = true; refresh_walked_all_ = full_walk; refresh_protects_ = alias_arms_; if (pinned_) { for (std::uint16_t& s : state_) s &= ~kPinned; pinned_ = false; } leonida::kernel_writes::for_each_pin(first_, last_, [&](std::uintptr_t from, std::uintptr_t to) { for (std::uintptr_t p = from & ~(kPage - 1); p < to; p += kPage) state_[(p - first_) / kPage] |= kPinned; pinned_ = true; }); // The write-watched pages written since the last asking are no longer clean: asked before the walk, so a write // after this is in the next asking. refresh_asks_ = refresh_written_ = 0; if (ask_written_locked()) cool(); // a block it guards again leaves the runs at the next refresh for (std::uintptr_t at = first_; at < last_;) { const std::size_t i0 = (at - first_) / kPage; if (!cover_[i0]) { // no copy reads it: left as the title set it std::size_t i = i0 + 1; while (i < state_.size() && !cover_[i]) ++i; at = first_ + i * kPage; continue; } // Between the refreshes that copy aliased pages (copy_aliased_, LEONIDA_SHADOW_ALIAS_MS), pages that are // only aliased, and pages that were not mapped or committed when last looked at (zero in the copies), are // passed over like unchanged ones and queried at the next such refresh: a mapping change over them is in // the journal (kRequery) anyway. speed-16/17/18: 730-820 VirtualQuery calls a refresh, ~19 us each under // Wine (NtQueryVirtualMemory waits for Wine's virtual-memory lock, which the mapping threads hold), a // fifth of the submitting thread's time. So are aliased pages whose cells no write reached (aliased_clean): // a mapping, commitment or protection change over a cell moves its version too. const auto skip = [&](std::size_t i) { const std::uint16_t s = state_[i]; return unchanged(s) || ((s & ~(kZero | kProtected)) == kAliased && aliased_clean(i)) || (!copy_aliased_ && (s == kAliased || s == (kZero | kAliased))); }; if (!full_walk && skip(i0)) { std::size_t i = i0 + 1; while (i < state_.size() && skip(i)) ++i; at = first_ + i * kPage; continue; } MEMORY_BASIC_INFORMATION region{}; std::uintptr_t next = at + kPage; Kind kind = Kind::zero; ++queries; if (VirtualQuery(reinterpret_cast(at), ®ion, sizeof(region))) { next = std::min(last_, reinterpret_cast(region.BaseAddress) + region.RegionSize); kind = classify(region); } if (kind == Kind::zero) kind = table_kind(at, next); std::size_t i1 = (next - first_) / kPage; for (std::size_t i = i0 + 1; i < i1; ++i) if (!cover_[i]) { // the region goes on past the pages copies read: the rest is passed over above i1 = i; next = first_ + i * kPage; break; } const bool streaming = (region.Protect & PAGE_WRITECOMBINE) != 0; switch (kind) { case Kind::zero: for (std::size_t i = i0; i < i1; ++i) { if (state_[i] & kZero) continue; const auto [offset, bytes] = span_of(i, i + 1); zero_targets(offset, bytes); leonida::shadow_keep::forget(sums_.data(), first_, begin_ + offset, begin_ + offset + bytes); if (!zeroed_.empty() && zeroed_.back().offset + zeroed_.back().bytes == offset) zeroed_.back().bytes += bytes; else zeroed_.push_back({offset, bytes, false}); state_[i] = std::uint16_t(kZero | (state_[i] & (kAliased | kPinned | kWatched))); } break; case Kind::writable: case Kind::read_only: for (std::size_t i = i0; i < i1;) { const Watch how = watch_of(state_[i]); std::size_t j = i + 1; while (j < i1 && watch_of(state_[j]) == how) ++j; switch (how) { case Watch::clean: break; // write-watched, not written since it was copied case Watch::written: // write-watched: written since, or not known yet // A page this tracker made read-only is opened first: dropping kProtected alone left it // read-only with no owner, so the next write could fault. unguard_ours(i, j); for (std::size_t k = i; k < j; ++k) state_[k] = std::uint16_t((state_[k] & ~(kZero | kProtected | kExternalRo)) | kClean); add_job(i, j, streaming, Copy::write_watched); break; case Watch::open: // write-watched, but pinned for a kernel write: copied until the pin ends unguard_ours(i, j); for (std::size_t k = i; k < j; ++k) state_[k] &= ~(kZero | kProtected | kClean | kExternalRo); add_job(i, j, streaming, Copy::write_watched); break; case Watch::guard: if (kind == Kind::writable) guard_writable(i, j, region.Protect, streaming); else guard_read_only(i, j, streaming, full_walk); break; } i = j; } break; case Kind::unwatched: unguard_ours(i0, i1); // as above: never drop kProtected over a page still read-only for us for (std::size_t i = i0; i < i1; ++i) state_[i] &= kAliased | kPinned | kWatched; add_job(i0, i1, streaming, Copy::copy_on_write); break; } for (std::size_t i = i0; i < i1; ++i) state_[i] &= std::uint16_t(~kRequery); // queried now at = next; } // Remember the generation from before the walk, so a change during the walk triggers another one. map_generation_ = map_generation; const DWORD protect_error = std::exchange(protect_error_, 0); ReleaseSRWLockExclusive(&lock_); if (dirty_fn_ && !zeroed_.empty()) { for (const Job& z : zeroed_) for_each_target(begin_ + z.offset, begin_ + z.offset + z.bytes, [&](const Target& t, std::uintptr_t a, std::uintptr_t b) { note_dirty(t.shadow + (a - t.begin), b - a); }); } if (protect_error) log_once("slot-133 shadow: VirtualProtect refused to watch the title's pages for writes, so they are " "copied at every submission; error", int(protect_error)); // The copies run without the lock: a write that faults meanwhile is let through and copied next time. Pages // copied because they are aliased go to the GPU when LEONIDA_SHADOW_GPU set gpu_copy and it takes them. // LEONIDA_SHADOW_JOIN=1: pieces of one job that go on where the one before ended, in the pages and in the copy // both, are one copy (one GPU region, one gpu_copy call); one the GPU refuses is copied by the CPU whole. static const bool join = [] { char value[4] = {}; return GetEnvironmentVariableA("LEONIDA_SHADOW_JOIN", value, sizeof(value)) == 1 && value[0] == '1'; }(); const auto copy_start = std::chrono::steady_clock::now(); pieces_.walk_ms = std::chrono::duration(copy_start - walk_start).count(); std::size_t copied = 0; for (const Job& job : jobs_) { if (keep_gpu_writes()) { // only the pieces whose title bytes changed (src/shadow_keep.h) copied += copy_changed(job); continue; } std::uint8_t* run_dst = nullptr; const std::uint8_t* run_src = nullptr; std::size_t run_bytes = 0; const auto flush = [&] { if (!run_bytes) return; ++pieces_.calls; if (job.aliased && gpu_copy) ++pieces_.gpu_calls; if (job.aliased && gpu_copy && gpu_copy(gpu_copy_context, run_dst, run_src, run_bytes)) gpu_bytes_ += run_bytes; else { copy_run(run_dst, run_src, run_bytes, job.streaming); note_dirty(run_dst, run_bytes); } run_bytes = 0; }; for_each_target(begin_ + job.offset, begin_ + job.offset + job.bytes, [&](const Target& t, std::uintptr_t from, std::uintptr_t to) { std::uint8_t* dst = t.shadow + (from - t.begin); const auto* src = reinterpret_cast(from); const std::size_t n = to - from; ++pieces_.pieces; pieces_.short_pieces += n < kPage; const bool follows = run_bytes && run_dst + run_bytes == dst && run_src + run_bytes == src; pieces_.joinable += follows; if (join && follows) { run_bytes += n; } else { flush(); run_dst = dst; run_src = src; run_bytes = n; if (!join) flush(); } copied += n; }); flush(); } pieces_.copy_ms = std::chrono::duration(std::chrono::steady_clock::now() - copy_start).count(); refresh_queries_ = queries; return copied; } // DeviceState::add_shadow, with every other tracker of its device held still (shadow_mutex) and the fault // handler kept out (g_shadow_pages_lock exclusive). The pages [first, last) (4 KiB aligned) are covered from // now on; the ones new here are unknown, so the next refresh queries them. void extend(std::uintptr_t first, std::uintptr_t last) { AcquireSRWLockExclusive(&lock_); if (first < first_) { const std::size_t n = (first_ - first) / kPage; state_.insert(state_.begin(), n, std::uint16_t(0)); idle_.insert(idle_.begin(), n, std::uint8_t(0)); sums_.insert(sums_.begin(), n * kPieces, std::uint64_t(0)); cover_.insert(cover_.begin(), n, 0u); first_ = first; } if (last > last_) { state_.resize((last - first_) / kPage, 0); idle_.resize(state_.size(), 0); sums_.resize(state_.size() * kPieces, 0); cover_.resize(state_.size(), 0); last_ = last; } alias_generation_ = ~std::uint64_t(0); // the new pages' alias marks watch_generation_ = ~std::uint64_t(0); // and whether they are write-watched ReleaseSRWLockExclusive(&lock_); } // Likewise: takes over `other`'s targets, pages and what is known of them (inside this tracker's range, which // never shares a page with it before). `other` is left with nothing to reopen: the caller unregisters and // deletes it, and the pages it made read-only are this tracker's now. void absorb(ShadowPages& other) { AcquireSRWLockExclusive(&lock_); AcquireSRWLockExclusive(&other.lock_); const std::size_t at = (other.first_ - first_) / kPage; for (std::size_t i = 0; i < other.state_.size(); ++i) { state_[at + i] |= other.state_[i]; cover_[at + i] += other.cover_[i]; idle_[at + i] = other.idle_[i]; std::copy_n(other.sums_.begin() + std::ptrdiff_t(i * kPieces), kPieces, sums_.begin() + std::ptrdiff_t((at + i) * kPieces)); } targets_.insert(targets_.end(), other.targets_.begin(), other.targets_.end()); if (other.map_generation_ != map_generation_) map_generation_ = ~std::uint64_t(0); // Its clean write-watched pages are clean as of its last asking: this tracker asks from the older of the two. if (other.reader_) { if (!reader_) { reader_ = leonida::title_write_watch::open_reader(); forget_clean(); } leonida::title_write_watch::merge_reader(reader_, other.reader_); } watch_generation_ = ~std::uint64_t(0); alias_generation_ = ~std::uint64_t(0); pinned_ |= other.pinned_; watch_ = watch_ && other.watch_; faults_.fetch_add(other.faults(), std::memory_order_relaxed); std::fill(other.state_.begin(), other.state_.end(), std::uint16_t(0)); other.targets_.clear(); ReleaseSRWLockExclusive(&other.lock_); index_targets(); ReleaseSRWLockExclusive(&lock_); } // Likewise: [begin, end), inside the covered pages, is copied to `shadow` from now on. fill() it next. void add_target(std::uintptr_t begin, std::uintptr_t end, std::uint8_t* shadow) { AcquireSRWLockExclusive(&lock_); targets_.push_back({begin, end, shadow}); for (std::uintptr_t p = begin & ~(kPage - 1); p < end; p += kPage) ++cover_[(p - first_) / kPage]; index_targets(); alias_generation_ = ~std::uint64_t(0); // the aliased blocks the copies read ReleaseSRWLockExclusive(&lock_); } // A new target's first copy, of the pages as they are now; their watched state is not touched. A page this // tracker keeps read-only is as the other targets have it; one written meanwhile is copied again at the next // refresh, like any page that isn't read-only here. Under shadow_mutex, so no refresh runs meanwhile. void fill(std::uintptr_t begin, std::uintptr_t end, std::uint8_t* shadow) { for (std::uintptr_t at = begin & ~(kPage - 1); at < end;) { MEMORY_BASIC_INFORMATION region{}; std::uintptr_t next = at + kPage; Kind kind = Kind::zero; if (VirtualQuery(reinterpret_cast(at), ®ion, sizeof(region))) { next = reinterpret_cast(region.BaseAddress) + region.RegionSize; kind = classify(region); } if (kind == Kind::zero) { // a reservation can be far larger than the new target next = std::min(next, end); kind = table_kind(at, next); } const std::uintptr_t from = std::max(at, begin), to = std::min(next, end); if (kind == Kind::zero) { std::memset(shadow + (from - begin), 0, to - from); note_dirty(shadow + (from - begin), to - from); } else { const bool streaming = (region.Protect & PAGE_WRITECOMBINE) != 0; copy_run(shadow + (from - begin), reinterpret_cast(from), to - from, streaming); note_dirty(shadow + (from - begin), to - from); // The sums stand for what every target holds. The new target now holds the title's current bytes, so // the pieces where those differ from the sums are brought to the other targets too, and the sums // follow; otherwise a title that later writes the old bytes back would leave the new target behind. // Whole pieces (inside this page, so this region) up to the targets' ends, as a refresh sums them: a // piece cut at the new target's edge would be summed short and copied again at the next refresh. constexpr std::uintptr_t kPiece = leonida::shadow_keep::kPiece; if (keep_gpu_writes()) reconcile(std::max(from & ~(kPiece - 1), begin_), std::min((to + kPiece - 1) & ~(kPiece - 1), end_), streaming); } at = next; } } // [from, to), readable title pages: the pieces whose bytes differ from the sums are copied to every target over // them and their sums updated, as a refresh does. void reconcile(std::uintptr_t from, std::uintptr_t to, bool streaming) { alignas(64) std::uint8_t page[kPage]; for (std::uintptr_t va = from; va < to;) { const std::size_t n = std::min(to - va, kPage - (va & (kPage - 1))); copy_run(page, reinterpret_cast(va), n, streaming); leonida::shadow_keep::copy_changed( page, va, n, sums_.data(), first_, [&](std::uintptr_t a, std::uintptr_t b, const std::uint8_t* source) { for_each_target(a, b, [&](const Target& t, std::uintptr_t lo, std::uintptr_t hi) { std::memcpy(t.shadow + (lo - t.begin), source + (lo - a), hi - lo); note_dirty(t.shadow + (lo - t.begin), hi - lo); }); }); va += n; } } // Under shadow_mutex: `shadow` is a retired window's copy (retire_orphan_windows). It is still refreshed, so it // never holds bytes older than the title's but what the GPU wrote in it, and what it holds goes back only where // no live copy changed the bytes (write_back). False when it isn't one of this tracker's. bool retire_target(const std::uint8_t* shadow) { AcquireSRWLockExclusive(&lock_); bool found = false; for (Target& t : targets_) if (t.shadow == shadow) t.retired = found = true; ReleaseSRWLockExclusive(&lock_); return found; } bool has_target(const std::uint8_t* shadow) const { return std::any_of(targets_.begin(), targets_.end(), [shadow](const Target& t) { return t.shadow == shadow; }); } // Under shadow_mutex: `shadow` is no longer a target. Pages no other target covers are made writable again and // passed over from now on. False when it isn't one of this tracker's. bool remove_target(const std::uint8_t* shadow) { const auto it = std::find_if(targets_.begin(), targets_.end(), [shadow](const Target& t) { return t.shadow == shadow; }); if (it == targets_.end()) return false; AcquireSRWLockExclusive(&lock_); const std::size_t i_end = (((it->end + kPage - 1) & ~(kPage - 1)) - first_) / kPage; for (std::size_t i = ((it->begin & ~(kPage - 1)) - first_) / kPage; i < i_end;) { if (--cover_[i]) { ++i; continue; } std::size_t j = i + 1; // [i, j): pages nothing covers now for (; j < i_end && cover_[j] == 1; ++j) cover_[j] = 0; reopen_locked(first_ + i * kPage, first_ + j * kPage); for (std::size_t k = i; k < j; ++k) state_[k] &= kAliased | kPinned | kWatched; i = j; } targets_.erase(it); index_targets(); watch_generation_ = ~std::uint64_t(0); // recounts the write-watched pages covered alias_generation_ = ~std::uint64_t(0); // and the aliased blocks the copies read ReleaseSRWLockExclusive(&lock_); return true; } // From a file shim, before the kernel writes [from, to): the pages there this tracker protected are writable again, // and the write-watched ones count as written (a device writing into locked pages need not set the kernel's bit). void reopen_range(std::uintptr_t from, std::uintptr_t to) { from = std::max(from & ~(kPage - 1), first_); to = std::min((to + kPage - 1) & ~(kPage - 1), last_); if (from >= to) return; const bool held = writer_.load(std::memory_order_relaxed) == GetCurrentThreadId(); // see write_back if (!held) AcquireSRWLockExclusive(&lock_); bool guarded = false; for (std::size_t i = (from - first_) / kPage, i1 = (to - first_) / kPage; i < i1; ++i) { state_[i] &= ~(kClean | kExternalRo); guarded |= (state_[i] & kProtected) != 0; } if (guarded) reopen_locked(from, to); if (!held) ReleaseSRWLockExclusive(&lock_); } // From the fault handler: a write to `address`, inside this range, faulted. True when the write can be retried: // the page is one this tracker made read-only, and the 64 KiB around it that it protected are read-write again; // or the page is writable already, because another thread's fault reopened it after this write faulted. The // second is asked here, under the lock, not by the handler afterwards: refresh() protects pages under the same // lock, so by a later look the page can be read-only again (and this tracker's again), and the handler refused a // write it should have retried, which ended the process (seen natively on Windows 11: threads writing one page // across a submission). bool reopen(std::uintptr_t address, bool* block_reopened = nullptr) { // On the thread whose write_back faulted, lock_ is held already (see write_back). const bool held = writer_.load(std::memory_order_relaxed) == GetCurrentThreadId(); if (!held) AcquireSRWLockExclusive(&lock_); const std::size_t index = (address - first_) / kPage; bool retry = (state_[index] & kProtected) != 0; if (retry) { const std::uintptr_t block = address & ~(kBlock - 1); const std::uintptr_t from = std::max(block, first_), to = std::min(block + kBlock, last_); // A write-watched block written again: asked about from now on, not guarded (what reopen_locked left // read-only stays guarded). No allocation in here: the faulting thread may hold the heap's lock. bool watched[kBlock / kPage] = {}; const std::size_t i0 = (from - first_) / kPage, i1 = (to - first_) / kPage; for (std::size_t i = i0; i < i1; ++i) watched[i - i0] = (state_[i] & (kWatched | kHot | kProtected)) == (kWatched | kProtected); reopen_locked(from, to, /*notify_map=*/false); retry = !(state_[index] & kProtected); if (retry && block_reopened) *block_reopened = true; faults_.fetch_add(1, std::memory_order_relaxed); for (std::size_t i = i0; i < i1; ++i) { if (!watched[i - i0] || (state_[i] & kProtected)) continue; state_[i] = std::uint16_t((state_[i] | kHot) & ~kClean); idle_[i] = 0; runs_stale_ = true; } } else { MEMORY_BASIC_INFORMATION region{}; retry = VirtualQuery(reinterpret_cast(address), ®ion, sizeof(region)) && classify(region) == Kind::writable; if (retry) state_[index] &= ~kExternalRo; } if (!held) ReleaseSRWLockExclusive(&lock_); return retry; } private: enum : std::uint16_t { kProtected = 1, // made read-only here: unchanged since it was copied kZero = 2, // zero in the copies (not committed when last looked at) kAliased = 4, // xmem maps its physical page at another address too kPinned = 8, // a kernel write into it may be in flight (leonida::kernel_writes) kWatched = 16, // in a write-watched reservation (leonida::title_write_watch) kClean = 32, // hot, and not written since it was copied after an asking kHot = 64, // write-watched and asked about at every refresh, never guarded kRequery = 128, // its mapping, commitment or protection changed (title_memory_map): queried at the next walk kExternalRo = 256, // observed read-only (not ours) and copied once: unchanged until kRequery }; // Refreshes a hot block may go without a write before it is guarded again. static constexpr std::uint8_t kCool = 64; // Hot runs this close in one reservation are asked about as one (a call costs about as much as 300 pages). static constexpr std::uintptr_t kMergeGap = 0x40000; enum class Kind { zero, writable, read_only, unwatched }; public: // Why the last refresh() copied the bytes it did (copy_bytes): pages guarded now (written since, or new), pages left // writable (no guard possible), pages xmem maps at another address too, pages pinned for a kernel write, // read-only pages that are not this tracker's, copy-on-write pages, write-watched pages found written. enum class Copy { guarded, unguarded, aliased, pinned, read_only, copy_on_write, write_watched, count }; const std::array& copy_bytes() const { return copy_bytes_; } // The last refresh()'s copies as pieces (one per job and target: a slot-133 buffer is a few KiB, so a run of // pages over many of them is many pieces), those under 4 KiB, those that go on where the one before ended in both // the title's pages and the copy (VItoriaBr's JOIN_COPIES case), the copy calls made after LEONIDA_SHADOW_JOIN // joined those, and the milliseconds of the walk (queries, guards, under the lock) and of the copies. struct Pieces { std::uint64_t pieces = 0, short_pieces = 0, joinable = 0, calls = 0, gpu_calls = 0; double walk_ms = 0, copy_ms = 0; }; const Pieces& pieces() const { return pieces_; } private: // How a committed, readable page is watched: by the kernel (clean, written or, pinned or aliased, open) or by // a guard. enum class Watch { clean, written, open, guard }; static Watch watch_of(std::uint16_t s) { if ((s & (kWatched | kHot)) != (kWatched | kHot)) return Watch::guard; if (s & (kAliased | kPinned)) return Watch::open; return s & kClean ? Watch::clean : Watch::written; } // A page known unchanged since the last refresh, which one that doesn't walk everything passes over. // Uncommitted (kZero) and externally read-only (kExternalRo) pages cannot change without a mapping or protection // change (which sets kRequery via title_memory_map::changed). static bool unchanged(std::uint16_t s) { const std::uint16_t base = s & ~kWatched; return base == kProtected || base == kExternalRo || base == kZero || s == (kWatched | kHot | kClean); } // One asking of the write watch, under lock_: the hot pages written since the last asking lose kClean (counted in // refresh_written_). From refresh() before its walk, and from write_back() before it trusts kClean. False when no // page is write-watched here. bool ask_written_locked() { const std::uint64_t watch_generation = leonida::title_write_watch::generation(); if (watch_generation != watch_generation_) { watch_generation_ = watch_generation; update_watched(); } if (runs_stale_) rebuild_watch_runs(); if (watch_runs_.empty()) return false; if (!reader_) { reader_ = leonida::title_write_watch::open_reader(); forget_clean(); } refresh_asks_ += watch_runs_.size(); leonida::title_write_watch::ask( reader_, watch_runs_, [&](std::uintptr_t from, std::uintptr_t to) { for (std::uintptr_t p = from; p < to; p += kPage) { std::uint16_t& s = state_[(p - first_) / kPage]; if (!(s & kHot)) continue; // asked over a gap between hot pages: guarded refresh_written_ += (s & kClean) != 0; s &= ~kClean; warm(p); } }, [&](std::uintptr_t from, std::uintptr_t to) { // Not write-watched after all (released and reserved again): guarded from now on. for (std::uintptr_t p = from; p < to; p += kPage) state_[(p - first_) / kPage] &= ~(kWatched | kClean | kHot); runs_stale_ = true; }); return true; } // A hot page `p` was found written: its block is not idle. void warm(std::uintptr_t p) { const std::uintptr_t block = p & ~(kBlock - 1); const std::size_t i0 = (std::max(block, first_) - first_) / kPage; const std::size_t i1 = (std::min(block + kBlock, last_) - first_) / kPage; for (std::size_t i = i0; i < i1; ++i) idle_[i] = 0; } // After an asking: the hot pages not found written are one refresh idler, and those idle for kCool refreshes are // guarded from now on (not clean: the walk copies them as it makes them read-only). void cool() { for (const auto& [from, to] : watch_runs_) for (std::size_t i = (from - first_) / kPage, i1 = (to - first_) / kPage; i < i1; ++i) { if (!(state_[i] & kHot)) continue; if (idle_[i] < kCool) { ++idle_[i]; continue; } state_[i] &= ~(kHot | kClean); idle_[i] = 0; runs_stale_ = true; } } // Guarded pages [i, j) of a read-write region (protection `current`): written since the last refresh, or newly // committed or mapped. Watched from now on, then copied. void guard_writable(std::size_t i0, std::size_t i1, DWORD current, bool streaming) { for (std::size_t i = i0; i < i1;) { const bool unwatched = state_[i] & (kAliased | kPinned); std::size_t j = i + 1; while (j < i1 && bool(state_[j] & (kAliased | kPinned)) == unwatched) ++j; for (std::size_t k = i; k < j; ++k) { state_[k] &= ~(kZero | kProtected | kExternalRo); // Writable with no write seen: its cells must be armed again (update_aliased). if (aliased_clean(k) && (rearm_.empty() || rearm_.back() != block_of(k))) rearm_.push_back(block_of(k)); } if (!unwatched && watch_) protect(i, j, current); if (unwatched && !copy_aliased_ && (state_[i] & kAliased)) { i = j; continue; } add_job(i, j, streaming, !unwatched ? (watch_ && (state_[i] & kProtected) ? Copy::guarded : Copy::unguarded) : (state_[i] & kAliased) ? Copy::aliased : Copy::pinned); i = j; } } // Guarded pages [i, j) of a read-only region: pages this tracker protected, externally read-only pages already // copied with no intervening mapping/protection change, and aliased pages whose cells no write reached are as the // last refresh left them; non-aliased pages already armed read-only by geometry_writes (TitleTextureCells / // GeometryViews / TitleMirror) adopt kProtected after one copy so ShadowPages skips them on subsequent refreshes // instead of recopying them forever as Copy::read_only; any other read-only page is copied once and marked // kExternalRo until a mapping/protection change triggers kRequery. void guard_read_only(std::size_t i0, std::size_t i1, bool streaming, bool full_walk) { const auto clean_at = [&](std::size_t k) { const std::uint16_t s = state_[k]; return (s & (kProtected | kAliased | kPinned)) == kProtected || (!full_walk && (s & (kExternalRo | kRequery | kAliased | kPinned)) == kExternalRo) || ((s & (kAliased | kPinned)) == kAliased && aliased_clean(k)); }; for (std::size_t i = i0; i < i1;) { const bool clean = clean_at(i); std::size_t j = i + 1; while (j < i1 && clean_at(j) == clean) ++j; if (!clean) { for (std::size_t p = i; p < j;) { const std::uint8_t flags = state_[p] & (kAliased | kPinned); std::size_t q = p + 1; while (q < j && (state_[q] & (kAliased | kPinned)) == flags) ++q; if (!copy_aliased_ && (flags & kAliased)) { p = q; continue; } if (!flags && watch_) { for (std::size_t chunk = p; chunk < q;) { constexpr std::size_t kChunk = 64; const std::size_t n = std::min(q - chunk, kChunk); std::uint8_t gw[kChunk]; leonida::geometry_writes::query_pages_guarded(first_ + chunk * kPage, n, gw); for (std::size_t o = 0; o < n;) { const bool adopted = gw[o] != 0; std::size_t o_end = o + 1; while (o_end < n && (gw[o_end] != 0) == adopted) ++o_end; for (std::size_t k = chunk + o; k < chunk + o_end; ++k) { state_[k] &= ~kZero; if (adopted) { state_[k] |= kProtected; state_[k] &= ~kExternalRo; } else { state_[k] |= kExternalRo; } } add_job(chunk + o, chunk + o_end, streaming, adopted ? Copy::guarded : Copy::read_only); o = o_end; } chunk += n; } } else { for (std::size_t k = p; k < q; ++k) { state_[k] &= ~kZero; if (!(state_[k] & (kProtected | kAliased | kPinned))) state_[k] |= kExternalRo; else state_[k] &= ~kExternalRo; } add_job(p, q, streaming, (flags & kAliased) ? Copy::aliased : (flags & kPinned) ? Copy::pinned : Copy::read_only); } p = q; } } i = j; } } // An aliased block's cell, its other addresses' cells, and their mapping and version when it was last armed. struct AliasedBlock { leonida::geometry_writes::Cell* cell = nullptr; Vector> peers; std::uint64_t mapping = 0, version = 0; bool armed = false; }; // The 64 KiB block of page i, and whether update_aliased found no write reached it. std::uintptr_t block_of(std::size_t i) const { return (first_ + i * kPage) & ~(kBlock - 1); } bool aliased_clean(std::size_t i) const { return !clean_.empty() && clean_[((first_ & (kBlock - 1)) + i * kPage) / kBlock]; } // At the start of refresh(), outside lock_ (the cells' lock is the write-fault handler's, and the other addresses // are asked for on the process heap). Each aliased block the copies read is guarded at every address xmem maps it // by a cell of the geometry watch, whose faults shadow_write_fault answers: a write through any of the addresses, // a remap or a protection change moves a cell's version. A block whose cells kept their versions since they were // armed is clean (clean_); any other is armed again before the walk copies it, so a write after the arming is // copied at the next refresh. A block is copied every time while its cells can't be armed: no other address // known, a page pinned for a kernel write, or the refreshes that leave aliased pages alone (copy_aliased_). void update_aliased() { namespace watch = leonida::geometry_writes; const std::uint64_t generation = leonida::title_page_aliases::generation(); AcquireSRWLockExclusive(&lock_); if (generation != alias_generation_) { alias_generation_ = generation; aliased_list_.clear(); for (std::uint16_t& s : state_) s &= ~kAliased; leonida::title_page_aliases::for_each_in(first_, last_, [&](std::uintptr_t va) { const std::uintptr_t from = std::max(va, first_), to = std::min(va + kBlock, last_); bool read = false; for (std::uintptr_t p = from; p < to; p += kPage) { state_[(p - first_) / kPage] |= kAliased; read |= cover_[(p - first_) / kPage] != 0; } if (read) aliased_list_.push_back(va); }); } Vector rearm; rearm.swap(rearm_); ReleaseSRWLockExclusive(&lock_); const std::uintptr_t base = first_ & ~(kBlock - 1); clean_.assign(aliased_list_.empty() ? 0 : (last_ - base + kBlock - 1) / kBlock, 0); alias_arms_ = 0; const auto aliases = watch::aliases.load(std::memory_order_acquire); const bool guard = aliases && watch_; for (auto it = aliased_blocks_.begin(); it != aliased_blocks_.end();) { if (guard && std::binary_search(aliased_list_.begin(), aliased_list_.end(), it->first)) { ++it; continue; } release_cells(it->first, it->second); it = aliased_blocks_.erase(it); } if (!guard) return; for (const std::uintptr_t va : rearm) if (const auto it = aliased_blocks_.find(va); it != aliased_blocks_.end()) it->second.armed = false; for (const std::uintptr_t va : aliased_list_) { AliasedBlock& b = aliased_blocks_[va]; if (!b.cell) b.cell = watch::acquire(va); std::uint64_t version = b.cell->version.load(std::memory_order_acquire); const std::uint64_t mapping = b.cell->mapping.load(std::memory_order_acquire); if (mapping != b.mapping) { std::vector others; if (aliases) aliases(va, others); auto old = std::move(b.peers); b.peers.clear(); for (const std::uintptr_t other : others) b.peers.emplace_back(other, watch::acquire(other)); for (const auto& [other, cell] : old) watch::release(other); b.mapping = mapping; b.armed = false; } for (const auto& [other, cell] : b.peers) version = std::max(version, cell->version.load(std::memory_order_acquire)); if (b.armed && version == b.version) { clean_[(va - base) / kBlock] = 1; continue; } b.armed = false; // A table page with no host view anywhere (src/title_frames.h) has no other address to guard: its own cell, // which every change of its frame moves, is all there is. if (!copy_aliased_ || (b.peers.empty() && !leonida::title_frames::backed(va))) continue; // allow_hot = false: ShadowPages does not poll geometry_writes::hot_tiles(), so a hot cell stays unarmed. b.armed = watch::arm(va, *b.cell, false); for (const auto& [other, cell] : b.peers) b.armed = watch::arm(other, *cell, false) && b.armed; alias_arms_ += 1 + b.peers.size(); b.version = version; } } static void release_cells(std::uintptr_t va, AliasedBlock& b) { if (b.cell) leonida::geometry_writes::release(va); for (const auto& [other, cell] : b.peers) leonida::geometry_writes::release(other); b = {}; } // With the lock held, when this tracker opens a new write-watch reader: no page is clean until that reader has // asked and the walk has copied it. The runs may have closed (their reservation released) and come back over a // reservation made at the same address since, which a page's watched mark alone doesn't tell (re-review of #61). void forget_clean() { for (std::uint16_t& page : state_) page &= std::uint16_t(~kClean); } // With the lock held, after the write-watched reservations changed: which pages are write-watched now. A page // that changes sides starts guarded: one this tracker keeps read-only stays so, and a hot one is not known any // more (the next walk queries, guards and copies it). void update_watched() { // Pages [i, upto) are write-watched now, or not. Either way a page that changes sides is guarded now (a guard // it has stays): only a hot one changes, to not known. std::size_t i = 0; const auto side = [&](std::size_t upto, bool watched) { for (; i < upto; ++i) if (bool(state_[i] & kWatched) != watched) state_[i] = std::uint16_t((state_[i] & ~(kWatched | kClean | kHot | kZero | kExternalRo)) | (watched ? kWatched : 0)); }; leonida::title_write_watch::for_each_in(first_, last_, [&](std::uintptr_t from, std::uintptr_t to) { side((from - first_) / kPage, false); side((to - first_) / kPage, true); }); side(state_.size(), false); rebuild_watch_runs(); } // The runs of hot pages to ask about, each inside one reservation, from the pages' marks; runs less than kMergeGap // apart are asked about as one. void rebuild_watch_runs() { runs_stale_ = false; Vector>& runs = watch_runs_; runs.clear(); const auto hot = [&](std::uintptr_t p) { return (state_[(p - first_) / kPage] & (kWatched | kHot)) == (kWatched | kHot); }; leonida::title_write_watch::for_each_in(first_, last_, [&](std::uintptr_t from, std::uintptr_t to) { const std::size_t first_run = runs.size(); for (std::uintptr_t p = from; p < to;) { if (!hot(p)) { p += kPage; continue; } std::uintptr_t q = p + kPage; while (q < to && hot(q)) q += kPage; if (runs.size() > first_run && p - runs.back().second < kMergeGap) runs.back().second = q; else runs.emplace_back(p, q); p = q; } }); watched_pages_ = hot_pages_ = 0; for (std::size_t i = 0; i < state_.size(); ++i) { watched_pages_ += (state_[i] & kWatched) && cover_[i]; hot_pages_ += (state_[i] & kHot) && cover_[i]; } if (watch_runs_.empty() && reader_) { leonida::title_write_watch::close_reader(reader_); reader_ = 0; } } struct Job { std::size_t offset, bytes; // from begin_ bool streaming; bool aliased; // copied because xmem maps the pages elsewhere too (Copy::aliased) }; struct Target { std::uintptr_t begin, end; // the title's bytes std::uint8_t* shadow; // where begin's byte goes bool retired = false; // a window nothing answers from, kept until its submissions are copied back }; // A page VirtualQuery finds unreadable may be one xmem's frame table holds: a stream pool's GPU-only page or its // CPU twin after queue slot 31's copies, with no host view (src/title_frames.h). It is read through its frame, like // a read-only page that is not this tracker's: never guarded here (there is nothing to protect), and clean only // while its geometry watch cells say so, which xmem's table updates and its physical page's host views move (xmem // marks every table page aliased). `next` is clipped to the run of pages that are alike. static Kind table_kind(std::uintptr_t at, std::uintptr_t& next) { if (!leonida::title_frames::may_hold(at, next)) return Kind::zero; bool backed = false; next = leonida::title_frames::run_end(at, next, backed); return backed ? Kind::read_only : Kind::zero; } static Kind classify(const MEMORY_BASIC_INFORMATION& region) { if (region.State != MEM_COMMIT || (region.Protect & PAGE_GUARD)) return Kind::zero; switch (region.Protect & 0xff) { case PAGE_READWRITE: case PAGE_EXECUTE_READWRITE: return Kind::writable; case PAGE_READONLY: case PAGE_EXECUTE_READ: return Kind::read_only; case PAGE_WRITECOPY: case PAGE_EXECUTE_WRITECOPY: return Kind::unwatched; default: return Kind::zero; // PAGE_NOACCESS, PAGE_EXECUTE: not readable } } // Offset from begin_ and size of pages [i, j): the first and last pages may stick out of the targets. std::pair span_of(std::size_t i, std::size_t j) const { const std::uintptr_t from = std::max(first_ + i * kPage, begin_), to = std::min(first_ + j * kPage, end_); return {from - begin_, to - from}; } void add_job(std::size_t i, std::size_t j, bool streaming, Copy why) { const auto [offset, bytes] = span_of(i, j); copy_bytes_[unsigned(why)] += bytes; const bool aliased = why == Copy::aliased; if (!jobs_.empty() && jobs_.back().streaming == streaming && jobs_.back().aliased == aliased && jobs_.back().offset + jobs_.back().bytes == offset) { jobs_.back().bytes += bytes; return; } jobs_.push_back({offset, bytes, streaming, aliased}); } // LEONIDA_SHADOW_KEEP (on; 0: every job copied whole, as before): a job's bytes reach the copies only where they // differ from those copied last (src/shadow_keep.h), so a shader's write into a copy of pages copied without a // sign that the title wrote them stays until the title changes those bytes. // shortcut: a title that rewrites the same bytes to reset a GPU-written value is not seen; needs a real write // signal (a write-back to the title's pages) then. static bool keep_gpu_writes() { static const bool on = [] { char value[2] = {}; std::size_t length = 0; return getenv_s(&length, value, sizeof(value), "LEONIDA_SHADOW_KEEP") != 0 || length == 0 || value[0] != '0'; }(); return on; } static constexpr std::size_t kPieces = kPage / leonida::shadow_keep::kPiece; std::size_t copy_changed(const Job& job) { std::size_t copied = 0; alignas(64) std::uint8_t page[kPage]; const auto copy_page_bytes = [&](std::uintptr_t va, const std::uint8_t* src, std::size_t n, bool streaming) { if (!copy_guarded_host(page, src, n, streaming)) { for (std::size_t off = 0; off < n;) { const std::size_t in_page = (va + off) & 4095; const std::size_t m = std::min(n - off, 4096 - in_page); if (!copy_guarded_host(page + off, src + off, m, streaming)) std::memset(page + off, 0, m); off += m; } } leonida::shadow_keep::copy_changed( page, va, n, sums_.data(), first_, [&](std::uintptr_t a, std::uintptr_t b, const std::uint8_t* source) { for_each_target(a, b, [&](const Target& t, std::uintptr_t from, std::uintptr_t to) { std::memcpy(t.shadow + (from - t.begin), source + (from - a), to - from); note_dirty(t.shadow + (from - t.begin), to - from); copied += to - from; }); }); }; const std::uintptr_t job_va = begin_ + job.offset; if (leonida::title_frames::may_hold(job_va, job_va + job.bytes)) { leonida::title_frames::for_each_part( job_va, job.bytes, [&](std::uintptr_t part, std::size_t len, std::uint8_t* frame) { for (std::size_t off = 0; off < len;) { const std::uintptr_t va = part + off; const std::size_t n = std::min(len - off, kPage - (va & (kPage - 1))); const auto* src = frame ? (frame + off) : reinterpret_cast(va); copy_page_bytes(va, src, n, job.streaming && !frame); off += n; } return true; }); return copied; } for (std::size_t at = job.offset, end = job.offset + job.bytes; at < end;) { const std::uintptr_t va = begin_ + at; const std::size_t n = std::min(end - at, kPage - (va & (kPage - 1))); copy_page_bytes(va, reinterpret_cast(va), n, job.streaming); at += n; } return copied; } // The targets sorted by start, the bytes they hold, and reach_[k], the furthest end among targets_[0..k]: the // targets over [from, to) are found from the first whose reach passes `from`. void index_targets() { std::sort(targets_.begin(), targets_.end(), [](const Target& a, const Target& b) { return a.begin < b.begin; }); reach_.resize(targets_.size()); target_bytes_ = 0; std::uintptr_t reach = 0; for (std::size_t k = 0; k < targets_.size(); ++k) { reach = std::max(reach, targets_[k].end); reach_[k] = reach; target_bytes_ += targets_[k].end - targets_[k].begin; } if (!targets_.empty()) { begin_ = targets_.front().begin; end_ = reach; } } // f(target, from, to) for each target's part of the title's bytes [from, to). template void for_each_target(std::uintptr_t from, std::uintptr_t to, F&& f) const { auto k = std::size_t(std::upper_bound(reach_.begin(), reach_.end(), from) - reach_.begin()); for (; k < targets_.size() && targets_[k].begin < to; ++k) { const Target& t = targets_[k]; const std::uintptr_t a = std::max(from, t.begin), b = std::min(to, t.end); if (a < b) f(t, a, b); } } void zero_targets(std::size_t offset, std::size_t bytes) { for_each_target(begin_ + offset, begin_ + offset + bytes, [](const Target& t, std::uintptr_t a, std::uintptr_t b) { std::memset(t.shadow + (a - t.begin), 0, b - a); }); } // Pages [i, j) of one region, read-write with protection `current`: read-only from now on, same cache attribute. void protect(std::size_t i, std::size_t j, DWORD current) { const DWORD base = current & 0xff; const DWORD read_only = (current & ~DWORD(0xff)) | (base == PAGE_READWRITE ? PAGE_READONLY : PAGE_EXECUTE_READ); DWORD old = 0; if (!VirtualProtect(reinterpret_cast(first_ + i * kPage), (j - i) * kPage, read_only, &old)) { protect_error_ = GetLastError(); // logged once the lock is released return; } for (std::size_t k = i; k < j; ++k) state_[k] |= kProtected; ++refresh_protects_; } // With the lock held: before pages [i, j) stop counting as ours (kProtected), the ones this tracker made read-only // are given back their write access, so no page stays read-only with no guard to answer its writes. void unguard_ours(std::size_t i, std::size_t j) { for (std::size_t k = i; k < j; ++k) if (state_[k] & kProtected) { ++unguarded_on_drop_; reopen_locked(first_ + i * kPage, first_ + j * kPage); return; } } std::uint64_t unguarded_on_drop_ = 0; // times unguard_ours found pages of ours to reopen (diagnostic) // With the lock held: the pages in [from, to) this tracker made read-only are read-write again. void reopen_locked(std::uintptr_t from, std::uintptr_t to, bool notify_map = true) { for (std::uintptr_t at = from; at < to;) { MEMORY_BASIC_INFORMATION region{}; std::uintptr_t next = at + kPage; DWORD base = 0; if (VirtualQuery(reinterpret_cast(at), ®ion, sizeof(region))) { next = std::min(to, reinterpret_cast(region.BaseAddress) + region.RegionSize); if (region.State == MEM_COMMIT) base = region.Protect & 0xff; } const std::size_t i0 = (at - first_) / kPage, i1 = (next - first_) / kPage; if (base != PAGE_READONLY && base != PAGE_EXECUTE_READ) { // Not read-only any more (remapped, decommitted, opened by another thread): nothing to undo. for (std::size_t i = i0; i < i1; ++i) state_[i] &= ~kProtected; } else { const DWORD writable = (region.Protect & ~DWORD(0xff)) | (base == PAGE_READONLY ? PAGE_READWRITE : PAGE_EXECUTE_READWRITE); for (std::size_t i = i0; i < i1;) { const bool ours = state_[i] & kProtected; std::size_t j = i + 1; while (j < i1 && bool(state_[j] & kProtected) == ours) ++j; DWORD old = 0; if (ours && VirtualProtect(reinterpret_cast(first_ + i * kPage), (j - i) * kPage, writable, &old)) { for (std::size_t k = i; k < j; ++k) state_[k] &= ~kProtected; const std::uintptr_t run_lo = first_ + i * kPage, run_hi = first_ + j * kPage; leonida::geometry_writes::note_external_reopen(run_lo, run_hi); if (notify_map) leonida::title_memory_map::changed(run_lo, run_hi); } i = j; } } at = next; } } void note_dirty(const void* ptr, std::size_t bytes) const { if (dirty_fn_ && bytes) dirty_fn_(dirty_context_, ptr, bytes); } DirtyFn dirty_fn_ = nullptr; void* dirty_context_ = nullptr; bool watch_; std::uintptr_t begin_ = 0, end_ = 0; // the targets' bytes: the first start and the furthest end std::uintptr_t first_ = 0, last_ = 0; // the pages covered SRWLOCK lock_ = SRWLOCK_INIT; // state_, cover_, the targets, and the protection of the pages std::atomic writer_{0}; // the thread in write_back, which holds lock_ while it copies into the title Vector held_pages_; // write_back's per-page decision, taken before its copies Vector state_; // per 4 KiB page Vector cover_; // per 4 KiB page: the targets that read it Vector targets_; // by start Vector reach_; // see index_targets std::size_t target_bytes_ = 0; std::uint64_t alias_generation_ = ~std::uint64_t(0); // Aliased blocks (update_aliased), refresh() only: those the copies read, in address order; their cells; per 64 KiB // block from first_ rounded down, whether no write reached it; and the clean blocks the walk found writable. Vector aliased_list_; leonida::host_heap::map aliased_blocks_; Vector clean_; Vector rearm_; std::uint64_t alias_arms_ = 0; // arm() calls of the last update_aliased() std::uint64_t map_generation_ = ~std::uint64_t(0); bool pinned_ = false; // some page has kPinned Vector jobs_; // refresh() only, which DeviceState::shadow_mutex serializes Vector zeroed_; // likewise DWORD protect_error_ = 0; // a VirtualProtect refusal of this refresh(), logged after it std::array copy_bytes_{}; // refresh() only, likewise bool copy_aliased_ = true; // likewise std::uint64_t gpu_bytes_ = 0; Pieces pieces_; // refresh() only, likewise std::uint64_t refresh_queries_ = 0; std::uint64_t refresh_protects_ = 0; // VirtualProtect calls of the last refresh() bool refresh_walked_all_ = false; // the last refresh() queried every page (the title memory map changed) std::atomic faults_{0}; // Write watching (leonida::title_write_watch): the reservations' generation the kWatched marks are from, the runs // of hot pages, this tracker's reader of the journal (0: none yet) and what the last refresh() asked. std::uint64_t watch_generation_ = ~std::uint64_t(0); Vector> watch_runs_; std::uint64_t reader_ = 0; std::size_t watched_pages_ = 0, hot_pages_ = 0; // covered pages write-watched, and hot Vector idle_; // per 4 KiB page: refreshes a hot page went without a write (kCool) Vector sums_; // per 256-byte piece from first_: sum of the bytes copied last, 0: not known bool runs_stale_ = false; // a page became hot or cold: watch_runs_ is rebuilt at the next refresh std::uint64_t refresh_asks_ = 0; std::uint64_t refresh_written_ = 0; }; // The live ShadowPages of every device, for the fault handler. Never freed: a fault can come at any time. In host_heap, // like everything changed under g_shadow_pages_lock (see ShadowPages). SRWLOCK g_shadow_pages_lock = SRWLOCK_INIT; leonida::host_heap::vector& shadow_pages_list() { static auto* list = new leonida::host_heap::vector; return *list; } // A title write into a committed, private, read-only page of title memory that no guard owns (the geometry watch, // the slot-133 shadows and the kernel-write unguarder all declined it): a guard of ours left behind, since the title // never writes memory it made read-only itself on the console. Said for the first 32 pages, with whether a shadow's // range still covers the page (its bookkeeping then calls the page unguarded). LEONIDA_STRAY_RO_HEAL=1: the page is // made writable again and the write retried, so the title goes on (a shadow may then miss that page's next writes: // the GPU copy may be stale for one frame). bool stray_read_only(EXCEPTION_POINTERS* info, std::uintptr_t address) { MEMORY_BASIC_INFORMATION m{}; if (!VirtualQuery(reinterpret_cast(address), &m, sizeof m)) return false; if (m.State != MEM_COMMIT || m.Type != MEM_PRIVATE || (m.Protect & 0xff) != PAGE_READONLY) return false; std::uint64_t lo = 0, hi = 0; if (!leonida::title_va_aliases().title_memory(address, lo, hi)) return false; static const bool heal = [] { const char* v = std::getenv("LEONIDA_STRAY_RO_HEAL"); return v && *v == '1'; }(); unsigned covering = 0; AcquireSRWLockShared(&g_shadow_pages_lock); for (ShadowPages* pages : shadow_pages_list()) covering += pages->contains(address); ReleaseSRWLockShared(&g_shadow_pages_lock); static std::atomic told{0}, healed{0}; const std::uintptr_t page = address & ~std::uintptr_t(0xfff); bool ok = false; if (heal) { DWORD old = 0; ok = VirtualProtect(reinterpret_cast(page), 0x1000, (m.Protect & ~DWORD(0xff)) | PAGE_READWRITE, &old) != 0; if (ok) { healed.fetch_add(1, std::memory_order_relaxed); leonida::title_memory_map::changed(page, page + 0x1000); } } if (told.fetch_add(1, std::memory_order_relaxed) < 32) { const auto rip = info && info->ContextRecord ? info->ContextRecord->Rip : 0; std::fprintf(stderr, "[rt] d3d12: stray read-only title page 0x%llx (write to 0x%llx from rip 0x%llx; " "allocation 0x%llx, protect 0x%lx): no guard owns it, %u shadow range(s) cover it; %s " "(%u healed so far)\n", static_cast(page), static_cast(address), static_cast(rip), static_cast( reinterpret_cast(m.AllocationBase)), static_cast(m.Protect), covering, !heal ? "left to fault (LEONIDA_STRAY_RO_HEAL=1 makes it writable)" : ok ? "made writable" : "could not be made writable", healed.load(std::memory_order_relaxed)); } return ok; } // A write to a page a shadow made read-only: the page is made writable again and the write retried. First in the // handler chain, so a startup trace doesn't log these as exceptions; any other access violation goes on down it. // Whatever thread wrote: the title's, or a host thread of the runtime's (a DirectStorage queue's copy). // // A physical page xmem maps at two addresses (a stream pool's CPU view and its GPU-only twin) has a protection per // address: a guard on one view never faults a write through the other, which the shadows see through the geometry // watch's cells they arm at every address of an aliased page (ShadowPages::update_aliased), so the guard to look for // is the faulting address's own. When none answers for it (each guard reopens only what it protected), xmem makes the // page writable again if its window is (kernel_writes' unguarder): a read-only page nobody reopens would fault that // write, and every later one, for good. LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) { const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; if (!record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2 || record->ExceptionInformation[0] != 1) return EXCEPTION_CONTINUE_SEARCH; const auto address = static_cast(record->ExceptionInformation[1]); bool tile_reopened = false; bool retry = leonida::geometry_writes::notify(address, address + 1, leonida::geometry_writes::Event::fault, &tile_reopened); // The geometry watch reopened the whole 64 KiB tile around the address: the shadows over it reopen it too, so a // page both guarded is not left writable while its shadow takes it for unchanged. constexpr std::uintptr_t kTile = leonida::geometry_writes::tile_size; const std::uintptr_t tile = address & ~(kTile - 1); AcquireSRWLockShared(&g_shadow_pages_lock); bool shadow_block_reopened = false; for (ShadowPages* pages : shadow_pages_list()) { if (pages->contains(address)) retry |= pages->reopen(address, &shadow_block_reopened); if (tile_reopened && pages->first() < tile + kTile && tile < pages->last()) pages->reopen_range(tile, tile + kTile); } if (shadow_block_reopened && !tile_reopened) { for (ShadowPages* pages : shadow_pages_list()) if (pages->first() < tile + kTile && tile < pages->last()) pages->reopen_range(tile, tile + kTile); } ReleaseSRWLockShared(&g_shadow_pages_lock); if (!retry) if (const auto unguard = leonida::kernel_writes::state().unguarder.load(std::memory_order_acquire)) retry = unguard(address, address + 1); if (!retry) retry = stray_read_only(info, address); return retry ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; } // leonida::kernel_writes' opener: a file shim is about to let the kernel write [from, to). void open_shadow_pages(std::uintptr_t from, std::uintptr_t to) { bool tiles_reopened = false; leonida::geometry_writes::notify(from, to, leonida::geometry_writes::Event::open, &tiles_reopened); if (tiles_reopened) { // whole tiles were reopened: so are the shadows' pages there (see shadow_write_fault) constexpr std::uintptr_t kTile = leonida::geometry_writes::tile_size; from &= ~(kTile - 1); to = (to + kTile - 1) & ~(kTile - 1); } AcquireSRWLockShared(&g_shadow_pages_lock); for (ShadowPages* pages : shadow_pages_list()) pages->reopen_range(from, to); ReleaseSRWLockShared(&g_shadow_pages_lock); } // fsdraw's backing hook: whether a slot-133 shadow keeps the GPU copy of a title VA (LEONIDA_FSDRAW_PROBE only). const char* fsdraw_backing(std::uint64_t title_va) { unsigned covering = 0; AcquireSRWLockShared(&g_shadow_pages_lock); for (ShadowPages* pages : shadow_pages_list()) covering += pages->contains(std::uintptr_t(title_va)); ReleaseSRWLockShared(&g_shadow_pages_lock); return covering ? "a slot-133 shadow" : "an alias with no slot-133 shadow (window, geometry view or import)"; } // Installs the handler once. false: it couldn't be, and shadows copy every page at every submission. bool watch_shadow_writes(); bool watch_shadow_writes() { static const bool installed = [] { if (!AddVectoredExceptionHandler(1, &shadow_write_fault)) return false; leonida::kernel_writes::set_opener(&open_shadow_pages); return true; }(); return installed; } // A ShadowPages the fault handler knows of for its whole life: registered before it protects anything, removed once // its destructor has made every page writable again. // The geometry watch's cells as TitleTextureWatch uses them: the title texture refresh's own queue of written tiles, // and arming only while the write-fault handler is installed. Pages not committed are left as they are (xmem's commit // or mapping of them bumps the cell); a tile pinned for a kernel write is busy until the write ends. struct TitleTextureCells { using Cell = leonida::geometry_writes::Cell; leonida::geometry_writes::WriteQueue queue; TitleTextureCells() { leonida::geometry_writes::subscribe_writes(queue); } ~TitleTextureCells() { leonida::geometry_writes::unsubscribe_writes(queue); } TitleTextureCells(const TitleTextureCells&) = delete; TitleTextureCells& operator=(const TitleTextureCells&) = delete; Cell* acquire(std::uintptr_t tile) { return leonida::geometry_writes::acquire(tile); } void release(std::uintptr_t tile) { leonida::geometry_writes::release(tile); } int arm(std::uintptr_t tile, Cell& cell) { bool pinned = false; leonida::kernel_writes::for_each_pin(tile, tile + leonida::geometry_writes::tile_size, [&](auto, auto) { pinned = true; }); if (pinned) return 0; // Refused otherwise: a write raced the arming (it is in the queue), or VirtualQuery or VirtualProtect failed. return leonida::geometry_writes::arm(tile, cell) ? 1 : -1; } // Batched arming of sorted, unique 64 KiB tiles: coalesces kernel-pin checks, geometry_writes::state().mutex // acquisitions, a per-tile known-protection cache invalidated via title_memory_map::changes_since() (skipping // VirtualQuery on repeat tile re-arms), and contiguous VirtualQuery/VirtualProtect runs across all examined // textures in a pass. // results[i]: 1 = armed (or hot & unpinned), 0 = busy (pinned), -1 = failed / raced write. bool is_tile_pinned(std::uintptr_t tile) const noexcept { constexpr std::uintptr_t kTile = leonida::geometry_writes::tile_size; const std::uintptr_t tile_hi = (tile <= UINTPTR_MAX - kTile) ? (tile + kTile) : UINTPTR_MAX; for (const auto& [p_lo, p_hi] : run_pin_ranges_) { if (tile < p_hi && p_lo < tile_hi) return true; } return false; } // True when no title_memory_map change after `since` overlapped [lo, hi). Sets `gen_out` to the generation // checked up to (leaf SRWLOCK shared read when generation moved). static bool range_clean_since(std::uint64_t since, std::uintptr_t lo, std::uintptr_t hi, std::uint64_t& gen_out) { if (since == Cell::kNoMapGen) return false; const std::uint64_t cur = leonida::title_memory_map::generation(); if (cur == since) { gen_out = cur; return true; } bool overlapped = false; std::uint64_t now = cur; if (!leonida::title_memory_map::changes_since( since, now, lo, hi, [&](std::uintptr_t c_from, std::uintptr_t c_to) { if (c_from < c_to) overlapped = true; })) { return false; } gen_out = now; return !overlapped; } static bool restore_uniform(const Cell& c, DWORD expected) noexcept { if (!expected) return false; for (const DWORD r : c.restore) if (r != expected) return false; return true; } static bool cell_known_writable(const Cell& c, DWORD& kp, DWORD& kg, std::uint64_t& gen) noexcept { if (c.known_state != MEM_COMMIT || !c.known_protect || !c.known_guarded || c.known_map_gen == Cell::kNoMapGen || c.known_mapping != c.mapping.load(std::memory_order_acquire)) return false; kp = c.known_protect; kg = c.known_guarded; gen = c.known_map_gen; return true; } // Cross-pass no-guard cache for TitleTextureCells: PAGE_NOACCESS ONLY! // NEVER cache PAGE_READONLY (ShadowPages::reopen() reopens RO->RW without title_memory_map::changed()), and NEVER // trust cross-pass MEM_RESERVE here (check_mapped_plane may raw VirtualAlloc(MEM_COMMIT) without map change; // MEM_RESERVE is cached intra-pass only via cached_state). static bool cell_known_noaccess(const Cell& c, std::uint64_t& gen) noexcept { if (c.known_state != MEM_COMMIT || c.known_protect != PAGE_NOACCESS || c.known_guarded != 0 || c.known_map_gen == Cell::kNoMapGen || c.known_mapping != c.mapping.load(std::memory_order_acquire)) return false; gen = c.known_map_gen; return true; } static void clear_cell_known(Cell& c) noexcept { c.known_state = 0; c.known_protect = 0; c.known_guarded = 0; c.known_map_gen = Cell::kNoMapGen; } static void seed_known_from_armed(Cell& c, DWORD r0) noexcept { if (c.armed_map_gen == Cell::kNoMapGen) return; const std::uint64_t cur_map = c.mapping.load(std::memory_order_acquire); if (c.known_state != 0 && c.known_mapping == cur_map && c.known_map_gen != Cell::kNoMapGen) return; const DWORD g = leonida::geometry_writes::read_only(r0); if (g != 0 && !(r0 & PAGE_GUARD)) { c.known_state = MEM_COMMIT; c.known_protect = r0; c.known_guarded = g; c.known_mapping = cur_map; c.known_map_gen = c.armed_map_gen; } } struct ArmStats { std::uint64_t hot = 0; std::uint64_t already = 0; std::uint64_t backed = 0; std::uint64_t fast_vp = 0; std::uint64_t bridged = 0; std::uint64_t vq = 0; std::uint64_t vq_cache = 0; std::uint64_t vq_vp = 0; }; ArmStats arm_stats; void arm_batch(const std::uintptr_t* tiles, Cell* const* cells, std::int8_t* results, std::size_t count) { constexpr std::size_t kMaxBatchRunPages = 1024; // up to 64 MiB per contiguous VirtualProtect run constexpr std::size_t kMaxLockBatchPages = 128; // pages per pin check + geometry_writes lock hold constexpr std::size_t kMaxBridgeGap = 8; // max already-armed cold gap tiles to bridge in one VP constexpr std::uintptr_t kTile = leonida::geometry_writes::tile_size; constexpr std::uintptr_t kHostPage = leonida::geometry_writes::page_size; if (!count) return; // Intra-pass VirtualQuery region cache persisted across outer i..j lock batches (validated via // range_clean_since). Includes MEM_RESERVE, MEM_FREE, PAGE_NOACCESS, and writable MEM_COMMIT regions; NEVER // caches PAGE_READONLY / PAGE_EXECUTE_READ (ShadowPages::reopen() reopens RO->RW without map change). std::uintptr_t cached_lo = 0; std::uintptr_t cached_hi = 0; DWORD cached_state = 0; DWORD cached_protect = 0; DWORD cached_guarded = 0; std::uint64_t cached_gen = 0; for (std::size_t i = 0; i < count;) { std::size_t j = i + 1; while (j < count) { const bool contiguous = (tiles[j] == tiles[j - 1] + kTile); const std::size_t len = j - i; if (len < kMaxLockBatchPages) { ++j; } else if (contiguous && len < kMaxBatchRunPages) { ++j; } else { break; } } const std::size_t batch_n = j - i; const std::uintptr_t* const batch_tiles = tiles + i; Cell* const* const batch_cells = cells + i; run_versions_.resize(batch_n); run_pinned_.assign(batch_n, 0); run_eligible_.assign(batch_n, 0); run_already_armed_.assign(batch_n, 0); run_failed_.assign(batch_n, 0); run_pin_ranges_.clear(); run_need_backed_idx_.clear(); run_need_backed_vas_.clear(); // Snapshot versions BEFORE querying kernel pins or taking geometry_writes::mutex. for (std::size_t k = 0; k < batch_n; ++k) run_versions_[k] = batch_cells[k]->version.load(std::memory_order_acquire); const std::uintptr_t pin_lo = batch_tiles[0]; const std::uintptr_t last_tile = batch_tiles[batch_n - 1]; const std::uintptr_t pin_hi = (last_tile <= UINTPTR_MAX - kTile) ? (last_tile + kTile) : UINTPTR_MAX; // Querying an OVERLAPPED pin can fault into xmem: NEVER call under geometry_writes::state().mutex. // Record every overlapping pin interval in run_pin_ranges_ so gap-bridging NEVER bridges a pinned tile. if (pin_lo < pin_hi) { leonida::kernel_writes::for_each_pin(pin_lo, pin_hi, [&](std::uintptr_t p_lo, std::uintptr_t p_hi) { run_pin_ranges_.emplace_back(p_lo, p_hi); const std::uintptr_t first_tile = p_lo & ~(kTile - 1); const std::uintptr_t* it = std::lower_bound(batch_tiles, batch_tiles + batch_n, first_tile); for (; it < batch_tiles + batch_n && *it < p_hi; ++it) run_pinned_[std::size_t(it - batch_tiles)] = 1; }); } const bool may_hold_frames = pin_lo < pin_hi && leonida::title_frames::may_hold(pin_lo, pin_hi); auto& s = leonida::geometry_writes::state(); { std::unique_lock lock(s.mutex); for (std::size_t k = 0; k < batch_n; ++k) { if (run_pinned_[k]) { results[i + k] = 0; // busy: kernel write in progress (even on hot tiles) continue; } Cell* const c = batch_cells[k]; if (c->hot) { results[i + k] = 1; ++arm_stats.hot; continue; } if (run_versions_[k] != c->version.load(std::memory_order_relaxed)) { results[i + k] = -1; // write raced arming continue; } // Zero-syscall fast path: all 16 host pages already guarded read-only (e.g. armed by // HotColdTracking::CellGuard earlier in this leader pass; guaranteed cleared by reopen(), // Event::replaced, TitleVirtualProtect, and unmap_page). const DWORD r0 = c->restore[0]; bool all_armed = r0 != 0; bool uniform_restore = all_armed; for (std::size_t sp = 1; all_armed && sp < c->restore.size(); ++sp) { if (!c->restore[sp]) { all_armed = false; uniform_restore = false; } else if (c->restore[sp] != r0) { uniform_restore = false; } } if (all_armed) { if (uniform_restore) seed_known_from_armed(*c, r0); run_already_armed_[k] = 1; results[i + k] = 1; ++arm_stats.already; continue; } if (may_hold_frames) { run_need_backed_idx_.push_back(k); run_need_backed_vas_.push_back(batch_tiles[k]); } else { run_eligible_[k] = 1; } } // Batch-check table-page backing outside geometry_writes::state().mutex ONLY for tiles that are not // pinned, hot, or already all-armed (never nest g_frame_lock and s.mutex; single g_frame_lock hold // with zero shared_ptr refcount churn). Re-verify version/hot/all_armed after re-acquiring s.mutex. if (!run_need_backed_idx_.empty()) { lock.unlock(); run_need_backed_out_.resize(run_need_backed_vas_.size()); leonida::title_frames::backed_batch(run_need_backed_vas_.data(), run_need_backed_out_.data(), run_need_backed_vas_.size()); lock.lock(); for (std::size_t m = 0; m < run_need_backed_idx_.size(); ++m) { const std::size_t k = run_need_backed_idx_[m]; Cell* const c = batch_cells[k]; if (c->hot) { results[i + k] = 1; ++arm_stats.hot; continue; } if (run_versions_[k] != c->version.load(std::memory_order_relaxed)) { results[i + k] = -1; // write/remap/pin raced during backed_batch continue; } const DWORD r0 = c->restore[0]; bool all_armed = r0 != 0; bool uniform_restore = all_armed; for (std::size_t sp = 1; all_armed && sp < c->restore.size(); ++sp) { if (!c->restore[sp]) { all_armed = false; uniform_restore = false; } else if (c->restore[sp] != r0) { uniform_restore = false; } } if (all_armed) { if (uniform_restore) seed_known_from_armed(*c, r0); run_already_armed_[k] = 1; results[i + k] = 1; ++arm_stats.already; continue; } if (run_need_backed_out_[m]) { results[i + k] = 1; ++arm_stats.backed; continue; } run_eligible_[k] = 1; } } for (std::size_t sub_start = 0; sub_start < batch_n;) { if (!run_eligible_[sub_start]) { ++sub_start; continue; } std::size_t sub_end = sub_start + 1; while (sub_end < batch_n && run_eligible_[sub_end] && batch_tiles[sub_end] == batch_tiles[sub_end - 1] + kTile) { ++sub_end; } // Gap-bridging fast path: coalesce scattered eligible tiles separated by <= kMaxBridgeGap // already-armed, unpinned cold tiles sharing identical Cell::known_protect/known_guarded/mapping // and uniform restore[0..15] == kp. Falls back to eligible-only [sub_start, sub_end) on any // failure or unexpected old protect (with mandatory VirtualProtect(old) rollback). DWORD kp = 0, kg = 0; std::uint64_t gen0 = 0; if (cell_known_writable(*batch_cells[sub_start], kp, kg, gen0)) { const std::uintptr_t span_lo = batch_tiles[sub_start]; std::size_t bridge_end = sub_start + 1; std::size_t last_eligible = sub_start; std::uint64_t run_min_gen = gen0; std::uint64_t last_min_gen = gen0; while (bridge_end < batch_n && (run_eligible_[bridge_end] || run_already_armed_[bridge_end])) { const std::uintptr_t prev_va = batch_tiles[bridge_end - 1]; const std::uintptr_t next_va = batch_tiles[bridge_end]; if (prev_va > UINTPTR_MAX - kTile || next_va > UINTPTR_MAX - kTile) break; const std::uintptr_t prev_end = prev_va + kTile; if (next_va < prev_end) break; const std::uintptr_t eligible_gap = next_va - (batch_tiles[last_eligible] + kTile); if (eligible_gap > kMaxBridgeGap * kTile) break; if ((next_va + kTile - span_lo) > kMaxBatchRunPages * kTile) break; const Cell& cn = *batch_cells[bridge_end]; DWORD nkp = 0, nkg = 0; std::uint64_t ngen = 0; if (!cell_known_writable(cn, nkp, nkg, ngen) || nkp != kp || nkg != kg) break; if (run_already_armed_[bridge_end] && (run_pinned_[bridge_end] || is_tile_pinned(next_va) || cn.hot || !restore_uniform(cn, kp))) { break; } std::uint64_t cand_min_gen = (std::min)(run_min_gen, ngen); bool gap_ok = true; for (std::uintptr_t gap_va = prev_end; gap_va < next_va; gap_va += kTile) { if (is_tile_pinned(gap_va)) { gap_ok = false; break; } const auto cit = s.cells.find(gap_va); if (cit == s.cells.end()) { gap_ok = false; break; } const Cell& gc = cit->second; DWORD gkp = 0, gkg = 0; std::uint64_t ggen = 0; if (gc.hot || !restore_uniform(gc, kp) || !cell_known_writable(gc, gkp, gkg, ggen) || gkp != kp || gkg != kg) { gap_ok = false; break; } cand_min_gen = (std::min)(cand_min_gen, ggen); } if (!gap_ok) break; run_min_gen = cand_min_gen; if (run_eligible_[bridge_end]) { last_eligible = bridge_end; last_min_gen = run_min_gen; } ++bridge_end; } const std::size_t bridge_end_eff = last_eligible + 1; if (bridge_end_eff > sub_end) { const std::uintptr_t span_hi = batch_tiles[last_eligible] + kTile; std::uint64_t verified_gen = 0; if (range_clean_since(last_min_gen, span_lo, span_hi, verified_gen)) { DWORD old{}; if (VirtualProtect(reinterpret_cast(span_lo), span_hi - span_lo, kg, &old)) { if (old == kp || old == kg) { for (std::size_t k = sub_start; k < bridge_end_eff; ++k) { if (run_eligible_[k]) { batch_cells[k]->restore.fill(kp); batch_cells[k]->armed_map_gen = verified_gen; batch_cells[k]->known_map_gen = verified_gen; results[i + k] = 1; } else { batch_cells[k]->armed_map_gen = verified_gen; batch_cells[k]->known_map_gen = verified_gen; } } ++arm_stats.fast_vp; ++arm_stats.bridged; if (cached_hi && span_lo >= cached_lo && span_hi <= cached_hi) cached_lo = span_hi; sub_start = bridge_end_eff; continue; } // Unexpected prior protection: `old` describes tile 0 (`span_lo`) only. // Restore eligible tiles individually (tile 0 to `old`, other eligible tiles // to their verified `kp`), leaving already-armed gap tiles at `kg`. for (std::size_t k = sub_start; k < bridge_end_eff; ++k) { if (!run_eligible_[k]) continue; DWORD dummy{}; VirtualProtect(reinterpret_cast(batch_tiles[k]), kTile, k == sub_start ? old : kp, &dummy); } } for (auto cit = s.cells.lower_bound(span_lo); cit != s.cells.end() && cit->first < span_hi; ++cit) { clear_cell_known(cit->second); } cached_hi = 0; } } } const std::uintptr_t sub_lo = batch_tiles[sub_start]; const std::uintptr_t sub_hi = sub_lo + (sub_end - sub_start) * kTile; for (std::uintptr_t p = sub_lo; p < sub_hi;) { // Fast path: tile-aligned repeat arm with verified uniform protection or cached PAGE_NOACCESS // (NEVER cross-pass MEM_RESERVE or PAGE_READONLY) -> 0 VirtualQuery syscalls. if ((p & (kTile - 1)) == 0 && sub_hi - p >= kTile) { const std::size_t tile_k = sub_start + std::size_t((p - sub_lo) / kTile); Cell* const c0 = batch_cells[tile_k]; DWORD fkp = 0, fkg = 0; std::uint64_t fgen0 = 0; if (cell_known_writable(*c0, fkp, fkg, fgen0)) { std::size_t fast_end = tile_k + 1; std::uint64_t min_gen = fgen0, max_gen = fgen0; while (fast_end < sub_end) { DWORD nkp = 0, nkg = 0; std::uint64_t ngen = 0; if (!cell_known_writable(*batch_cells[fast_end], nkp, nkg, ngen) || nkp != fkp || nkg != fkg) break; min_gen = (std::min)(min_gen, ngen); max_gen = (std::max)(max_gen, ngen); ++fast_end; } std::uintptr_t end = p + (fast_end - tile_k) * kTile; std::uint64_t verified_gen = 0; bool clean = range_clean_since(min_gen, p, end, verified_gen); if (!clean && min_gen != max_gen && fast_end > tile_k + 1) { std::size_t prefix_end = tile_k + 1; while (prefix_end < fast_end && batch_cells[prefix_end]->known_map_gen == fgen0) ++prefix_end; fast_end = prefix_end; end = p + (fast_end - tile_k) * kTile; clean = range_clean_since(fgen0, p, end, verified_gen); } if (clean) { DWORD old{}; if (VirtualProtect(reinterpret_cast(p), end - p, fkg, &old)) { if (old == fkp || old == fkg) { for (std::size_t t = tile_k; t < fast_end; ++t) { batch_cells[t]->restore.fill(fkp); batch_cells[t]->armed_map_gen = verified_gen; batch_cells[t]->known_map_gen = verified_gen; } ++arm_stats.fast_vp; if (cached_hi && p >= cached_lo && end <= cached_hi) cached_lo = end; p = end; continue; } // Unexpected prior protection (caller bypassed title_memory_map::changed): // `old` describes tile 0 (`p`) only; restore tile 0 to `old` and remaining // tiles to their verified `fkp` before falling through to VirtualQuery. for (std::uintptr_t q = p; q < end; q += kTile) { DWORD dummy{}; VirtualProtect(reinterpret_cast(q), kTile, q == p ? old : fkp, &dummy); } } for (std::size_t t = tile_k; t < fast_end; ++t) clear_cell_known(*batch_cells[t]); cached_hi = 0; } } else if (cell_known_noaccess(*c0, fgen0)) { std::size_t fast_end = tile_k + 1; std::uint64_t min_gen = fgen0, max_gen = fgen0; while (fast_end < sub_end) { std::uint64_t ngen = 0; if (!cell_known_noaccess(*batch_cells[fast_end], ngen)) break; min_gen = (std::min)(min_gen, ngen); max_gen = (std::max)(max_gen, ngen); ++fast_end; } std::uintptr_t end = p + (fast_end - tile_k) * kTile; std::uint64_t verified_gen = 0; bool clean = range_clean_since(min_gen, p, end, verified_gen); if (!clean && min_gen != max_gen && fast_end > tile_k + 1) { std::size_t prefix_end = tile_k + 1; while (prefix_end < fast_end && batch_cells[prefix_end]->known_map_gen == fgen0) ++prefix_end; fast_end = prefix_end; end = p + (fast_end - tile_k) * kTile; clean = range_clean_since(fgen0, p, end, verified_gen); } if (clean) { for (std::size_t t = tile_k; t < fast_end; ++t) batch_cells[t]->known_map_gen = verified_gen; arm_stats.vq_cache += (fast_end - tile_k); if (cached_hi && p >= cached_lo && end <= cached_hi) cached_lo = end; p = end; continue; } } } std::uintptr_t region_base = 0; std::uintptr_t region_end = 0; DWORD state = 0; DWORD protect = 0; DWORD guarded = 0; std::uint64_t query_gen = 0; bool from_cache = false; std::uint64_t cache_now = 0; if (p >= cached_lo && p < cached_hi && range_clean_since(cached_gen, p, (std::min)(sub_hi, cached_hi), cache_now)) { region_base = cached_lo; region_end = cached_hi; state = cached_state; protect = cached_protect; guarded = cached_guarded; query_gen = cached_gen; from_cache = true; ++arm_stats.vq_cache; } else { query_gen = leonida::title_memory_map::generation(); ++arm_stats.vq; MEMORY_BASIC_INFORMATION m{}; if (!VirtualQuery(reinterpret_cast(p), &m, sizeof m)) { const std::size_t tile_k = sub_start + std::size_t((p - sub_lo) / kTile); run_failed_[tile_k] = 1; p = (p & ~(kTile - 1)) + kTile; continue; } region_base = reinterpret_cast(m.BaseAddress); region_end = region_base + m.RegionSize; state = m.State; protect = m.Protect; guarded = leonida::geometry_writes::read_only(m.Protect); const DWORD base_prot = protect & 255u; // Intra-pass region cache: MEM_RESERVE, MEM_FREE, PAGE_NOACCESS, and writable MEM_COMMIT. // NEVER cache PAGE_READONLY / PAGE_EXECUTE_READ (ShadowPages::reopen() bypasses map_gen). const bool cacheable_region = state == MEM_RESERVE || state == MEM_FREE || (state == MEM_COMMIT && !(protect & PAGE_GUARD) && (guarded != 0 || base_prot == PAGE_NOACCESS)); if (cacheable_region && region_end > sub_hi) { cached_lo = p; cached_hi = region_end; cached_state = state; cached_protect = protect; cached_guarded = guarded; cached_gen = query_gen; } else { cached_hi = 0; } } const std::uintptr_t end = (std::min)(sub_hi, region_end); if (end <= p) { const std::size_t tile_k = sub_start + std::size_t((p - sub_lo) / kTile); run_failed_[tile_k] = 1; cached_hi = 0; p = (p & ~(kTile - 1)) + kTile; continue; } if (state == MEM_COMMIT && !(protect & PAGE_GUARD) && guarded) { DWORD old{}; ++arm_stats.vq_vp; if (VirtualProtect(reinterpret_cast(p), end - p, guarded, &old)) { for (std::uintptr_t q = p; q < end; q += kHostPage) { const std::size_t tile_k = sub_start + std::size_t((q - sub_lo) / kTile); const std::size_t sub_p = std::size_t((q & (kTile - 1)) / kHostPage); batch_cells[tile_k]->restore[sub_p] = protect; batch_cells[tile_k]->armed_map_gen = Cell::kNoMapGen; } const std::uintptr_t first_full = (p + kTile - 1) & ~(kTile - 1); const std::uintptr_t last_full = end & ~(kTile - 1); std::uint64_t after_gen = 0; if (first_full < last_full && region_base <= first_full && region_end >= last_full && range_clean_since(query_gen, first_full, last_full, after_gen)) { for (std::uintptr_t t = first_full; t < last_full; t += kTile) { const std::size_t tile_k = sub_start + std::size_t((t - sub_lo) / kTile); Cell* const c = batch_cells[tile_k]; c->known_state = MEM_COMMIT; c->known_protect = protect; c->known_guarded = guarded; c->known_mapping = c->mapping.load(std::memory_order_acquire); c->known_map_gen = after_gen; c->armed_map_gen = after_gen; } } if (cached_hi && p >= cached_lo && end <= cached_hi) cached_lo = end; } else if (from_cache) { cached_hi = 0; continue; } else { cached_hi = 0; for (std::uintptr_t t = p; t < end;) { const std::uintptr_t t_end = (std::min)(end, (t & ~(kTile - 1)) + kTile); const std::size_t tile_k = sub_start + std::size_t((t - sub_lo) / kTile); ++arm_stats.vq_vp; if (VirtualProtect(reinterpret_cast(t), t_end - t, guarded, &old)) { for (std::uintptr_t q = t; q < t_end; q += kHostPage) { const std::size_t sub_p = std::size_t((q & (kTile - 1)) / kHostPage); batch_cells[tile_k]->restore[sub_p] = protect; batch_cells[tile_k]->armed_map_gen = Cell::kNoMapGen; } } else { run_failed_[tile_k] = 1; } t = t_end; } } } else { const std::uintptr_t first_full = (p + kTile - 1) & ~(kTile - 1); const std::uintptr_t last_full = end & ~(kTile - 1); if (first_full < last_full) { const bool is_noaccess = state == MEM_COMMIT && !(protect & PAGE_GUARD) && (protect & 255u) == PAGE_NOACCESS; std::uint64_t after_gen = 0; if (is_noaccess && region_base <= first_full && region_end >= last_full && range_clean_since(query_gen, first_full, last_full, after_gen)) { for (std::uintptr_t t = first_full; t < last_full; t += kTile) { const std::size_t tile_k = sub_start + std::size_t((t - sub_lo) / kTile); Cell* const c = batch_cells[tile_k]; c->known_state = MEM_COMMIT; c->known_protect = PAGE_NOACCESS; c->known_guarded = 0; c->known_mapping = c->mapping.load(std::memory_order_acquire); c->known_map_gen = after_gen; } } else { // Clear stale writable cache without trampling CellGuard's MEM_RESERVE cache. for (std::uintptr_t t = first_full; t < last_full; t += kTile) { const std::size_t tile_k = sub_start + std::size_t((t - sub_lo) / kTile); Cell* const c = batch_cells[tile_k]; if (!(state == MEM_RESERVE && c->known_state == MEM_RESERVE)) clear_cell_known(*c); } } } if (cached_hi && p >= cached_lo && end <= cached_hi) cached_lo = end; } p = end; } for (std::size_t k = sub_start; k < sub_end; ++k) results[i + k] = run_failed_[k] ? -1 : 1; sub_start = sub_end; } } i = j; } } std::vector run_versions_; std::vector run_pinned_; std::vector run_eligible_; std::vector run_already_armed_; std::vector run_failed_; std::vector> run_pin_ranges_; std::vector run_need_backed_idx_; std::vector run_need_backed_vas_; std::vector run_need_backed_out_; void acquire_batch(const std::uintptr_t* tiles, Cell** out_cells, std::size_t count) { leonida::geometry_writes::acquire_batch(tiles, out_cells, count); } void release_batch(const std::pair* items, std::size_t count) { leonida::geometry_writes::release_batch(items, count); } void aliases(std::uintptr_t tile, std::vector& out) { if (const auto f = leonida::geometry_writes::aliases.load(std::memory_order_acquire)) f(tile, out); } void take_written(std::vector& out, bool& overflow) { leonida::geometry_writes::take_written(queue, out, overflow); } void hot_tiles(std::vector& out) { leonida::geometry_writes::hot_tiles(out); } bool has_written() const { return queue.pending.load(std::memory_order_acquire); } std::size_t hot_count() const { return leonida::geometry_writes::state().hot_count.load(std::memory_order_acquire); } std::uint64_t hot_generation() const { auto& s = leonida::geometry_writes::state(); if constexpr (requires { s.hot_generation; }) { return s.hot_generation.load(std::memory_order_acquire); } else { return static_cast(s.hot_count.load(std::memory_order_acquire)); } } bool enabled() const { return watch_shadow_writes(); } }; struct ShadowPagesDeleter { void operator()(ShadowPages* pages) const { pages->reopen_all(); AcquireSRWLockExclusive(&g_shadow_pages_lock); std::erase(shadow_pages_list(), pages); ReleaseSRWLockExclusive(&g_shadow_pages_lock); delete pages; } }; using ShadowPagesPtr = std::unique_ptr; ShadowPagesPtr make_shadow_pages(const std::uint8_t* pages, std::uint8_t* shadow, std::size_t size) { const bool watch = watch_shadow_writes(); auto* tracker = new ShadowPages(pages, shadow, size, watch); if (watch) { shadow_pages_list(); // made (on the process heap) before the lock the fault handler waits for AcquireSRWLockExclusive(&g_shadow_pages_lock); shadow_pages_list().push_back(tracker); ReleaseSRWLockExclusive(&g_shadow_pages_lock); } return ShadowPagesPtr(tracker); } // The furthest range end is the span to refresh at submission. Sampler ranges use their full hardware // heap limit. Buffer-view translation retains its existing per-table budget. // The refresh of title-backed sampler tables (this count, the sampler entries of DeviceState::visible_heaps and the // sampler-heap case of scan_title_table) is adapted from the patch sampler-table-refresh of // Sigtryggur-Mani-Gudmundsson/graphics-runtime-patches at d9a0bc1b (author smg, as "Codex"), GPL-3.0; the // descriptor mapping provider registered in set_device_outer is from its patch descriptor-write-through. constexpr std::uint32_t kViewScanLimit = 1024; std::uint32_t table_descriptor_count(const rt::rootsig::RootParameter& param) { if (param.type != rt::rootsig::ParamType::Table || param.ranges.empty()) return 0; const std::uint32_t limit = param.ranges.front().range_type == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER ? D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE : UINT_MAX; std::uint64_t next = 0, end = 0; for (const auto& range : param.ranges) { const std::uint64_t start = range.offset_in_table == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND ? next : range.offset_in_table; const std::uint64_t count = range.num_descriptors == UINT_MAX ? limit : range.num_descriptors; next = start + count; end = std::max(end, next); } return std::uint32_t(std::min(end, limit)); } // Two test settings that make the standalone device look like a GPU with fewer Vulkan queues, so the path where D3D12 // queues share a VkQueue runs on any GPU; both together give the Intel UHD 770 on Windows and lavapipe (one family, // one queue). LEONIDA_VK_MAX_QUEUES_PER_FAMILY=N (1 to 16): at most N VkQueues per queue family (unset, or not a // number from 1 to 16: 16). LEONIDA_VK_GRAPHICS_FAMILY_ONLY=1: COMPUTE and COPY queues use the graphics family, as on // a GPU without async compute or transfer families. The game's device ignores both (QueueTestSettings::ignore). // The setting's value, or false when it is unset; set but ignored, it says so. bool queue_test_setting(const char* name, char* text, size_t size, rt::d3d12::QueueTestSettings settings) { size_t length = 0; if (getenv_s(&length, text, size, name) != 0 || length <= 1) return false; if (settings == rt::d3d12::QueueTestSettings::apply) return true; std::fprintf(stderr, "[rt] d3d12: %s is a test setting; the game's device ignores it (all its Vulkan queues)\n", name); return false; } bool graphics_family_only(rt::d3d12::QueueTestSettings settings) { char text[8] = {}; const bool on = queue_test_setting("LEONIDA_VK_GRAPHICS_FAMILY_ONLY", text, sizeof(text), settings) && text[0] != '0'; if (on) std::fprintf(stderr, "[rt] d3d12: LEONIDA_VK_GRAPHICS_FAMILY_ONLY: every D3D12 queue in the graphics family\n"); return on; } std::uint32_t max_queues_per_family(rt::d3d12::QueueTestSettings settings) { constexpr std::uint32_t most = 16; char text[16] = {}; if (!queue_test_setting("LEONIDA_VK_MAX_QUEUES_PER_FAMILY", text, sizeof(text), settings)) return most; char* end = nullptr; const unsigned long value = std::strtoul(text, &end, 10); if (end == text || *end || value < 1 || value > most) { std::fprintf(stderr, "[rt] d3d12: LEONIDA_VK_MAX_QUEUES_PER_FAMILY=%s is not a number from 1 to %u: ignored\n", text, most); return most; } std::fprintf(stderr, "[rt] d3d12: LEONIDA_VK_MAX_QUEUES_PER_FAMILY: at most %lu Vulkan queue(s) per family\n", value); return std::uint32_t(value); } // The pipelines build stage writes its cache beside gta6rt.exe, independently of the working directory. // LEONIDA_PIPELINE_CACHE_DIR= keeps it there instead, so several builds of gta6rt share one warmed cache. std::filesystem::path pipeline_cache_path() { { std::wstring dir(32768, L'\0'); const DWORD n = GetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", dir.data(), static_cast(dir.size())); if (n > 0 && n < dir.size()) { dir.resize(n); std::error_code ec; std::filesystem::create_directories(dir, ec); return std::filesystem::path(dir) / L"pipeline_cache.bin"; } } std::wstring path(32768, L'\0'); const DWORD length = GetModuleFileNameW(nullptr, path.data(), static_cast(path.size())); if (!length || length >= path.size()) return {}; path.resize(length); return std::filesystem::path(path).parent_path() / L"pipeline_cache.bin"; } // What the runtime itself compiled, kept next to the offline seed and never written over it (D3D-704). std::filesystem::path pipeline_cache_session_path() { std::filesystem::path path = pipeline_cache_path(); if (!path.empty()) path.replace_filename(L"pipeline_cache.session.bin"); return path; } // The pipelines the offline seed does not have, kept next to it and written while the game runs // (src/heavy_pipeline_cache.h). std::filesystem::path pipeline_cache_heavy_path() { std::filesystem::path path = pipeline_cache_path(); if (!path.empty()) path.replace_filename(L"pipeline_cache.heavy.bin"); return path; } // LEONIDA_COMPILE_GATE unset or `auto` (src/compile_gate_policy.h): decides the compile gate for this GPU and driver // before the VulkanContext (and its SubmitMutex) exists. The verdict comes from compile_gate_calibration.txt beside // the pipeline cache, or from a calibration on `info.queue` (src/compile_gate_calibration.h), written there once. // Only in gta6rt's title process (compile_gate_policy::calibration_allowed): a build host, a test or anything else // that creates a device keeps the classic gate and never calibrates. A forced setting returns at once. void decide_auto_compile_gate(const VulkanDeviceInfo& info, PFN_vkGetDeviceProcAddr get_device, const leonida::cached_pso::Identity& identity) { namespace policy = leonida::compile_gate_policy; using leonida::CompileGateMode; using leonida::SubmitMutex; if (SubmitMutex::compile_gate_setting() != policy::Setting::automatic) return; if (!policy::calibration_allowed.load() || compile_helper::build_host.load()) return; // classic, as before `auto` static std::once_flag once; std::call_once(once, [&] { const auto decide = [](CompileGateMode mode, const std::string& why) { SubmitMutex::decide_auto_gate(mode); std::fprintf(stderr, "[rt] compile-gate: auto: %s (%s; LEONIDA_COMPILE_GATE=classic|adaptive overrides)\n", mode == CompileGateMode::adaptive ? "adaptive" : "classic", why.c_str()); }; const auto utf8 = [](const std::filesystem::path& path) { const std::wstring& wide = path.native(); const int n = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), int(wide.size()), nullptr, 0, nullptr, nullptr); std::string out(std::size_t(n > 0 ? n : 0), '\0'); if (n > 0) WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), int(wide.size()), out.data(), n, nullptr, nullptr); return out; }; if (!identity.vendor || !info.device || !info.queue || !get_device) { decide(CompileGateMode::classic, "the GPU or its queue is not known, so no calibration"); return; } const std::string driver = policy::describe_driver(identity.vendor, identity.driver); if (info.physical && info.get_instance_proc) { if (const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { VkPhysicalDeviceProperties props{}; get_props(info.physical, &props); if (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) { decide(CompileGateMode::classic, driver + " is a CPU device, not calibrated"); return; } } } policy::CacheKey key; key.vendor = identity.vendor; key.device = identity.device; key.driver = identity.driver; std::memcpy(key.uuid, identity.cache_uuid, sizeof key.uuid); std::filesystem::path path = pipeline_cache_path(); if (!path.empty()) path.replace_filename(L"compile_gate_calibration.txt"); std::string text; if (!path.empty()) { std::ifstream in(path, std::ios::binary); if (in) text.assign(std::istreambuf_iterator(in), std::istreambuf_iterator()); } char value[4] = {}; std::size_t length = 0; const bool recalibrate = getenv_s(&length, value, "LEONIDA_COMPILE_GATE_RECALIBRATE") == 0 && length > 1 && policy::recalibrate(value); if (!recalibrate) { if (const auto cached = policy::find_entry(text, key)) { decide(policy::mode_for(cached->verdict.outcome), "cached calibration of " + driver + ": " + policy::describe_verdict(cached->verdict) + "; in " + utf8(path) + ", LEONIDA_COMPILE_GATE_RECALIBRATE=1 measures again"); return; } } const auto seed = static_cast(std::chrono::steady_clock::now().time_since_epoch().count()) | 1u; const leonida::compile_gate_calibration::Result result = leonida::compile_gate_calibration::calibrate(get_device, info.device, info.queue, info.queue_family, seed); if (!result.ok) { decide(CompileGateMode::classic, "calibration of " + driver + " failed: " + result.error + "; not cached"); return; } std::string where = "not cached (no pipeline cache folder)"; if (!policy::cache_verdict(result.verdict.outcome)) { where = "not cached: the next launch measures again"; } else if (!path.empty()) { const std::string updated = policy::replace_entry(text, {key, result.verdict}); std::filesystem::path temp = path; temp += L".tmp"; bool written = false; { std::ofstream out(temp, std::ios::binary | std::ios::trunc); out.write(updated.data(), std::streamsize(updated.size())); written = bool(out); } std::error_code ec; if (written) std::filesystem::rename(temp, path, ec); where = written && !ec ? "cached in " + utf8(path) : "not cached (" + utf8(path) + " could not be written)"; } char took[64]; std::snprintf(took, sizeof took, " in %.1f s", result.total_ms / 1000.0); decide(policy::mode_for(result.verdict.outcome), "calibrated on " + driver + took + ": " + policy::describe_verdict(result.verdict) + "; " + where); }); } // LEONIDA_HEAVY_PIPELINE_CACHE_MS: a compile at least this long schedules a write of the heavy cache; 0 turns the // heavy cache off. One line for a value that is not a number. std::uint32_t heavy_pipeline_cache_ms() { static const std::uint32_t ms = [] { char text[32] = {}; size_t length = 0; const bool present = getenv_s(&length, text, "LEONIDA_HEAVY_PIPELINE_CACHE_MS") == 0 && length > 1; const auto threshold = leonida::heavy_pipeline_cache::parse_threshold(present ? text : ""); if (!threshold.valid) std::fprintf(stderr, "[rt] d3d12: LEONIDA_HEAVY_PIPELINE_CACHE_MS=%s is not a number of milliseconds; " "using %u\n", text, threshold.ms); return threshold.ms; }(); return ms; } std::size_t pipeline_cache_save_limit(); // LOCAL FIX (pipeline journal, pipeline_cache_journal.h): where each compute pipeline's own cache file goes, beside // the session file (so LEONIDA_PIPELINE_CACHE_DIR moves it too). Empty, and no journal, with LEONIDA_PIPELINE_JOURNAL=0 // or LEONIDA_PIPELINE_CACHE_BYTES=0. const leonida::pipeline_journal::Roots& pipeline_journal_roots() { static const auto roots = []() -> leonida::pipeline_journal::Roots { wchar_t value[2]{}; if (GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL", value, 2) == 1 && value[0] == L'0') return {}; if (!pipeline_cache_save_limit()) return {}; std::filesystem::path path = pipeline_cache_path(); if (!path.empty()) path.replace_filename(L"pipeline_cache.d"); std::wstring seed(32768, L'\0'); const DWORD n = GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL_SEED_DIR", seed.data(), static_cast(seed.size())); if (n >= seed.size()) return {}; seed.resize(n); auto result = leonida::pipeline_journal::resolve_roots(path, seed); if (!seed.empty() && result.writable.empty()) std::fprintf(stderr, "[rt] d3d12: invalid or overlapping compute journal directories; journal disabled\n"); return result; }(); return roots; } const std::filesystem::path& pipeline_journal_dir() { return pipeline_journal_roots().writable; } // The offline seed's size (pipeline_cache.bin) when the device cache was created from it, 0 otherwise: the save limit // does not count it (pipeline_cache_store::over_save_limit). std::atomic g_offline_seed_bytes{0}; // LEONIDA_PIPELINE_CACHE_BYTES, in bytes; 0 turns the session file off. One line for a value that is not a number. std::size_t pipeline_cache_save_limit() { char text[32] = {}; size_t length = 0; const bool present = getenv_s(&length, text, "LEONIDA_PIPELINE_CACHE_BYTES") == 0 && length > 1; const auto limit = leonida::pipeline_cache_store::parse_save_limit(present ? text : ""); if (!limit.valid) std::fprintf(stderr, "[rt] d3d12: LEONIDA_PIPELINE_CACHE_BYTES=%s is not a byte count; using %zu\n", text, limit.bytes); return limit.bytes; } // A corpus cache may be several GiB. Keep the read-only view alive through vkCreatePipelineCache // and deny writers while the view is in use. class PipelineCacheSeed { public: explicit PipelineCacheSeed(const std::filesystem::path& path) { if (path.empty()) return; file_ = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (file_ == INVALID_HANDLE_VALUE) return; LARGE_INTEGER length{}; constexpr auto header_size = static_cast(sizeof(VkPipelineCacheHeaderVersionOne)); if (!GetFileSizeEx(file_, &length) || length.QuadPart < header_size) return; const HANDLE mapping = CreateFileMappingW(file_, nullptr, PAGE_READONLY, 0, 0, nullptr); if (!mapping) return; data_ = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0); CloseHandle(mapping); if (data_) size_ = static_cast(length.QuadPart); } ~PipelineCacheSeed() { if (data_) UnmapViewOfFile(data_); if (file_ != INVALID_HANDLE_VALUE) CloseHandle(file_); } PipelineCacheSeed(const PipelineCacheSeed&) = delete; PipelineCacheSeed& operator=(const PipelineCacheSeed&) = delete; const void* data() const { return data_; } std::size_t size() const { return size_; } bool compatible(const leonida::cached_pso::Identity& identity) const { return leonida::pipeline_cache_store::header_matches(data_, size_, identity); } private: HANDLE file_ = INVALID_HANDLE_VALUE; const void* data_ = nullptr; std::size_t size_ = 0; }; VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_cache, VkDevice device, const leonida::cached_pso::Identity& identity, bool session = false) { auto start = compile_us(); const auto name = session ? "pipeline_cache.session.bin" : "pipeline_cache.bin"; const PipelineCacheSeed seed(session ? pipeline_cache_session_path() : pipeline_cache_path()); if (!seed.data()) return VK_NULL_HANDLE; if (!seed.compatible(identity)) { std::fprintf(stderr, "[rt] d3d12: %s does not match this Vulkan device\n", name); return VK_NULL_HANDLE; } const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), seed.data()}; VkPipelineCache cache = VK_NULL_HANDLE; const auto mapped = compile_us(); if (create_cache(device, &create, nullptr, &cache) != VK_SUCCESS) { std::fprintf(stderr, "[rt] d3d12: Vulkan declined the pipeline cache seed\n"); return VK_NULL_HANDLE; } std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from %s\n", seed.size(), name); if (!session) g_offline_seed_bytes.store(seed.size(), std::memory_order_relaxed); if (trace_pipeline_compile()) std::fprintf(stderr, "[rt] pipeline-cache op=load bytes=%zu map_us=%lld driver_us=%lld file=%s\n", seed.size(), mapped-start, compile_us()-mapped, name); return cache; } // D3D-704: merges what earlier launches compiled into the cache the pipelines are created against. The offline seed // and the session file cannot be handed over as one VkPipelineCacheCreateInfo -- Vulkan reads a single blob -- so the // session cache is created on its own and merged in. A missing, foreign or corrupt session file leaves the cache as // it was, and so does a driver that does not expose vkMergePipelineCaches. bool merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, const leonida::cached_pso::Identity& identity) { if (!cache || !vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkMergePipelineCaches) return false; if (!pipeline_cache_save_limit()) return false; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off const auto start = compile_us(); const PipelineCacheSeed seed(pipeline_cache_session_path()); if (!seed.data()) return false; if (!seed.compatible(identity)) { std::fprintf(stderr, "[rt] d3d12: pipeline_cache.session.bin does not match this Vulkan device\n"); return false; } const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), seed.data()}; const auto mapped = compile_us(); VkPipelineCache session = VK_NULL_HANDLE; if (vk.vkCreatePipelineCache(device, &create, nullptr, &session) != VK_SUCCESS) { std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.session.bin\n"); return false; } const auto created = compile_us(); const VkResult result = vk.vkMergePipelineCaches(device, cache, 1, &session); const auto merged = compile_us(); vk.vkDestroyPipelineCache(device, session, nullptr); if (trace_pipeline_compile()) std::fprintf(stderr, "[rt] pipeline-cache op=merge bytes=%zu map_us=%lld driver_us=%lld merge_us=%lld release_us=%lld result=%d\n", seed.size(), mapped-start, created-mapped, merged-created, compile_us()-merged, int(result)); if (result == VK_SUCCESS) std::fprintf(stderr, "[rt] d3d12: merged %zu bytes from pipeline_cache.session.bin\n", seed.size()); else std::fprintf(stderr, "[rt] d3d12: vkMergePipelineCaches on pipeline_cache.session.bin returned %d; ignored\n", static_cast(result)); return result == VK_SUCCESS; } // LEONIDA_SKIP_COMPUTE=[,...]: compute programs whose library name contains one of the parts are // never built and every dispatch of theirs is dropped ("all" or "*": every compute program). For getting past a // program that hangs the GPU, such as a translated loop that never ends on the input it is given here, while the // program or its input is being fixed. What the program would have written keeps its previous contents. // gta6rt --precompile-pipelines builds the listed programs anyway unless it is given --skip-listed. bool skip_compute(const std::string& name) { static const std::vector parts = [] { std::vector out; const DWORD need = GetEnvironmentVariableA("LEONIDA_SKIP_COMPUTE", nullptr, 0); // with the terminator if (need == 0) return out; std::string text(need, '\0'); const DWORD n = GetEnvironmentVariableA("LEONIDA_SKIP_COMPUTE", text.data(), need); if (n == 0 || n >= need) return out; text.resize(n); for (std::size_t at = 0; at <= text.size();) { const std::size_t end = std::min(text.find(',', at), text.size()); if (end > at) out.push_back(text.substr(at, end - at)); at = end + 1; } return out; }(); for (const std::string& part : parts) if (part == "all" || part == "*" || name.find(part) != std::string::npos) return true; return false; } // Graphics pipelines are built at their first draw, not at CreatePipelineState (LEONIDA_LAZY_PIPELINES=0: at // creation, as before). The title creates ~50,000 graphics PSOs at startup and draws a small part of them; each live // VkPipeline and its shader modules cost the driver ~90 KiB of host memory, ~4.5 GiB for the whole set. bool lazy_graphics_pipelines() { static const bool lazy = [] { wchar_t value[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_LAZY_PIPELINES", value, 2) == 1 && value[0] == L'0'); }(); return lazy; } // Texture descriptions the console accepts and a PC GPU may not: an R9G9B9E5 render target (RDNA2 renders and // stores to it; NVIDIA only samples it) and an sRGB RGBA8 or BGRA8 texture with unordered access. The title asks // GetResourceAllocationInfo for them at boot and asserts when the answer is "invalid", so the device gives them a // host format that can do the job (DeviceState::r9g9b9e5_target_stand_in, srgb_uav_emulated). // LEONIDA_CONSOLE_FORMATS=0 refuses them, as a PC D3D12 runtime does. bool console_format_stand_ins() { static const bool on = [] { wchar_t value[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_CONSOLE_FORMATS", value, 2) == 1 && value[0] == L'0'); }(); return on; } // A driver's compiler needs hundreds of MiB for a very large module; several at once exhausted host memory. Large are // compute modules over 128 KiB and graphics pipelines of PipelineCompiles::large_spirv_bytes or more. They compile side by // side while their estimates fit the memory that is free (big_compile_gate). LEONIDA_SERIAL_BIG_COMPILES=1: one at a time, // as before there was a budget (graphics: one after another in each submission). 0: as many as are asked for. enum class BigCompiles { budget, serial, unlimited }; BigCompiles big_compiles() { static const BigCompiles mode = [] { wchar_t v[2]{}; const DWORD n = GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2); if (n == 0) return BigCompiles::budget; return n == 1 && v[0] == L'0' ? BigCompiles::unlimited : BigCompiles::serial; }(); return mode; } bool big_compute(std::size_t spirv_bytes) { return spirv_bytes > 128 * 1024; } // Where large compiles wait for memory: one for the process, as the memory is the machine's. Never destroyed: static // destruction must not race the compile worker. leonida::LargeModuleGate& big_compile_gate() { static auto* const gate = [] { char text[32]{}; std::size_t length = 0; const bool present = getenv_s(&length, text, "LEONIDA_BIG_COMPILE_BUDGET_MB") == 0 && length > 1; const auto setting = leonida::large_compile_budget(present ? text : ""); if (!setting.valid) std::fprintf(stderr, "[rt] d3d12: LEONIDA_BIG_COMPILE_BUDGET_MB=%s is not a number; not used\n", text); auto budget = [fixed = setting.fixed] { return fixed ? *fixed : leonida::large_compile_budget_bytes(); }; std::fprintf(stderr, "[rt] d3d12: large pipelines compile side by side within %llu MiB (%s)\n", static_cast(budget() >> 20), setting.fixed ? "LEONIDA_BIG_COMPILE_BUDGET_MB" : "3/4 of the memory free now"); return new leonida::LargeModuleGate(std::move(budget)); }(); return *gate; } bool startup_cache_checkpoints_enabled() { static const bool enabled = [] { wchar_t value[2]{}; return GetEnvironmentVariableW(L"LEONIDA_STARTUP_CACHE_CHECKPOINTS", value, 2) == 1 && value[0] == L'1'; }(); return enabled; } // Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write. // RT-PIPELINE-CACHE-GROWTH-STALL: says once when the title's builds keep compiling but the driver's cache stops // growing, so the next run would compile them again (pipeline_cache_store::GrowthWatch). The size is taken when the // cache is created and at every session save, also one over the write limit. std::mutex& pipeline_cache_growth_mutex() { static std::mutex mutex; return mutex; } leonida::pipeline_cache_store::GrowthWatch& pipeline_cache_growth() { static leonida::pipeline_cache_store::GrowthWatch watch; return watch; } void note_pipeline_cache_size(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache) { std::size_t size = 0; if (!cache || !vk.vkGetPipelineCacheData || vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS) return; std::lock_guard lock(pipeline_cache_growth_mutex()); pipeline_cache_growth().observe(size, leonida::pipeline_profile::compiled_builds().load()); } void report_pipeline_cache_growth(std::size_t size) { const auto compiled = leonida::pipeline_profile::compiled_builds().load(); std::lock_guard lock(pipeline_cache_growth_mutex()); auto& watch = pipeline_cache_growth(); const std::size_t before = watch.bytes(); const unsigned long long builds = compiled - watch.compiled(); if (watch.stalled(size, compiled)) std::fprintf(stderr, "[rt] d3d12: the Vulkan pipeline cache grew %zu bytes (to %zu) over %llu pipeline builds " "that compiled: the driver no longer keeps new pipelines, so the next run compiles them " "again. A large pipeline_cache.bin or pipeline_cache.session.bin can cause it " "(docs/d3d12_vulkan.md, pipeline caches)\n", size > before ? size - before : 0, size, builds); } void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, bool checkpoint = false, const char* op = nullptr) { if (!cache || !vk.vkGetPipelineCacheData) return; // The output is an opaque Vulkan blob. A prefix is not an incremental cache, so past the limit nothing is written. const auto limit = pipeline_cache_save_limit(); if (!limit) return; const auto start = compile_us(); std::size_t size = 0; if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS || size <= sizeof(VkPipelineCacheHeaderVersionOne)) return; report_pipeline_cache_growth(size); const std::size_t seed = g_offline_seed_bytes.load(std::memory_order_relaxed); if (leonida::pipeline_cache_store::over_save_limit(size, seed, limit)) { std::fprintf(stderr, "[rt] d3d12: pipeline cache is %zu bytes (%zu of them the offline seed), over the " "%zu-byte write limit for what a session adds\n", size, seed, limit); return; } const auto queried = compile_us(); // A size query can itself serialize the driver cache. Let newly queued work run first. if (checkpoint && PipelineCompiler::instance().has_compile_waiter()) return; const auto path = pipeline_cache_session_path(); if (path.empty()) return; CacheStagingFile staging(path, size); if (!staging.data) { std::fprintf(stderr, "[rt] d3d12: could not map staging file for %zu pipeline cache bytes\n", size); return; } auto written = size; const auto result = vk.vkGetPipelineCacheData(device, cache, &written, staging.data); const auto filled = compile_us(); const bool ok = result == VK_SUCCESS && written >= sizeof(VkPipelineCacheHeaderVersionOne) && written <= size && staging.publish(path, written); if (trace_pipeline_compile()) std::fprintf(stderr, "[rt] pipeline-cache op=%s bytes=%zu query_us=%lld fill_us=%lld publish_us=%lld ok=%d result=%d\n", op ? op : checkpoint ? "checkpoint" : "teardown", written, queried-start, filled-queried, compile_us()-filled, int(ok), int(result)); if (ok) std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.session.bin\n", written); else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result)); } // The heavy cache, seeded from pipeline_cache.heavy.bin when it is there and made for this device; empty otherwise. VkPipelineCache create_heavy_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, const leonida::cached_pso::Identity& identity) { const auto path = pipeline_cache_heavy_path(); clean_stale_cache_files(path); VkPipelineCache cache = VK_NULL_HANDLE; { const PipelineCacheSeed seed(path); if (seed.data() && seed.compatible(identity)) { const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), seed.data()}; if (vk.vkCreatePipelineCache(device, &create, nullptr, &cache) == VK_SUCCESS) { std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from pipeline_cache.heavy.bin\n", seed.size()); return cache; } std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.heavy.bin; starting it empty\n"); } else if (seed.data()) { std::fprintf(stderr, "[rt] d3d12: pipeline_cache.heavy.bin does not match this Vulkan device; starting " "it empty\n"); } } const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; if (vk.vkCreatePipelineCache(device, &create, nullptr, &cache) != VK_SUCCESS) return VK_NULL_HANDLE; return cache; } // Writes the heavy cache whole: a staging file renamed over pipeline_cache.heavy.bin, so the file on disk is always // a complete blob. It only holds what the offline seed missed, so it has no size limit of its own. bool save_heavy_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, std::uint64_t compiles, std::uint64_t hits) { if (!cache || !vk.vkGetPipelineCacheData) return false; const auto path = pipeline_cache_heavy_path(); if (path.empty()) return false; const auto start = compile_us(); std::size_t size = 0; if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS || size <= sizeof(VkPipelineCacheHeaderVersionOne)) return false; CacheStagingFile staging(path, size); if (!staging.data) { std::fprintf(stderr, "[rt] d3d12: could not map a staging file for %zu heavy pipeline cache bytes\n", size); return false; } auto written = size; const VkResult result = vk.vkGetPipelineCacheData(device, cache, &written, staging.data); // VK_INCOMPLETE means the cache grew after the size query and the blob is a truncated snapshot; it must not // replace a complete file. The writer tries again later with a fresh size. const bool ok = result == VK_SUCCESS && written > sizeof(VkPipelineCacheHeaderVersionOne) && written <= size && staging.publish(path, written); if (ok) std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.heavy.bin in %.1f s (%llu slow builds " "and %llu other builds past the offline cache so far)\n", written, double(compile_us() - start) / 1e6, static_cast(compiles), static_cast(hits)); else std::fprintf(stderr, "[rt] d3d12: pipeline_cache.heavy.bin not written (%d); the previous file is kept\n", int(result)); return ok; } // A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, // for a wave32 shader on a 64-wide default, reads lanes that are not its own), unless the translator's // partition-invariance tier says otherwise. Logged once per stage with the first shader's name, then again at 10, 100, // 1000... of that stage so a whole corpus stays readable. void report_subgroup_unavailable(const leonida::ShaderEntry& entry, const leonida::SubgroupRequest& request, const leonida::SubgroupSizeCaps& caps) { static std::mutex mutex; static std::map, unsigned>> seen; // stage -> names, next report std::lock_guard lock(mutex); auto& [names, next_report] = seen[entry.stage]; if (!names.insert(entry.name).second) return; if (names.size() == 1) next_report = 10; else if (names.size() != next_report) return; else next_report *= 10; const bool emulable = entry.stage == "cs" || entry.stage == "ms"; const std::string so_far = names.size() > 1 ? " (shaders of this stage so far: " + std::to_string(names.size()) + ")" : ""; if (leonida::graphics_partition_invariant(entry)) { // The translator proved this shader's results do not change when its wave is cut into two 32-lane halves // (docs/design.md, "Wave64 graphics"), so neither a 64-wide subgroup nor emulation is needed. std::fprintf(stderr, "[rt] d3d12: %s (%s) is a 64-wide shader but this device cannot require that subgroup size for " "the stage (device sizes %u..%u, default %u, subgroupSizeControl %s); it runs at the device's " "size, which is exact for it: the translator's partition-invariance analysis puts it in tier " "%s%s\n", entry.name.c_str(), entry.stage.c_str(), caps.min_size, caps.max_size, caps.default_size, caps.subgroup_size_control ? "on" : "off", entry.wave64_graphics.c_str(), so_far.c_str()); return; } std::fprintf(stderr, "[rt] d3d12: %s (%s) is a %u-wide shader but this device cannot require that subgroup size for the " "stage (device sizes %u..%u, default %u, subgroupSizeControl %s); it runs at the device's size and " "is inexact where lanes of the other half matter%s\n", entry.name.c_str(), entry.stage.c_str(), request.wanted, caps.min_size, caps.max_size, caps.default_size, caps.subgroup_size_control ? "on" : "off", so_far.c_str()); if (emulable && request.wanted == 64) std::fprintf(stderr, "[rt] d3d12: translate wave64 %s shaders with --wave64-emulate for this GPU " "(make_game.py --wave64-emulate auto does)\n", entry.stage.c_str()); else if (request.wanted == 64) std::fprintf(stderr, "[rt] d3d12: no emulation exists for wave64 %s shaders yet (docs/d3d12_vulkan.md, " "subgroup size)\n", entry.stage.c_str()); } // VK_FORMAT_A8_UNORM_KHR where the Vulkan headers have VK_KHR_maintenance5. Older headers have no A8 render targets: // VulkanDeviceInfo::a8_render_target is then never set, so this is never used as UNDEFINED. #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME constexpr VkFormat kA8UnormFormat = VK_FORMAT_A8_UNORM_KHR; #else constexpr VkFormat kA8UnormFormat = VK_FORMAT_UNDEFINED; #endif // Xbox DXGI values published by Microsoft's DirectXTex (DirectXTexP.h). constexpr auto xbox_d16s8=static_cast(118); constexpr auto xbox_d16_plane=static_cast(119); constexpr auto xbox_s8_plane=static_cast(120); struct Format { VkFormat format = VK_FORMAT_UNDEFINED; VkImageAspectFlags aspects = 0; bool typeless = false; // created with MUTABLE_FORMAT so typed views can reinterpret it bool d24_as_float = false; // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (no D24 on the GPU) bool d24 = false; // a D24_UNORM_S8_UINT family format, native or stored as D32 // An A8_UNORM render target stored as VK_FORMAT_A8_UNORM_KHR (VulkanDeviceInfo::a8_render_target): its RTVs render // to the alpha channel and its SRVs view it in that format, whose one channel the T# names as X (gfx10's // channels_a). Other A8_UNORM textures are R8_UNORM images. Vulkan puts A8 in a compatibility class of its own, // so one image cannot be viewed both ways. bool a8_as_alpha = false; // A UAV texture whose format has no storage support, stored as the mutable unsigned image `format` names (R32_UINT // for R9G9B9E5_SHAREDEXP, R16_UINT for B5G5R5A1_UNORM): the format its SRVs, RTVs and T#s use. Its storage view is // `format`, in the uint class; shaders write the packed bits. UNDEFINED for every other texture. VkFormat uint_backed = VK_FORMAT_UNDEFINED; // A 96-bit R32G32B32 format, held in the R32G32B32A32 image `format` names (ResourceBinding::rgb96). bool rgb96 = false; bool xbox_depth16_stencil8 = false; bool rgba4_render_fallback = false; }; // 96-bit textures are always RGBA32 images, even where the GPU has an RGB32 one (most have none with optimal // tiling): D3D12 places subresources at multiples of 512 bytes, Vulkan wants a copy's buffer offset to be a // multiple of the 12-byte texel (VUID-vkCmdCopyBufferToImage-dstImage-07975), so copies need the repack either // way (docs section 4.2). constexpr Format rgb96_format(VkFormat wide, bool typeless = false) { Format format{wide, VK_IMAGE_ASPECT_COLOR_BIT, typeless}; format.rgb96 = true; return format; } // DXGI -> Vulkan for the formats render targets, depth buffers and common textures use. R32 and R16 typeless become // depth formats when the resource allows depth-stencil; R32G8X24 and R24G8 always do, as Vulkan has no colour format // with their layout. // The console's own depth-stencil family, DXGI values past the PC list: D16_UNORM_S8_UINT (118) and its plane views // R16_UNORM_X8_TYPELESS (119) and X16_TYPELESS_G8_UINT (120). The title sizes and creates its depth targets in it // (and asserts when GetResourceAllocationInfo calls the description invalid). No D16S8 on the PC GPUs in reach, and // the PC has no such DXGI format: they are the D24_UNORM_S8_UINT family here, whose planes are viewed the same way // (depth as UNORM in X, stencil as UINT). Every entry point that takes a format from the title goes through this. // // That holds where the GPU has D24_UNORM_S8_UINT as a depth-stencil attachment. Where it has none (AMD), the D24S8 // family would itself be stored as D32_SFLOAT_S8_UINT, a third precision the title did not ask for; there the // family is kept as it is and takes the D16/S8 path (Format::xbox_depth16_stencil8: D16_UNORM_S8_UINT where the GPU // has it, else the first usable of D32_SFLOAT_S8_UINT and D24_UNORM_S8_UINT, with clears and stores quantised to // 16 bits), which is the path an AMD card was measured on past the title's first frames. The device decides when it // is created; LEONIDA_CONSOLE_D16S8=native or =d24 chooses for every GPU. Process-wide, like the title's one device. std::atomic g_console_d16s8_native{false}; inline bool console_d16s8_native() { return g_console_d16s8_native.load(std::memory_order_relaxed); } inline DXGI_FORMAT pc_format(DXGI_FORMAT format) { if (console_d16s8_native()) return format; switch (static_cast(format)) { case 118: return DXGI_FORMAT_D24_UNORM_S8_UINT; case 119: return DXGI_FORMAT_R24_UNORM_X8_TYPELESS; case 120: return DXGI_FORMAT_X24_TYPELESS_G8_UINT; default: return format; } } Format vulkan_format(DXGI_FORMAT format, bool depth) { constexpr VkImageAspectFlags color = VK_IMAGE_ASPECT_COLOR_BIT, d = VK_IMAGE_ASPECT_DEPTH_BIT, ds = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; format = pc_format(format); switch (format) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: return {VK_FORMAT_R32G32B32A32_SFLOAT, color, true}; case DXGI_FORMAT_R32G32B32A32_FLOAT: return {VK_FORMAT_R32G32B32A32_SFLOAT, color}; case DXGI_FORMAT_R32G32B32A32_UINT: return {VK_FORMAT_R32G32B32A32_UINT, color}; case DXGI_FORMAT_R32G32B32A32_SINT: return {VK_FORMAT_R32G32B32A32_SINT, color}; case DXGI_FORMAT_R32G32B32_TYPELESS: return rgb96_format(VK_FORMAT_R32G32B32A32_SFLOAT, true); case DXGI_FORMAT_R32G32B32_FLOAT: return rgb96_format(VK_FORMAT_R32G32B32A32_SFLOAT); case DXGI_FORMAT_R32G32B32_UINT: return rgb96_format(VK_FORMAT_R32G32B32A32_UINT); case DXGI_FORMAT_R32G32B32_SINT: return rgb96_format(VK_FORMAT_R32G32B32A32_SINT); case DXGI_FORMAT_R16G16B16A16_TYPELESS: return {VK_FORMAT_R16G16B16A16_SFLOAT, color, true}; case DXGI_FORMAT_R16G16B16A16_FLOAT: return {VK_FORMAT_R16G16B16A16_SFLOAT, color}; case DXGI_FORMAT_R16G16B16A16_UNORM: return {VK_FORMAT_R16G16B16A16_UNORM, color}; case DXGI_FORMAT_R16G16B16A16_SNORM: return {VK_FORMAT_R16G16B16A16_SNORM, color}; case DXGI_FORMAT_R16G16B16A16_UINT: return {VK_FORMAT_R16G16B16A16_UINT, color}; case DXGI_FORMAT_R16G16B16A16_SINT: return {VK_FORMAT_R16G16B16A16_SINT, color}; case DXGI_FORMAT_R32G32_TYPELESS: return {VK_FORMAT_R32G32_SFLOAT, color, true}; case DXGI_FORMAT_R32G32_FLOAT: return {VK_FORMAT_R32G32_SFLOAT, color}; case DXGI_FORMAT_R32G32_UINT: return {VK_FORMAT_R32G32_UINT, color}; case DXGI_FORMAT_R32G32_SINT: return {VK_FORMAT_R32G32_SINT, color}; case DXGI_FORMAT_R10G10B10A2_TYPELESS: return {VK_FORMAT_A2B10G10R10_UNORM_PACK32, color, true}; case DXGI_FORMAT_R10G10B10A2_UNORM: return {VK_FORMAT_A2B10G10R10_UNORM_PACK32, color}; case DXGI_FORMAT_R10G10B10A2_UINT: return {VK_FORMAT_A2B10G10R10_UINT_PACK32, color}; // XR_BIAS is the same packed 10:10:10:2 bit layout as R10G10B10A2_UNORM. Vulkan has no XR_BIAS format: // the application biases and scales the channels in its shader, so the resource itself is an ordinary UNORM. case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: return {VK_FORMAT_A2B10G10R10_UNORM_PACK32, color}; case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: return {VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, color}; case DXGI_FORMAT_R11G11B10_FLOAT: return {VK_FORMAT_B10G11R11_UFLOAT_PACK32, color}; case DXGI_FORMAT_R8G8B8A8_TYPELESS: return {VK_FORMAT_R8G8B8A8_UNORM, color, true}; case DXGI_FORMAT_R8G8B8A8_UNORM: return {VK_FORMAT_R8G8B8A8_UNORM, color}; case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return {VK_FORMAT_R8G8B8A8_SRGB, color}; case DXGI_FORMAT_R8G8B8A8_SNORM: return {VK_FORMAT_R8G8B8A8_SNORM, color}; case DXGI_FORMAT_R8G8B8A8_UINT: return {VK_FORMAT_R8G8B8A8_UINT, color}; case DXGI_FORMAT_R8G8B8A8_SINT: return {VK_FORMAT_R8G8B8A8_SINT, color}; case DXGI_FORMAT_B8G8R8A8_TYPELESS: return {VK_FORMAT_B8G8R8A8_UNORM, color, true}; case DXGI_FORMAT_B8G8R8A8_UNORM: return {VK_FORMAT_B8G8R8A8_UNORM, color}; // DXGI names channels from the low bits up, Vulkan from the high bits down: B in bits 0-3, A in 12-15 in both. // Vulkan 1.3 requires sampling it (formerly VK_EXT_4444_formats). case DXGI_FORMAT_B4G4R4A4_UNORM: return {VK_FORMAT_A4R4G4B4_UNORM_PACK16, color}; // A in bits 0-3 and R in 12-15 (cleared and read back on native D3D12, AMD and WARP): Vulkan's R4G4B4A4_PACK16. case DXGI_FORMAT_A4B4G4R4_UNORM: return {VK_FORMAT_R4G4B4A4_UNORM_PACK16, color}; case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return {VK_FORMAT_B8G8R8A8_SRGB, color}; // The X byte has no channel of its own: the BGRA8 images hold it, and shader views read alpha as 1. case DXGI_FORMAT_B8G8R8X8_TYPELESS: return {VK_FORMAT_B8G8R8A8_UNORM, color, true}; case DXGI_FORMAT_B8G8R8X8_UNORM: return {VK_FORMAT_B8G8R8A8_UNORM, color}; case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return {VK_FORMAT_B8G8R8A8_SRGB, color}; case DXGI_FORMAT_R16G16_TYPELESS: return {VK_FORMAT_R16G16_SFLOAT, color, true}; case DXGI_FORMAT_R16G16_FLOAT: return {VK_FORMAT_R16G16_SFLOAT, color}; case DXGI_FORMAT_R16G16_UNORM: return {VK_FORMAT_R16G16_UNORM, color}; case DXGI_FORMAT_R16G16_SNORM: return {VK_FORMAT_R16G16_SNORM, color}; case DXGI_FORMAT_R16G16_UINT: return {VK_FORMAT_R16G16_UINT, color}; case DXGI_FORMAT_R16G16_SINT: return {VK_FORMAT_R16G16_SINT, color}; case DXGI_FORMAT_R8G8_TYPELESS: return {VK_FORMAT_R8G8_UNORM, color, true}; case DXGI_FORMAT_R8G8_UNORM: return {VK_FORMAT_R8G8_UNORM, color}; case DXGI_FORMAT_R8G8_SNORM: return {VK_FORMAT_R8G8_SNORM, color}; case DXGI_FORMAT_R16_UNORM: return {VK_FORMAT_R16_UNORM, color}; case DXGI_FORMAT_R16_SNORM: return {VK_FORMAT_R16_SNORM, color}; case DXGI_FORMAT_R16_UINT: return {VK_FORMAT_R16_UINT, color}; case DXGI_FORMAT_R16_SINT: return {VK_FORMAT_R16_SINT, color}; // DXGI names packed channels from the high bits down, Vulkan's PACK formats the same way but spelled the other // way round: B5G6R5 (blue in bits 0-4) is R5G6B5_PACK16 and B5G5R5A1 (alpha in bit 15) is A1R5G5B5_PACK16. case DXGI_FORMAT_B5G6R5_UNORM: return {VK_FORMAT_R5G6B5_UNORM_PACK16, color}; case DXGI_FORMAT_B5G5R5A1_UNORM: return {VK_FORMAT_A1R5G5B5_UNORM_PACK16, color}; case DXGI_FORMAT_R8G8_UINT: return {VK_FORMAT_R8G8_UINT, color}; case DXGI_FORMAT_R8G8_SINT: return {VK_FORMAT_R8G8_SINT, color}; case DXGI_FORMAT_R16_FLOAT: return {VK_FORMAT_R16_SFLOAT, color}; case DXGI_FORMAT_R8_UNORM: return {VK_FORMAT_R8_UNORM, color}; case DXGI_FORMAT_R8_TYPELESS: return {VK_FORMAT_R8_UNORM, color, true}; case DXGI_FORMAT_R8_SNORM: return {VK_FORMAT_R8_SNORM, color}; case DXGI_FORMAT_R8_UINT: return {VK_FORMAT_R8_UINT, color}; case DXGI_FORMAT_R8_SINT: return {VK_FORMAT_R8_SINT, color}; case DXGI_FORMAT_R32_FLOAT: return {VK_FORMAT_R32_SFLOAT, color}; case DXGI_FORMAT_R32_UINT: return {VK_FORMAT_R32_UINT, color}; case DXGI_FORMAT_R32_SINT: return {VK_FORMAT_R32_SINT, color}; case DXGI_FORMAT_BC1_TYPELESS: return {VK_FORMAT_BC1_RGBA_UNORM_BLOCK, color, true}; case DXGI_FORMAT_BC1_UNORM: return {VK_FORMAT_BC1_RGBA_UNORM_BLOCK, color}; case DXGI_FORMAT_BC1_UNORM_SRGB: return {VK_FORMAT_BC1_RGBA_SRGB_BLOCK, color}; case DXGI_FORMAT_BC2_TYPELESS: return {VK_FORMAT_BC2_UNORM_BLOCK, color, true}; case DXGI_FORMAT_BC2_UNORM: return {VK_FORMAT_BC2_UNORM_BLOCK, color}; case DXGI_FORMAT_BC2_UNORM_SRGB: return {VK_FORMAT_BC2_SRGB_BLOCK, color}; case DXGI_FORMAT_BC3_TYPELESS: return {VK_FORMAT_BC3_UNORM_BLOCK, color, true}; case DXGI_FORMAT_BC3_UNORM: return {VK_FORMAT_BC3_UNORM_BLOCK, color}; case DXGI_FORMAT_BC3_UNORM_SRGB: return {VK_FORMAT_BC3_SRGB_BLOCK, color}; case DXGI_FORMAT_BC4_TYPELESS: return {VK_FORMAT_BC4_UNORM_BLOCK, color, true}; case DXGI_FORMAT_BC4_UNORM: return {VK_FORMAT_BC4_UNORM_BLOCK, color}; case DXGI_FORMAT_BC4_SNORM: return {VK_FORMAT_BC4_SNORM_BLOCK, color}; case DXGI_FORMAT_BC5_TYPELESS: return {VK_FORMAT_BC5_UNORM_BLOCK, color, true}; case DXGI_FORMAT_BC5_UNORM: return {VK_FORMAT_BC5_UNORM_BLOCK, color}; case DXGI_FORMAT_BC5_SNORM: return {VK_FORMAT_BC5_SNORM_BLOCK, color}; case DXGI_FORMAT_BC6H_TYPELESS: return {VK_FORMAT_BC6H_UFLOAT_BLOCK, color, true}; case DXGI_FORMAT_BC6H_UF16: return {VK_FORMAT_BC6H_UFLOAT_BLOCK, color}; case DXGI_FORMAT_BC6H_SF16: return {VK_FORMAT_BC6H_SFLOAT_BLOCK, color}; case DXGI_FORMAT_BC7_TYPELESS: return {VK_FORMAT_BC7_UNORM_BLOCK, color, true}; case DXGI_FORMAT_BC7_UNORM: return {VK_FORMAT_BC7_UNORM_BLOCK, color}; case DXGI_FORMAT_BC7_UNORM_SRGB: return {VK_FORMAT_BC7_SRGB_BLOCK, color}; case DXGI_FORMAT_D32_FLOAT: return {VK_FORMAT_D32_SFLOAT, d}; case DXGI_FORMAT_D16_UNORM: return {VK_FORMAT_D16_UNORM, d}; case xbox_d16s8: return {VK_FORMAT_D16_UNORM_S8_UINT, ds}; case xbox_d16_plane: return {VK_FORMAT_D16_UNORM_S8_UINT, d}; case xbox_s8_plane: return {VK_FORMAT_D16_UNORM_S8_UINT, VK_IMAGE_ASPECT_STENCIL_BIT}; case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return {VK_FORMAT_D32_SFLOAT_S8_UINT, ds}; case DXGI_FORMAT_D24_UNORM_S8_UINT: return {VK_FORMAT_D24_UNORM_S8_UINT, ds}; case DXGI_FORMAT_R32_TYPELESS: return depth ? Format{VK_FORMAT_D32_SFLOAT, d, true} : Format{VK_FORMAT_R32_SFLOAT, color, true}; case DXGI_FORMAT_R16_TYPELESS: return depth ? Format{VK_FORMAT_D16_UNORM, d, true} : Format{VK_FORMAT_R16_UNORM, color, true}; case DXGI_FORMAT_R32G8X24_TYPELESS: return {VK_FORMAT_D32_SFLOAT_S8_UINT, ds, true}; case DXGI_FORMAT_R24G8_TYPELESS: return {VK_FORMAT_D24_UNORM_S8_UINT, ds, true}; default: return {}; } } Format texture_storage_format(DXGI_FORMAT format, bool depth) { return vulkan_format(format == DXGI_FORMAT_A8_UNORM ? DXGI_FORMAT_R8_UNORM : format, depth); } // The three-channel format a view of a 96-bit texture names in its T# (GFX10_FORMAT_32_32_32_*): the format // whose channels the view's swizzle is taken from, so alpha reads as one whatever the image's fourth channel holds. VkFormat rgb96_named_format(VkFormat image_view_format) { switch (image_view_format) { case VK_FORMAT_R32G32B32A32_SFLOAT: return VK_FORMAT_R32G32B32_SFLOAT; case VK_FORMAT_R32G32B32A32_UINT: return VK_FORMAT_R32G32B32_UINT; case VK_FORMAT_R32G32B32A32_SINT: return VK_FORMAT_R32G32B32_SINT; default: return VK_FORMAT_UNDEFINED; } } // And back: the format of the view of the RGBA32 image that shows such a T#. VkFormat rgb96_view_format(VkFormat image_format, std::uint32_t gfx10_format) { for (const VkFormat wide : {VK_FORMAT_R32G32B32A32_SFLOAT, VK_FORMAT_R32G32B32A32_UINT, VK_FORMAT_R32G32B32A32_SINT}) if (leonida::gfx10::format_from_vulkan(rgb96_named_format(wide)) == gfx10_format) return rgb96_named_format(image_format) != VK_FORMAT_UNDEFINED ? wide : VK_FORMAT_UNDEFINED; return VK_FORMAT_UNDEFINED; } // Bytes per texel or block as D3D12 lays the format out in a footprint. leonida::BlockFormat footprint_block(const Format& format, VkImageAspectFlags aspect) { leonida::BlockFormat block = leonida::block_format(format.format, aspect); if (format.rgb96 && block.bytes) block.bytes = leonida::rgb96_bytes; return block; } // 96-bit textures are sampled and copied, nothing else yet: the flags creation refuses, and // GetResourceAllocationInfo with it. The PC runtime (WARP) refuses unordered access and depth too; it does make // 96-bit render targets (d3d12_rgb96_test prints both devices' answers). bool rgb96_refused(const D3D12_RESOURCE_DESC& desc) { return vulkan_format(desc.Format, false).rgb96 && (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); } // B8G8R8X8: the BGRA8 Vulkan formats with the alpha byte unused. Its typeless family is a family of its own, so // only a castable-format list lets a view cross between it and B8G8R8A8, although both land on the same VkFormat. bool alpha_unused(DXGI_FORMAT format) { return format == DXGI_FORMAT_B8G8R8X8_TYPELESS || format == DXGI_FORMAT_B8G8R8X8_UNORM || format == DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; } // The 8-bit four-channel UNORM and SRGB formats in either channel order, B8G8R8X8 included. A texture in one of them // takes an RTV in another when its castable-format list names it: WARP and AMD's D3D12 driver store the clear or the // draw in the view's channel order and encoding. bool rgba8_any_order(DXGI_FORMAT format) { switch (format) { case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return true; default: return false; } } // The full mip chain's length for a texture this size. UINT16 full_mips(UINT64 width, UINT height, UINT depth) { UINT16 mips = 0; for (UINT64 size = std::max({width, height, depth}); size; size >>= 1) ++mips; return mips; } // XR_BIAS is a display format: the PC runtime accepts it only as a single-mip, single-sample 2D texture, and // refuses 3D, extra mips and multisampling in creation, allocation and footprints alike. bool xr_bias_compatible(const D3D12_RESOURCE_DESC& desc) { if (desc.Format != DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM) return true; if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1) return false; const UINT mips = desc.MipLevels ? desc.MipLevels : full_mips(desc.Width, desc.Height, 1); return mips == 1; } // The Xbox tiled layout word (slot 76, docs/d3d12_vulkan.md section 4.2) is outside D3D12_TEXTURE_LAYOUT's // enumerators, so compare as an integer. constexpr UINT kXboxTiledLayout = 0x101; bool is_tiled_layout(D3D12_TEXTURE_LAYOUT layout) { return layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE || static_cast(layout) == kXboxTiledLayout; } // A volume RTV covers W slices of one mip. UINT_MAX extends through the last slice of that mip. leonida::TargetView volume_rtv(leonida::ResourceId id, const D3D12_RESOURCE_DESC& resource, const D3D12_RENDER_TARGET_VIEW_DESC* view) { if (!(resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || vulkan_format(resource.Format, false).typeless) return {}; if (view && (view->ViewDimension != D3D12_RTV_DIMENSION_TEXTURE3D || (view->Format != DXGI_FORMAT_UNKNOWN && view->Format != resource.Format))) return {}; const D3D12_TEX3D_RTV slices = view ? view->Texture3D : D3D12_TEX3D_RTV{0, 0, UINT_MAX}; if (slices.MipSlice >= resource.MipLevels) return {}; const UINT depth = std::max(1u, UINT(resource.DepthOrArraySize) >> slices.MipSlice); if (slices.FirstWSlice >= depth) return {}; const UINT remaining = depth - slices.FirstWSlice; const UINT count = slices.WSize == UINT_MAX ? remaining : slices.WSize; if (!count || count > remaining) return {}; return {id, slices.MipSlice, slices.FirstWSlice, count}; } leonida::TargetView line_target_view(leonida::ResourceId id, const D3D12_RESOURCE_DESC& resource, UINT mip, UINT first_layer, UINT layer_count) { if (resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D || mip >= resource.MipLevels || first_layer >= resource.DepthOrArraySize) return {}; const UINT remaining = UINT(resource.DepthOrArraySize) - first_layer; const UINT count = layer_count == UINT_MAX ? remaining : layer_count; if (!count || count > remaining) return {}; return {id, mip, first_layer, count}; } // ArraySize of a 2D-array RTV or DSV: UINT_MAX is every slice from the first on, as on the host. Any other count // is kept, and UINT_MAX with a first slice past the array too, so an out-of-range view is refused as before. UINT view_slices(const D3D12_RESOURCE_DESC& resource, UINT first_layer, UINT layer_count) { const bool remaining = layer_count == UINT_MAX && first_layer < resource.DepthOrArraySize; return remaining ? resource.DepthOrArraySize - first_layer : layer_count; } // 64-bit 2x32 color formats whose 2D UAVs receive an R64_UINT storage alias at set 0 binding 29 for 64-bit atomics. static bool is_r32g32_format(VkFormat format) { return format == VK_FORMAT_R32G32_UINT || format == VK_FORMAT_R32G32_SINT || format == VK_FORMAT_R32G32_SFLOAT; } // The VkImage a texture description becomes, with its mip count already resolved (MipLevels != 0). Shared by // texture creation and GetResourceAllocationInfo, so the sizes reported are the sizes later allocated. // Keeps the optional VkImageFormatListCreateInfo alongside VkImageCreateInfo so info.pNext stays valid. // attachment_usable: the GPU can render to `format`. A UAV texture then also gets COLOR_ATTACHMENT usage, because // ClearUnorderedAccessView* with rectangles clears through an attachment (vkCmdClearAttachments). struct TextureCreateInfo { VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; VkImageFormatListCreateInfo format_list{VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO}; std::array view_formats{}; TextureCreateInfo(const D3D12_RESOURCE_DESC& desc, const Format& format, bool attachment_usable, VkSampleCountFlags programmable_samples, bool r64ui_atomic_alias = false) { const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; info.flags = format.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; if (volume && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) info.flags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT; info.imageType = volume ? VK_IMAGE_TYPE_3D : one_d ? VK_IMAGE_TYPE_1D : VK_IMAGE_TYPE_2D; info.format = format.format; info.extent = {std::uint32_t(desc.Width), one_d ? 1u : desc.Height, volume ? UINT(desc.DepthOrArraySize) : 1u}; info.mipLevels = desc.MipLevels; info.arrayLayers = volume ? 1 : desc.DepthOrArraySize; info.samples = VkSampleCountFlagBits(std::max(1u, desc.SampleDesc.Count)); if ((programmable_samples & info.samples) && (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) info.flags |= VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT; info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; // No B8G8R8X8 view is ever a UAV, so its typeless family needs no storage usage (not every GPU has it for BGRA8). if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !alpha_unused(desc.Format)) { info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; if (!volume && info.samples == VK_SAMPLE_COUNT_1_BIT && attachment_usable) info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; } if (!(desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; if (format.uint_backed) { // The unsigned format owns the storage usage; views in the logical format restrict their usage (SAMPLED_BIT // for SRVs, COLOR_ATTACHMENT_BIT for RTVs). info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT; view_formats = {format.format, format.uint_backed}; format_list.viewFormatCount = 2; format_list.pViewFormats = view_formats.data(); info.pNext = &format_list; } else if (r64ui_atomic_alias && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && info.samples == VK_SAMPLE_COUNT_1_BIT && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && is_r32g32_format(format.format)) { // 64-bit image atomics (VK_EXT_shader_image_atomic_int64) bind a 2D VK_FORMAT_R64_UINT storage view of // R32G32_* UAVs at set 0 binding 29. EXTENDED_USAGE_BIT is required because R64_UINT supports // STORAGE_BIT but not SAMPLED_BIT or COLOR_ATTACHMENT_BIT. Typeless images keep no format list so all // 64-bit view formats remain legal; typed R32G32_* images list {format, R64_UINT}. info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT; if (!format.typeless) { view_formats = {format.format, VK_FORMAT_R64_UINT}; format_list.viewFormatCount = 2; format_list.pViewFormats = view_formats.data(); info.pNext = &format_list; } } } TextureCreateInfo(const TextureCreateInfo&) = delete; TextureCreateInfo& operator=(const TextureCreateInfo&) = delete; }; // The console descriptor heaps' ranges (Xbox slot 14): a descriptor table the title binds at a console VA inside one // is read by shaders at the console VA of its copy in the GPU address arena (DeviceState::add_console_heap). Process // wide, like the title's addresses; read by every SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable. class ConsoleHeapRanges { public: void add(std::uint64_t console_va, std::uint64_t bytes, std::uint64_t shader_va) { std::unique_lock lock(mutex_); ranges_.push_back({console_va, bytes, shader_va}); count_.store(ranges_.size(), std::memory_order_release); } void remove(std::uint64_t console_va) { std::unique_lock lock(mutex_); std::erase_if(ranges_, [console_va](const Range& r) { return r.console_va == console_va; }); count_.store(ranges_.size(), std::memory_order_release); } std::uint64_t shader_va(std::uint64_t va) const { if (!count_.load(std::memory_order_acquire)) return va; std::shared_lock lock(mutex_); for (const Range& r : ranges_) if (va >= r.console_va && va - r.console_va < r.bytes) return r.shader_va + (va - r.console_va); return va; } // The console heap holding `va`: its console VA and size. False when no console heap with a copy holds it. bool range_of(std::uint64_t va, std::uint64_t& console_va, std::uint64_t& bytes) const { if (!count_.load(std::memory_order_acquire)) return false; std::shared_lock lock(mutex_); for (const Range& r : ranges_) if (va >= r.console_va && va - r.console_va < r.bytes) { console_va = r.console_va; bytes = r.bytes; return true; } return false; } private: struct Range { std::uint64_t console_va, bytes, shader_va; }; mutable std::shared_mutex mutex_; std::vector ranges_; std::atomic count_{0}; }; ConsoleHeapRanges& console_heap_ranges() { static ConsoleHeapRanges ranges; return ranges; } // LEONIDA_CONSOLE_HEAP_SHADOW=0 keeps a console descriptor heap as it was before its arena copy existed: its bytes in // the title's memory only, where no shader reads them (the comparison for a run that misbehaves with the copy). bool console_heap_shadow_enabled() { static const bool enabled = [] { char text[4] = {}; size_t length = 0; return !(getenv_s(&length, text, "LEONIDA_CONSOLE_HEAP_SHADOW") == 0 && length > 1 && text[0] == '0'); }(); return enabled; } // What a T# the title wrote itself into a console descriptor heap came to (bind_title_image, after Resource). // not_tsharp: words with an image TYPE that do not decode as a T#: data, not a descriptor (the retail heap's last // 27 MiB are also the slot-133 pool, whose buffers sit there; T14 in ref/GAP-ANALYSIS-2.md). // TitleImage is defined in d3d12_com.h. class Resource; struct DeviceState; // `why`, when given, says what refused a T#: the first refusals are logged with their words (scan_console_slots). TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why = nullptr); // Why a T# found no room (bind_image_locked): set 0's array of its dimension, or that array's storage range, was full. // A console heap's slot record keeps such a T# waiting for room (DeviceState::fix_console_slot). constexpr const char* kTsharpArrayFull = "the bindless array of the T#'s dimension is full"; constexpr const char* kTsharpStorageFull = "the bindless storage arrays of the T#'s dimension are full"; // Why a T# found no texture (TitleImage::unknown), by what its address is (bind_title_image): the title's memory (a // texture the title placed there without any call the layer sees); an address of the layer's own textures // (Resource::image_address: 1 << 32 and up, 256 apart) whose texture is gone; an address whose low 32 bits are one of // those (the title rebuilt the T# with other high bits) and whose texture is there with the T#'s shape, there with // another shape, or gone; or none of these (no memory of the title's or texture of ours: data that decodes as a T#, // or an address the layer does not know). constexpr const char* kTsharpNoTextureTitleMemory = "no texture at the T# address: title memory"; constexpr const char* kTsharpNoTextureGone = "no texture at the T# address: a texture of ours that is gone"; constexpr const char* kTsharpNoTextureLow32Same = "no texture at the T# address: its low 32 bits name a texture of ours of its shape"; constexpr const char* kTsharpNoTextureLow32Other = "no texture at the T# address: its low 32 bits name a texture of ours of another shape"; constexpr const char* kTsharpNoTextureLow32Gone = "no texture at the T# address: its low 32 bits name a texture of ours that is gone"; constexpr const char* kTsharpNoTextureNothing = "no texture at the T# address: no title memory and no texture of ours"; struct TitleTexture; // a texture the title keeps in its own memory (TitleTexture, after Resource) // Overload returning the bindless index word (and optionally the bound owner's texture address when a high==0x10 // rebuilt T# matched a committed layer texture) under the same descriptor_mutex hold (null to skip). TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why, std::uint32_t* out_index_word, std::uint64_t* out_texture_address = nullptr); // The first refused T#s of each reason, with where they sit in the heap and their words, and counts of the // distinct slots refused overall and per reason (a slot is scanned again every pass over the heap). // Zero-allocation on the hot path: reasons are matched by pointer identity first (all runtime reasons are static // literals), with an owned string fallback for synthetic test strings. struct UnboundTsharpTracker { struct ReasonBucket { const char* literal = nullptr; std::string owned; std::unordered_set slots; std::uint64_t count = 0; unsigned logged = 0; }; std::mutex mutex; std::unordered_set total_slots; std::vector buckets; std::uint64_t total_refusals = 0; std::atomic capped{false}; bool is_capped() const noexcept { return capped.load(std::memory_order_acquire); } ReasonBucket& bucket_locked(const char* why) { const char* r = why ? why : "?"; for (ReasonBucket& b : buckets) { if (b.literal == r) return b; } for (ReasonBucket& b : buckets) { if (b.owned == r) return b; } ReasonBucket& b = buckets.emplace_back(); b.literal = r; b.owned = r; return b; } void note(std::uint64_t heap_va, std::size_t offset, const leonida::gfx10::ImageWords& words, const char* why) { std::lock_guard lock(mutex); ReasonBucket& b = bucket_locked(why); ++total_refusals; ++b.count; if (total_slots.size() >= 262144) { capped.store(true, std::memory_order_release); return; // enough to say how many } const bool fresh_overall = total_slots.insert(offset).second; if (total_slots.size() >= 262144) capped.store(true, std::memory_order_release); const bool fresh_reason = b.slots.insert(offset).second; if ((!fresh_overall && !fresh_reason) || b.logged >= 6) return; ++b.logged; std::fprintf(stderr, "[rt] d3d12: unbound T# in console heap 0x%llx at +0x%zx (%zu distinct slots so far, %zu for '%s'): %s: " "%08x %08x %08x %08x %08x %08x %08x %08x\n", static_cast(heap_va), offset, total_slots.size(), b.slots.size(), b.owned.c_str(), b.owned.c_str(), words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7]); } void note_capped(const char* why, std::uint64_t count) { if (!count) return; std::lock_guard lock(mutex); ReasonBucket& b = bucket_locked(why); total_refusals += count; b.count += count; } UnboundTsharpStats stats() { std::lock_guard lock(mutex); UnboundTsharpStats s; s.total_distinct_slots = total_slots.size(); s.total_refusals = total_refusals; for (const ReasonBucket& b : buckets) { s.by_reason[b.owned].distinct_slots = b.slots.size(); s.by_reason[b.owned].total_refusals = b.count; } return s; } void reset() { std::lock_guard lock(mutex); total_slots.clear(); buckets.clear(); total_refusals = 0; capped.store(false, std::memory_order_release); } }; UnboundTsharpTracker& unbound_tsharp_tracker() { static UnboundTsharpTracker tracker; return tracker; } // What a device's children need from it, kept apart from the COM class so children can hold a plain pointer. class Resource; leonida::VramBudget read_vram_budget(const VulkanDeviceInfo& info); // VK_EXT_memory_budget (defined below) struct DeviceState { std::mutex mapped_texture_mutex; std::set mapped_textures; std::atomic map_count{}; bool publish_mapped_textures(); std::mutex title_image_mutex; std::multimap title_images; VulkanDeviceInfo info; std::vector families; template void share(CreateInfo& create) const { leonida::share_across_queue_families(create, families); } std::unique_ptr context; // The blocks textures share (allocate_image). Freed after the context, whose deferred queue holds ranges of them. std::unique_ptr image_memory; VkPhysicalDeviceMemoryProperties memory{}; leonida::TitleImagePool title_image_pool; PFN_vkGetImageMemoryRequirements2 bound_image_requirements = nullptr; // D3D-96: upload-heap buffers prefer DEVICE_LOCAL | HOST_VISIBLE memory, so the GPU reads them from VRAM. Only // with Resizable BAR (leonida::resizable_bar); LEONIDA_UPLOAD_SYSMEM=1 keeps them in system memory to compare. bool upload_in_vram = false; // D3D-299: the first texture or default-heap buffer that lands outside device-local memory is logged, once. mutable std::once_flag spill_logged; // What D3D12_OPTIONS1 answers with: the physical device's own subgroup facts, read on first use. struct SubgroupFacts { UINT lane_min = 0; UINT lane_max = 0; bool wave_ops = false; }; SubgroupFacts subgroups; std::once_flag subgroups_once; // VkPhysicalDeviceMeshShaderPropertiesEXT, read on first use by a mesh PSO; zeros when it cannot be asked. VkPhysicalDeviceMeshShaderPropertiesEXT mesh_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT}; bool mesh_properties_read = false; std::mutex mesh_properties_mutex; PFN_vkGetPhysicalDeviceFormatProperties format_properties = nullptr; PFN_vkGetPhysicalDeviceImageFormatProperties image_format_properties = nullptr; PFN_vkGetPhysicalDeviceImageFormatProperties2 image_format_properties2 = nullptr; PFN_vkGetDeviceImageMemoryRequirements image_requirements = nullptr; // Vulkan 1.3 or VK_KHR_maintenance4 LUID luid{}; // VkPhysicalDeviceIDProperties::deviceLUID; zero when the driver reports none // An integrated GPU (VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU): D3D12_FEATURE_ARCHITECTURE answers UMA, the custom // heap equivalents are in MEMORY_POOL_L0 and custom heaps in L1 are refused, as the host runtime does there. bool uma = false; leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against // LEONIDA_PIPELINE_ORDER_LOG=1: which pipelines the title asks for first, appended to pipeline_order.log beside the // session cache (pipeline_order.h). Null when off: the pipelines then carry no hook at all. std::unique_ptr order_log; // LEONIDA_PIPELINE_PREWARM_ORDER= ("1": pipeline_order.log beside the session cache): the graphics pipelines an // earlier run asked for first, queued as warm-ups in that order when the title creates them (pipeline_prewarm.h). // Null when off. Read before start_order_log, which appends this run to the same file when both are on. std::unique_ptr prewarm_plan; void load_prewarm_plan() { namespace prewarm = leonida::pipeline_prewarm; wchar_t value[1024]{}; const DWORD n = GetEnvironmentVariableW(L"LEONIDA_PIPELINE_PREWARM_ORDER", value, DWORD(std::size(value))); if (n == 0 || n >= std::size(value) || (n == 1 && value[0] == L'0')) return; try { std::filesystem::path path = value; if (n == 1 && value[0] == L'1') { path = pipeline_cache_session_path(); if (path.empty()) { std::fprintf(stderr, "[rt] pipeline-prewarm: no session cache folder; nothing is prewarmed\n"); return; } path.replace_filename(L"pipeline_order.log"); } const auto count = [](const char* name, std::uint64_t fallback) { char text[32]{}; const DWORD m = GetEnvironmentVariableA(name, text, sizeof(text)); return prewarm::parse_count(m > 0 && m < sizeof(text) ? text : nullptr, fallback); }; prewarm::Options options; options.budget_ms = count("LEONIDA_PIPELINE_PREWARM_BUDGET_MS", prewarm::default_budget_ms); options.max_entries = std::size_t(count("LEONIDA_PIPELINE_PREWARM_MAX_ENTRIES", prewarm::default_max_entries)); auto plan = prewarm::load_plan(path, pso_identity.vendor, pso_identity.device, options); std::fprintf(stderr, "%s\n", plan.message.c_str()); if (plan) prewarm_plan = std::make_unique(std::move(plan)); } catch (const std::exception& e) { std::fprintf(stderr, "[rt] pipeline-prewarm: the order log could not be read (%s); nothing is prewarmed\n", e.what()); } } void start_order_log() { char text[8]{}; const DWORD n = GetEnvironmentVariableA("LEONIDA_PIPELINE_ORDER_LOG", text, sizeof(text)); if (n == 0 || n >= sizeof(text) || !leonida::pipeline_order::parse_enabled(text)) return; auto path = pipeline_cache_session_path(); if (path.empty()) return; path.replace_filename(L"pipeline_order.log"); leonida::pipeline_order::Recorder::Config config; config.path = std::move(path); config.vendor = pso_identity.vendor; config.device = pso_identity.device; config.now_ms = &order_now_ms; order_log = std::make_unique(std::move(config)); order_log->start(std::chrono::milliseconds(250)); } // The one line of counts, once: at the exit save or when the device goes, whichever comes first. void close_order_log() { if (!order_log) return; const std::string line = order_log->close(); if (line.empty()) return; if (order_log->failed()) std::fprintf(stderr, "[rt] pipeline-order: could not write %ls\n", order_log->path().c_str()); else std::fprintf(stderr, "%s\n", line.c_str()); } // Milliseconds since this process started. static std::uint32_t order_now_ms() { static const ULONGLONG started = [] { FILETIME created{}, exited{}, kernel{}, user{}; if (!GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user)) return ULONGLONG(0); return (ULONGLONG(created.dwHighDateTime) << 32) | created.dwLowDateTime; }(); FILETIME now{}; GetSystemTimeAsFileTime(&now); const ULONGLONG t = (ULONGLONG(now.dwHighDateTime) << 32) | now.dwLowDateTime; return started && t > started ? std::uint32_t(std::min((t - started) / 10000, 0xfffffffeull)) : 0; } std::once_flag pipeline_cache_once; VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE; // The shared cache started from a file (the offline seed or an earlier session): a compute pipeline the journal // has no file for may still be in it (build_compute asks it first, when it can ask without a compile). bool pipeline_cache_seeded = false; std::atomic journal_hits{0}, journal_writes{0}, journal_shared_hits{0}; std::atomic journal_bytes{0}; // on disk: counted at the cache's creation, then added to std::uint64_t journal_budget = leonida::pipeline_journal::default_budget; // Ask the shared cache first, with FAIL_ON_PIPELINE_COMPILE_REQUIRED, while the driver honours it. // LEONIDA_PIPELINE_JOURNAL_ASK_SHARED=0: never. std::atomic journal_ask_shared{[] { wchar_t value[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL_ASK_SHARED", value, 2) == 1 && value[0] == L'0'); }()}; std::atomic next_checkpoint{GetTickCount64() + 120000}; std::atomic active_compiles{0}; VkPipelineCache pipeline_cache() { std::call_once(pipeline_cache_once, [this] { const auto& vk = context->vk; if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return; if (pipeline_cache_save_limit()) clean_stale_cache_files(pipeline_cache_session_path()); // A build host (precompile, compile helper) journals every pipeline: no seed, no session file. if (!compile_helper::build_host) pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity); if (pipeline_cache_handle) { pipeline_cache_seeded = true; merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); } else if (pipeline_cache_save_limit() && direct_session_cache() && !compile_helper::build_host) { // With no offline seed the session file can initialize the actual cache directly. pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity, true); pipeline_cache_seeded = pipeline_cache_handle != VK_NULL_HANDLE; } if (!pipeline_cache_handle) { const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) pipeline_cache_handle = VK_NULL_HANDLE; else if (!direct_session_cache() && !compile_helper::build_host) pipeline_cache_seeded = merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); } note_pipeline_cache_size(vk, info.device, pipeline_cache_handle); if (!pipeline_journal_dir().empty()) { char text[32] = {}; size_t length = 0; if (getenv_s(&length, text, "LEONIDA_PIPELINE_JOURNAL_BYTES") == 0 && length > 1) { const auto budget = leonida::pipeline_cache_store::parse_save_limit(text); if (budget.valid) journal_budget = budget.bytes; } // Old staging files out, and the least recently used files when over the budget: translator // regenerations leave files no build names any more. const auto tidy = leonida::pipeline_journal::tidy(pipeline_journal_dir(), journal_budget); journal_bytes = tidy.bytes; if (tidy.evicted || tidy.swept) std::fprintf(stderr, "[rt] d3d12: pipeline journal: removed %zu least recently used file(s) over " "the %llu-byte budget and %zu stale staging file(s); %zu file(s), %llu bytes " "left\n", tidy.evicted, static_cast(journal_budget), tidy.swept, tidy.entries, static_cast(tidy.bytes)); } if (!pipeline_journal_dir().empty()) std::fprintf(stderr, "[rt] d3d12: compute pipelines are journaled one file each in %ls\n", pipeline_journal_dir().c_str()); if (compile_helper::enabled() && !pipeline_journal_dir().empty()) compile_helper::Client::instance().prestart(); }); // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache. return pipeline_cache_handle; } // The heavy pipeline cache (src/heavy_pipeline_cache.h) and the thread that writes it. std::once_flag heavy_cache_once; VkPipelineCache heavy_cache_handle = VK_NULL_HANDLE; std::mutex heavy_mutex; std::condition_variable heavy_wake; leonida::heavy_pipeline_cache::WriteSchedule heavy_schedule; // under heavy_mutex bool heavy_stop = false; // under heavy_mutex std::thread heavy_writer; // started at the first slow build std::atomic heavy_compiles{0}, heavy_hits{0}; std::atomic heavy_changed{false}; // a build went into the heavy cache since it was loaded VkPipelineCache heavy_cache() { std::call_once(heavy_cache_once, [this] { if (context->vk.vkCreatePipelineCache) heavy_cache_handle = create_heavy_pipeline_cache(context->vk, info.device, pso_identity); }); return heavy_cache_handle; } // A build past the offline cache took `took_ms`: a slow one schedules a write. void note_heavy_build(ULONGLONG took_ms) { heavy_changed = true; if (took_ms < heavy_pipeline_cache_ms()) { ++heavy_hits; return; } ++heavy_compiles; std::lock_guard lock(heavy_mutex); if (heavy_stop) return; heavy_schedule.note_heavy(GetTickCount64()); if (!heavy_writer.joinable()) { try { heavy_writer = std::thread([this] { write_heavy_cache_loop(); }); } catch (const std::exception&) { return; // no thread: the cache is still written at teardown } } heavy_wake.notify_one(); } void write_heavy_cache_loop() { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); std::unique_lock lock(heavy_mutex); while (!heavy_stop) { if (!heavy_schedule.dirty()) { heavy_wake.wait(lock); continue; } const std::uint64_t now = GetTickCount64(); if (!heavy_schedule.due(now)) { heavy_wake.wait_for(lock, std::chrono::milliseconds(heavy_schedule.due_ms() - now)); continue; } const std::uint64_t generation = heavy_schedule.generation(); lock.unlock(); const bool saved = save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, heavy_compiles.load(), heavy_hits.load()); lock.lock(); // A failed write leaves the cache dirty: it is tried again after a growing delay, not only at teardown. if (saved) heavy_schedule.written(generation, now); else heavy_schedule.failed(now); } } // At device teardown, with no build running: stop the writer and write the cache if any build went into it. // Fast builds never schedule a write, so this is where they are kept: without an offline seed every build is // a miss, and these are the builds pipeline_cache.session.bin used to keep. void finish_heavy_cache() { { std::lock_guard lock(heavy_mutex); heavy_stop = true; } heavy_wake.notify_all(); if (heavy_writer.joinable()) heavy_writer.join(); if (!heavy_cache_handle) return; if (heavy_changed.load() && !active_compiles.load()) save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, heavy_compiles.load(), heavy_hits.load()); context->vk.vkDestroyPipelineCache(info.device, heavy_cache_handle, nullptr); heavy_cache_handle = VK_NULL_HANDLE; } // vkCreateGraphicsPipelines through `create(cache, flags)` (compute pipelines have their journal). With the heavy // cache, the offline cache is asked first without compiling; a pipeline it does not have is built against the heavy // cache, which a slow build then writes back to disk. A caller that already asked for a cache-only create keeps it. template VkResult create_pipeline(VkPipelineCreateFlags flags, Create&& create) { constexpr VkPipelineCreateFlags cache_only = VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT; const VkPipelineCache corpus = pipeline_cache(); if (!info.heavy_pipeline_cache || (flags & cache_only)) return create(corpus, flags); const VkResult cached = create(corpus, flags | cache_only); if (cached != VK_PIPELINE_COMPILE_REQUIRED) return cached; const VkPipelineCache heavy = heavy_cache(); const ULONGLONG started = GetTickCount64(); const VkResult built = create(heavy ? heavy : corpus, flags); if (built == VK_SUCCESS && heavy) note_heavy_build(GetTickCount64() - started); return built; } QueueClock clock; // device-wide calibration entry points std::vector timestamp_bits; QueueClock clock_for(std::uint32_t family) const { QueueClock result = clock; result.timestamp_valid_bits = leonida::queue_family_timestamp_bits(timestamp_bits, family); return result; } bool copy_timestamps_supported() const { // Copy queues can fall back to a graphics queue when their own pool is busy. const bool has_copy_pool = !info.command_queues.empty() && !info.copy_queues.empty(); const auto dedicated_copy = has_copy_pool ? std::optional{info.copy_family} : std::nullopt; return context->timestamp_period() > 0 && leonida::copy_queue_timestamp_families_supported( timestamp_bits, info.queue_family, dedicated_copy); } PFN_vkGetPhysicalDeviceFormatProperties2 format_properties2 = nullptr; // True when VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 lacks native STORAGE_IMAGE but mutable R32_UINT+{R32_UINT,E5B9G9R9} // is supported, so R9G9B9E5_SHAREDEXP UAV textures are backed by R32_UINT with separate storage/sampled views. bool r9g9b9e5_uav_emulated = false; // The same for B5G5R5A1_UNORM: VK_FORMAT_A1R5G5B5_UNORM_PACK16 without STORAGE_IMAGE, backed by mutable R16_UINT. bool b5g5r5a1_uav_emulated = false; // True when the GPU cannot render to VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 but can render and store to // VK_FORMAT_B10G11R11_UFLOAT_PACK32: an R9G9B9E5_SHAREDEXP texture that allows render targets is then an // R11G11B10F image of the same texel size, viewed in that format by every RTV, SRV, UAV and T#, and pipelines // that name R9G9B9E5 as a target format render in it (console_format_stand_ins). Its contents were rendered or // stored, never uploaded, so the different bit layout is not visible to the title's shaders. bool r9g9b9e5_target_stand_in = false; // True when VK_FORMAT_R8G8B8A8_SRGB (B8G8R8A8_SRGB) has no STORAGE_IMAGE support but its UNORM twin does: an sRGB // texture that allows unordered access is a mutable UNORM image (Format::uint_backed names the sRGB format its // SRVs and RTVs use), and its storage views write the UNORM bits unconverted, as the console does. bool rgba8_srgb_uav_emulated = false; bool bgra8_srgb_uav_emulated = false; // Cached physical-device no-attachment sample counts for D3D12_OPTIONS19. UINT no_output_sample_counts = 0; std::uint32_t max_compute_shared_memory_size = 0; std::uint32_t f16_half_top_location = 29; float max_sampler_lod_bias = 0; // Shared VkPipelineLayout cache keyed by (push_stages, push_bytes, with_bindless). // Avoids creating tens of thousands of identical layouts concurrently across slot 57/67 threads. struct SharedLayoutKey { VkShaderStageFlags push_stages = 0; std::uint32_t push_bytes = 0; bool with_bindless = false; auto operator<=>(const SharedLayoutKey&) const = default; }; std::mutex shared_layout_mutex; std::map shared_pipeline_layouts; VkPipelineLayout shared_pipeline_layout(VkShaderStageFlags push_stages, std::uint32_t push_bytes, bool with_bindless) { std::lock_guard lock(shared_layout_mutex); const SharedLayoutKey key{push_stages, push_bytes, with_bindless}; if (const auto it = shared_pipeline_layouts.find(key); it != shared_pipeline_layouts.end()) return it->second; if (!context || !context->vk.vkCreatePipelineLayout) return VK_NULL_HANDLE; const VkPushConstantRange push{push_stages, 0, push_bytes}; VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; VkDescriptorSetLayout set0_layout = VK_NULL_HANDLE; if (with_bindless) { if (!bindless) return VK_NULL_HANDLE; set0_layout = bindless->layout(); layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set0_layout; } VkPipelineLayout layout = VK_NULL_HANDLE; if (context->vk.vkCreatePipelineLayout(info.device, &layout_info, nullptr, &layout) != VK_SUCCESS) return VK_NULL_HANDLE; shared_pipeline_layouts.emplace(key, layout); return layout; } D3D12_CONSERVATIVE_RASTERIZATION_TIER conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED; VkSampleCountFlags sample_grid_1 = 0, sample_grid_4 = 0; D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER sample_positions_tier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED; bool conservative_post_depth_coverage = false; // VkPhysicalDeviceDepthStencilResolveProperties: the modes a depth or stencil ResolveSubresourceRegion can use. VkResolveModeFlags depth_resolve_modes = 0; VkResolveModeFlags stencil_resolve_modes = 0; // VK_EXT_host_image_copy; null unless the device enabled it and its copies accept GENERAL. PFN_vkCopyMemoryToImageEXT copy_memory_to_image = nullptr; PFN_vkCopyImageToMemoryEXT copy_image_to_memory = nullptr; PFN_vkTransitionImageLayoutEXT transition_image_layout = nullptr; // VK_EXT_external_memory_host; null unless info.host_pointer_alignment is set and the entry point loaded. PFN_vkGetMemoryHostPointerPropertiesEXT get_host_pointer_properties = nullptr; // Slot-133 imports whose memory is allocated (create_host_buffer), for title_host_imports. std::atomic host_imports{0}; // The live shadow buffers of Xbox device slot 133 (Resource::create_shadow_buffer): title-placed buffers whose // pages the driver would not import. Each is brought up to date from the title's pages before every submission // of command lists (VulkanContext::set_before_execute), copying only what the title wrote since the last one // (ShadowPages). The title windows below are refreshed with them. The first refresh is logged with what it cost, // then the refreshes of every 5 seconds. mutable std::mutex shadow_mutex; // nothing else is taken under it but the ShadowPages' own locks std::vector shadows; std::uint64_t shadow_submissions = 0; std::uint64_t shadow_logged = 0; // shadow_submissions at the last log line std::chrono::steady_clock::time_point shadow_log_time{}; std::uint64_t shadow_bytes = 0; // copied since the last log line std::uint64_t shadow_queries = 0; // VirtualQuery calls since the last log line std::uint64_t shadow_protects = 0; // VirtualProtect calls since the last log line std::uint64_t shadow_walks = 0; // trackers that queried every page (the title memory map changed), likewise std::uint64_t shadow_asks = 0; // GetWriteWatch calls, likewise std::uint64_t shadow_written = 0; // write-watched pages they found written, likewise std::array shadow_copy_bytes{}; // by cause, likewise ShadowPages::Pieces shadow_pieces; // summed over the refreshes since the last log line std::chrono::steady_clock::time_point shadow_alias_time{}; // the last refresh that copied aliased pages double shadow_ms = 0; // spent since the last log line double shadow_max_ms = 0; // the longest refresh since the last log line double heap_ms = 0; // spent in refresh_console_heaps since the last log line std::uint64_t shadow_faults = 0; // the write faults counted at the last log line // Persistent 3-worker pool (+ caller thread = 4 threads) to parallelize ShadowPages::refresh across independent // trackers (shadow_keep hashing, memcpy, arena_mark_dirty_ptr). Declared after `shadows` so it joins first. struct ShadowRefreshPool { static constexpr std::size_t kHelpers = 3; static constexpr std::size_t kChunk = 32; std::mutex mu; std::condition_variable cv_work, cv_done; std::vector threads; const std::vector* list = nullptr; bool copy_aliased = true; std::atomic next{0}; std::atomic copied{0}; std::size_t epoch = 0; std::size_t active = 0; bool stop = false; ~ShadowRefreshPool() { { std::lock_guard lock(mu); stop = true; ++epoch; } cv_work.notify_all(); for (auto& t : threads) if (t.joinable()) t.join(); } void run_chunk(const std::vector& s_list, bool aliased) { const std::size_t n = s_list.size(); std::uint64_t local_copied = 0; for (;;) { const std::size_t begin = next.fetch_add(kChunk, std::memory_order_relaxed); if (begin >= n) break; const std::size_t end = std::min(begin + kChunk, n); for (std::size_t i = begin; i < end; ++i) local_copied += s_list[i]->refresh(aliased); } if (local_copied) copied.fetch_add(local_copied, std::memory_order_relaxed); } std::uint64_t run(const std::vector& s_list, bool aliased) { if (s_list.size() < kChunk * 2) { std::uint64_t total = 0; for (const ShadowPagesPtr& s : s_list) total += s->refresh(aliased); return total; } { std::lock_guard lock(mu); if (threads.empty()) { threads.reserve(kHelpers); for (std::size_t i = 0; i < kHelpers; ++i) { threads.emplace_back([this] { std::size_t seen = 0; for (;;) { const std::vector* cur = nullptr; bool ca = true; { std::unique_lock lk(mu); cv_work.wait(lk, [&] { return stop || epoch != seen; }); if (stop) return; seen = epoch; cur = list; ca = copy_aliased; } run_chunk(*cur, ca); std::lock_guard lk(mu); if (--active == 0) cv_done.notify_one(); } }); } } list = &s_list; copy_aliased = aliased; next.store(0, std::memory_order_relaxed); copied.store(0, std::memory_order_relaxed); active = threads.size(); ++epoch; } cv_work.notify_all(); run_chunk(s_list, aliased); { std::unique_lock lk(mu); cv_done.wait(lk, [&] { return active == 0; }); } return copied.load(std::memory_order_relaxed); } } shadow_refresh_pool; // A copy of the title's bytes [pages, pages + size) at `shadow`: filled now, then brought up to date before every // submission. Copies whose pages overlap or touch share one tracker (ShadowPages: a page has one owner that may // watch it), so a copy that reaches one or more trackers joins them into one. void add_shadow(const std::uint8_t* pages, std::uint8_t* shadow, std::size_t size) { constexpr std::uintptr_t kPage = ShadowPages::kPage; const auto begin = reinterpret_cast(pages), end = begin + size; const std::uintptr_t first = begin & ~(kPage - 1), last = (end + kPage - 1) & ~(kPage - 1); std::lock_guard lock(shadow_mutex); std::vector hits; // ascending std::uintptr_t lo = first, hi = last; for (std::size_t i = 0; i < shadows.size(); ++i) if (shadows[i]->first() <= last && first <= shadows[i]->last()) { hits.push_back(i); lo = std::min(lo, shadows[i]->first()); hi = std::max(hi, shadows[i]->last()); } if (hits.empty()) { ShadowPagesPtr tracker = make_shadow_pages(pages, shadow, size); tracker->set_dirty_hook(this, &DeviceState::shadow_mark_dirty); tracker->refresh(); shadows.push_back(std::move(tracker)); return; } ShadowPages& keep = *shadows[hits.front()]; // The fault handler is kept out while the pages change hands: it finds them in `keep` from then on, with // what the others knew of them (the pages they made read-only stay so, now `keep`'s). AcquireSRWLockExclusive(&g_shadow_pages_lock); keep.extend(lo, hi); for (std::size_t k = 1; k < hits.size(); ++k) { ShadowPages* other = shadows[hits[k]].get(); keep.absorb(*other); std::erase(shadow_pages_list(), other); } keep.add_target(begin, end, shadow); ReleaseSRWLockExclusive(&g_shadow_pages_lock); for (std::size_t k = hits.size(); k-- > 1;) shadows.erase(shadows.begin() + std::ptrdiff_t(hits[k])); keep.fill(begin, end, shadow); } void retire_shadow(const std::uint8_t* mapped) { std::lock_guard lock(shadow_mutex); for (const ShadowPagesPtr& s : shadows) if (s->retire_target(mapped)) return; } // A retired window's memory is freed: what its copy holds that the title's pages do not, written by submissions // that have all completed, goes back once more (where no live copy changed those bytes), then the copy leaves // its tracker. void free_retired_shadow(const std::uint8_t* mapped, std::uint64_t start, std::uint64_t size) { std::lock_guard lock(shadow_mutex); for (auto it = shadows.begin(); it != shadows.end(); ++it) { ShadowPages& s = **it; if (!s.has_target(mapped)) continue; const std::pair range{static_cast(start), static_cast(start + size)}; ShadowPages::ReadbackLookup rebar_lookup{}; if (arena.staged) { std::vector readbacks; std::map> ext_readbacks; collect_staged_shadow_readbacks(s, &range, 1, mapped, readbacks, ext_readbacks); sync_retired_readbacks_to_host(readbacks, ext_readbacks); } else { prepare_rebar_readbacks( [&](const auto& add) { s.for_each_target_range(&range, 1, mapped, add); }, rebar_lookup); } title_write_back_total += s.write_back(&range, 1, nullptr, mapped, rebar_lookup.count ? &rebar_lookup : nullptr); s.remove_target(mapped); if (!s.targets()) shadows.erase(it); return; } } void remove_shadow(const std::uint8_t* mapped) { std::lock_guard lock(shadow_mutex); for (auto it = shadows.begin(); it != shadows.end(); ++it) if ((*it)->remove_target(mapped)) { if (!(*it)->targets()) shadows.erase(it); return; } } // heaps / pages: whether this submission refreshes the console heaps and the slot-133 shadows and title windows // (LEONIDA_REFRESH_PER_FRAME leaves some submissions without them). void refresh_shadows(bool heaps = true, bool pages = true) { using clock = std::chrono::steady_clock; // First, and without shadow_mutex: fixing a console heap's slots can make a title window (add_shadow). const auto heaps_start = clock::now(); if (heaps) { const leonida::submit_phases::Scope timed(leonida::submit_phases::heaps); refresh_console_heaps(); } heap_ms += std::chrono::duration(clock::now() - heaps_start).count(); probe_census(); // LOCAL DIAGNOSTIC if (!pages) return; const leonida::submit_phases::Scope timed(leonida::submit_phases::shadows); std::unique_lock lock(shadow_mutex, std::defer_lock); leonida::submit_phases::lock_timed(lock); if (shadows.empty()) return; const auto start = clock::now(); // LEONIDA_SHADOW_ALIAS_MS (0 by default: every submission): pages xmem maps at two addresses that a write // reached, or whose cells can't be armed (ShadowPages::update_aliased), are copied at most this often. After // the story load they were 59 MiB a submission (speed-6), copied every time; a GPU read of them is at most // this many milliseconds behind the title's writes. static const auto alias_period = std::chrono::milliseconds([] { char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_SHADOW_ALIAS_MS", text, sizeof(text)); return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 0ull; }()); const bool copy_aliased = alias_period.count() == 0 || start - shadow_alias_time >= alias_period; if (copy_aliased) shadow_alias_time = start; const std::uint64_t copied = shadow_refresh_pool.run(shadows, copy_aliased); if (copied) leonida::submit_phases::note_change(leonida::submit_phases::change_pages); // not a floor one for (const ShadowPagesPtr& s : shadows) { shadow_queries += s->refresh_queries(); shadow_protects += s->refresh_protects(); shadow_walks += s->refresh_walked_all(); shadow_asks += s->refresh_asks(); shadow_written += s->refresh_written(); for (unsigned k = 0; k < shadow_copy_bytes.size(); ++k) shadow_copy_bytes[k] += s->copy_bytes()[k]; const ShadowPages::Pieces& p = s->pieces(); shadow_pieces.pieces += p.pieces; shadow_pieces.short_pieces += p.short_pieces; shadow_pieces.joinable += p.joinable; shadow_pieces.calls += p.calls; shadow_pieces.gpu_calls += p.gpu_calls; shadow_pieces.walk_ms += p.walk_ms; shadow_pieces.copy_ms += p.copy_ms; } const auto now = clock::now(); const double ms = std::chrono::duration(now - start).count(); shadow_ms += ms; shadow_max_ms = std::max(shadow_max_ms, ms); shadow_bytes += copied; ++shadow_submissions; if (shadow_submissions != 1 && now - shadow_log_time < std::chrono::seconds(5)) return; std::uint64_t size = 0, faults = 0, copies = 0, watched = 0, hot = 0; for (const ShadowPagesPtr& s : shadows) size += s->size(), faults += s->faults(), copies += s->targets(), watched += s->watched_bytes(), hot += s->hot_bytes(); const double count = double(shadow_submissions - shadow_logged); std::fprintf(stderr, "[rt] d3d12: slot-133 shadow buffers and title windows (%llu KiB in %llu copies, %zu trackers, " "%zu title windows; %llu KiB of pages write-watched, %llu KiB hot): submissions %llu-%llu copied %.1f KiB each " "from the title's pages in %.3f ms on average (%.3f max; console heaps %.3f ms), %.1f VirtualQuery, " "%.1f VirtualProtect and %.1f GetWriteWatch calls (%.1f pages found written) and %.1f trackers " "walked in full per refresh, %llu write faults\n", static_cast(size / 1024), static_cast(copies), shadows.size(), title_window_count.load(std::memory_order_relaxed), static_cast(watched / 1024), static_cast(hot / 1024), static_cast(shadow_logged + 1), static_cast(shadow_submissions), double(shadow_bytes) / 1024.0 / count, shadow_ms / count, shadow_max_ms, heap_ms / count, double(shadow_queries) / count, double(shadow_protects) / count, double(shadow_asks) / count, double(shadow_written) / count, double(shadow_walks) / count, static_cast(faults >= shadow_faults ? faults - shadow_faults : faults)); const auto kib = [&](ShadowPages::Copy c) { return double(shadow_copy_bytes[unsigned(c)]) / 1024.0 / count; }; std::fprintf(stderr, "[rt] d3d12: slot-133 shadow copies by cause, KiB a submission: guarded now %.1f, unguarded %.1f, " "aliased %.1f, pinned %.1f, read-only (not ours) %.1f, copy-on-write %.1f, write-watched %.1f\n", kib(ShadowPages::Copy::guarded), kib(ShadowPages::Copy::unguarded), kib(ShadowPages::Copy::aliased), kib(ShadowPages::Copy::pinned), kib(ShadowPages::Copy::read_only), kib(ShadowPages::Copy::copy_on_write), kib(ShadowPages::Copy::write_watched)); std::fprintf(stderr, "[rt] d3d12: slot-133 shadow copies as pieces, a refresh: %.1f pieces (%.1f under 4 KiB, %.1f going on " "where the one before ended), %.1f copy calls (%.1f offered to the GPU); walk %.3f ms, copies %.3f " "ms\n", double(shadow_pieces.pieces) / count, double(shadow_pieces.short_pieces) / count, double(shadow_pieces.joinable) / count, double(shadow_pieces.calls) / count, double(shadow_pieces.gpu_calls) / count, shadow_pieces.walk_ms / count, shadow_pieces.copy_ms / count); shadow_pieces = {}; shadow_copy_bytes = {}; shadow_logged = shadow_submissions; shadow_log_time = now; shadow_bytes = shadow_queries = shadow_protects = shadow_walks = shadow_asks = shadow_written = 0; shadow_ms = shadow_max_ms = heap_ms = 0; shadow_faults = faults; } // Textures the title keeps in its own memory, by the GPU address it names them by (Device:: // write_placed_texture_view, register_title_texture, refresh_title_textures): the slot-133 textures and the // images made for slot-70 views of memory no resource covers. title_texture_mutex is taken before // descriptor_mutex. A slot-133 texture tells the registry when the title maps it and when it goes; both are // defined after TitleTexture. std::mutex title_texture_mutex; std::map> title_textures; VkDeviceSize title_partial_bytes = 0; // image memory of textures filled in part, under title_texture_mutex void clear_partial_budget(TitleTexture& t); // Which registered textures may have changed since their last fill (title_texture_watch.h), under // title_texture_mutex: their tiles are geometry-watch cells, armed read-only. TitleTextureCells texture_cells; leonida::TitleTextureWatch texture_watch{texture_cells}; void index_texture(const TitleTexture& t); struct TitleMirrorCheckItem { std::uint64_t cpu = 0; std::uint64_t gpu = 0; std::uint64_t bytes = 0; const std::vector* written_tiles = nullptr; // non-null when per-tile sync filtering allowed const std::vector* tile_cmp_written = nullptr; // non-null when partial-tile mirror cmp allowed const leonida::TilePieces* pieces = nullptr; std::uint64_t max_version = 0; bool ex_armed = false; bool active = false; // Outputs filled by page_mirror_check_batch(): bool full_ok = false; bool single_chunk = false; VkBuffer buffer = VK_NULL_HANDLE; VkDeviceSize offset = 0; VkDeviceSize chunk_size = 0; VkSemaphore timeline = VK_NULL_HANDLE; std::uint64_t value = 0; std::uint64_t mirror_hash = 0; int tile_cmp = 0; // +1 unchanged, -1 changed, 0 unknown/fallback // Why try_full_view() rejected this item (for cpu_fallback_by[6] telemetry): // 0 = none/accepted, 1 = unmirrored_plain, 2 = unmirrored_other, 3 = in_feed, 4 = pending_bind std::uint8_t reject_reason = 0; // Internal scratch for page_mirror_check_batch(): enum class Mode : std::uint8_t { none, full, partial_tiles } mode = Mode::none; std::uint64_t mirror_va = 0; }; void page_mirror_check_batch(std::vector& items, std::vector& feed_pages, std::uint64_t mirror_synced_serial = 0, const std::function)>& parallel_run = {}); // The CPU-view ranges of the registered GPU-written textures (render targets, depth, unordered access), by their // registry address. A texture over such memory is not filled from it (index_texture): the title's pages there // hold what the CPU last put there, never what our GPU renders into the image, and a fill uploaded those old // bytes, in 64 KiB pieces as write-backs and neighbours' writes marked their tiles written. Under // title_texture_mutex. struct GpuOwned { std::uint64_t address = 0; // the registry address it was placed at std::uintptr_t begin = 0, end = 0; }; std::map gpu_owned; // by the GPU-written resource std::uint64_t gpu_owned_refusals = 0; bool over_gpu_owned(std::uintptr_t begin, std::uintptr_t end) const { for (const auto& [owner, range] : gpu_owned) if (range.begin < end && begin < range.end) return true; return false; } void add_gpu_owned(const void* owner, std::uint64_t address, std::uintptr_t cpu, std::uint64_t span); // The GPU-written resource is gone: the texture registered at its address (one kept there while the target // covered it) is filled from memory again, and the T#s naming the address find it. void drop_gpu_owned(const void* owner); // T#s and slot-70 views at an address a GPU-written texture covers: resolved to its image, and the other textures' // that could not be, by why (bind_title_image, place_title_view). Logged by the title texture refresh. enum { kOverTargetResolved, kOverTargetFormat, kOverTargetExtent, kOverTargetRange, kOverTargetKinds }; std::array, kOverTargetKinds> over_gpu_target{}; // Textures named by their first descriptor since the last refresh (Resource::note_shader_view; any thread, under // any lock: this one is a leaf). std::mutex titles_named_mutex; std::vector titles_named; std::vector> titles_view_mips; std::atomic titles_named_pending{false}; void title_texture_named(std::uint64_t address) { std::lock_guard lock(titles_named_mutex); titles_named.push_back(address); titles_named_pending.store(true, std::memory_order_release); } void title_texture_view_mip(std::uint64_t address, std::uint32_t min_mip) { std::lock_guard lock(titles_named_mutex); titles_view_mips.emplace_back(address, min_mip); titles_named_pending.store(true, std::memory_order_release); } void title_texture_mapped(const void* resource, std::uint64_t address); void title_texture_unmapped(const void* resource, std::uint64_t address); // the title wrote texels void title_texture_gone(const void* resource, std::uint64_t address); // Textures destroyed while their thread held title_texture_mutex (inside the registry, t_in_title_textures): a // descriptor it overwrote held the last reference. Their GPU placement is removed at once; title_texture_gone // cannot take the registry mutex again there (MSVC's // std::mutex throws resource_deadlock_would_occur, which Wine's msvcp140 aborts on), so their entries only stop // naming the resource and are removed by drain_titles_gone once the mutex is free. Under title_texture_mutex. std::vector> titles_gone; std::atomic titles_gone_pending{false}; void drain_titles_gone(); // Windows of the title's own memory in the GPU address arena (src/title_va_alias.h, docs/d3d12_vulkan.md // section 3.3 "Title-chosen addresses"): a root view or buffer V# that names the title's memory outside any // slot-133 buffer (a per-frame constant ring, #8862 section 3.5) gets a copy of the 64 KiB-aligned pages it // covers, refreshed before every submission like a slot-133 shadow, and the address of that copy. A window never // covers bytes an existing range already serves (it stays inside the free span, in both views of a stream pool), // and is kept while an address range still answers from it (the ring comes round to the same pages), up to // LEONIDA_TITLE_WINDOWS_MB (64 MiB by default); one a newer range replaced everywhere is retired // (retire_orphan_windows). A window that does not fit is not made: the range is backed by a geometry copy // instead, or the view written with a zero-size range (src/title_window_plan.h). struct TitleWindow { std::uint64_t start; std::uint64_t shader_va; std::uint64_t size; std::uint8_t* mapped; // the copy, as the tracker of its pages writes it }; static constexpr std::uint64_t kTitleWindowAlign = 65536; static constexpr std::uint64_t kTitleWindowMax = 16ull << 20; // the most one address pulls in // One mapping serves this much of a stream pool: the readable run of a 16-24 GiB reservation, whose frames the // title remaps per request, so a whole-pool allocation is not possible. static constexpr std::uint64_t kPoolExtentMax = 1ull << 20; std::mutex title_window_mutex; // taken before shadow_mutex, never under it std::mutex external_windows_mutex; // leaf lock around external_windows mutate/lookup (ordered after title_window_mutex) rt::d3d12::TitleBufferWindows external_windows; struct DeferredExternalFree { std::uint64_t ticket; VkDeviceSize offset; VkDeviceSize size; }; std::deque deferred_external_frees; std::atomic external_window_made{false}; // a window lies outside the arena: device_reachable looks there void drain_deferred_external_frees_locked() { if (deferred_external_frees.empty() || !context) return; const std::uint64_t completed = context->completed_retire_ticket(); while (!deferred_external_frees.empty() && deferred_external_frees.front().ticket <= completed) { const auto entry = deferred_external_frees.front(); deferred_external_frees.pop_front(); external_windows.free(*this, entry.offset, entry.size); } } static VkDeviceSize external_window_cap(bool staged) { static const VkDeviceSize env_cap = []() -> VkDeviceSize { char text[32] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_EXTERNAL_WINDOWS_MB", text, sizeof(text)); if (n > 0 && n < sizeof(text)) { const unsigned long long mb = std::strtoull(text, nullptr, 10); if (mb > 0) return VkDeviceSize(mb) << 20; } return 0; }(); if (env_cap) return env_cap; // Staged mode counts both VRAM and host staging mirror in reserved_; 4 GiB total = up to 2 GiB VRAM + 2 GiB // sysmem mirror. Unstaged mode caps at 2 GiB. return staged ? (4096ull << 20) : (2048ull << 20); } bool external_windows_allocate(VkDeviceSize bytes, VkDeviceSize& offset, std::uint8_t*& mapped, VkBuffer* out_buffer = nullptr, VkDeviceSize* out_buffer_offset = nullptr, VkDeviceAddress* out_address = nullptr) { std::lock_guard lock(external_windows_mutex); drain_deferred_external_frees_locked(); if (!external_windows.allocate(*this, bytes, offset, mapped, false, external_window_cap(external_windows.staged()), nullptr, out_buffer, out_buffer_offset, out_address)) return false; external_window_made.store(true, std::memory_order_release); return true; } void external_windows_free(VkDeviceSize offset, VkDeviceSize bytes) { std::lock_guard lock(external_windows_mutex); drain_deferred_external_frees_locked(); external_windows.free(*this, offset, bytes); } void external_windows_release_deferred(VkDeviceSize offset, VkDeviceSize bytes) { if (!bytes) return; const std::uint64_t ticket = context ? context->submitted_retire_ticket() + 1 : 0; std::lock_guard lock(external_windows_mutex); drain_deferred_external_frees_locked(); deferred_external_frees.push_back({ticket, offset, bytes}); } void collect_staged_shadow_readbacks(const ShadowPages& s, const std::pair* ranges, std::size_t count, const std::uint8_t* only, std::vector& arena_out, std::map>& ext_out) const { if (!arena.staged || !count) return; const auto arena_lo = reinterpret_cast(arena.mapped); const auto arena_hi = arena_lo + static_cast(arena.size); const bool check_ext = external_windows.staged(); s.for_each_target_range(ranges, count, only, [&](const std::uint8_t* ptr, std::size_t len) { const auto dst = reinterpret_cast(ptr); if (arena.mapped && dst >= arena_lo && dst < arena_hi && len <= arena_hi - dst) { const VkDeviceSize off = static_cast(dst - arena_lo); arena_out.push_back({off, off, static_cast(len)}); return; } if (check_ext) { std::size_t slot = 0; VkBufferCopy region{}; if (external_windows.find_staged_range(ptr, len, slot, region)) ext_out[slot].push_back(region); } }); } // Grow-only HOST_VISIBLE | HOST_CACHED scratch buffer for DMA readback from uncached ReBAR (WC BAR1) arena // and external window buffers during ShadowPages::write_back. Guarded by shadow_mutex. struct RebarReadbackScratch { VkBuffer buffer = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; std::uint8_t* mapped = nullptr; VkDeviceSize capacity = 0; bool coherent = true; std::vector entries; } rebar_readback; void destroy_rebar_readback() { if (!context) return; auto& vk = context->vk; if (rebar_readback.mapped && rebar_readback.memory) { vk.vkUnmapMemory(info.device, rebar_readback.memory); rebar_readback.mapped = nullptr; } if (rebar_readback.buffer) { vk.vkDestroyBuffer(info.device, rebar_readback.buffer, nullptr); rebar_readback.buffer = VK_NULL_HANDLE; } if (rebar_readback.memory) { vk.vkFreeMemory(info.device, rebar_readback.memory, nullptr); rebar_readback.memory = VK_NULL_HANDLE; } rebar_readback.capacity = 0; rebar_readback.entries.clear(); } bool ensure_rebar_readback(VkDeviceSize need) { if (need <= rebar_readback.capacity && rebar_readback.buffer && rebar_readback.mapped) return true; if (!context) return false; VkDeviceSize cap = std::max(rebar_readback.capacity ? rebar_readback.capacity * 2 : (16ull << 20), (need + 65535ull) & ~65535ull); auto& vk = context->vk; VkBufferCreateInfo binfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; binfo.size = cap; binfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; share(binfo); VkBuffer buf = VK_NULL_HANDLE; if (vk.vkCreateBuffer(info.device, &binfo, nullptr, &buf) != VK_SUCCESS) return false; VkMemoryRequirements req{}; vk.vkGetBufferMemoryRequirements(info.device, buf, &req); VkMemoryPropertyFlags chosen = 0; VkDeviceMemory mem = VK_NULL_HANDLE; { leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::staging); mem = allocate(req, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT, 0, &chosen, false); } void* ptr = nullptr; if (!mem || vk.vkBindBufferMemory(info.device, buf, mem, 0) != VK_SUCCESS || vk.vkMapMemory(info.device, mem, 0, VK_WHOLE_SIZE, 0, &ptr) != VK_SUCCESS) { if (buf) vk.vkDestroyBuffer(info.device, buf, nullptr); if (mem) vk.vkFreeMemory(info.device, mem, nullptr); return false; } destroy_rebar_readback(); rebar_readback.buffer = buf; rebar_readback.memory = mem; rebar_readback.mapped = static_cast(ptr); rebar_readback.capacity = cap; rebar_readback.coherent = (chosen & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0; return true; } bool arena_uncached_rebar() const { if (arena.staged || !arena.buffer || !arena.mapped || !arena.size) return false; if (arena.memory_type >= memory.memoryTypeCount) return false; const VkMemoryPropertyFlags flags = memory.memoryTypes[arena.memory_type].propertyFlags; return (flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) == 0; } template bool prepare_rebar_readbacks(Emit&& emit, ShadowPages::ReadbackLookup& out) { out = {}; if (arena.staged || !context) return false; const bool arena_wc = arena_uncached_rebar(); const auto arena_lo = reinterpret_cast(arena.mapped); const auto arena_hi = arena_lo + static_cast(arena.size); struct Req { VkBuffer buf; VkDeviceSize src_off; std::uintptr_t src_ptr; VkDeviceSize len; }; std::vector reqs; emit([&](const std::uint8_t* ptr, std::size_t len) { if (!ptr || !len) return; const auto p = reinterpret_cast(ptr); if (arena_wc && p >= arena_lo && p < arena_hi && len <= arena_hi - p) { reqs.push_back({arena.buffer, static_cast(p - arena_lo), p, static_cast(len)}); return; } VkBuffer ext_buf = VK_NULL_HANDLE; VkDeviceSize ext_off = 0; if (external_windows.find_uncached_buffer(ptr, len, ext_buf, ext_off)) reqs.push_back({ext_buf, ext_off, p, static_cast(len)}); }); if (reqs.empty()) return false; std::sort(reqs.begin(), reqs.end(), [](const Req& a, const Req& b) { if (a.buf != b.buf) return a.buf < b.buf; if (a.src_off != b.src_off) return a.src_off < b.src_off; return a.len > b.len; }); // Merge overlapping/adjacent ranges per VkBuffer. std::vector merged; merged.reserve(reqs.size()); for (const Req& r : reqs) { if (!merged.empty() && merged.back().buf == r.buf && r.src_off <= merged.back().src_off + merged.back().len) { const VkDeviceSize end = std::max(merged.back().src_off + merged.back().len, r.src_off + r.len); merged.back().len = end - merged.back().src_off; } else { merged.push_back(r); } } VkDeviceSize total = 0; for (const Req& r : merged) total = ((total + 63ull) & ~63ull) + r.len; if (!ensure_rebar_readback(total)) return false; std::vector> per_buf_copies; std::vector bufs; rebar_readback.entries.clear(); rebar_readback.entries.reserve(merged.size()); VkDeviceSize dst_off = 0; for (const Req& r : merged) { dst_off = (dst_off + 63ull) & ~63ull; if (bufs.empty() || bufs.back() != r.buf) { bufs.push_back(r.buf); per_buf_copies.emplace_back(); } per_buf_copies.back().push_back({r.src_off, dst_off, r.len}); rebar_readback.entries.push_back( {r.src_ptr, r.src_ptr + static_cast(r.len), rebar_readback.mapped + dst_off}); dst_off += r.len; } std::vector batches; batches.reserve(bufs.size()); for (std::size_t i = 0; i < bufs.size(); ++i) batches.push_back({bufs[i], rebar_readback.buffer, per_buf_copies[i]}); if (!context->copy_buffers_sync(batches, info.queue, info.queue_family)) { rebar_readback.entries.clear(); return false; } std::sort(rebar_readback.entries.begin(), rebar_readback.entries.end(), [](const auto& a, const auto& b) { return a.src_lo < b.src_lo; }); out = {rebar_readback.entries.data(), rebar_readback.entries.size()}; return true; } std::vector title_windows; std::atomic title_window_count{0}; // title_windows.size(), read without the mutex std::uint64_t title_window_bytes = 0; std::uint64_t title_window_cap = 64ull << 20; // What the GPU wrote into a copy of the title's memory goes back to the title's pages: the ranges reached since // the last submission (title_va_alias.h note_reached), copied back at the next refresh before the forward copy. // A window is a read-side mirror, so without this a UAV or a raw write lands in the copy and the title never sees // it (#1537, the WRITE_INVALID stop at the world start). std::mutex title_write_back_mutex; // its own: taken under shadow_mutex, never the other way round std::atomic has_title_write_back{false}; std::atomic has_passive_title_write_back{false}; std::atomic writes_buffer_meta_complete{false}; static constexpr std::size_t kTitleWriteBackBatches = 64; // pending batches before the oldest goes back unfenced static constexpr std::size_t kTitleWriteBackRanges = 8192; // ranges kept per submission static constexpr std::uint64_t kTitleWriteBackBytes = 64ull << 20; // bytes copied back per submission std::map title_write_back; // start -> end, of the submission about to run leonida::PassiveWriteBackTracker passive_write_back{kTitleWriteBackRanges, kTitleWriteBackBytes}; std::deque>> title_write_back_pending; // by ticket std::uint64_t title_write_back_refused = 0; // ranges past the caps, logged once std::uint64_t title_write_back_bytes = 0; // queued for this submission std::uint64_t title_write_back_total = 0; // copied back, all submissions std::uint64_t title_write_back_calls = 0; // log line count std::uint64_t title_write_back_unfenced = 0; // The stream pools' mappings (title_gpu_views): one per readable run of a pool that no other mapping serves yet. A // window goes once no address answers from it (retire_orphan_windows); a geometry copy goes when its view is // retired (the pages were freed, unmapped or remapped: drain_geometry_releases), and the next request for those // pages makes a new one. struct PoolSpan { std::uint64_t source; // the readable side of the pair the copy is made from std::uint64_t twin; // the extent's address in the pair's other view (0 when there is none) std::uint64_t shader_va; std::uint64_t size; bool geometry; // a geometry copy, not charged to the title-window budget }; std::vector pool_spans; std::atomic pool_span_count{0}; std::uint64_t pool_span_bytes = 0; std::uint64_t pool_spans_retired = 0; // extents gone with their copy (forget_pool_span, retire_orphan_windows) std::uint64_t title_window_refusals = 0; // windows neither the budget nor the arena allowed std::uint64_t unbacked_requests = 0; // title addresses no backing could be made for (zero-size views) std::uint64_t pool_covers = 0; // stream-pool requests given one mapping over windows they ran into // Title windows no address range answers from any more (retire_orphan_windows): the removed ranges' copies, as the // alias table's listener records them, and the retired windows whose memory waits for the GPU: freed as a retired // geometry view's is, once every replay in progress at the retirement has recorded its submissions (ticket // kAfterExecutes until then, see stamp_retired_windows) and those have completed. A command list resolves its root // views when they are recorded, so a list recorded before the retirement and executed (again) after it still // names the window: the ticket is taken only once every list (and every copy a held batch or the async worker // keeps) whose recording began before the retirement is gone (src/command_list_epochs.h). Its copy stays a target // of its pages' tracker until then, still refreshed: what those submissions wrote in it goes back to the title's // pages (write_back_titles, and once more when it is freed), not dropped with it. struct RetiredWindow { std::uint64_t start, shader_va, size, ticket, epoch; std::uint8_t* mapped; std::uint64_t lists; // the command-list epoch of the retirement }; static constexpr std::size_t kWindowAliasRemovals = 4096; // kept before every window is looked at instead std::mutex window_alias_removal_mutex; // a leaf: taken in alias_changed, under the alias table's lock std::vector> window_alias_removals; // (shader VA, bytes) bool window_alias_removals_overflow = false; std::atomic window_alias_removals_pending{false}; std::mutex retired_window_mutex; // taken under title_window_mutex; only GeometryViews' execute_mutex_ under it std::vector retired_windows; std::atomic retired_window_count{0}; std::atomic retired_windows_unstamped{false}; std::uint64_t title_windows_retired = 0, title_window_bytes_retired = 0, window_retirements = 0; rt::d3d12::GeometryViews geometry; // A retired geometry view: its alias ranges go, and so does every answer made through it without one // (vsharp_address and placed views take geometry_va() directly), by its CPU and its GPU-twin address. static void forget_geometry_alias(std::uintptr_t source, std::size_t size, VkDeviceSize va) { auto& aliases = leonida::title_va_aliases(); aliases.remove(source, va); aliases.forget_copy(source, size, va); if (const auto twin = leonida::title_gpu_views::other_view(source)) { aliases.remove(twin, va); aliases.forget_copy(twin, size, va); } } // Before the submission's console heap slots are translated (refresh_shadows): a view retired here is answered // by nothing from now on. It is freed only after every replay in progress has recorded its submissions and those // have completed (GeometryViews::kAfterExecutes, execute_end): this submission's own lists, recorded before, and // another queue's replay that translated its slots before this retirement may still name it. A ticket read here // would be one short of this submission, which records its own only after before_execute_ (and with an idle GPU // the view would be reaped in this very call). // A retired view's last copy is made here from the title's pages as they are now, when they are still readable // (GeometryViews::retire_range). // A stream-pool extent it backed leaves pool_spans: the next request for those pages makes a new mapping. void drain_geometry_releases() { if (!context || !geometry.has_pending_reclaim()) return; geometry.stamp_retired([this] { return context->submitted_retire_ticket(); }); const std::uint64_t completed_ticket = geometry.has_retired() ? context->completed_retire_ticket() : 0; geometry.drain_released( *this, rt::d3d12::GeometryViews::kAfterExecutes, completed_ticket, [this](std::uintptr_t source, std::size_t size, VkDeviceSize va) { forget_geometry_alias(source, size, va); forget_pool_span(va); }, copy_geometry); } void forget_pool_span(VkDeviceSize va) { std::lock_guard windows(title_window_mutex); const auto it = std::find_if(pool_spans.begin(), pool_spans.end(), [&](const PoolSpan& span) { return span.geometry && span.shader_va == va; }); if (it == pool_spans.end()) return; pool_span_bytes -= it->size; pool_spans.erase(it); pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); ++pool_spans_retired; } // Before refresh_shadows (next to drain_geometry_releases): stamps retired windows whose pre-retirement replays // and command lists have finished, and frees those whose GPU ticket has completed so any target_gone slot changes // from destroyed external blocks apply during this submission's heap refresh. void reclaim_retired_windows() { if (!context || !retired_window_count.load(std::memory_order_acquire)) return; stamp_retired_windows(); // lists reset or released since the last replay const std::uint64_t completed = context->completed_retire_ticket(); std::lock_guard windows(title_window_mutex); free_retired_windows(completed); } // After this submission's refresh (the windows' last copy is the one it made): a title window no address range // answers from any more leaves the refresh. Its ranges went because a newer range was entered over them (a // slot-133 buffer placed over the pages, a BVH input's exact copy, src/title_va_alias.h add), and a window nothing // reaches is only cost: its tracker walks its pages at every refresh and its bytes count against // LEONIDA_TITLE_WINDOWS_MB. Its stream-pool extent and its budget go at once; its copy leaves its tracker and its // memory is freed later (retired_windows, reclaimed in reclaim_retired_windows). Only windows whose copy a // removed range answered from are looked at (alias_changed records those). void retire_orphan_windows() { if (!context || !window_alias_removals_pending.load(std::memory_order_acquire)) return; std::vector> removed; // (shader VA, bytes) bool every = false; { std::lock_guard lock(window_alias_removal_mutex); removed.swap(window_alias_removals); every = window_alias_removals_overflow; window_alias_removals_overflow = false; window_alias_removals_pending.store(false, std::memory_order_release); } if (removed.empty() && !every) return; std::lock_guard windows(title_window_mutex); std::sort(removed.begin(), removed.end()); std::uint64_t longest = 0; for (const auto& r : removed) longest = std::max(longest, r.second); const auto touched = [&](const TitleWindow& window) { // a removed range answered from inside this copy if (every) return true; auto it = std::lower_bound(removed.begin(), removed.end(), std::pair{window.shader_va + window.size, std::uint64_t(0)}); while (it != removed.begin()) { --it; if (window.shader_va - std::min(window.shader_va, it->first) >= longest) break; if (it->first + it->second > window.shader_va) return true; } return false; }; auto& aliases = leonida::title_va_aliases(); std::vector gone; // shader VAs of the windows retired, sorted below for (const TitleWindow& window : title_windows) if (touched(window) && !aliases.answers_into(window.shader_va, window.size)) gone.push_back(window.shader_va); if (gone.empty()) return; std::sort(gone.begin(), gone.end()); const auto is_gone = [&](std::uint64_t va) { return std::binary_search(gone.begin(), gone.end(), va); }; const std::size_t spans = pool_spans.size(); std::erase_if(pool_spans, [&](const PoolSpan& span) { if (span.geometry || !is_gone(span.shader_va)) return false; pool_span_bytes -= span.size; return true; }); pool_spans_retired += spans - pool_spans.size(); pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); std::vector retiring; const std::uint64_t epoch = geometry.execute_epoch(); const std::uint64_t lists = leonida::command_list_epochs::advance(); std::uint64_t bytes = 0; std::erase_if(title_windows, [&](const TitleWindow& window) { if (!is_gone(window.shader_va)) return false; retire_shadow(window.mapped); retiring.push_back({window.start, window.shader_va, window.size, rt::d3d12::GeometryViews::kAfterExecutes, epoch, window.mapped, lists}); title_window_bytes -= window.size; bytes += window.size; return true; }); title_window_count.store(title_windows.size(), std::memory_order_relaxed); { std::lock_guard retired(retired_window_mutex); retired_windows.insert(retired_windows.end(), retiring.begin(), retiring.end()); retired_window_count.store(retired_windows.size(), std::memory_order_release); retired_windows_unstamped.store(true, std::memory_order_release); } title_windows_retired += retiring.size(); title_window_bytes_retired += bytes; ++window_retirements; if (window_retirements <= 4 || !(window_retirements & (window_retirements - 1))) std::fprintf(stderr, "[rt] d3d12: %zu title windows (%llu KiB) no address answers from any more were " "retired (%zu windows, %llu KiB left; %llu retired, %llu KiB returned so far)\n", retiring.size(), static_cast(bytes >> 10), title_windows.size(), static_cast(title_window_bytes >> 10), static_cast(title_windows_retired), static_cast(title_window_bytes_retired >> 10)); } // The memory of retired windows whose submissions have completed by `completed`; what their copies hold goes back // once more first (free_retired_shadow). title_window_mutex held. void free_retired_windows(std::uint64_t completed) { std::vector due; { std::lock_guard retired(retired_window_mutex); std::erase_if(retired_windows, [&](const RetiredWindow& window) { if (window.ticket == rt::d3d12::GeometryViews::kAfterExecutes || window.ticket > completed) return false; due.push_back(window); return true; }); retired_window_count.store(retired_windows.size(), std::memory_order_release); } for (const RetiredWindow& window : due) { free_retired_shadow(window.mapped, window.start, window.size); if (window.shader_va < arena.size) { arena_release(window.shader_va, window.size, arena_window); } else { backing(arena.address + window.shader_va, window.size, window.start, false); external_windows_free(window.shader_va, window.size); } } } // A replay has recorded its submissions, or a refresh runs: retired windows that only replays now finished and // only lists now gone may name get the submissions recorded so far as their ticket (GeometryViews::stamp_retired // does the same for its views). void stamp_retired_windows() { if (!retired_windows_unstamped.load(std::memory_order_acquire)) return; // Under the lock: a window retired by a replay begun after `oldest` was read must not be stamped here. std::lock_guard retired(retired_window_mutex); const std::uint64_t oldest = geometry.oldest_execute(); // Before the ticket: a list released after this read has had its submissions counted in it. const std::uint64_t oldest_list = leonida::command_list_epochs::oldest(); const std::uint64_t ticket = context->submitted_retire_ticket(); bool left = false; for (RetiredWindow& window : retired_windows) { if (window.ticket != rt::d3d12::GeometryViews::kAfterExecutes) continue; if (window.epoch < oldest && window.lists <= oldest_list) window.ticket = ticket; else left = true; } retired_windows_unstamped.store(left, std::memory_order_release); } static rt::d3d12::GeometryCopy copy_geometry(std::uint8_t* to, const std::uint8_t* from, std::size_t size) { using Result = rt::d3d12::GeometryCopy; if (!leonida::texture_memory_readable(reinterpret_cast(from), size)) return Result::unreadable; return copy_guarded(to, from, size, false) ? Result::copied : Result::interrupted; } // Why geometry_va gave no copy (diagnostics: the classes of V#s that resolve to nothing, fix_vsharp). enum class NoCopy : std::uint8_t { none, no_geometry, not_title, past_range, known_buffer, private_pages, refused, pool_alias, count }; // `refused` (when given) is set when a copy was asked for and refused (no room under the cap, or no block): it may // be made once geometry copies are freed (GeometryViews::free_generation). `why`: the reason for an answer of 0. std::uint64_t geometry_va(std::uint64_t guest, std::uint64_t span, bool read_only, bool* refused = nullptr, NoCopy* why = nullptr, bool passive = false) { const auto no = [why](NoCopy reason) { if (why) *why = reason; return std::uint64_t(0); }; // The page mirror holds the title's bytes at heap_base + the address the GPU names (a GPU-only page reads its // own physical page there, not its CPU view's), so no copy is made. if (span && guest && page_mirror.mirror && leonida::title_va_aliases().shader_va(guest, span) == guest && page_mirror_resolve(guest, span)) { if (!read_only) { if (passive) note_passive_title_write(guest, span); else note_title_write(guest, span); } return guest; } if (!geometry.cap() || !span || !guest || !watch_shadow_writes()) return no(NoCopy::no_geometry); const auto cpu = leonida::title_gpu_views::to_cpu(guest, span); auto& aliases = leonida::title_va_aliases(); const auto alias = aliases.shader_va(cpu, span); if (alias != cpu) return alias; if (cpu == guest) { std::uint64_t lo{}, hi{}; if (!aliases.title_memory(guest, lo, hi)) return no(NoCopy::not_title); if (span > hi - guest) return no(NoCopy::past_range); if (context->knows_buffer_va(guest)) return no(NoCopy::known_buffer); if (!read_only && !leonida::title_gpu_views::other_view(cpu)) { MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(reinterpret_cast(cpu), ®ion, sizeof region) || region.Type != MEM_MAPPED) { const std::uint64_t found = geometry.find(cpu, span); return found ? found : no(NoCopy::private_pages); } } } const std::uint64_t va = geometry.resolve(*this, cpu, span, copy_geometry); if (!va && refused) *refused = true; return va ? va : no(cpu != guest ? NoCopy::pool_alias : NoCopy::refused); } // LEONIDA_STREAM_BUFFER_WINDOWS=0: a window may not come from a block outside the arena. static bool stream_windows() { static const bool enabled = [] { const char* flag = std::getenv("LEONIDA_STREAM_BUFFER_WINDOWS"); return !flag || std::string_view(flag) != "0"; }(); return enabled; } // A committed page the host may read: the title's reservations start uncommitted. A page xmem's frame table holds // (no host view: src/title_frames.h) is read through its frame. static bool readable_page(std::uint64_t address) { if (leonida::title_frames::backed(static_cast(address))) return true; MEMORY_BASIC_INFORMATION region{}; return VirtualQuery(reinterpret_cast(static_cast(address)), ®ion, sizeof(region)) && region.State == MEM_COMMIT && region.Protect && !(region.Protect & (PAGE_NOACCESS | PAGE_GUARD)); } // The end of the readable run that starts at the page `address`, at most `end` (a pool's frames are mapped per // request, so its range is read until the first page the title has not committed). static std::uint64_t readable_run_end(std::uint64_t address, std::uint64_t end) { std::uint64_t at = address; while (at < end) { if (leonida::title_frames::may_hold(static_cast(at), static_cast(end))) { bool backed = false; const std::uint64_t run = leonida::title_frames::run_end(static_cast(at), static_cast(end), backed); if (backed) { at = run; continue; } } MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(reinterpret_cast(static_cast(at)), ®ion, sizeof(region)) || region.State != MEM_COMMIT || !region.Protect || (region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) break; const auto region_end = reinterpret_cast(region.BaseAddress) + region.RegionSize; if (region_end <= at) break; at = region_end; } return std::min(at, end); } // One line per call site (and then at 2, 4, 8... of it): a view the layer had to write with no backing, and how // many so far. It is written with a zero-size range, so a shader never adds heap_base to a raw title address. void note_unbacked(const char* site, std::uint64_t va, std::uint64_t bytes) { static std::mutex mutex; static std::map counts; std::lock_guard lock(mutex); std::uint64_t& seen = counts[site]; ++seen; if (seen != 1 && (seen & (seen - 1))) return; std::fprintf(stderr, "[rt] d3d12: %s: title address 0x%llx (%llu bytes) got no GPU copy: the view is written with no " "records (loads 0, stores dropped); %llu so far\n", site, static_cast(va), static_cast(bytes), static_cast(seen)); } // A window for [start, start + size): an arena range or a block outside the arena, charged to // LEONIDA_TITLE_WINDOWS_MB and refreshed before every submission by the tracker of its pages. 0 when neither the // budget nor the arena has room. `credit`: bytes of windows this one replaces, retired at the next submission // (cover_pool_request), not counted against it. title_window_mutex held. std::uint64_t make_title_window(std::uint64_t start, std::uint64_t size, std::uint64_t credit = 0) { if (!leonida::title_window_fits(title_window_cap, title_window_bytes - std::min(credit, title_window_bytes), size)) { ++title_window_refusals; log_once("title memory named by a shader address is past LEONIDA_TITLE_WINDOWS_MB, no window; MiB copied " "so far:", int(title_window_bytes >> 20)); return 0; } VkDeviceSize offset = 0; std::uint8_t* mapped{}; if (arena_allocate(size, kTitleWindowAlign, offset, arena_window)) { mapped = arena_host(offset, size); } else if (leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::windows); stream_windows() && external_windows_allocate(size, offset, mapped)) { } else { ++title_window_refusals; log_once("GPU address arena full (raise LEONIDA_ARENA_MB): title memory has no window; window KiB:", int(std::min(size >> 10, INT_MAX))); return 0; } if (offset >= arena.size) backing(arena.address + offset, size, start, true); const auto* pages = reinterpret_cast(static_cast(start)); add_shadow(pages, mapped, std::size_t(size)); title_windows.push_back({start, offset, size, mapped}); title_window_count.store(title_windows.size(), std::memory_order_relaxed); title_window_bytes += size; if (title_windows.size() <= 4 || !(title_windows.size() & (title_windows.size() - 1))) std::fprintf(stderr, "[rt] d3d12: a %llu KiB window of the title's memory, named by a shader address, is " "mirrored before every submission (%zu windows, %llu KiB)\n", static_cast(size >> 10), title_windows.size(), static_cast(title_window_bytes >> 10)); return offset; } // Undoes make_title_window for a window no range was entered for (the table refused the mapping): nothing has // answered from it, so no submission names it and its memory goes at once. title_window_mutex held. void drop_title_window(std::uint64_t shader_va) { const auto it = std::find_if(title_windows.begin(), title_windows.end(), [&](const TitleWindow& window) { return window.shader_va == shader_va; }); if (it == title_windows.end()) return; const TitleWindow window = *it; title_windows.erase(it); title_window_count.store(title_windows.size(), std::memory_order_relaxed); title_window_bytes -= window.size; remove_shadow(window.mapped); if (window.shader_va < arena.size) { arena_release(window.shader_va, window.size, arena_window); } else { backing(arena.address + window.shader_va, window.size, window.start, false); external_windows_free(window.shader_va, window.size); } } // Merges disjoint [va, end) into `ranges`, absorbing every overlapping or adjacent entry. Returns the net bytes // added (0 when already covered). static std::uint64_t merge_write_back_interval(std::map& ranges, std::uint64_t va, std::uint64_t end) { auto it = ranges.lower_bound(va); if (it != ranges.begin() && std::prev(it)->second >= va) --it; std::uint64_t merged_begin = va, merged_end = end; std::uint64_t removed_bytes = 0; std::size_t removed_count = 0; for (auto scan = it; scan != ranges.end() && scan->first <= merged_end; ++scan) { merged_begin = std::min(merged_begin, scan->first); merged_end = std::max(merged_end, scan->second); removed_bytes += scan->second - scan->first; ++removed_count; } if (removed_count == 1 && merged_begin == it->first && merged_end == it->second) return 0; for (auto scan = it; scan != ranges.end() && scan->first <= merged_end;) scan = ranges.erase(scan); ranges.emplace(merged_begin, merged_end); return (merged_end - merged_begin) - removed_bytes; } static bool title_write_back_enabled() { static const bool on = [] { char value[2] = {}; std::size_t length = 0; return getenv_s(&length, value, sizeof(value), "LEONIDA_TITLE_WRITEBACK") != 0 || value[0] != '0'; }(); return on; } // A binding of the title's memory reached for the coming submission: keep its range for the copy back after it. // Explicit writes (GPU copies, clears, WriteBufferImmediate, ResolveQueryData, BVH, root UAVs) always enter here. void note_title_write(std::uint64_t va, std::uint64_t bytes) { if (!title_write_back_enabled() || !va || !bytes) return; std::uint64_t lo = 0, hi = 0; if (!leonida::title_va_aliases().title_memory(va, lo, hi) || va >= hi) return; const std::uint64_t end = va + std::min(bytes, hi - va); std::lock_guard lock(title_write_back_mutex); auto it = title_write_back.lower_bound(va); if (it != title_write_back.begin() && std::prev(it)->second >= va) --it; std::uint64_t merged_begin = va, merged_end = end; std::uint64_t removed_bytes = 0; std::size_t removed_count = 0; for (auto scan = it; scan != title_write_back.end() && scan->first <= merged_end; ++scan) { merged_begin = std::min(merged_begin, scan->first); merged_end = std::max(merged_end, scan->second); removed_bytes += scan->second - scan->first; ++removed_count; } if (removed_count == 1 && merged_begin == it->first && merged_end == it->second) return; const std::uint64_t added_bytes = (merged_end - merged_begin) - removed_bytes; if ((!removed_count && title_write_back.size() >= kTitleWriteBackRanges) || (added_bytes && title_write_back_bytes + added_bytes > kTitleWriteBackBytes)) { if (!title_write_back_refused++) log_once("past LEONIDA_TITLE_WRITEBACK's caps: reached ranges are not copied back this submission; " "ranges refused:", 1); return; } for (auto scan = it; scan != title_write_back.end() && scan->first <= merged_end;) scan = title_write_back.erase(scan); title_write_back.emplace(merged_begin, merged_end); title_write_back_bytes += added_bytes; has_title_write_back.store(true, std::memory_order_release); } struct WriteBackExecEntry { const DeviceState* dev; std::uint64_t id; }; struct WriteBackExecStack { static constexpr std::size_t kCap = 16; WriteBackExecEntry entries[kCap]; std::size_t count; }; static_assert(std::is_trivially_destructible_v, "write_back_exec_stack must stay trivially destructible (no TLS callback in gta6rt.exe)"); static WriteBackExecStack& write_back_exec_stack() { static thread_local WriteBackExecStack stack{}; return stack; } // Passive V# descriptor-heap range: when every loaded shader carries `writes_buffer` metadata, defer write-back // until a submission actually executes a shader with `writes_buffer == true` (promote_passive_title_writes). // Without complete metadata (older shader packs or shader-less tests), fall back to immediate note_title_write. // On cap pressure across consecutive read-only submissions, evict oldest passive ranges (FIFO by sequence) instead // of refusing, so newly resolved writable V#s always enter `passive_write_back`. void note_passive_title_write(std::uint64_t va, std::uint64_t bytes) { if (!writes_buffer_meta_complete.load(std::memory_order_acquire)) { note_title_write(va, bytes); return; } if (!title_write_back_enabled() || !va || !bytes) return; std::uint64_t lo = 0, hi = 0; if (!leonida::title_va_aliases().title_memory(va, lo, hi) || va >= hi) return; const std::uint64_t end = va + (std::min)(bytes, hi - va); std::lock_guard lock(title_write_back_mutex); passive_write_back.note(va, end); has_passive_title_write_back.store(!passive_write_back.empty(), std::memory_order_release); } void begin_execute_write_back() { std::uint64_t id = 0; { std::lock_guard lock(title_write_back_mutex); id = passive_write_back.begin_execute(); } auto& stack = write_back_exec_stack(); if (stack.count < WriteBackExecStack::kCap) stack.entries[stack.count++] = {this, id}; } void end_execute_write_back() { auto& stack = write_back_exec_stack(); std::uint64_t id = 0; for (std::size_t i = stack.count; i > 0; --i) { if (stack.entries[i - 1].dev == this) { id = stack.entries[i - 1].id; for (std::size_t j = i; j < stack.count; ++j) stack.entries[j - 1] = stack.entries[j]; --stack.count; break; } } if (!id) return; std::lock_guard lock(title_write_back_mutex); passive_write_back.end_execute(id); has_passive_title_write_back.store(!passive_write_back.empty(), std::memory_order_release); } // Called after a submission containing at least one emitted shader with `writes_buffer == true` reaches the GPU: // promote pending passive console-heap V# ranges relevant to this execute into `title_write_back_pending` at // `ticket`, stamp newly promoted entries with the max concurrent active execute ID, and prune entries once every // concurrent execute that needed them has promoted or ended. void promote_passive_title_writes(std::uint64_t ticket) { if (!has_passive_title_write_back.load(std::memory_order_acquire)) return; std::uint64_t exec_id = 0; const auto& stack = write_back_exec_stack(); for (std::size_t i = stack.count; i > 0; --i) { if (stack.entries[i - 1].dev == this) { exec_id = stack.entries[i - 1].id; break; } } std::lock_guard lock(title_write_back_mutex); if (passive_write_back.empty()) { has_passive_title_write_back.store(false, std::memory_order_release); return; } std::map promoted; const bool emitted = passive_write_back.promote(exec_id, [&](std::uint64_t begin, std::uint64_t end) { merge_write_back_interval(promoted, begin, end); }); has_passive_title_write_back.store(!passive_write_back.empty(), std::memory_order_release); if (!emitted) return; const std::uint64_t stamp = title_write_back_pending.empty() ? ticket : (std::max)(ticket, title_write_back_pending.back().first); if (!title_write_back_pending.empty() && title_write_back_pending.back().first == stamp) { auto& target = title_write_back_pending.back().second; for (const auto& [begin, end] : promoted) merge_write_back_interval(target, begin, end); } else { title_write_back_pending.emplace_back(stamp, std::move(promoted)); } has_title_write_back.store(true, std::memory_order_release); } // What the GPU wrote into those copies goes back to the title's pages, so a later read by the title or the next // forward copy sees it. Runs FIRST in before_execute_() (before refresh_page_mirror and refresh_console_heaps), // when pending_ sparse binds are empty and before any map()/upload() mutates homes or agreed sums. Only retired // batches (ticket <= completed_retire_ticket()) are drained; unretired batches past kTitleWriteBackBatches are // coalesced into the next unretired batch rather than force-drained early. All drained batches are merged into one // disjoint sorted list so each mirrored page is read back at most once per call. void write_back_titles() { const bool any_queued = has_title_write_back.load(std::memory_order_acquire); const bool any_async = page_mirror.readback_async_pending.load(std::memory_order_acquire); if (!context || (!any_queued && !any_async)) return; std::vector> raw; if (any_queued) { const std::uint64_t done = context->completed_retire_ticket(); std::lock_guard lock(title_write_back_mutex); if (!title_write_back.empty()) { // The ranges of the submission about to execute, which is the next ticket. const std::uint64_t next_ticket = context->submitted_retire_ticket() + 1; const std::uint64_t stamp = title_write_back_pending.empty() ? next_ticket : std::max(next_ticket, title_write_back_pending.back().first); if (!title_write_back_pending.empty() && title_write_back_pending.back().first == stamp) { for (const auto& [begin, end] : title_write_back) merge_write_back_interval(title_write_back_pending.back().second, begin, end); } else { title_write_back_pending.push_back({stamp, std::move(title_write_back)}); } title_write_back.clear(); title_write_back_bytes = 0; } while (!title_write_back_pending.empty() && title_write_back_pending.front().first <= done) { for (const auto& [begin, end] : title_write_back_pending.front().second) raw.emplace_back(begin, end); title_write_back_pending.pop_front(); } // Bound pending queue depth without prematurely reading back unretired GPU work: coalesce the oldest // unretired batch into the second-oldest so it waits until both have retired. while (title_write_back_pending.size() > kTitleWriteBackBatches) { auto oldest = std::move(title_write_back_pending.front().second); title_write_back_pending.pop_front(); auto& target = title_write_back_pending.front().second; for (const auto& [begin, end] : oldest) merge_write_back_interval(target, begin, end); if (!title_write_back_unfenced++) log_once("more than 64 title write-back batches wait on their submissions: coalescing oldest " "unretired batches until they retire; batches:", 1); } if (title_write_back.empty() && title_write_back_pending.empty()) has_title_write_back.store(false, std::memory_order_release); } std::vector> finished; if (!raw.empty()) { std::sort(raw.begin(), raw.end()); finished.reserve(raw.size()); for (const auto& [begin, end] : raw) { if (!finished.empty() && begin <= finished.back().second) finished.back().second = std::max(finished.back().second, end); else finished.emplace_back(begin, end); } } std::uint64_t written = 0, ranges = 0; if (!finished.empty()) { std::unique_lock lock(shadow_mutex, std::defer_lock); leonida::submit_phases::lock_timed(lock); if (!shadows.empty()) { // Each shadow takes all the ranges over it in one call, in address order (batches can overlap), and // decides which of its pages are held once for all of them (ShadowPages::write_back). std::vector> over; ShadowPages::ReadbackLookup rebar_lookup{}; if (arena.staged) { std::vector readbacks; std::map> ext_readbacks; for (const ShadowPagesPtr& s : shadows) { over.clear(); for (const auto& [begin, end] : finished) if (end > s->first() && begin < s->last()) over.push_back({static_cast(begin), static_cast(end)}); if (!over.empty()) collect_staged_shadow_readbacks(*s, over.data(), over.size(), nullptr, readbacks, ext_readbacks); } sync_retired_readbacks_to_host(readbacks, ext_readbacks); } else { prepare_rebar_readbacks( [&](const auto& add) { for (const ShadowPagesPtr& s : shadows) { over.clear(); for (const auto& [begin, end] : finished) if (end > s->first() && begin < s->last()) over.push_back( {static_cast(begin), static_cast(end)}); if (!over.empty()) s->for_each_target_range(over.data(), over.size(), nullptr, add); } }, rebar_lookup); } for (const ShadowPagesPtr& s : shadows) { over.clear(); for (const auto& [begin, end] : finished) if (end > s->first() && begin < s->last()) over.push_back({static_cast(begin), static_cast(end)}); if (over.empty()) continue; std::size_t reached = 0; written += s->write_back(over.data(), over.size(), &reached, nullptr, rebar_lookup.count ? &rebar_lookup : nullptr); ranges += reached; } } } const std::uint64_t mirrored = page_mirror_write_back_ranges(finished, false); // non-blocking poll/kick written += mirrored; ranges += mirrored != 0; title_write_back_total += written; if (!written) return; if (++title_write_back_calls <= 4 || !(title_write_back_calls & (title_write_back_calls - 1))) std::fprintf(stderr, "[rt] d3d12: %llu KiB of the GPU's writes in %llu reached range(s) went back to the " "title's pages (%llu KiB so far)\n", static_cast(written >> 10), static_cast(ranges), static_cast(title_write_back_total >> 10)); } // A stream pool's address (a CPU view paired with a GPU-only alias). Rule B // first: the CPU view is where the host reads the frames, so that is what the copy is made from; the GPU-only // pages are the same frames through the title's queue slot 31 and are read only when the CPU view is not // committed. One mapping serves a page-aligned readable run (kPoolExtentMax at most), not one 128 KiB window per // vertex buffer, and both of the pair's addresses are entered in the table, so a V# naming either view reaches // the same bytes instead of asking for a second mapping. // True when `va` is in a pool (out = its shader VA, or 0 when nothing could back the run). title_window_mutex // held. bool resolve_pool_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out, bool has_mapping = false) { leonida::title_gpu_views::Range view{}; if (!leonida::title_gpu_views::view_at(static_cast(va), 1, view)) return false; const auto want = std::max(bytes, 1); const auto unbacked = [&](const char* reason) { if (has_mapping) return false; // fall back to existing shorter mapping (e.g. root-view 64 KiB probe) out = 0; ++unbacked_requests; note_unbacked(reason, va, bytes); return true; }; const std::uint64_t offset = va >= view.gpu && va - view.gpu < view.size ? va - view.gpu : va - view.cpu; if (want > view.size - offset) return unbacked("stream pool (bounds)"); // Rule B: the CPU view where the host reads the frames, the GPU-only pages only when that view has none. const std::uint64_t source = leonida::title_gpu_views::to_host_view(static_cast(va), want); const std::uint64_t twin = leonida::title_gpu_views::other_view(static_cast(source)); const std::uint64_t twin_view = twin ? twin : source; // the pair always has two addresses auto& aliases = leonida::title_va_aliases(); const auto other = source == va ? twin_view : source; const auto max_size = std::min(view.size - offset, kPoolExtentMax); const auto reuse = [&] { return aliases.reuse_pool_mapping(va, other, want, max_size, out); }; if (reuse()) return true; if (!readable_page(source)) return unbacked("stream pool (unreadable)"); const std::uint64_t pool_end = (source >= view.gpu && source - view.gpu < view.size ? view.gpu : view.cpu) + view.size; const std::uint64_t run_end = readable_run_end(source & ~(kTitleWindowAlign - 1), std::min(pool_end, source + kPoolExtentMax)); // Up to the next mapping in either view at most, never over it. leonida::TitleWindowRange extent{}; if (!leonida::title_pool_extent(source - offset, pool_end, source, run_end, kTitleWindowAlign, kPoolExtentMax, extent)) return unbacked("stream pool (no extent)"); std::uint64_t source_lo, source_hi, twin_lo, twin_hi; aliases.gap(source, source_lo, source_hi); aliases.gap(twin_view, twin_lo, twin_hi); // A request that runs past what would serve it, the mapping holding its first byte or the extent clipped // at the next one, gets one mapping over itself and the windows it reaches (cover_pool_request) rather than // a zero-size view; only a range that is not a window in the way (a slot-133 buffer, a geometry copy) still // leaves it with none. const std::uint64_t request_end = source + want; if (!leonida::clip_title_pool_extent(extent, source, twin_view, source_lo, source_hi, twin_lo, twin_hi)) return reuse() || cover_pool_request(source, twin_view, source, request_end, source - offset, pool_end, out) || unbacked("stream pool (clip)"); if (want > std::min(extent.size - (source - extent.start), run_end - source)) { if (reuse() || cover_pool_request(source, twin_view, extent.start, request_end, source - offset, pool_end, out)) return true; // The committed readable run at `source` is shorter than `want` (e.g., a root view probed with // kRootViewBytes = 64 KiB near the end of a committed stream-pool block). Still map the valid committed // extent so root views get a real GPU pointer instead of 0; V#s with a declared length > room still // enforce `room < bytes` in vsharp_address(). if (extent.size == 0 || source < extent.start || source >= extent.start + extent.size) return unbacked("stream pool (short)"); } const auto twin_start = twin_view - (source - extent.start); std::uint64_t shader = 0; if (geometry.cap() && watch_shadow_writes() && !context->knows_buffer_va(extent.start, extent.size)) shader = geometry.resolve(*this, extent.start, extent.size, copy_geometry); const bool geometry_copy = shader != 0; if (!shader) shader = make_title_window(extent.start, extent.size); if (!shader) return reuse() || unbacked("stream pool (no window)"); if (!aliases.add_twin(extent.start, twin_start, extent.size, shader)) { if (!geometry_copy) drop_title_window(shader); return reuse() || unbacked("stream pool (add_twin)"); } pool_spans.push_back({extent.start, twin_start, shader, extent.size, geometry_copy}); pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); pool_span_bytes += extent.size; if (pool_spans.size() <= 4 || !(pool_spans.size() & (pool_spans.size() - 1))) std::fprintf(stderr, "[rt] d3d12: a %llu KiB stream-pool extent is one %s mapping (alias 0x%llx and CPU view " "0x%llx share shader VA 0x%llx; %zu extents, %llu KiB)\n", static_cast(extent.size >> 10), geometry_copy ? "geometry-copy" : "window", static_cast(twin_view), static_cast(source), static_cast(shader), pool_spans.size(), static_cast(pool_span_bytes >> 10)); out = shader + (source - extent.start); return true; } // One mapping for a stream-pool request [source, end) that what would serve it stops short of: the extent from // `start` clipped at the next mapping, or the mapping holding `source`, ends first (title_pool_cover). It covers // the request and, whole, the windows it reaches in either view; the range entered over theirs replaces them // (TitleVaAliases::replace_twin), and they are retired at the next submission like any window nothing answers // from (retire_orphan_windows), what the GPU wrote in them copied back first. Their bytes are not charged twice // meanwhile. False when another kind of range is in the way (a slot-133 buffer, a geometry copy), the pages are not // all readable, or the mapping cannot be made. title_window_mutex held. bool cover_pool_request(std::uint64_t source, std::uint64_t twin_view, std::uint64_t start, std::uint64_t end, std::uint64_t pool_lo, std::uint64_t pool_end, std::uint64_t& out) { std::vector replaced; // title_windows entries the ranges in the way answer from const auto window_of = [&](std::uint64_t shader_va) { std::size_t i = 0; for (; i < title_windows.size(); ++i) if (shader_va - title_windows[i].shader_va < title_windows[i].size) break; return i; }; const auto owned = [&](std::uint64_t shader_va) { const std::size_t i = window_of(shader_va); if (i == title_windows.size()) return false; if (std::find(replaced.begin(), replaced.end(), i) == replaced.end()) replaced.push_back(i); return true; }; // What replace_twin may erase: only those windows. A slot-133 buffer is entered without title_window_mutex, // so one may have been placed over the cover's span (in either view) since it was planned. const auto planned = [&](std::uint64_t shader_va) { return std::find(replaced.begin(), replaced.end(), window_of(shader_va)) != replaced.end(); }; auto& aliases = leonida::title_va_aliases(); leonida::TitleWindowRange cover{}; if (end > pool_end || !leonida::title_pool_cover(aliases, pool_lo, pool_end, source, twin_view, start, end, kTitleWindowAlign, kTitleWindowMax, owned, cover)) return false; const std::uint64_t cover_end = cover.start + cover.size; if (readable_run_end(cover.start & ~(kTitleWindowAlign - 1), cover_end) < cover_end) return false; std::uint64_t credit = 0; for (const std::size_t i : replaced) credit += title_windows[i].size; const std::uint64_t twin_start = twin_view - (source - cover.start); std::uint64_t shader = 0; if (geometry.cap() && watch_shadow_writes() && !context->knows_buffer_va(cover.start, cover.size)) shader = geometry.resolve(*this, cover.start, cover.size, copy_geometry); const bool geometry_copy = shader != 0; if (!shader) shader = make_title_window(cover.start, cover.size, credit); if (!shader) return false; if (!aliases.replace_twin(cover.start, twin_start, cover.size, shader, planned)) { if (!geometry_copy) drop_title_window(shader); return false; } pool_spans.push_back({cover.start, twin_start, shader, cover.size, geometry_copy}); pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); pool_span_bytes += cover.size; ++pool_covers; if (pool_covers <= 4 || !(pool_covers & (pool_covers - 1))) std::fprintf(stderr, "[rt] d3d12: a stream-pool request ran past the mapping that would serve it: one %llu KiB " "%s covers it and the %zu window(s) it reached, retired at the next submission (%llu so " "far)\n", static_cast(cover.size >> 10), geometry_copy ? "geometry copy" : "window", replaced.size(), static_cast(pool_covers)); out = shader + (source - cover.start); return true; } // Whether a shader that forms heap_base + `va` reaches memory of the device's: the arena, a registered buffer (an // upload or readback heap, an import, by its VA), a geometry copy, a title window outside the arena, or the copy // of any title range (an address the layer already wrote for the title). A raw title address is none of these. // A V#'s base is 48 bits and translated shaders sign-extend it (Gen.host_addr), so a wrapped one is also tried // with its upper bits set. `buffers_checked`: the caller already asked the buffer index about `va` itself (the // resolver does). Cheapest first; title_window_mutex only once a window outside the arena exists, and never // called with it held. bool device_reachable(std::uint64_t va, bool buffers_checked = false) { if (va < arena.size) return true; // Title memory the page mirror holds: heap_base + va is its chunk. if (page_mirror.mirror && page_mirror_resolve(va, 1)) return true; const bool wrapped = va < (1ull << 48) && (va >> 47); const std::uint64_t candidates[2] = {va, wrapped ? va | ~((1ull << 48) - 1) : va}; auto& aliases = leonida::title_va_aliases(); for (int i = 0; i < (wrapped ? 2 : 1); ++i) { const std::uint64_t at = candidates[i]; if (aliases.shader_side(at)) return true; std::uint64_t host = 0, room = 0; if (geometry.cap() && geometry.lookup(arena.address + at, host, room)) return true; if (external_window_made.load(std::memory_order_acquire)) { std::lock_guard lock(external_windows_mutex); if (external_windows.lookup(arena.address + at, host, room)) return true; } if (context && !(i == 0 && buffers_checked) && context->knows_buffer_va(at)) return true; } return false; } // One line per kind (and then at 2, 4, 8... of it): an address outside the title's memory that names nothing of // the device's, written as a zero-size view (a V#) or 0 (a root view) instead of a raw address. void note_unmapped(std::uint64_t va, std::uint64_t bytes) { static std::atomic seen{0}; const std::uint64_t n = seen.fetch_add(1, std::memory_order_relaxed) + 1; if (n != 1 && (n & (n - 1))) return; std::fprintf(stderr, "[rt] d3d12: address 0x%llx (%llu bytes) is neither the title's memory nor any allocation of the " "device's: the view is written with no base and no records (loads 0, stores dropped); %llu so " "far\n", static_cast(va), static_cast(bytes), static_cast(n)); } // Called through title_va_aliases().resolve for an address with no copy yet. False: not the title's memory. // True: it is, and `out` is its shader VA, 0 when no backing could be made (never the raw address). An address // past the arena that is not the title's memory either gets 0 too when nothing of the device's is there // (device_reachable): heap_base + such an address is no allocation, and a shader that reads or writes through it // takes an MMU fault (measured with Aftermath at world start: compute reads ~4 GiB and ~10 GiB above anything // allocated). bool resolve_title_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { out = va; if (!arena_ready() || !context) return false; if (context->knows_buffer_va(va)) return false; // an upload or readback buffer's biased VA, say if (va < arena.size) { // Below the arena's size an address is an arena address unless the title's own memory is there (its // heap is: arena_allocate keeps out of those ranges). std::uint64_t lo = 0, hi = 0; if (!leonida::title_va_aliases().title_memory(va, lo, hi)) return false; } auto& aliases = leonida::title_va_aliases(); // Only title memory can request a new copy. Elsewhere, require existing GPU backing. std::uint64_t title_lo = 0, title_hi = 0; if (!aliases.title_memory(va, title_lo, title_hi)) { // Root descriptors carry a pointer without a declared length. Validate the base. out = vsharp_address(va, 1, leonida::TitleVaAliases::root_view, false, false, nullptr, nullptr, nullptr, false); return true; } const std::uint64_t want = std::max(bytes, 1); std::lock_guard lock(title_window_mutex); std::uint64_t made = 0, available = 0; const bool has_mapping = aliases.range_of(va, made, available) && made != va; if (has_mapping && available >= want) { out = made; return true; } // The page mirror: the address itself (heap_base + va), no window, extent or copy. // TitleVaAliases::resolve calls note_reached(va, bytes) after we return true iff writable && out != 0. if (page_mirror_resolve(va, want)) { out = va; return true; } // Never fall through to make_title_window / ShadowPages over memory covered by the page mirror (e.g. a span // exceeding kMirrorNameMax): a shadow tracker over mirrored pages fights HotColdTracking's guards. if (page_mirror.mirror && page_mirror_covers(va, 1)) { out = 0; return true; } // A stream pool's address: one mapping for its readable run, shared by both of its views. if (resolve_pool_memory(va, bytes, out, has_mapping)) return true; if (has_mapping) { out = made; return true; } if (readable_page(va)) { std::uint64_t lo = 0, hi = UINT64_MAX; aliases.gap(va, lo, hi); // never over a slot-133 buffer's range or another window lo = std::max(lo, title_lo); // nor past the title's range hi = std::min(hi, title_hi); leonida::TitleWindowRange range{}; if (leonida::title_window_range(va, want, lo, hi, kTitleWindowAlign, kTitleWindowMax, title_window_cap, title_window_bytes, range)) { if (const std::uint64_t offset = make_title_window(range.start, range.size)) { aliases.add(range.start, range.size, offset); out = offset + (va - range.start); return true; } } } // No window (the budget or the arena is full, or the page is not committed yet): the persistent geometry // copy backs the range instead, refreshed when its source pages change. A raw address never comes out of // this; when neither backing is available the view is written with no records. if (const std::uint64_t copy = geometry_va(va, want, false)) { aliases.add(va, want, copy); out = copy; return true; } out = 0; ++unbacked_requests; note_unbacked("title memory", va, bytes); return true; } // ---- Acceleration-structure addresses (XDXR builds, docs/d3d12_vulkan.md 4.8) ---- // A BuildRaytracingAccelerationStructure, CopyRaytracingAccelerationStructure or postbuild names its memory by the // title's GPU VAs, and the builder reaches each at heap_base + VA. A VA in the title's own memory (a slot-133 // buffer, or pages no resource covers: the retail title builds into its own heap) is past the arena, so heap_base // + VA is no allocation, and the first write of a build there lost the device (measured natively with Nsight // Aftermath: xdxr_build.comp MODE_INIT, an MMU write fault at heap_base + a title address). So every address goes // through the same resolver as the root views and V#s (src/title_va_alias.h): it becomes the VA of the memory's // GPU copy, and the copy must hold every byte the builder touches from it. An address that has no such copy is // refused, and the command is not recorded: nothing is written through it, and the destination keeps what it had. enum BvhField : unsigned { bvh_dst, bvh_scratch, bvh_source, bvh_instances, bvh_vertices, bvh_indices, bvh_transform, bvh_copy_dst, bvh_copy_src, bvh_postbuild_dst, bvh_postbuild_src, bvh_layout, bvh_field_count }; static constexpr const char* kBvhFieldNames[bvh_field_count] = { "destination", "scratch", "update source", "instance descs", "vertices", "indices", "transform", "copy destination", "copy source", "postbuild destination", "postbuild source", "instance pointer array"}; std::array, bvh_field_count> bvh_refused{}; std::atomic bvh_refused_total{0}, bvh_resolved_builds{0}, bvh_translated{0}; // Each structure's layout size by the title VA it was built at, so a copy of it knows how much to pull in. std::mutex bvh_size_mutex; std::map bvh_sizes; // The VA shaders reach [va, va + bytes) by, in `out`; `room` (when given) gets the bytes the copy has from `va` // on when it is one of the title's ranges, and 0 for an arena VA (the replay sizes it by its buffer). `gpu`: the // builder writes the bytes, or they are a structure it wrote (a destination, scratch, an update or copy source): // only the title-memory copies the GPU's writes stay in (a slot-133 import or shadow, a title window). Otherwise // they are inputs the title wrote (vertices, indices, a transform, instance descs), which a geometry copy can also // answer, as for a placed buffer view. False: no copy holds all of the bytes. // A persistent copy of exactly [va, va + bytes) from the title's pages, entered in the alias table, so a shader // or a build reaches the whole range by one address. A GPU-written structure (a BVH destination or its scratch) // keeps the GPU's writes in the copy: that is the only place the structure is read from afterwards, so the copy // is the structure. It is made even when a shorter range already maps the start: spreading a window's address over // bytes it does not cover would be a lie. 0 when geometry copies are off (LEONIDA_GEOMETRY_MB), their cap refuses // it, or the range is not the title's memory. std::uint64_t copy_title_range(std::uint64_t va, std::uint64_t bytes) { const std::uint64_t span = std::max(bytes, 1); auto& aliases = leonida::title_va_aliases(); std::uint64_t lo = 0, hi = 0; if (!aliases.title_memory(va, lo, hi) || span > hi - va) return 0; // In the page mirror the structure is the title's own pages (their homes keep what the GPU writes). if (page_mirror_resolve(va, span)) { note_title_write(va, span); return va; } if (!geometry.cap() || !watch_shadow_writes()) return 0; const auto cpu = leonida::title_gpu_views::to_host_view(static_cast(va), static_cast(span)); if (context->knows_buffer_va(cpu, span)) return 0; const std::uint64_t copy = geometry.resolve(*this, cpu, span, copy_geometry); if (!copy) return 0; std::lock_guard lock(title_window_mutex); aliases.add(va, span, copy); return copy; } bool bvh_va(std::uint64_t va, std::uint64_t bytes, bool gpu, std::uint64_t& out, std::uint64_t* room = nullptr) { out = va; if (room) *room = 0; if (!va) return true; bytes = std::max(bytes, 1); if (va > UINT64_MAX - bytes) return false; auto& aliases = leonida::title_va_aliases(); if (!gpu) { if (const std::uint64_t copy = geometry_va(va, bytes, true)) { out = copy; if (room) *room = bytes; if (copy != va) bvh_translated.fetch_add(1, std::memory_order_relaxed); return true; } } const std::uint64_t to = aliases.resolve(va, bytes, leonida::TitleVaAliases::bvh_address); std::uint64_t shader = 0, available = 0; if (aliases.range_of(va, shader, available)) { // The range the address is in must be the one it was translated by, and reach past the last byte: a // window is at most kTitleWindowMax and stops at the next range, so a large structure can outrun it. if (shader == to && available >= bytes) { out = shader; if (room) *room = available; bvh_translated.fetch_add(1, std::memory_order_relaxed); return true; } } // No range holds all of it (no window at all after the budget ran out, or one that ends early): a copy of // the whole structure backs it, so the command is recorded and its destination or scratch is reachable. if (const std::uint64_t copy = copy_title_range(va, bytes)) { out = copy; if (room) *room = bytes; bvh_translated.fetch_add(1, std::memory_order_relaxed); return true; } if (to != va) return false; // Not in a range: an arena VA, or one of the layer's buffers outside the arena (an upload or readback heap, // whose VA is its device address minus heap_base). The title's own memory without a copy is neither. std::uint64_t lo = 0, hi = 0; if (aliases.title_memory(va, lo, hi)) return false; if (va + bytes <= arena.size) return true; return context && context->knows_buffer_va(va, bytes); } void bvh_refuse(BvhField field, std::uint64_t va, std::uint64_t bytes) { const std::uint64_t first = bvh_refused[field].fetch_add(1, std::memory_order_relaxed); const std::uint64_t total = bvh_refused_total.fetch_add(1, std::memory_order_relaxed) + 1; if (!first) std::fprintf(stderr, "[rt] d3d12: an acceleration-structure command was not recorded: its %s at 0x%llx (%llu " "bytes) has no GPU copy that holds all of it (title memory without a window, past " "LEONIDA_TITLE_WINDOWS_MB, a window that ends early, or no allocation); nothing is written " "through it\n", kBvhFieldNames[field], static_cast(va), static_cast(bytes)); if (total & (total - 1)) return; char counts[512]; int at = 0; for (unsigned f = 0; f < bvh_field_count && at < int(sizeof counts) - 64; ++f) if (const std::uint64_t n = bvh_refused[f].load(std::memory_order_relaxed)) at += std::snprintf(counts + at, sizeof counts - std::size_t(at), "%s%s %llu", at ? ", " : "", kBvhFieldNames[f], static_cast(n)); std::fprintf(stderr, "[rt] d3d12: %llu acceleration-structure commands not recorded for an unresolved address (%s); " "%llu builds resolved, %llu addresses translated to GPU copies\n", static_cast(total), counts, static_cast(bvh_resolved_builds.load(std::memory_order_relaxed)), static_cast(bvh_translated.load(std::memory_order_relaxed))); } void bvh_note_size(std::uint64_t title_va, std::uint64_t bytes) { if (!title_va || !bytes) return; std::lock_guard lock(bvh_size_mutex); if (bvh_sizes.size() >= (1u << 16)) bvh_sizes.clear(); // a guess only: it sizes a copy's window bvh_sizes[title_va] = bytes; } std::uint64_t bvh_known_size(std::uint64_t title_va) { std::lock_guard lock(bvh_size_mutex); const auto it = bvh_sizes.find(title_va); return it == bvh_sizes.end() ? 0 : it->second; } // BuildRaytracingAccelerationStructure: every address of `b` in place, or false (logged) when one has no copy. // Unchanged on a device that builds KHR structures (they are named by their resources' VAs) or none. bool resolve_xdxr_build(leonida::BuildAccelerationStructure& b) { if (!context || !context->xdxr_acceleration_structures()) return true; leonida::XdxrLayout layout; // A count the format cannot hold: left as it was, and refused when the list is prepared (xdxr_check). if (!layout.compute(leonida::VulkanContext::xdxr_elements(b), b.is_tlas, leonida::VulkanContext::xdxr_box16(b))) return true; const std::uint64_t title_dst = b.dst_va; std::uint64_t out = 0; // The destination holds the records the traversal shaders find by a 256-byte-unit address (an INSTANCE // record's BLAS, a BVH descriptor's base), so its copy must keep that alignment. if (!bvh_va(b.dst_va, layout.size, true, out) || (out & 255)) return bvh_refuse(bvh_dst, b.dst_va, layout.size), false; b.dst_va = out; // The other addresses keep the alignment D3D12 gives them too (CommandList checks it again). if (!bvh_va(b.scratch_va, layout.scratch, true, out) || (out & 255)) return bvh_refuse(bvh_scratch, b.scratch_va, layout.scratch), false; b.scratch_va = out; if (b.update && b.src_va) { if (b.src_va == title_dst) { b.src_va = b.dst_va; } else { if (!bvh_va(b.src_va, layout.size, true, out) || (out & 255)) return bvh_refuse(bvh_source, b.src_va, layout.size), false; b.src_va = out; } } if (b.is_tlas) { // The builder reads 64-byte descs one after another (xdxr_build.comp MODE_INSTANCES); a pointer array // would be read as descs, past its end. if (b.instance_count && b.instance_pointers) return bvh_refuse(bvh_layout, b.instances_va, 8ull * b.instance_count), false; if (b.instance_count) { if (!bvh_va(b.instances_va, 64ull * b.instance_count, false, out)) return bvh_refuse(bvh_instances, b.instances_va, 64ull * b.instance_count), false; b.instances_va = out; } } else { for (auto& t : b.triangles) { const std::uint64_t triangles = (t.index_type ? t.index_count : t.vertex_count) / 3; if (!triangles) continue; // Unindexed: three vertices a triangle. Indexed: the VertexCount the title declared (an index past // it is not read: xdxr_build.comp vertex() makes its triangle inactive). const std::uint64_t vertices = t.index_type ? t.vertex_count : 3 * triangles; const std::uint64_t element = t.vertex_format == VK_FORMAT_R32G32_SFLOAT ? 8 : 12; const std::uint64_t vertex_bytes = vertices ? (vertices - 1) * t.vertex_stride + element : 0; if (vertex_bytes && !bvh_va(t.vertex_va, vertex_bytes, false, out)) return bvh_refuse(bvh_vertices, t.vertex_va, vertex_bytes), false; t.vertex_va = out; if (t.index_type && t.index_va) { const std::uint64_t index_bytes = 3 * triangles * (t.index_type == 1 ? 2 : 4); if (!bvh_va(t.index_va, index_bytes, false, out)) return bvh_refuse(bvh_indices, t.index_va, index_bytes), false; t.index_va = out; } if (t.transform_va) { if (!bvh_va(t.transform_va, 48, false, out)) return bvh_refuse(bvh_transform, t.transform_va, 48), false; t.transform_va = out; } } } bvh_note_size(title_dst, layout.size); bvh_resolved_builds.fetch_add(1, std::memory_order_relaxed); return true; } // CopyRaytracingAccelerationStructure: both addresses, with the room their copies have (the replay bounds the // copy by it). The source's size comes from its build when the layer saw it, else from its header only. bool resolve_xdxr_copy(leonida::CopyAccelerationStructure& c) { if (!context || !context->xdxr_acceleration_structures()) return true; const std::uint64_t known = bvh_known_size(c.src_va); const std::uint64_t want = known ? known : leonida::XdxrLayout::header_size; const std::uint64_t title_dst = c.dst_va; std::uint64_t out = 0, room = 0; if (!bvh_va(c.src_va, want, true, out, &room) || (out & 255)) return bvh_refuse(bvh_copy_src, c.src_va, want), false; c.src_va = out; c.src_room = room; if (!bvh_va(c.dst_va, want, true, out, &room) || (out & 255)) return bvh_refuse(bvh_copy_dst, c.dst_va, want), false; c.dst_va = out; c.dst_room = room; if (known) bvh_note_size(title_dst, known); return true; } // A postbuild: its destination (8 bytes a source) and each source structure's header, which it reads. bool resolve_xdxr_postbuild(leonida::AccelerationStructurePostbuild& info) { if (!context || !context->xdxr_acceleration_structures()) return true; std::uint64_t out = 0, room = 0; const std::uint64_t bytes = 8ull * info.sources.size(); if (!bvh_va(info.dest_va, bytes, true, out, &room) || (out & 7)) return bvh_refuse(bvh_postbuild_dst, info.dest_va, bytes), false; info.dest_va = out; info.dest_room = room; for (auto& source : info.sources) { if (!bvh_va(source, leonida::XdxrLayout::header_size, true, out) || (out & 255)) return bvh_refuse(bvh_postbuild_src, source, leonida::XdxrLayout::header_size), false; source = out; } return true; } // The console's value writes (list slots 71 and 72) whose address is an arena offset: a default-heap buffer. // The arena is host-visible, so its host mapping holds the bytes the GPU reads. As in resolve_title_memory, an // address below the arena's size is an arena address unless the title's own memory is there (arena_allocate // keeps out of those ranges); an arena address is never stored to as a host address, so it is the arena's // whether or not it can be written here (src/value_write_sink.h). Below the first offset the arena hands out are // the null region, the zero page and the quad indices, which shaders read: a value there is refused, as is one // past the end. leonida::value_sink::Landing write_arena_value(std::uint64_t va, const void* bytes, unsigned size) { using leonida::value_sink::Landing; if (!arena_ready() || va >= arena.size) return Landing::elsewhere; std::uint64_t title_lo = 0, title_hi = 0; if (leonida::title_va_aliases().title_memory(va, title_lo, title_hi)) return Landing::elsewhere; if (!bytes || !size || va < arena.first || size > arena.size - va) return Landing::refused; // A sparse resource's memory is bound by the sparse pass, not by the arena's mapping. if (context && context->is_sparse_va(va)) return Landing::refused; // The value names an arena address, not an allocation this code holds: the store runs under the backing's // shared lock, so no reclaim frees the memory under it, and an address with no memory behind it is refused. // An aligned value in one store, so a reader never sees half of it. const bool stored = arena.backing.with_host(va, size, [&](std::uint8_t* host) { if (size == 4 && !(va & 3)) std::atomic_ref(*reinterpret_cast(host)) .store(*static_cast(bytes), std::memory_order_relaxed); else if (size == 8 && !(va & 7)) std::atomic_ref(*reinterpret_cast(host)) .store(*static_cast(bytes), std::memory_order_relaxed); else std::memcpy(host, bytes, size); }); if (!stored) { note_unbacked_arena(va, size); return Landing::refused; } arena_mark_dirty(va, size); return Landing::landed; } struct ShaderVisibleHeap { VkDeviceSize end; D3D12_DESCRIPTOR_HEAP_TYPE type; }; std::mutex visible_heap_mutex; std::map visible_heaps; std::map cpu_view_heaps; bool known_view_heap(std::uintptr_t addr) { std::lock_guard lock(visible_heap_mutex); std::uint64_t off = 0; if (arena.backing.offset_of(reinterpret_cast(addr), 1, off)) { auto visible = visible_heaps.upper_bound(off); if (visible != visible_heaps.begin()) { --visible; if (visible->second.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && off < visible->second.end && (off-visible->first)%kDescriptorSize==0) return true; } } auto it = cpu_view_heaps.upper_bound(addr); if (it == cpu_view_heaps.begin()) return false; --it; return addr < it->second && (addr-it->first) % kDescriptorSize == 0; } // The T#s of a bound table in one of the layer's heaps get the index word their entry has now (tsharp_index_word): // Create*View wrote it, but a T# whose view came later (a stream published, a texture made at the address) or went // since, and one the title wrote raw or copied from where no index was, would otherwise keep the word of then. void refresh_tsharp_index_words(std::uint8_t* table, VkDeviceSize bytes) { namespace g = leonida::gfx10; std::lock_guard lock(descriptor_mutex); for (VkDeviceSize at = 0; at + kDescriptorSize <= bytes; at += kDescriptorSize) { g::ImageWords words; std::memcpy(words.data(), table + at, sizeof(words)); if (!g::is_image(words)) continue; const std::uint32_t word = tsharp_index_word_locked(g::tsharp_key(words)); if (word != words[g::kTsharpIndexDword]) std::memcpy(table + at + 4 * g::kTsharpIndexDword, &word, sizeof(word)); } } // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy, // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. void scan_title_table(std::uint64_t table_va, std::uint32_t descriptors) { probe_table(table_va, descriptors); // LOCAL DIAGNOSTIC VkDeviceSize end = 0; bool sampler = false; { std::lock_guard lock(visible_heap_mutex); auto it = visible_heaps.upper_bound(table_va); if (it == visible_heaps.begin()) return; --it; const auto& heap = it->second; const UINT step = descriptor_increment(heap.type); if (table_va >= heap.end || (table_va - it->first) % step != 0) return; sampler = heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; const auto slots = sampler ? descriptors : std::min(descriptors, kViewScanLimit); end = table_va + std::min(heap.end - table_va, VkDeviceSize(slots) * step); } auto& aliases = leonida::title_va_aliases(); // The table is in a live shader-visible heap (visible_heaps), one arena allocation: one mapping. std::uint8_t* const table = arena_host(table_va, end - table_va); if (!table) return; // Slots the title wrote in its own backing of this heap, if it gave the heap one. aliases.pull_descriptors(table, std::size_t(end - table_va)); if (sampler) { arena_mark_dirty(table_va, end - table_va); return; // S# words describe sampling state. They have no buffer address to translate. } if (tsharp_index_words) refresh_tsharp_index_words(table, end - table_va); for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { auto* words = reinterpret_cast(table + (at - table_va)); if (words[3] >> 30) continue; if (retry_nulled_table_slot(at, words, aliases)) continue; const std::uint32_t original[3] = {words[0], words[1], words[2]}; bool unbacked = false; if (!rebase_title_vsharp(words, aliases, true, &unbacked) && unbacked) { // Title memory no window or geometry copy could back, or an address nothing backs: no base and no // records, so a shader's load returns 0 and its store is dropped rather than written at heap_base + // the raw address. The words are kept to look at again (retry_nulled_table_slot). The null form is the // one a zero-size view has (base 0, no records): base 0 is the arena's zero page, which reads 0. words[0] = 0; words[1] &= 0xFFFF0000u; words[2] = 0; note_nulled_table_slot(at, original, words[3]); } // The slot's second V# is a UAV counter (raw, 4 bytes, in the descriptor's upper 16 bytes): a store to it // at heap_base + a raw title address loses the device just as one through the buffer V# does. Nothing // retries it - a counter whose backing arrives later stays with no records until the title rewrites it. if (at + kDescriptorSize <= end) fix_vsharp(words + 4, VsharpPath::table); } arena_mark_dirty(table_va, end - table_va); } // The table slots scan_title_table wrote null in place (the layer's heaps have no separate GPU copy), by arena // offset, with the words the title gave them: at each later scan that still finds the null form there, the // original is tried again, kNulledTableTries times at most, so a V# whose buffer or copy comes after the // descriptor gets its base back. A slot the title rewrote meanwhile is forgotten and scanned as new. At most // kNulledTableSlots are kept (past that a nulled slot stays null until rewritten). The null form is base 0 with no // records, as a zero-size view has; a slot holding it is recognised by the rest of the words the title gave it, // so a view Create*View wrote (also base 0) is only retried when its other words match a nulled slot's exactly. struct NulledTableSlot { std::uint32_t words[4]; std::uint32_t tries; }; static constexpr std::size_t kNulledTableSlots = 65536; static constexpr std::uint32_t kNulledTableTries = 16; std::mutex nulled_table_mutex; std::unordered_map nulled_table_slots; std::atomic nulled_table_count{0}; void note_nulled_table_slot(VkDeviceSize at, const std::uint32_t (&original)[3], std::uint32_t word3) { std::lock_guard lock(nulled_table_mutex); if (nulled_table_slots.size() >= kNulledTableSlots) return; nulled_table_slots[at] = {{original[0], original[1], original[2], word3}, 0}; nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed); } // A heap's arena range is released: what was noted in it is no longer anybody's slot. void forget_nulled_table_slots(VkDeviceSize offset, VkDeviceSize bytes) { if (!nulled_table_count.load(std::memory_order_relaxed)) return; std::lock_guard lock(nulled_table_mutex); std::erase_if(nulled_table_slots, [&](const auto& e) { return e.first - offset < bytes; }); nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed); } // True when `at` is a slot this scan nulled earlier and still holds that null form: tried again (and restored // when its address is backed now), so the caller moves on. bool retry_nulled_table_slot(VkDeviceSize at, std::uint32_t* words, leonida::TitleVaAliases& aliases) { if (!nulled_table_count.load(std::memory_order_relaxed)) return false; NulledTableSlot entry{}; { std::lock_guard lock(nulled_table_mutex); const auto it = nulled_table_slots.find(at); if (it == nulled_table_slots.end()) return false; entry = it->second; // entry.words[2] != 0: a view the title wrote with zero records is not one this scan nulled. const bool still_null = words[0] == 0 && words[2] == 0 && entry.words[2] != 0 && words[3] == entry.words[3] && words[1] == (entry.words[1] & 0xFFFF0000u); if (!still_null || ++it->second.tries > kNulledTableTries) { nulled_table_slots.erase(it); nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed); return still_null; // rewritten by the title: scanned as new; out of tries: left null } } std::uint32_t retry[4] = {entry.words[0], entry.words[1], entry.words[2], words[3]}; bool unbacked = false; const bool rebased = rebase_title_vsharp(retry, aliases, true, &unbacked); if (!rebased && unbacked) return true; // still nothing behind it: stays null, looked at again next scan words[0] = retry[0]; words[1] = retry[1]; words[2] = retry[2]; std::lock_guard lock(nulled_table_mutex); nulled_table_slots.erase(at); nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed); return true; } // A buffer V# (its first four dwords at `w`) whose base is in the title's own memory gets the console VA of a GPU // copy of that memory, in place. False for anything else: a null slot, an image, a V# already in the arena, or // memory no copy could be made of. `unbacked` (when given) is set for the last case: title memory with neither a // window nor a geometry copy behind it, which the caller writes as a zero-size range. bool rebase_title_vsharp(std::uint32_t* w, leonida::TitleVaAliases& aliases, bool make_window = true, bool* unbacked = nullptr) { const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3]; if (!(w0 | w1 | w2 | w3) || (w3 >> 30)) return false; // null, or not a buffer V# (TYPE, dword 3 bits 30-31) const std::uint64_t base = std::uint64_t(w0) | (std::uint64_t(w1 & 0xFFFFu) << 32); std::uint64_t host{}, remaining{}; // A base already rewritten to a copy below heap_base holds the low 48 bits of a negative offset. const std::uint64_t written = signed_vsharp_offsets() && (base & (1ull << 47)) ? base | ~((1ull << 48) - 1) : base; if (base < arena.size || (geometry.cap() && geometry.lookup(arena.address + written, host, remaining))) return false; const std::uint32_t stride = (w1 >> 16) & 0x3FFFu; const std::uint64_t span = std::uint64_t(w2) * (stride ? stride : 1); // A V# the layer wrote for one of its own buffers that the driver put below the arena (an upload buffer in // ReBAR memory, say): the low 48 bits of a negative offset, which the shaders read sign-extended // (vsharp_address). Not the title's memory: left as it is, never nulled. if (base & (1ull << 47)) { std::lock_guard lock(backing_mutex); if (gpu_backings.covers(arena.address + (base | ~((1ull << 48) - 1)), std::max(span, 1))) return false; } std::uint64_t to{}; if (geometry.cap()) { const leonida::gfx10::BufferWords words{w0, w1, w2, w3}; leonida::gfx10::Buffer desc{}; if (leonida::gfx10::decode(words, desc)) { // Untyped heap slots can contain ordinary pointers or other data. Large extents with // no format or fields outside our buffer encoding need independent evidence of a view. // An explicit table or a placed SRV can still establish the backing for those words. if (!make_window && span > kTitleWindowMax && (!desc.format || leonida::gfx10::encode(desc) != words)) { to = geometry.find(leonida::title_gpu_views::to_cpu(base, span), span); if (!to) return false; } else { to = geometry_va(base, span, false); } } } // A heap scan sees free-list links, raw data and inactive slots. Only explicit bindings may // request general-purpose windows. The heap can reuse an existing one or make a geometry mirror. if (!to) to = make_window ? aliases.resolve(base, span, leonida::TitleVaAliases::table_view) : aliases.shader_va(base, span); // to == 0: the title's memory, and neither a window nor a geometry copy could back it, or an address that is // nobody's (resolve_title_memory). to == base: no copy was asked for (a heap scan only looks existing ones up) // or the address is left as it is; that holds only when the device can reach it (a raw title address, or one // past every allocation, cannot be). A copy whose VA does not fit the V#'s 48 bits (an import below heap_base, // off by default) cannot be named here either, and the raw base is no better. False in each case, and // `unbacked` tells the caller to write it with no records instead of leaving a base a shader would add // heap_base to. if (!to || to == base || (to >> 48)) { // The resolver (make_window) answers 0 for an address the device cannot reach, so a base it left as it // is needs no second look; a heap scan only looked existing copies up and asks here. if (unbacked) *unbacked = !to || (to >> 48) || (!make_window && !device_reachable(base)); return false; } w[0] = std::uint32_t(to); w[1] = (w1 & 0xFFFF0000u) | std::uint32_t((to >> 32) & 0xFFFFu); return true; } // Indexed by actual Vulkan address, never by a placed buffer's CPU address. std::atomic backing_generation{}; // every add and release std::mutex backing_mutex; leonida::BufferVaIndex gpu_backings; // What changed for the console heaps' slot records (ConsoleHeap::records) since the last submission: backings and // copies released or added, alias ranges removed or added, title memory added. Unbounded: every change is applied // at the next refresh_console_heaps, which takes the whole list. Written from any thread, under the lock of what // changed (backing_mutex, the alias table's); slot_change_mutex is taken last and nothing is taken under it. // Nothing is kept before a console resource heap with a CPU copy exists (no slot has a record then). std::mutex slot_change_mutex; std::vector slot_changes; std::atomic slot_change_count{0}; // slot_changes.size(), readable without the lock std::atomic slot_records_live{false}; void note_slot_change(leonida::SlotChange::Kind kind, std::uint64_t lo, std::uint64_t bytes) { if (!bytes || !slot_records_live.load(std::memory_order_acquire)) return; const std::uint64_t hi = lo + bytes < lo ? UINT64_MAX : lo + bytes; std::lock_guard lock(slot_change_mutex); slot_changes.push_back({kind, lo, hi}); slot_change_count.store(slot_changes.size(), std::memory_order_release); } // A device range [address, address + bytes) as the V# bases that name it directly: arena offsets in the V#'s 48 // bits (a buffer below the arena, as sign-extended offsets, vsharp_address). Nothing for a range no V# reaches. void note_slot_source_added(VkDeviceAddress address, std::uint64_t bytes) { constexpr std::uint64_t mask = (1ull << 48) - 1; const std::uint64_t offset = address - arena.address; if (offset <= mask) note_slot_change(leonida::SlotChange::source_added, offset, bytes); else if (offset >= ~(mask >> 1)) note_slot_change(leonida::SlotChange::source_added, offset & mask, bytes); } // The alias table's changes (TitleVaAliases::add_listener), under its lock. static void alias_changed(void* device, leonida::TitleVaAliases::Change change, std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) { auto& self = *static_cast(device); using Change = leonida::TitleVaAliases::Change; if (change == Change::removed) { // What resolved through the range (by its base), and what names its copy (by the copy's address). self.note_slot_change(leonida::SlotChange::source_gone, title_va, bytes); self.note_slot_change(leonida::SlotChange::target_gone, self.arena.address + shader_va, bytes); // A title window it answered from may be answered by nothing now (retire_orphan_windows). if (self.title_window_count.load(std::memory_order_relaxed)) { std::lock_guard lock(self.window_alias_removal_mutex); if (self.window_alias_removals.size() < kWindowAliasRemovals) self.window_alias_removals.push_back({shader_va, bytes}); else self.window_alias_removals_overflow = true; self.window_alias_removals_pending.store(true, std::memory_order_release); } } else { self.note_slot_change(leonida::SlotChange::source_added, title_va, bytes); } } // A title-window or geometry-copy block was destroyed (TitleBufferWindows::destroy_block; its GPU work completed): // as for a released backing, the backed table cuts it and the key entries and heap slots answering into it go at // the next refresh, so no table names the freed memory. void title_block_gone(VkDeviceAddress address, VkDeviceSize bytes) { std::lock_guard lock(backing_mutex); backing_generation.fetch_add(1, std::memory_order_relaxed); note_slot_change(leonida::SlotChange::target_gone, address, bytes); if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes); } void backing(VkDeviceAddress address, uint64_t bytes, uint64_t id, bool add) { std::lock_guard lock(backing_mutex); backing_generation.fetch_add(1, std::memory_order_relaxed); if (add) { gpu_backings.insert(address, bytes, id); // A V# that named this range before it was backed, directly or through an alias, can resolve now. note_slot_change(leonida::SlotChange::target_added, address, bytes); note_slot_source_added(address, bytes); } else { gpu_backings.erase(address, id); // The heap slots whose copy names it are fixed again at the next refresh. note_slot_change(leonida::SlotChange::target_gone, address, bytes); // LEONIDA_CONSOLE_HEAP_GPU: the key entries answering into it go at the next refresh. if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes); } } enum class VsharpPath { table, shadow, scratch }; enum class VsharpResult { unchanged, rebased, empty }; // `refused` (when given): for an answer of 0, the copy an alias range named that was not backed (0: none), so the // console heap's slot record is found again when a backing is added there. uint64_t vsharp_address(uint64_t base, uint64_t bytes, leonida::TitleVaAliases::Kind kind = leonida::TitleVaAliases::created_view, bool make_window = true, bool try_geometry = false, uint64_t* refused = nullptr, bool* refused_room = nullptr, NoCopy* no_copy = nullptr, bool writable = true, bool passive = false) { if (refused) *refused = 0; if (refused_room) *refused_room = false; if (!base || !bytes) return 0; auto& aliases = leonida::title_va_aliases(); constexpr uint64_t mask = (1ull << 48) - 1; // A negative offset (a buffer of the layer's that the driver put below the arena) fits the 48 bits as the // translated shaders read them, sign-extended (docs/design.md, "Heap-relative buffer device addresses"); only // a buffer registered in gpu_backings or the geometry copies is ever accepted, so LEONIDA_IMPORT_BELOW_ARENA // still decides alone whether title memory is imported there. const auto encodable = [&](uint64_t offset) { const uint64_t limit = signed_vsharp_offsets() ? mask / 2 : mask; if (offset <= limit) return bytes - 1 <= limit - offset; return offset >= UINT64_MAX - mask / 2 && bytes - 1 <= mask / 2 - offset; // unsigned distance across zero }; const auto backed = [&](uint64_t offset) { if (!encodable(offset)) return false; const auto bda = arena.address + offset; { std::lock_guard lock(backing_mutex); if (gpu_backings.covers(bda, bytes)) return true; } uint64_t host{}, room{}; return geometry.cap() && geometry.lookup(bda, host, room) && room >= bytes; }; const auto path = [this](unsigned p) { vsharp_paths[p].fetch_add(1, std::memory_order_relaxed); }; uint64_t to{}, room{}; if (aliases.range_of(base, to, room)) { // A range that ends before the V# does: the resolver may give a stream pool's request one mapping for all // of it (resolve_pool_memory), as TitleVaAliases::resolve asks it for a short range. uint64_t whole{}; if (to && room < bytes && make_window && resolve_title_memory(base, bytes, whole) && whole) aliases.range_of(base, to, room); if (!to || room < bytes || !backed(to)) { if (refused) *refused = to; return path(1), 0; } aliases.note_translation(kind); return path(0), to; } // Title memory the page mirror holds: the V# names it as the title wrote it (heap_base + base is the mirror). if (page_mirror.mirror) { uint64_t lo{}, hi{}; if (aliases.title_memory(base, lo, hi) && bytes <= hi - base && page_mirror_resolve(base, bytes)) { if (writable) { if (passive) note_passive_title_write(base, bytes); else note_title_write(base, bytes); // a raw V# has no read/write bit; API CBVs/SRVs pass false } return path(6), base; } } // An already rewritten descriptor carries only the low 48 bits. uint64_t offset = base; if (signed_vsharp_offsets() && base <= mask && (base & (1ull << 47))) offset |= ~mask; if (backed(offset)) return path(2), offset; // Read the other way: bit 47 as a sign, for a below-arena buffer's V# the layer wrote itself. if (offset == base && base <= mask && (base & (1ull << 47)) && backed(base | ~mask)) return base | ~mask; if (try_geometry) { to = geometry_va(base, bytes, false, refused_room, no_copy, passive); if (to && encodable(to)) return path(3), to; } uint64_t lo{}, hi{}; if (make_window && bytes <= kTitleWindowMax && aliases.title_memory(base, lo, hi) && bytes <= hi - base) { to = aliases.resolve(base, bytes, kind, writable); uint64_t mapped{}; if (to && aliases.range_of(base, mapped, room) && mapped == to && room >= bytes && backed(to)) return path(4), to; if (refused) *refused = to; } return path(5), 0; } // vsharp_address's outcomes (diagnostics): alias hit, alias refused, arena VA, geometry copy, window, none. static constexpr unsigned kVsharpPathCount = 7; std::array, kVsharpPathCount> vsharp_paths{}; // LEONIDA_UNBACKED_VSHARP=1 (diagnostic): the buffer V#s fix_vsharp writes empty because nothing backs their base. // One line for each of the first 120 distinct bases (span and stride), and every 8192 such V#s a summary by 4 GiB // range of the base, so the address ranges the world's data comes from can be compared with the title memory. static void note_unbacked_vsharp(uint64_t base, uint64_t span, uint32_t stride, const uint32_t* w) { static const bool on = [] { const char* v = std::getenv("LEONIDA_UNBACKED_VSHARP"); return v && *v == '1'; }(); if (!on) return; static std::mutex mutex; static std::unordered_map seen; // base -> span static std::map by_range; // base >> 32 -> distinct bases static uint64_t count = 0; std::lock_guard lock(mutex); ++count; if (seen.emplace(base, span).second) { ++by_range[base >> 32]; if (seen.size() <= 120) std::fprintf(stderr, "[rt] unbacked-vsharp: #%zu base 0x%llx span %llu stride %u words %08x %08x %08x %08x\n", seen.size(), static_cast(base), static_cast(span), stride, w[0], w[1], w[2], w[3]); } if (!(count % 8192)) { std::vector> top; for (const auto& [range, n] : by_range) top.emplace_back(n, range); std::sort(top.rbegin(), top.rend()); std::string text; char item[64]; for (std::size_t i = 0; i < top.size() && i < 10; ++i) { std::snprintf(item, sizeof(item), "%s0x%llx00000000 x%llu", i ? "; " : "", static_cast(top[i].second), static_cast(top[i].first)); text += item; } std::fprintf(stderr, "[rt] unbacked-vsharp: %llu empty V#s, %zu distinct bases; by 4 GiB range: %s\n", static_cast(count), seen.size(), text.c_str()); } } // What fix_vsharp resolved a V# to, for a console heap's slot record (ConsoleHeapSlotRecords::set). struct VsharpRecord { leonida::ConsoleHeapSlotRecords::State state = leonida::ConsoleHeapSlotRecords::none; uint64_t base = 0, span = 0, target = 0; bool geometry = false; // its resolution asked for a geometry copy }; // The classes of the V# halves a console heap resolves to nothing (diagnostics, the heap's log line): what their // base is, as the lookups found it (note_resolution). enum Nothing : unsigned { nothing_refused, // an alias range or window names a copy that is not backed nothing_arena, // an arena offset nothing backs (freed, or never handed out) nothing_negative, // bit 47 set: a below-arena form nothing backs nothing_no_copy, // no geometry copy asked for (no format, a span past the window limit) nothing_not_title, // not the title's memory and not ours: freed or never allocated nothing_past_range, // the title's memory, the span past the end of its range nothing_known_buffer, // the title's memory under a buffer the device has (its V# is the buffer's) nothing_private, // the title's private pages: a heap's V# finds a copy but makes none nothing_room, // a copy refused for room or a block nothing_pool_alias, // the GPU-only view of pool memory whose copy was refused nothing_other, // no geometry copies at all, or the base is 0 nothing_classes }; static constexpr const char* kNothingNames[nothing_classes] = { "copy not backed", "arena offset", "bit 47", "no copy asked", "not title memory", "past its range", "a buffer's", "private pages", "no room", "pool alias", "other"}; struct ConsoleHeap; // `heap` (a console heap's slot): its counters (resolutions, their time, the classes of V#s that resolve to // nothing). `answers` (a slot the title rewrote): a V# whose exact range another half of that heap has a record // for, made the same way, takes that half's answer (ConsoleHeapSlotRecords::answer) after the changes noted since // are applied (sync_slot_changes): a record is fixed again by every change that could alter its answer, so a // current one gives what resolving again would. In the world 63-70% of the changed V# halves carry words seen // before, and each resolution walked the alias table, the backings, the geometry copies and the title memory // (VirtualQuery included) again. VsharpResult fix_vsharp(uint32_t* w, VsharpPath path, VsharpRecord* record = nullptr, ConsoleHeap* heap = nullptr, bool answers = false) { if ((w[3] >> 30) || !w[2]) return VsharpResult::unchanged; // image, empty slot or raw pointer const uint64_t base = uint64_t(w[0]) | (uint64_t(w[1] & 0xffff) << 32); const uint32_t stride = (w[1] >> 16) & 0x3fffu; const uint64_t span = uint64_t(w[2]) * (stride ? stride : 1); const leonida::gfx10::BufferWords words{w[0], w[1], w[2], w[3]}; leonida::gfx10::Buffer desc{}; const bool copy_geometry = leonida::gfx10::decode(words, desc) && (path != VsharpPath::scratch || span <= kTitleWindowMax || (desc.format && leonida::gfx10::encode(desc) == words)); if (heap && answers && record && answered_by_record(*heap, base, span, copy_geometry, *record)) { if (record->state == leonida::ConsoleHeapSlotRecords::resolved) { const uint64_t to = record->target - arena.address; // mod 2^64, as it was recorded if ((to & ((1ull << 48) - 1)) == base) { if (page_mirror.mirror && to == base && base >= arena.size) note_passive_title_write(base, span); return VsharpResult::unchanged; } w[0] = uint32_t(to); w[1] = (w[1] & 0xffff0000u) | uint32_t((to >> 32) & 0xffff); return VsharpResult::rebased; } note_unbacked_vsharp(base, span, stride, w); w[0] = w[1] = w[2] = 0; return VsharpResult::empty; } uint64_t refused = 0; bool refused_room = false; NoCopy no_copy = NoCopy::none; const auto start = heap ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; const auto to = vsharp_address(base, span, leonida::TitleVaAliases::table_view, path != VsharpPath::scratch, copy_geometry, &refused, &refused_room, &no_copy, true, true); if (heap) note_resolution(*heap, start, base, to, refused, copy_geometry, no_copy); if (record) { // The copy's device address (mod 2^64: a buffer below the arena has a negative offset). A geometry copy // refused for room is asked for again when copies are freed (SlotChange::geometry_room). using Records = leonida::ConsoleHeapSlotRecords; record->state = to ? Records::resolved : refused_room ? Records::waiting_room : Records::waiting; record->base = base; record->span = span; record->geometry = copy_geometry; record->target = to ? arena.address + to : refused ? arena.address + refused : 0; } if (!to) { static std::atomic_flag noted[3]{}; if (!noted[unsigned(path)].test_and_set(std::memory_order_relaxed)) { const char* where = path == VsharpPath::table ? "inline table" : path == VsharpPath::shadow ? "console shadow" : "console scratch"; std::fprintf(stderr, "[rt] d3d12: %s V# at 0x%llx (%llu bytes) has no GPU backing; zero records\n", where, (unsigned long long)base, (unsigned long long)span); } note_unbacked_vsharp(base, span, stride, w); w[0] = w[1] = w[2] = 0; return VsharpResult::empty; } if ((to & ((1ull << 48) - 1)) == base) return VsharpResult::unchanged; w[0] = uint32_t(to); w[1] = (w[1] & 0xffff0000u) | uint32_t((to >> 32) & 0xffff); return VsharpResult::rebased; } rt::d3d12::TitleImageUpload title_upload; // accessed with title_upload_mutex held std::mutex title_upload_mutex; // after title_texture_mutex when both are taken (the fill worker takes it alone) // WriteToSubresource/ReadFromSubresource without host image copy: one staging copy at a time, submitted to a // VkQueue the game's first queues do not use and waited for (review D9): the copy family's for colour textures, // the graphics family's for the rest (staged_copy). Created on first use. std::mutex staging_mutex; std::unique_ptr staging_queue; std::unique_ptr staging_copy_queue; // The GPU address arena (docs/d3d12_vulkan.md section 3.3): one host-visible, device-addressable VkBuffer that // stands in for the console's GPU address space. A console VA is an offset in it, and heap_base (push-constant // dwords 32-33) is its device address. It is at most 4 GiB, so every VA fits the 32-bit descriptor-table // pointers some shaders use, and no larger than the device's maxBufferSize and maxMemoryAllocationSize // (src/arena_size.h). The first 64 KiB are never handed out, so no resource has VA 0. // Its memory (src/arena_backing.h): with sparse binding, 2 MiB blocks bound as allocations need them and unbound // once the GPU is past their last use; without, one allocation over the whole arena (`memory`). The CPU reaches // an arena offset through arena_host() (or backing.with_host for an offset the caller does not hold), never by // adding it to one base pointer: a sparse arena has no single mapping. struct Arena { VkBuffer buffer = VK_NULL_HANDLE; bool indirect_arguments = false; VkDeviceMemory memory = VK_NULL_HANDLE; // without sparse binding only VkDeviceMemory zero_page = VK_NULL_HANDLE; // sparse unbind zero page (AMD Windows proprietary workaround) std::uint32_t sparse_memory_types = 0; // arena.buffer memoryTypeBits when sparse leonida::ArenaBacking backing; bool memory_type_known = false; VkBuffer staging_buffer = VK_NULL_HANDLE; VkDeviceMemory staging_memory = VK_NULL_HANDLE; std::uint32_t staging_memory_type = 0; bool staged = false; leonida::ArenaStaging staging; std::vector last_upload; // guarded by VulkanContext::tracker_mutex_ during execute_now std::uint8_t* mapped = nullptr; VkDeviceAddress address = 0; VkDeviceSize size = 0; VkDeviceSize first = 0; // the first offset handed out: below it are the null region and kArenaReserved std::uint32_t memory_type = 0; std::mutex mutex; leonida::ArenaBlocks blocks; // offset -> size, guarded by mutex (src/arena_blocks.h) // Diagnostics: a fault line is rate-limited, and the full block walk runs only on a fault or LEONIDA_ARENA_CHECK=1. ULONGLONG fault_report_ms = 0; std::uint64_t faults_suppressed = 0; bool check_all = false; // The high-water mark (D3D-55, open question 5): the arena's size is a guess until a run measures it. // `peak_end` is the highest end offset ever handed out, the size the arena must have; `peak_in_use` is the // most bytes live at once, which differs from it by fragmentation. bool log = false; // LEONIDA_ARENA_LOG=1: one line per VA handed out VkDeviceSize in_use = 0, peak_in_use = 0, peak_end = 0; VkDeviceSize use_in_use[5] = {}, use_peak[5] = {}; std::uint64_t allocations = 0, failures = 0; } arena; void arena_mark_dirty(VkDeviceSize offset, VkDeviceSize bytes) { if (arena.staged && bytes) arena.staging.mark(offset, bytes); } void arena_mark_dirty_ptr(const void* ptr, std::size_t bytes) { if (!arena.staged || !bytes || !ptr) return; if (arena.mapped) { const auto addr = reinterpret_cast(ptr); const auto base = reinterpret_cast(arena.mapped); if (addr >= base) { const std::uintptr_t off = addr - base; if (off < arena.size) { arena.staging.mark(static_cast(off), static_cast(std::min( bytes, static_cast(arena.size) - off))); return; } } } external_windows.mark_dirty_ptr(ptr, bytes); } static void shadow_mark_dirty(void* ctx, const void* ptr, std::size_t bytes) { static_cast(ctx)->arena_mark_dirty_ptr(ptr, bytes); } bool sync_arena_to_host(std::vector& copies) { if (!arena.staged || !context || copies.empty()) return true; arena.staging.subtract_dirty(copies); if (copies.empty()) return true; if (!context->copy_buffer_sync(arena.buffer, arena.staging_buffer, copies, info.queue, info.queue_family)) return false; arena.staging.note_readback(copies); return true; } // Batches arena + external window readbacks for already-retired GPU submissions into ONE copy submission on the // dedicated DMA copy queue (when available), avoiding stalls behind active graphics/compute work on info.queue. bool sync_retired_readbacks_to_host(std::vector& arena_copies, std::map>& ext_readbacks) { if (!arena.staged || !context) return true; std::vector batches; batches.reserve(1 + ext_readbacks.size()); bool has_arena = false; if (!arena_copies.empty()) { arena.staging.subtract_dirty(arena_copies); if (!arena_copies.empty()) { batches.push_back({arena.buffer, arena.staging_buffer, arena_copies}); has_arena = true; } } std::vector ext_slots; if (!ext_readbacks.empty()) external_windows.collect_host_readbacks(ext_readbacks, batches, ext_slots); if (batches.empty()) return true; if (!context->copy_buffers_sync(batches, readback_queue_handle(), readback_queue_family())) return false; if (has_arena) arena.staging.note_readback(arena_copies); if (!ext_slots.empty()) external_windows.note_host_readbacks(ext_slots, ext_readbacks); return true; } bool sync_arena_to_host(VkDeviceSize offset, VkDeviceSize bytes) { if (!arena.staged || !context || !bytes || offset >= arena.size) return true; const VkDeviceSize clamped = std::min(bytes, arena.size - offset); std::vector copies{{offset, offset, clamped}}; return sync_arena_to_host(copies); } std::uint32_t sparse_buffer_memory_types = 0; bool sparse_image_tiles = false; bool sparse_unbind_zero_page = false; VkDeviceMemory allocate_sparse_zero_page(VkDeviceSize bytes, std::uint32_t memory_type_bits, leonida::memory_breakdown::Consumer consumer) const { if (!bytes || !memory_type_bits || !context) return VK_NULL_HANDLE; VkMemoryRequirements req{}; req.size = bytes; req.alignment = bytes; req.memoryTypeBits = memory_type_bits; leonida::memory_breakdown::Owner owner(consumer); VkDeviceMemory mem = allocate(req, leonida::kArenaRequiredMemory, leonida::kArenaPreferredMemory, nullptr, /*device_address=*/true); if (!mem) return VK_NULL_HANDLE; void* mapped = nullptr; if (context->vk.vkMapMemory(info.device, mem, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { context->vk.vkFreeMemory(info.device, mem, nullptr); return VK_NULL_HANDLE; } std::memset(mapped, 0, std::size_t(bytes)); context->vk.vkUnmapMemory(info.device, mem); return mem; } bool tiles_share_arena() const { return (sparse_buffer_memory_types & (1u << arena.memory_type)) != 0; } VkBufferCreateInfo sparse_buffer_info(VkDeviceSize bytes) const { VkBufferCreateInfo result{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; result.size = bytes; result.flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT | VK_BUFFER_CREATE_SPARSE_ALIASED_BIT; result.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; if (info.conditional_rendering) result.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; // D3D12 reserved buffers are visible to DIRECT, COPY and COMPUTE queues without exposing Vulkan // queue-family ownership. Their tile bindings and accesses may use distinct families, so match the // CONCURRENT sharing policy used for ordinary buffers and the GPU address arena. share(result); return result; } // Per-page cache used while page_mirror.mutex is continuously held across filter_heap_page / // filter_heap_page_pieces / apply_in_place_changes / filter_heap_pages_batch_locked. Deduplicates repeated V# // (base, span) classifications within the same page fill so repeated descriptors avoid redundant lookups while // preserving exact ConsoleHeapSlotRecords state. Stored in DeviceState::page_mirror (not thread_local, so // gta6rt.exe emits zero C++ TLS destructor callbacks). struct FilterPageCache { enum class Outcome : std::uint8_t { empty = 0, mirrored, backed, waiting, defer }; struct Entry { std::uint64_t base = 0; std::uint64_t span = 0; std::uint64_t target = 0; ConsoleHeap* mirror_range_heap = nullptr; std::uint32_t gen = 0; Outcome outcome = Outcome::empty; }; static constexpr std::size_t kSize = 1024; std::array entries{}; std::uint32_t gen = 0; bool signed_vsharp = false; bool has_mirror = false; bool has_geometry = false; std::uint64_t arena_size = 0; void reset() noexcept { if (++gen == 0) { entries = {}; gen = 1; } } static std::size_t bucket(std::uint64_t base, std::uint64_t span) noexcept { const std::uint64_t h = (base >> 4) ^ (span * 0x9e3779b97f4a7c15ull); return static_cast((h ^ (h >> 17) ^ (h >> 31)) & (kSize - 1)); } Entry* find(std::uint64_t base, std::uint64_t span) noexcept { Entry& e = entries[bucket(base, span)]; return (e.gen == gen && e.outcome != Outcome::empty && e.base == base && e.span == span) ? &e : nullptr; } void put(std::uint64_t base, std::uint64_t span, Outcome outcome, std::uint64_t target = 0, ConsoleHeap* mr_heap = nullptr) noexcept { entries[bucket(base, span)] = {base, span, target, mr_heap, gen, outcome}; } }; struct FilterClearOp { std::uint32_t slot = 0; std::uint8_t halves = 0; // bit 0: half 0, bit 1: half 1 }; struct FilterPageWork { ConsoleHeap* heap = nullptr; std::uint8_t* out_buf = nullptr; bool persistent_buf = false; bool flushed = false; std::array written_slots{}; std::size_t written_count = 0; std::size_t changed = 0; std::uint64_t changed_class[4] = {}; std::uint64_t vsharp_halves = 0; std::uint64_t vsharps_as_written = 0; std::uint64_t vsharps_rejected = 0; std::uint64_t resolved = 0; std::vector clear_ops; std::vector defer_slots; std::vector> mirror_ranges; std::vector phase_b_full; void reset() noexcept { heap = nullptr; out_buf = nullptr; persistent_buf = false; flushed = false; written_slots = {}; written_count = 0; changed = 0; changed_class[0] = changed_class[1] = changed_class[2] = changed_class[3] = 0; vsharp_halves = 0; vsharps_as_written = 0; vsharps_rejected = 0; resolved = 0; clear_ops.clear(); defer_slots.clear(); mirror_ranges.clear(); phase_b_full.clear(); } }; // The page mirror (src/title_mirror.h): the title's GPU-readable pages at heap_base + their title address, so a V# // or a pointer the title wrote into its own memory reads them unchanged. Made once the sparse arena exists // (create_page_mirror), fed by xmem (src/title_frames.h, Feed), brought up to date before every submission // (refresh_page_mirror). Off (nothing made, every path as before) without bufferDeviceAddressCaptureReplay, aliased // strict sparse residency, the arena's bind queue, a sparse arena or signed V# offsets, or with LEONIDA_PAGE_MIRROR=0. struct PageMirror { std::mutex mutex; // everything below but `feed` std::unique_ptr mirror; std::vector chunks; VkDeviceMemory zero_page = VK_NULL_HANDLE; // sparse unbind zero page (AMD Windows proprietary workaround) VkSemaphore timeline = VK_NULL_HANDLE; // signalled by each bind batch std::uint64_t value = 0; std::uint64_t space_generation = ~std::uint64_t(0); // xmem's feed, queued under its own lock on the runtime's heap (xmem calls it with its locks held). struct Change { std::uintptr_t page; std::uint8_t* frame; std::shared_ptr keep; }; SRWLOCK feed_lock = SRWLOCK_INIT; leonida::host_heap::vector feed; std::atomic feed_pending{false}; std::atomic space_gen_atomic{0}; std::atomic in_place_pending{false}; std::atomic refresh_in_flight{0}; std::atomic flush_in_flight{0}; std::atomic fast_refreshes{0}; std::atomic resolved_fast{0}; std::atomic clipped_fast{0}; std::atomic since_ns_atomic{ std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()) .count()}; // Read-mostly snapshot of chunk coverage (base -> VkBuffer) + plain/ensured intervals so title recording // threads calling page_mirror_resolve() / page_mirror_buffer() take a shared lock and never contend on // page_mirror.mutex against async workers. // Lock order: page_mirror.mutex -> resolve_cache.mutex (never reversed). struct ResolveCache { std::shared_mutex mutex; std::uint64_t space_generation = 0; std::vector> chunks; std::map plain, ensured; } resolve_cache; std::vector taken; struct FeedOrder { std::uintptr_t page = 0; std::uint32_t seq = 0; }; struct FeedCollapsed { std::uint32_t seq = 0; bool had_prior = false; }; std::vector feed_order; std::vector feed_collapsed; std::vector feed_unwatch; std::vector feed_watch; // Which mirrored pages the host wrote (src/title_mirror_tracking.h): a policy behind a small interface, the // plainest correct one (a guard on every page) until a measured one replaces it. std::unique_ptr tracking; std::vector written; std::vector fed_now; // pages a change of this refresh mapped (sorted when non-empty) // Ordinary title memory (not physical pages) in the mirror's range: base -> end of each such reservation, the // runs of it whose pages are mirrored (merged: begin -> end), and those pages. Mirrored as readers name it // (page_mirror_resolve): each page its own home, filled from the page itself. A release or decommit there // (geometry_writes::note_released) unmaps them. std::map plain, ensured; std::set identity; leonida::geometry_writes::ReleaseQueue released; std::vector> released_ranges; // Since the last log line. std::uint64_t refreshes = 0, fed = 0, dirty = 0, uploads = 0, batches = 0, binds = 0, arm_failures = 0; std::uint64_t resolved = 0, resolve_refused = 0, identity_mapped = 0, identity_released = 0, clipped = 0; std::uint64_t written_back = 0, buffers = 0; std::uint64_t units_local = 0, units_host = 0; // home units by memory, all so far bool last_local = true; std::uint64_t presents = 0; // present serial at the last log line std::uint64_t faults_seen = 0, hot_seen = 0, cold_seen = 0; // the tracking's counters at the last log line std::uint64_t uploaded_seen = 0, conflicts_seen = 0; // the mirror's, likewise std::uint64_t unbinds_seen = 0, homes_freed_seen = 0; // The write-back's GPU copy of the homes it looks at (page_mirror_write_back_ranges): a host-cached buffer of // kReadbackPages pages, its command buffer and fence, made at the first write-back. Protected by // `readback_mutex` (lock order: `readback_mutex` -> `mutex`, never the reverse) so `mutex` is released across // the GPU copy and `vkWaitSemaphores`. And its cost since the last line: calls, milliseconds (the copies' // waits among them), the most one took, the bytes copied. std::mutex readback_mutex; VkBuffer readback = VK_NULL_HANDLE; VkDeviceMemory readback_memory = VK_NULL_HANDLE; const std::uint8_t* readback_host = nullptr; VkCommandPool readback_pool = VK_NULL_HANDLE; VkCommandBuffer readback_commands = VK_NULL_HANDLE; VkSemaphore readback_done = VK_NULL_HANDLE; // a timeline: value readback_value once the last copy is done std::uint64_t readback_value = 0; bool readback_failed = false; bool readback_in_flight = false; // under `mutex`: another thread is copying homes out; note mutations below // Lock order: readback_mutex -> page_mirror.mutex -> readback_submit_mutex -> submit_mutex / arena.mutex. // Serialises readback copy submission against hooks.bind so vkQueueBindSparse never races ahead of an // in-flight vkCmdCopyBuffer or waits on an unsubmitted readback_done semaphore value. std::mutex readback_submit_mutex; std::atomic readback_active_value{0}; // timeline value on readback_done for the submitted copy std::unordered_set readback_invalidated; // under `mutex`: physical frames invalidated during copy std::vector readback_slice_frames; // under `mutex`: sorted unique frames in active slice std::vector> readback_slice_skip_masks; // under `mutex`: upload()-modified pieces per slice frame std::unique_ptr readback_hash_pool; // under `readback_mutex`: lock-free Phase 1 hasher leonida::TitleMirror::PrehashedReadback readback_prehashed; // under `readback_mutex`: reusable Phase 1 sums std::vector> readback_exec_skip_masks; // under `readback_mutex`: Phase 2 per-slice masks std::vector readback_exec_skip_page; // under `readback_mutex`: Phase 2 skip flags struct AsyncReadback { bool active = false; std::uint64_t signal_value = 0; std::vector slice; std::vector> ranges; std::vector remaining_refs; std::size_t remaining_cursor = 0; double cpu_ms = 0; double waited_ms = 0; std::uint64_t read_bytes = 0; std::uint64_t slice_copied_bytes = 0; std::uint64_t written = 0; } readback_async; // under `readback_mutex` std::vector> readback_queued_ranges; // under `readback_mutex` std::atomic readback_async_pending{false}; // lock-free hint for write_back_titles() std::uint64_t write_back_calls = 0, read_back_bytes = 0; double write_back_ms = 0, write_back_wait_ms = 0, write_back_max_ms = 0; double ms = 0; // 7-part sub-split telemetry since the last 10 s log (ns / counts, under `mutex`). std::uint64_t split_lock_ns = 0, split_feed_ns = 0, split_collect_ns = 0; std::uint64_t split_arm_ns = 0, split_upload_ns = 0, split_filter_ns = 0, split_other_ns = 0; std::uint64_t split_vp_calls = 0, split_vq_calls = 0; std::uint64_t split_fast_tiles = 0, split_slow_tiles = 0, split_skip_tiles = 0; std::uint64_t split_bridged_runs = 0, split_wc_tiles = 0; std::uint64_t split_whole_pages = 0, split_inc_pages = 0, split_alias_pages = 0; std::uint64_t retire_poll_skip = 0; std::vector resolve_watch; std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now(); // The console heaps read in place (add_heap_in_place): their filter state is under this mutex too. std::vector in_place; // Reusable 64 KiB scratch buffer for filter_heap_page (under `mutex`; falls back to heap only if reentrant). std::array filter_scratch{}; bool filter_scratch_in_use = false; // Reusable filter caches & scratch buffers (under `mutex`; member-owned rather than thread_local so // gta6rt.exe has no C++ TLS destructor callbacks). std::unique_ptr filter_page_cache; bool filter_page_cache_in_use = false; std::unique_ptr out_scratch; bool out_scratch_in_use = false; std::vector batch_page_work; std::vector batch_out_bufs; bool batch_work_in_use = false; } page_mirror; static void page_mirror_feed(void* context, std::uintptr_t page, std::uint8_t* frame, const std::shared_ptr& keep) { auto& m = static_cast(context)->page_mirror; AcquireSRWLockExclusive(&m.feed_lock); m.feed.push_back({page, frame, keep}); m.feed_pending.store(true, std::memory_order_release); ReleaseSRWLockExclusive(&m.feed_lock); } static bool page_mirror_wanted() { static const bool on = [] { const char* v = std::getenv("LEONIDA_PAGE_MIRROR"); return !(v && v[0] == '0'); }(); return on; } void create_page_mirror(bool sparse_aliasing) { const char* why = nullptr; if (!page_mirror_wanted()) why = "LEONIDA_PAGE_MIRROR=0"; else if (!sparse_aliasing || !sparse_buffer_memory_types) why = "no aliased strict sparse buffers"; else if (!info.buffer_device_address_capture_replay) why = "no bufferDeviceAddressCaptureReplay"; else if (!info.arena_bind_queue) why = "no queue of its own for sparse binds"; else if (!arena.backing.sparse()) why = "the arena is one allocation"; else if (!signed_vsharp_offsets()) why = "the shaders read V# bases unsigned"; else if (!leonida::title_frames::attach_fn.load(std::memory_order_acquire)) why = "xmem is not loaded"; else if (!watch_shadow_writes()) why = "no write-fault handler to see the title's writes"; if (why) { std::fprintf(stderr, "[rt] d3d12: page mirror off: %s; title-written addresses read as before\n", why); return; } auto& vk = context->vk; VkSemaphoreTypeCreateInfo timeline_type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; timeline_type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; VkSemaphoreCreateInfo semaphore{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &timeline_type}; if (vk.vkCreateSemaphore(info.device, &semaphore, nullptr, &page_mirror.timeline) != VK_SUCCESS) { std::fprintf(stderr, "[rt] d3d12: page mirror off: no timeline semaphore\n"); return; } leonida::TitleMirrorHooks hooks; hooks.make_chunk = [this](std::uint64_t title_base, std::uint64_t bytes, VkBuffer& out) { auto& f = context->vk; VkBufferOpaqueCaptureAddressCreateInfo at{VK_STRUCTURE_TYPE_BUFFER_OPAQUE_CAPTURE_ADDRESS_CREATE_INFO}; const std::uint64_t want = arena.address + title_base; at.opaqueCaptureAddress = want; VkBufferCreateInfo create = sparse_buffer_info(bytes); create.flags |= VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT; at.pNext = create.pNext; create.pNext = &at; if (f.vkCreateBuffer(info.device, &create, nullptr, &out) != VK_SUCCESS) return false; VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = out; const std::uint64_t got = f.vkGetBufferDeviceAddress(info.device, &address); if (got != want) { std::fprintf(stderr, "[rt] d3d12: page mirror: the chunk for title 0x%llx came at 0x%llx, not 0x%llx\n", static_cast(title_base), static_cast(got), static_cast(want)); f.vkDestroyBuffer(info.device, out, nullptr); out = VK_NULL_HANDLE; return false; } page_mirror.chunks.push_back(out); return true; }; // Where a unit of homes goes, decided per unit as it is made: device-local memory while the device's budget // (VK_EXT_memory_budget) keeps room for the title's textures and render targets after it (kHomeHeadroom, or an // eighth of the budget if more), host memory otherwise; the GPU then reads those homes over the bus. A // device without the budget extension, or with every heap device-local (an integrated GPU), keeps device-local. hooks.make_unit = [this](VkDeviceMemory& out, std::uint8_t*& host) { VkMemoryRequirements requirements{}; requirements.size = leonida::TitleMirror::kUnitBytes; requirements.alignment = leonida::TitleMirror::kPage; requirements.memoryTypeBits = sparse_buffer_memory_types; std::uint32_t host_types = 0; // the sparse buffers' memory types outside device-local heaps for (std::uint32_t t = 0; t < memory.memoryTypeCount; ++t) if ((sparse_buffer_memory_types >> t & 1) && !(memory.memoryTypes[t].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) host_types |= 1u << t; bool local = true; if (host_types) { const leonida::VramBudget budget = read_vram_budget(info); if (budget.available) { constexpr std::uint64_t kHomeHeadroom = std::uint64_t(1536) << 20; const std::uint64_t headroom = std::max(kHomeHeadroom, budget.local_budget / 8); local = budget.local_usage + leonida::TitleMirror::kUnitBytes + headroom <= budget.local_budget; } } if (!local) requirements.memoryTypeBits = host_types; leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::mirror); out = allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, local ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : VK_MEMORY_PROPERTY_HOST_CACHED_BIT); if (out) { ++(local ? page_mirror.units_local : page_mirror.units_host); if (local != page_mirror.last_local) { page_mirror.last_local = local; std::fprintf(stderr, "[rt] d3d12: page mirror: homes go to %s from now on (%llu units in device-local " "memory, %llu in host memory so far)\n", local ? "device-local memory again: the budget has room" : "host memory (the GPU reads them over the bus): device-local memory is near " "its budget", static_cast(page_mirror.units_local), static_cast(page_mirror.units_host)); } } void* mapped = nullptr; if (!out || context->vk.vkMapMemory(info.device, out, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { if (out) context->vk.vkFreeMemory(info.device, out, nullptr); out = VK_NULL_HANDLE; return false; } host = static_cast(mapped); return true; }; hooks.free_unit = [this](VkDeviceMemory memory) { context->vk.vkFreeMemory(info.device, memory, nullptr); }; // On the arena's bind queue, under the arena's lock (its external synchronisation, see create_arena). hooks.bind = [this](const std::vector& binds, std::uint64_t value) { std::lock_guard readback_submit_guard(page_mirror.readback_submit_mutex); const std::uint64_t wait_readback = (page_mirror.readback_in_flight && page_mirror.readback_done) ? page_mirror.readback_active_value.load(std::memory_order_acquire) : 0; VkTimelineSemaphoreSubmitInfo signal{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; signal.waitSemaphoreValueCount = wait_readback ? 1u : 0u; signal.pWaitSemaphoreValues = &wait_readback; signal.signalSemaphoreValueCount = 1; signal.pSignalSemaphoreValues = &value; VkBindSparseInfo bind{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, &signal}; bind.waitSemaphoreCount = wait_readback ? 1u : 0u; bind.pWaitSemaphores = &page_mirror.readback_done; bind.bufferBindCount = std::uint32_t(binds.size()); bind.pBufferBinds = binds.data(); bind.signalSemaphoreCount = 1; bind.pSignalSemaphores = &page_mirror.timeline; std::lock_guard lock(arena.mutex); const VkResult result = context->observe_result( context->vk.vkQueueBindSparse(info.arena_bind_queue, 1, &bind, VK_NULL_HANDLE), "vkQueueBindSparse (page mirror)"); if (result == VK_ERROR_DEVICE_LOST) context->mark_device_lost(); return result == VK_SUCCESS; }; hooks.copy = [this](std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { const bool streaming = page_mirror.tracking && page_mirror.tracking->is_wc_page(reinterpret_cast(from)); return copy_guarded_host(to, from, bytes, streaming); }; hooks.copy_and_sum = [this](std::uint8_t* to, const std::uint8_t* from, std::size_t pieces, std::uint64_t* sums) { const bool streaming = page_mirror.tracking && page_mirror.tracking->is_wc_page(reinterpret_cast(from)); if (streaming) { if (!copy_guarded_host(to, from, pieces * leonida::shadow_keep::kPiece, true)) return false; leonida::shadow_keep::sum_of_batch_256(to, pieces, sums); return true; } return copy_and_sum_guarded_host(to, from, pieces, sums); }; // The pages of a console heap read in place (add_heap_in_place): their home holds the filtered slots. hooks.filter = [this](std::uint64_t va, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool fresh) { return filter_heap_page(va, to, from, bytes, fresh); }; hooks.filter_pieces = [this](std::uint64_t va, std::uint8_t* to, const std::uint8_t* scratch, std::size_t bytes, bool fresh, const std::array& changed_pieces) { return filter_heap_page_pieces(va, to, scratch, bytes, fresh, changed_pieces); }; if (sparse_unbind_zero_page) { std::uint32_t zero_types = sparse_buffer_memory_types; if (arena.sparse_memory_types) zero_types &= arena.sparse_memory_types; page_mirror.zero_page = allocate_sparse_zero_page(leonida::TitleMirror::kPage, zero_types, leonida::memory_breakdown::Consumer::mirror); if (page_mirror.zero_page) { hooks.zero_page = page_mirror.zero_page; std::fprintf(stderr, "[rt] d3d12: page mirror unbinds alias a 64 KiB zero page (cross-queue sparse unbind workaround)\n"); } else { std::fprintf(stderr, "[rt] d3d12: page mirror: failed to allocate 64 KiB sparse unbind zero page " "(memoryTypeBits=0x%x); falling back to VK_NULL_HANDLE unbinds\n", zero_types); } } page_mirror.mirror = std::make_unique(std::move(hooks)); page_mirror.tracking = std::make_unique(); leonida::geometry_writes::subscribe(page_mirror.released); // A vertex, index, copy or indirect-argument address no buffer of ours holds is looked up in the mirror. context->set_mirror_buffer([this](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { return page_mirror_buffer(va, size, buffer, offset); }); leonida::title_frames::attach_fn.load(std::memory_order_acquire)(this, &page_mirror_feed); std::fprintf(stderr, "[rt] d3d12: page mirror on: the title's reservations in [0x%llx, 0x%llx) at heap_base + " "their address (0x%llx up), bound to one home per physical page\n", static_cast(leonida::title_mirror_space::kLow), static_cast(leonida::title_mirror_space::kHigh), static_cast(arena.address + leonida::title_mirror_space::kLow)); } // For the readers that move onto the mirror (descriptor heaps read in place, geometry, shadows): whether every // page of [va, va + bytes) lies in a chunk of the mirror (a page with nothing bound reads zero there), and the // device address that holds the title address `va`. Every submission of command lists waits for the mirror's last // bind (VulkanContext::note_mirror_bind), so a reader recorded after refresh_page_mirror sees what it bound. bool page_mirror_covers(std::uint64_t va, std::uint64_t bytes) { if (!page_mirror.mirror || !bytes || va + bytes < va) return false; std::lock_guard lock(page_mirror.mutex); sync_mirror_space_locked(); // a reservation made just now (a heap in it, say) is covered at once for (std::uint64_t c = va & ~(leonida::TitleMirror::kChunk - 1); c < va + bytes; c += leonida::TitleMirror::kChunk) if (!page_mirror.mirror->covers(c)) return false; return true; } std::uint64_t page_mirror_address(std::uint64_t va) const { return arena.address + va; } // Whether a V# naming [base, base + span) can be read as the title wrote it, by a heap read in place: heap_base + // its base lies in the sparse arena (where nothing is bound reads zero), in title memory the mirror holds (named // to it as vsharp_address's mirror path does, page_mirror_resolve_locked: ordinary memory is mirrored then; // `mirrored` says so, for the write-back of what shaders store there), or in a non-sparse buffer or geometry copy // of ours (including below-arena bit-47 V#s regardless of signed_vsharp_offsets(), matching vsharp_address; when // `tracked_target` is given, it receives the backing's device address so the slot records a resolved target and // is re-filtered on target_gone). page_mirror.mutex held: only the in-place filter asks. bool reachable_as_written(std::uint64_t base, std::uint64_t span, bool& mirrored, std::uint64_t* tracked_target = nullptr) { constexpr std::uint64_t mask = (1ull << 48) - 1; mirrored = false; if (tracked_target) *tracked_target = 0; if (!base) return false; if (!span) span = 1; const auto encodable = [&](std::uint64_t offset) { const std::uint64_t limit = signed_vsharp_offsets() ? mask / 2 : mask; if (offset <= limit) return span - 1 <= limit - offset; return offset >= UINT64_MAX - mask / 2 && span - 1 <= mask / 2 - offset; }; const auto backed_direct = [&](std::uint64_t offset) { if (!encodable(offset)) return false; const VkDeviceAddress bda = arena.address + offset; bool ok = false; { std::lock_guard lock(backing_mutex); ok = gpu_backings.covers(bda, span); } if (!ok && geometry.cap()) { std::uint64_t host{}, room{}; ok = geometry.lookup(bda, host, room) && room >= span; } if (ok && tracked_target) *tracked_target = bda; return ok; }; std::uint64_t offset = base; if (signed_vsharp_offsets() && base <= mask && (base & (1ull << 47))) offset |= ~mask; if (offset < arena.size && span <= arena.size - offset) return true; if (page_mirror.mirror && offset == base && page_mirror_resolve_locked(base, span, true)) return mirrored = true; if (backed_direct(offset)) return true; // Read the other way: bit 47 as a sign, for a below-arena buffer's V# the layer wrote itself (vsharp_address). if (offset == base && base <= mask && (base & (1ull << 47)) && backed_direct(base | ~mask)) return true; return false; } // Title memory [va, va + bytes) as a reader names it (a V#, a root view, a vertex or index view, a stream-pool // range): true when the mirror holds all of it, and then the shader VA of the range is `va` itself (heap_base + // va). Physical pages are in the mirror as xmem maps them; ordinary memory is mirrored here, page by page, the first // time a reader names it (watched first, then filled; bound at this submission's flush). False (the caller keeps // its old backing) when the mirror is off, a page lies outside every chunk, or more than kMirrorNameMax of // ordinary memory not mirrored yet is named at once (a V# with a wild size: counted). static constexpr std::uint64_t kMirrorNameMax = std::uint64_t(256) << 20; bool page_mirror_resolve(std::uint64_t va, std::uint64_t bytes) { if (!page_mirror.mirror || !bytes || va + bytes < va) return false; // Fast shared-lock check for already-covered & already-ensured ranges (avoids page_mirror.mutex contention // between title recording threads and async queue submit workers). { auto& rc = page_mirror.resolve_cache; std::shared_lock shared(rc.mutex); if (rc.space_generation == leonida::title_mirror_space::generation() && !rc.chunks.empty()) { constexpr std::uint64_t kChunk = leonida::TitleMirror::kChunk; constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; const std::uint64_t end = va + bytes; bool covered = true; for (std::uint64_t c = va & ~(kChunk - 1); c < end; c += kChunk) { const auto it = std::lower_bound( rc.chunks.begin(), rc.chunks.end(), c, [](const auto& entry, std::uint64_t key) { return entry.first < key; }); if (it == rc.chunks.end() || it->first != c) { covered = false; break; } if (c > UINT64_MAX - kChunk) break; } if (covered) { bool all_ensured = true; auto it = rc.plain.upper_bound(va); if (it != rc.plain.begin() && std::prev(it)->second > va) --it; for (; it != rc.plain.end() && it->first < end; ++it) { const std::uint64_t from = (std::max)(it->first, va) & ~(kPage - 1); const std::uint64_t to = ((std::min)(it->second, end) + kPage - 1) & ~(kPage - 1); auto eit = rc.ensured.upper_bound(from); if (eit == rc.ensured.begin() || std::prev(eit)->first > from || std::prev(eit)->second < to) { all_ensured = false; break; } } if (all_ensured) { page_mirror.resolved_fast.fetch_add(1, std::memory_order_relaxed); return true; } } else { return false; } } } std::lock_guard lock(page_mirror.mutex); return page_mirror_resolve_locked(va, bytes, true); } // The reservations xmem placed since the last look get chunks, and the ordinary ones are known as such // (page_mirror.mutex held). void sync_mirror_space_locked() { auto& m = page_mirror; const std::uint64_t g = leonida::title_mirror_space::generation(); if (g == m.space_generation) return; m.space_generation = g; m.plain.clear(); std::vector> covered_chunks; leonida::title_mirror_space::for_each_taken([&](std::uint64_t base, std::uint64_t end, bool plain) { m.mirror->cover(base, end); if (plain) m.plain[base] = end; constexpr std::uint64_t kChunk = leonida::TitleMirror::kChunk; for (std::uint64_t c = base & ~(kChunk - 1); c < end; c += kChunk) { VkBuffer buf = VK_NULL_HANDLE; VkDeviceSize off = 0; if (m.mirror->chunk_at(c, buf, off)) covered_chunks.emplace_back(c, buf); if (c > UINT64_MAX - kChunk) break; } }); std::sort(covered_chunks.begin(), covered_chunks.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); covered_chunks.erase( std::unique(covered_chunks.begin(), covered_chunks.end(), [](const auto& a, const auto& b) { return a.first == b.first; }), covered_chunks.end()); { std::unique_lock rc_lock(m.resolve_cache.mutex); // TitleMirror never removes covered chunks until destroy_page_mirror(), so union monotonically to keep // resolve_cache.chunks 100% identical to m.mirror->covers()/chunk_at() even if a reservation is released. m.resolve_cache.chunks.insert(m.resolve_cache.chunks.end(), covered_chunks.begin(), covered_chunks.end()); std::sort(m.resolve_cache.chunks.begin(), m.resolve_cache.chunks.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); m.resolve_cache.chunks.erase( std::unique(m.resolve_cache.chunks.begin(), m.resolve_cache.chunks.end(), [](const auto& a, const auto& b) { return a.first == b.first; }), m.resolve_cache.chunks.end()); m.resolve_cache.plain = m.plain; m.resolve_cache.ensured = m.ensured; m.resolve_cache.space_generation = g; } m.space_gen_atomic.store(g, std::memory_order_release); } bool page_mirror_resolve_locked(std::uint64_t va, std::uint64_t bytes, bool make, bool defer_fill = false) { auto& m = page_mirror; if (!bytes || va + bytes < va) return false; sync_mirror_space_locked(); constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; const std::uint64_t end = va + bytes; for (std::uint64_t c = va & ~(leonida::TitleMirror::kChunk - 1); c < end; c += leonida::TitleMirror::kChunk) if (!m.mirror->covers(c)) return false; auto it = m.plain.upper_bound(va); if (it != m.plain.begin() && std::prev(it)->second > va) --it; for (; it != m.plain.end() && it->first < end; ++it) { const std::uint64_t from = (std::max)(it->first, va) & ~(kPage - 1); const std::uint64_t to = ((std::min)(it->second, end) + kPage - 1) & ~(kPage - 1); if (ensured_covers(from, to)) continue; if (!make) return false; if (to - from > kMirrorNameMax) { ++m.resolve_refused; return false; } m.resolve_watch.clear(); for (std::uint64_t page = from; page < to; page += kPage) { if (!m.mirror->mirrored(page)) m.resolve_watch.push_back(page); } if (!m.resolve_watch.empty()) { // Watch before filling so any write after the fill is in the next collect. m.tracking->watch_batch(m.resolve_watch.data(), m.resolve_watch.size()); for (const std::uint64_t page : m.resolve_watch) { auto* const frame = reinterpret_cast(static_cast(page)); note_readback_frame_invalidated_locked(frame); m.mirror->map(page, frame, nullptr, leonida::TitleMirror::kUnstamped, defer_fill); m.identity.insert(page); ++m.identity_mapped; } } ensure_run(from, to); } ++m.resolved; return true; } // The merged runs of mirrored ordinary memory (page_mirror.mutex held). bool ensured_covers(std::uint64_t from, std::uint64_t to) const { const auto& e = page_mirror.ensured; auto it = e.upper_bound(from); if (it == e.begin()) return false; --it; return it->first <= from && it->second >= to; } void ensure_run(std::uint64_t from, std::uint64_t to) { auto& e = page_mirror.ensured; auto it = e.upper_bound(from); if (it != e.begin() && std::prev(it)->second >= from) --it; while (it != e.end() && it->first <= to) { from = std::min(from, it->first); to = std::max(to, it->second); it = e.erase(it); } e[from] = to; std::unique_lock rc_lock(page_mirror.resolve_cache.mutex); page_mirror.resolve_cache.ensured = e; } // A slot-133 buffer over mirrored title memory (Resource::create_mirror_buffer): the chunk and offset that hold // all of [va, va + bytes), naming it to the mirror first. False when the mirror does not hold all of it or it // spans two chunks (one buffer binding cannot): the buffer then gets its old backing. bool page_mirror_chunk(std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) { if (!page_mirror.mirror || !bytes) return false; std::lock_guard lock(page_mirror.mutex); if (!page_mirror_resolve_locked(va, bytes, true, /*defer_fill=*/true) || !page_mirror.mirror->chunk_at(va, buffer, offset) || bytes > leonida::TitleMirror::kChunk - offset) return false; ++page_mirror.buffers; return true; } // VulkanContext's mirror lookup (set_mirror_buffer): the chunk and offset that hold [va, va + size), when the mirror // holds all of it already (named before: nothing is mirrored during a replay, whose binds would land after it). A // range that runs past its chunk is cut at the chunk's end (counted): a buffer binding cannot span two chunks. bool page_mirror_buffer(std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { if (!page_mirror.mirror || !size || va + size < va) return false; // Shared-lock fast path via resolve_cache so concurrent queue replays never stall behind // refresh_page_mirror()'s page_mirror.mutex hold. { auto& rc = page_mirror.resolve_cache; std::shared_lock shared(rc.mutex); if (rc.space_generation == leonida::title_mirror_space::generation() && !rc.chunks.empty()) { constexpr std::uint64_t kChunk = leonida::TitleMirror::kChunk; constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; const std::uint64_t end = va + size; VkBuffer first_chunk = VK_NULL_HANDLE; for (std::uint64_t c = va & ~(kChunk - 1); c < end; c += kChunk) { const auto it = std::lower_bound( rc.chunks.begin(), rc.chunks.end(), c, [](const auto& entry, std::uint64_t key) { return entry.first < key; }); if (it == rc.chunks.end() || it->first != c || !it->second) return false; if (!first_chunk) first_chunk = it->second; if (c > UINT64_MAX - kChunk) break; } auto it = rc.plain.upper_bound(va); if (it != rc.plain.begin() && std::prev(it)->second > va) --it; for (; it != rc.plain.end() && it->first < end; ++it) { const std::uint64_t from = (std::max)(it->first, va) & ~(kPage - 1); const std::uint64_t to = ((std::min)(it->second, end) + kPage - 1) & ~(kPage - 1); auto eit = rc.ensured.upper_bound(from); if (eit == rc.ensured.begin() || std::prev(eit)->first > from || std::prev(eit)->second < to) return false; } buffer = first_chunk; offset = va & (kChunk - 1); const std::uint64_t room = kChunk - offset; if (size > room) { size = room; page_mirror.clipped_fast.fetch_add(1, std::memory_order_relaxed); } page_mirror.resolved_fast.fetch_add(1, std::memory_order_relaxed); return true; } } std::lock_guard lock(page_mirror.mutex); if (!page_mirror_resolve_locked(va, size, false) || !page_mirror.mirror->chunk_at(va, buffer, offset)) return false; const std::uint64_t room = leonida::TitleMirror::kChunk - offset; if (size > room) { size = room; ++page_mirror.clipped; } return true; } // What the GPU wrote into the homes of mirrored pages of [begin, end) goes back to the title's pages // (TitleMirror::write_back: merged at the 256-byte piece, a piece only the GPU changed goes back, one both changed // keeps the title's bytes), once the submissions that could write them have retired (write_back_titles). The homes // are copied out by the GPU into host-cached memory first, kReadbackPages at a time: the CPU never reads a home, // which in device-local memory is an uncached read over the bus (run 64w: 14.5 s for one submission's 64 MiB). // Written through kernel_writes, which opens and pins the page and every other address of its physical page, so // the readers over them take the bytes. Returns the bytes written. static constexpr std::size_t kReadbackPages = 1024; // 64 MiB a copy bool readback_use_copy_queue() const noexcept { return !info.copy_queues.empty() && info.copy_family != UINT32_MAX; } std::uint32_t readback_queue_family() const noexcept { return readback_use_copy_queue() ? info.copy_family : info.queue_family; } VkQueue readback_queue_handle() const noexcept { return readback_use_copy_queue() ? info.copy_queues.back() : info.queue; } bool make_readback_locked() { auto& m = page_mirror; if (m.readback) return true; if (m.readback_failed) return false; auto& vk = context->vk; const VkDevice dev = info.device; m.readback_failed = true; VkBufferCreateInfo buffer{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; buffer.size = kReadbackPages * leonida::TitleMirror::kPage; buffer.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; if (vk.vkCreateBuffer(dev, &buffer, nullptr, &m.readback) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(dev, m.readback, &requirements); m.readback_memory = allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT); void* mapped = nullptr; VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; pool.queueFamilyIndex = readback_queue_family(); VkCommandBufferAllocateInfo commands{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; commands.commandBufferCount = 1; VkSemaphoreTypeCreateInfo timeline{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; timeline.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; VkSemaphoreCreateInfo semaphore{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &timeline}; const bool ok = m.readback_memory && vk.vkBindBufferMemory(dev, m.readback, m.readback_memory, 0) == VK_SUCCESS && vk.vkMapMemory(dev, m.readback_memory, 0, VK_WHOLE_SIZE, 0, &mapped) == VK_SUCCESS && vk.vkCreateCommandPool(dev, &pool, nullptr, &m.readback_pool) == VK_SUCCESS && (commands.commandPool = m.readback_pool, vk.vkAllocateCommandBuffers(dev, &commands, &m.readback_commands) == VK_SUCCESS) && vk.vkCreateSemaphore(dev, &semaphore, nullptr, &m.readback_done) == VK_SUCCESS; if (!ok) { destroy_readback_locked(); std::fprintf(stderr, "[rt] d3d12: page mirror: no buffer to copy homes out for the write-back: the GPU's " "writes into mirrored pages do not go back to the title\n"); return false; } m.readback_host = static_cast(mapped); m.readback_failed = false; return true; } void destroy_readback_locked() { auto& m = page_mirror; auto& vk = context->vk; const VkDevice dev = info.device; if (m.readback_done) vk.vkDestroySemaphore(dev, m.readback_done, nullptr); if (m.readback_pool) vk.vkDestroyCommandPool(dev, m.readback_pool, nullptr); if (m.readback) vk.vkDestroyBuffer(dev, m.readback, nullptr); if (m.readback_memory) vk.vkFreeMemory(dev, m.readback_memory, nullptr); m.readback_done = VK_NULL_HANDLE; m.readback_value = 0; m.readback_pool = VK_NULL_HANDLE; m.readback_commands = VK_NULL_HANDLE; m.readback = VK_NULL_HANDLE; m.readback_memory = VK_NULL_HANDLE; m.readback_host = nullptr; } // Submits the GPU copy of `refs` (at most kReadbackPages, page_mirror.readback_mutex held, page_mirror.mutex NOT // held) into the host-cached readback buffer after mirror bind batch `wait`, signalling `m.readback_done` at `done` // without blocking on the CPU. Emits 256-byte-aligned sub-page VkBufferCopy regions matching sorted disjoint // `ranges` while preserving exact `dstOffset = i * kPage + sub_off` staging layout. bool submit_homes_copy_locked(const leonida::TitleMirror::HomeRef* refs, std::size_t count, const std::vector>& ranges, std::uint64_t wait, std::uint64_t done, std::uint64_t& copied_bytes_out) { auto& m = page_mirror; auto& vk = context->vk; constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; constexpr std::uint64_t kPiece = leonida::shadow_keep::kPiece; copied_bytes_out = 0; VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; if (vk.vkResetCommandBuffer(m.readback_commands, 0) != VK_SUCCESS || vk.vkBeginCommandBuffer(m.readback_commands, &begin) != VK_SUCCESS) return false; // One copy command per run of pages/sub-pages in one chunk; adjacent regions in both src and dst are joined. std::vector regions; VkBuffer source = VK_NULL_HANDLE; const auto emit = [&] { if (source && !regions.empty()) vk.vkCmdCopyBuffer(m.readback_commands, source, m.readback, std::uint32_t(regions.size()), regions.data()); regions.clear(); }; const auto push_region = [&](VkDeviceSize src_off, VkDeviceSize dst_off, VkDeviceSize len) { if (!len) return; copied_bytes_out += len; if (!regions.empty() && regions.back().srcOffset + regions.back().size == src_off && regions.back().dstOffset + regions.back().size == dst_off) regions.back().size += len; else regions.push_back({src_off, dst_off, len}); }; std::size_t cursor = 0; for (std::size_t i = 0; i < count; ++i) { const std::uint64_t page = refs[i].page; const VkBuffer chunk = refs[i].chunk; const VkDeviceSize offset = refs[i].offset; if (!chunk) { vk.vkEndCommandBuffer(m.readback_commands); return false; } if (chunk != source) { emit(); source = chunk; } if (ranges.empty()) { push_region(offset, i * kPage, kPage); continue; } if (i > 0 && page < refs[i - 1].page) cursor = 0; while (cursor < ranges.size() && ranges[cursor].second <= page) ++cursor; if (cursor >= ranges.size() || ranges[cursor].first >= page + kPage) continue; // Coalesce 256-byte-aligned sub-ranges on this page so no two VkBufferCopy regions overlap. std::uint64_t run_lo = kPage, run_hi = kPage; for (std::size_t r = cursor; r < ranges.size() && ranges[r].first < page + kPage; ++r) { const std::uint64_t lo = (std::max)(ranges[r].first, page); const std::uint64_t hi = (std::min)(ranges[r].second, page + kPage); if (lo >= hi) continue; const std::uint64_t sub_lo = (lo - page) & ~(kPiece - 1); const std::uint64_t sub_hi = ((hi - page) + kPiece - 1) & ~(kPiece - 1); if (run_lo == kPage) { run_lo = sub_lo; run_hi = sub_hi; } else if (sub_lo <= run_hi) { if (sub_hi > run_hi) run_hi = sub_hi; } else { push_region(offset + run_lo, i * kPage + run_lo, run_hi - run_lo); run_lo = sub_lo; run_hi = sub_hi; } } if (run_lo < run_hi) push_region(offset + run_lo, i * kPage + run_lo, run_hi - run_lo); } emit(); VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT; vk.vkCmdPipelineBarrier(m.readback_commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &barrier, 0, nullptr, 0, nullptr); if (vk.vkEndCommandBuffer(m.readback_commands) != VK_SUCCESS) return false; VkTimelineSemaphoreSubmitInfo values{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; values.waitSemaphoreValueCount = wait ? 1u : 0u; values.pWaitSemaphoreValues = &wait; values.signalSemaphoreValueCount = 1; values.pSignalSemaphoreValues = &done; const VkPipelineStageFlags stage = VK_PIPELINE_STAGE_TRANSFER_BIT; VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &values}; submit.waitSemaphoreCount = wait ? 1u : 0u; submit.pWaitSemaphores = &m.timeline; submit.pWaitDstStageMask = &stage; submit.commandBufferCount = 1; submit.pCommandBuffers = &m.readback_commands; submit.signalSemaphoreCount = 1; submit.pSignalSemaphores = &m.readback_done; VkResult result; { std::unique_lock lock(context->submit_mutex(), std::defer_lock); leonida::submit_phases::lock_timed(lock); result = context->observe_result(vk.vkQueueSubmit(readback_queue_handle(), 1, &submit, VK_NULL_HANDLE), "vkQueueSubmit (page mirror write-back copy)"); } if (result == VK_ERROR_DEVICE_LOST) context->mark_device_lost(); return result == VK_SUCCESS; } bool poll_readback_locked(std::uint64_t done, bool& ready) { auto& m = page_mirror; std::uint64_t current = 0; const VkResult result = context->observe_result( context->vk.vkGetSemaphoreCounterValue(info.device, m.readback_done, ¤t), "vkGetSemaphoreCounterValue (page mirror write-back copy)"); if (result == VK_ERROR_DEVICE_LOST) context->mark_device_lost(); ready = result == VK_SUCCESS && current >= done; return result == VK_SUCCESS; } bool wait_readback_locked(std::uint64_t done) { auto& m = page_mirror; VkSemaphoreWaitInfo until{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; until.semaphoreCount = 1; until.pSemaphores = &m.readback_done; until.pValues = &done; const VkResult result = context->observe_result( context->vk.vkWaitSemaphores(info.device, &until, UINT64_MAX), "vkWaitSemaphores (page mirror write-back copy)"); if (result == VK_ERROR_DEVICE_LOST) context->mark_device_lost(); return result == VK_SUCCESS; } // Records whole-frame invalidation only if `frame` is actually in the currently active readback slice // (`page_mirror.mutex` held). Avoids poisoning `readback_invalidated` with unrelated hot/feed pages. void note_readback_frame_invalidated_locked(std::uint8_t* frame) { auto& m = page_mirror; if (!m.readback_in_flight || !frame || m.readback_slice_frames.empty()) return; if (std::binary_search(m.readback_slice_frames.begin(), m.readback_slice_frames.end(), frame)) m.readback_invalidated.insert(frame); } // Records piece-level upload() overwrites for frames in the active readback slice (`page_mirror.mutex` held). // For any piece the CPU just uploaded, CPU wins under TitleMirror's conflict rule so Phase 2 simply skips those // pieces without invalidating the whole page or pushing hot pages into an infinite retry_pages loop. void note_readback_pieces_uploaded_locked(std::uint8_t* frame, const std::array& changed_pieces) { auto& m = page_mirror; if (!m.readback_in_flight || !frame || m.readback_slice_frames.empty()) return; const auto it = std::lower_bound(m.readback_slice_frames.begin(), m.readback_slice_frames.end(), frame); if (it == m.readback_slice_frames.end() || *it != frame) return; const std::size_t idx = static_cast(it - m.readback_slice_frames.begin()); for (std::size_t w = 0; w < 4; ++w) m.readback_slice_skip_masks[idx][w] |= changed_pieces[w]; } void clear_readback_in_flight_locked() { auto& m = page_mirror; m.readback_in_flight = false; m.readback_active_value.store(0, std::memory_order_release); m.readback_invalidated.clear(); m.readback_slice_frames.clear(); m.readback_slice_skip_masks.clear(); } // Launches the next valid slice (<= kReadbackPages) from `refs[cursor..]` asynchronously (page_mirror.readback_mutex // held, page_mirror.mutex NOT held). Returns true if a copy is now in flight; false if no valid pages remained. bool kick_async_readback_locked(std::vector&& refs, std::size_t cursor, std::vector>&& ranges, double cpu_ms, double waited_ms, std::uint64_t read_bytes, std::uint64_t batch_written, std::uint64_t& written_out) { auto& m = page_mirror; using clock = std::chrono::steady_clock; const auto kick_start = clock::now(); std::vector slice; slice.reserve(kReadbackPages); while (cursor < refs.size()) { const std::size_t count = (std::min)(kReadbackPages, refs.size() - cursor); const std::size_t next_cursor = cursor + count; slice.clear(); std::uint64_t wait = 0; std::uint64_t done = 0; std::unique_lock submit_lock(m.readback_submit_mutex, std::defer_lock); { std::unique_lock mirror_lock(m.mutex, std::defer_lock); leonida::submit_phases::lock_timed(mirror_lock); if (!m.mirror) return false; for (std::size_t i = 0; i < count; ++i) { const auto& r = refs[cursor + i]; if (m.mirror->has_pending(r.page) || m.mirror->frame_at(r.page) != r.frame) continue; slice.push_back(r); } if (slice.empty()) { cursor = next_cursor; continue; } wait = m.value; done = ++m.readback_value; // Mark in_flight and take readback_submit_mutex before releasing m.mutex (lock order: // readback_mutex -> m.mutex -> readback_submit_mutex) so hooks.bind cannot submit // vkQueueBindSparse while submit_homes_copy_locked is submitting vkCmdCopyBuffer. m.readback_in_flight = true; m.readback_active_value.store(0, std::memory_order_release); m.readback_invalidated.clear(); m.readback_slice_frames.clear(); m.readback_slice_frames.reserve(slice.size()); for (const auto& r : slice) m.readback_slice_frames.push_back(r.frame); std::sort(m.readback_slice_frames.begin(), m.readback_slice_frames.end()); m.readback_slice_frames.erase( std::unique(m.readback_slice_frames.begin(), m.readback_slice_frames.end()), m.readback_slice_frames.end()); m.readback_slice_skip_masks.assign(m.readback_slice_frames.size(), {}); submit_lock.lock(); } std::uint64_t slice_copied_bytes = 0; const bool submitted = submit_homes_copy_locked(slice.data(), slice.size(), ranges, wait, done, slice_copied_bytes); if (submitted) m.readback_active_value.store(done, std::memory_order_release); submit_lock.unlock(); if (!submitted) { std::unique_lock mirror_lock(m.mutex, std::defer_lock); leonida::submit_phases::lock_timed(mirror_lock); clear_readback_in_flight_locked(); return false; } m.readback_async.active = true; m.readback_async.signal_value = done; m.readback_async.slice = std::move(slice); m.readback_async.ranges = std::move(ranges); m.readback_async.remaining_refs = std::move(refs); m.readback_async.remaining_cursor = next_cursor; m.readback_async.cpu_ms = cpu_ms + std::chrono::duration(clock::now() - kick_start).count(); m.readback_async.waited_ms = waited_ms; m.readback_async.read_bytes = read_bytes; m.readback_async.slice_copied_bytes = slice_copied_bytes; m.readback_async.written = batch_written; return true; } // All slices of this batch finished (or were skipped due to pending/remap). const double ms = cpu_ms + std::chrono::duration(clock::now() - kick_start).count(); { std::unique_lock mirror_lock(m.mutex, std::defer_lock); leonida::submit_phases::lock_timed(mirror_lock); m.read_back_bytes += read_bytes; ++m.write_back_calls; m.write_back_ms += ms; m.write_back_wait_ms += waited_ms; m.write_back_max_ms = (std::max)(m.write_back_max_ms, ms); m.written_back += batch_written; } written_out += batch_written; return false; } // Polls or waits on `m.readback_async` (page_mirror.readback_mutex held, page_mirror.mutex NOT held). // Returns true when no async readback remains in flight; false when `!wait_blocking` and a GPU copy is still running. bool finish_async_readback_locked(bool wait_blocking, std::vector& retry_pages, std::uint64_t& written_out) { auto& m = page_mirror; using clock = std::chrono::steady_clock; constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; struct PageWriteBackWriter { struct PageGuard { std::uint64_t pin = 0; bool scratch_frame = false; bool table_fallback = false; PageGuard() = default; PageGuard(std::uint64_t p, bool scratch, bool fallback) : pin(p), scratch_frame(scratch), table_fallback(fallback) {} PageGuard(const PageGuard&) = delete; PageGuard& operator=(const PageGuard&) = delete; PageGuard(PageGuard&& o) noexcept : pin(std::exchange(o.pin, 0)), scratch_frame(o.scratch_frame), table_fallback(o.table_fallback) {} ~PageGuard() { if (pin) leonida::kernel_writes::end_write(pin, false); } }; PageGuard begin_page(std::uint64_t page_va, std::uint8_t* frame, std::size_t first_off, std::size_t span_bytes) const { // xmem physical-page scratch views (frame != page_va) are unguarded host-mapped scratch: bypass // kernel_writes::begin_write/end_write completely and copy directly via move_guarded. if (reinterpret_cast(frame) != static_cast(page_va)) return PageGuard(0, true, false); void* const dst = frame + first_off; const auto dst_va = reinterpret_cast(dst); if (leonida::title_frames::may_hold(dst_va, dst_va + span_bytes)) return PageGuard(0, false, true); const std::uint64_t pin = leonida::kernel_writes::begin_write(dst, span_bytes, nullptr); return PageGuard(pin, false, false); } bool write(const PageGuard& guard, std::uint64_t at, const std::uint8_t* bytes, std::size_t n) const { if (!n) return true; void* const dst = reinterpret_cast(static_cast(at)); if (guard.scratch_frame) return leonida::kernel_writes::detail::move_guarded(dst, bytes, n); if (guard.table_fallback) return leonida::kernel_writes::write(dst, bytes, n); if (leonida::kernel_writes::detail::move_guarded(dst, bytes, n)) return true; return leonida::kernel_writes::reopen(dst, n) && leonida::kernel_writes::detail::move_guarded(dst, bytes, n); } } write; while (m.readback_async.active) { if (!wait_blocking) { bool ready = false; if (!poll_readback_locked(m.readback_async.signal_value, ready)) { std::unique_lock mirror_lock(m.mutex, std::defer_lock); leonida::submit_phases::lock_timed(mirror_lock); clear_readback_in_flight_locked(); m.readback_async = {}; return true; } if (!ready) return false; // GPU copy still running; return non-blockingly } else { const auto wait_start = clock::now(); const bool ok = wait_readback_locked(m.readback_async.signal_value); const double wms = std::chrono::duration(clock::now() - wait_start).count(); m.readback_async.waited_ms += wms; m.readback_async.cpu_ms += wms; if (!ok) { std::unique_lock mirror_lock(m.mutex, std::defer_lock); leonida::submit_phases::lock_timed(mirror_lock); clear_readback_in_flight_locked(); m.readback_async = {}; return true; } } const auto work_start = clock::now(); std::uint64_t slice_written = 0; const std::size_t slice_pages = m.readback_async.slice.size(); // Phase 1 (lock-free with respect to page_mirror.mutex): compute 256-byte GPU piece hashes across the // host-cached readback buffer in parallel using m.readback_hash_pool (owned solely by readback_mutex). if (slice_pages >= leonida::TitleMirror::kParallelThreshold && !m.readback_hash_pool) m.readback_hash_pool = leonida::TitleMirror::make_worker_pool(); leonida::TitleMirror::prehash_readback_slice(m.readback_async.slice.data(), slice_pages, m.readback_async.ranges, m.readback_host, m.readback_prehashed, m.readback_hash_pool.get()); // Phase 2 (short page_mirror.mutex hold): O(pieces) uint64 compare + coalesced write-back runs. { std::unique_lock mirror_lock(m.mutex, std::defer_lock); leonida::submit_phases::lock_timed(mirror_lock); if (!m.mirror) { clear_readback_in_flight_locked(); m.readback_async = {}; return true; } bool any_skip_page = false; bool any_skip_mask = false; if (!m.readback_invalidated.empty()) { m.readback_exec_skip_page.assign(slice_pages, 0); for (std::size_t i = 0; i < slice_pages; ++i) { const auto& r = m.readback_async.slice[i]; if (m.readback_invalidated.count(r.frame)) { m.readback_exec_skip_page[i] = 1; any_skip_page = true; if (!m.mirror->has_pending(r.page) && m.mirror->frame_at(r.page) == r.frame) retry_pages.push_back(r.page); } } } if (!m.readback_slice_frames.empty()) { bool any_nonzero_mask = false; for (const auto& mask : m.readback_slice_skip_masks) { if (mask[0] | mask[1] | mask[2] | mask[3]) { any_nonzero_mask = true; break; } } if (any_nonzero_mask) { m.readback_exec_skip_masks.assign(slice_pages, {}); for (std::size_t i = 0; i < slice_pages; ++i) { if (any_skip_page && m.readback_exec_skip_page[i]) continue; const auto it = std::lower_bound(m.readback_slice_frames.begin(), m.readback_slice_frames.end(), m.readback_async.slice[i].frame); if (it != m.readback_slice_frames.end() && *it == m.readback_async.slice[i].frame) { const std::size_t idx = static_cast(it - m.readback_slice_frames.begin()); const auto& mask = m.readback_slice_skip_masks[idx]; if (mask[0] | mask[1] | mask[2] | mask[3]) { m.readback_exec_skip_masks[i] = mask; any_skip_mask = true; } } } } } clear_readback_in_flight_locked(); slice_written = m.mirror->write_back_prehashed( m.readback_async.slice.data(), slice_pages, m.readback_prehashed, m.readback_host, any_skip_mask ? m.readback_exec_skip_masks.data() : nullptr, any_skip_page ? m.readback_exec_skip_page.data() : nullptr, write); } const double slice_cpu_ms = std::chrono::duration(clock::now() - work_start).count(); auto refs = std::move(m.readback_async.remaining_refs); const std::size_t cursor = m.readback_async.remaining_cursor; auto ranges = std::move(m.readback_async.ranges); const double cpu_ms = m.readback_async.cpu_ms + slice_cpu_ms; const double waited_ms = m.readback_async.waited_ms; const std::uint64_t read_bytes = m.readback_async.read_bytes + m.readback_async.slice_copied_bytes; const std::uint64_t batch_written = m.readback_async.written + slice_written; m.readback_async = {}; const bool launched_next = kick_async_readback_locked(std::move(refs), cursor, std::move(ranges), cpu_ms, waited_ms, read_bytes, batch_written, written_out); if (!wait_blocking && launched_next) return false; } return true; } std::uint64_t page_mirror_write_back_ranges(const std::vector>& ranges, bool blocking = true) { auto& m = page_mirror; if (!m.mirror || (ranges.empty() && !m.readback_async_pending.load(std::memory_order_acquire))) return 0; constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; std::vector retry_pages; std::uint64_t written = 0; { // Lock order: readback_mutex -> page_mirror.mutex. Release page_mirror.mutex around the GPU copy and wait // so concurrent refreshes and descriptor filtering never stall on vkWaitSemaphores. std::unique_lock readback_lock(m.readback_mutex, std::defer_lock); leonida::submit_phases::lock_timed(readback_lock); bool idle = !m.readback_async.active || finish_async_readback_locked(blocking, retry_pages, written); if (!idle) { // An async GPU copy is still running and caller requested non-blocking poll: queue incoming ranges and // only fall back to blocking if the pending range queue reaches its cap. if (!ranges.empty()) { m.readback_queued_ranges.insert(m.readback_queued_ranges.end(), ranges.begin(), ranges.end()); if (m.readback_queued_ranges.size() > kTitleWriteBackRanges) { // Compact first; only block if distinct disjoint ranges still exceed the cap. std::sort(m.readback_queued_ranges.begin(), m.readback_queued_ranges.end()); std::vector> compacted; compacted.reserve(m.readback_queued_ranges.size()); for (const auto& [b, e] : m.readback_queued_ranges) { if (!compacted.empty() && b <= compacted.back().second) compacted.back().second = (std::max)(compacted.back().second, e); else compacted.emplace_back(b, e); } m.readback_queued_ranges = std::move(compacted); } if (m.readback_queued_ranges.size() > kTitleWriteBackRanges) { idle = finish_async_readback_locked(true, retry_pages, written); } } if (!idle) { m.readback_async_pending.store(true, std::memory_order_release); } } if (idle) { std::vector> work; if (!m.readback_queued_ranges.empty()) { work = std::move(m.readback_queued_ranges); m.readback_queued_ranges.clear(); } if (!ranges.empty()) work.insert(work.end(), ranges.begin(), ranges.end()); if (!work.empty()) { std::sort(work.begin(), work.end()); std::vector> merged; merged.reserve(work.size()); for (const auto& [b, e] : work) { if (!merged.empty() && b <= merged.back().second) merged.back().second = (std::max)(merged.back().second, e); else merged.emplace_back(b, e); } std::vector refs; { std::unique_lock mirror_lock(m.mutex, std::defer_lock); leonida::submit_phases::lock_timed(mirror_lock); if (m.mirror) refs = m.mirror->homes_in_ranges(merged); } if (!refs.empty() && make_readback_locked()) { if (kick_async_readback_locked(std::move(refs), 0, std::move(merged), 0.0, 0.0, 0, 0, written) && blocking) { finish_async_readback_locked(true, retry_pages, written); } } } m.readback_async_pending.store(m.readback_async.active || !m.readback_queued_ranges.empty(), std::memory_order_release); } } for (const std::uint64_t page : retry_pages) note_title_write(page, kPage); return written; } std::uint64_t page_mirror_write_back(std::uint64_t begin, std::uint64_t end) { if (begin >= end) return 0; const std::vector> one{{begin, end}}; return page_mirror_write_back_ranges(one, true); } // Last in the before-execute hook, once every reader of this submission has named what it reads: the binds noted // since the last batch go in one, and every queue's next submission waits for it (the ordering rule). void flush_page_mirror() { auto& m = page_mirror; if (!m.mirror) return; // O(1) lock-free clean fast-path: verify BOTH no pending binds AND no concurrent flush in flight (seq_cst // after reading has_pending_binds() ensures another queue cannot slip past before note_mirror_bind() runs). if (!m.mirror->has_pending_binds() && m.flush_in_flight.load(std::memory_order_seq_cst) == 0) return; std::unique_lock lock(m.mutex, std::defer_lock); leonida::submit_phases::lock_timed(lock); m.flush_in_flight.fetch_add(1, std::memory_order_seq_cst); struct FlushGuard { std::atomic& n; ~FlushGuard() { n.fetch_sub(1, std::memory_order_release); } } in_flight{m.flush_in_flight}; if (m.mirror->flush(m.value + 1)) { ++m.value; ++m.batches; m.binds += m.mirror->last_batch(); const std::uint64_t retire_ticket = context->note_mirror_bind(m.timeline, m.value); m.mirror->stamp_freed(retire_ticket); } } // Lightweight feed-only drain for coalesced submissions: applies any pending CopyPageMappingsBatchX / xmem // remaps and lazy 2 GiB chunk creations + sparse binds without running write_back, arm_batch, incremental // upload, shadow refresh, or title texture refresh (avoiding full-pass single-flight convoys). // Returns true if any slow-path work ran under page_mirror.mutex. bool drain_page_mirror_feed_only() { auto& m = page_mirror; if (!m.mirror) return false; if (!m.feed_pending.load(std::memory_order_acquire) && leonida::title_mirror_space::generation() == m.space_gen_atomic.load(std::memory_order_acquire) && !m.mirror->has_pending_binds() && m.refresh_in_flight.load(std::memory_order_seq_cst) == 0 && m.flush_in_flight.load(std::memory_order_seq_cst) == 0) { return false; } std::unique_lock lock(m.mutex, std::defer_lock); leonida::submit_phases::lock_timed(lock); m.refresh_in_flight.fetch_add(1, std::memory_order_seq_cst); m.flush_in_flight.fetch_add(1, std::memory_order_seq_cst); struct FeedDrainGuard { std::atomic& r; std::atomic& f; ~FeedDrainGuard() { f.fetch_sub(1, std::memory_order_release); r.fetch_sub(1, std::memory_order_release); } } in_flight{m.refresh_in_flight, m.flush_in_flight}; sync_mirror_space_locked(); m.taken.clear(); AcquireSRWLockExclusive(&m.feed_lock); for (auto& change : m.feed) m.taken.push_back(std::move(change)); m.feed.clear(); m.feed_pending.store(false, std::memory_order_release); ReleaseSRWLockExclusive(&m.feed_lock); bool did_work = false; if (!m.taken.empty()) { did_work = true; m.fed += m.taken.size(); if (m.readback_in_flight) { for (const auto& change : m.taken) { note_readback_frame_invalidated_locked(m.mirror->frame_at(change.page)); note_readback_frame_invalidated_locked(change.frame); } } if (m.taken.size() == 1) { auto& change = m.taken[0]; if (!change.frame) m.tracking->unwatch(change.page); else if (m.mirror->covers(change.page)) m.tracking->watch(change.page); // defer_fill=false so newly created homes and aliased pages are filled/filtered before flush(). m.mirror->map(change.page, change.frame, std::move(change.keep), leonida::TitleMirror::kUnstamped, false); } else { m.feed_order.resize(m.taken.size()); for (std::size_t idx = 0; idx < m.taken.size(); ++idx) m.feed_order[idx] = {m.taken[idx].page, static_cast(idx)}; std::sort(m.feed_order.begin(), m.feed_order.end(), [](const auto& a, const auto& b) { return a.page != b.page ? (a.page < b.page) : (a.seq < b.seq); }); m.feed_collapsed.clear(); m.feed_unwatch.clear(); m.feed_watch.clear(); for (std::size_t r = 0; r < m.feed_order.size();) { std::size_t r_end = r + 1; while (r_end < m.feed_order.size() && m.feed_order[r_end].page == m.feed_order[r].page) ++r_end; const std::uint32_t last_seq = m.feed_order[r_end - 1].seq; const bool had_prior = (r_end - r) > 1; const auto& final_change = m.taken[last_seq]; m.feed_collapsed.push_back({last_seq, had_prior}); if (!final_change.frame) m.feed_unwatch.push_back(final_change.page); else if (m.mirror->covers(final_change.page)) m.feed_watch.push_back(final_change.page); r = r_end; } if (!m.feed_unwatch.empty()) m.tracking->unwatch_batch(m.feed_unwatch.data(), m.feed_unwatch.size()); if (!m.feed_watch.empty()) m.tracking->watch_batch(m.feed_watch.data(), m.feed_watch.size()); std::sort(m.feed_collapsed.begin(), m.feed_collapsed.end(), [](const auto& a, const auto& b) { return a.seq < b.seq; }); for (const auto& entry : m.feed_collapsed) { auto& change = m.taken[entry.seq]; const bool same_frame_after_churn = entry.had_prior && change.frame && m.mirror->frame_at(change.page) == change.frame; m.mirror->map(change.page, change.frame, std::move(change.keep), leonida::TitleMirror::kUnstamped, false); if (same_frame_after_churn && m.mirror->dirty(change.page)) ++m.dirty; } } m.taken.clear(); } if (m.mirror->has_pending_binds() && m.mirror->flush(m.value + 1)) { did_work = true; ++m.value; ++m.batches; m.binds += m.mirror->last_batch(); const std::uint64_t retire_ticket = context->note_mirror_bind(m.timeline, m.value); m.mirror->stamp_freed(retire_ticket); } return did_work; } void destroy_page_mirror() { if (!page_mirror.mirror) return; if (const auto attach = leonida::title_frames::attach_fn.load(std::memory_order_acquire)) attach(this, nullptr); context->set_mirror_buffer({}); leonida::geometry_writes::unsubscribe(page_mirror.released); std::lock_guard readback_lock(page_mirror.readback_mutex); if (page_mirror.readback_async.active && page_mirror.readback_done) { wait_readback_locked(page_mirror.readback_async.signal_value); } page_mirror.readback_async = {}; page_mirror.readback_queued_ranges.clear(); page_mirror.readback_async_pending.store(false, std::memory_order_release); page_mirror.readback_hash_pool.reset(); page_mirror.readback_prehashed = {}; page_mirror.readback_exec_skip_masks.clear(); page_mirror.readback_exec_skip_page.clear(); std::lock_guard lock(page_mirror.mutex); clear_readback_in_flight_locked(); { std::unique_lock rc_lock(page_mirror.resolve_cache.mutex); page_mirror.resolve_cache.chunks.clear(); page_mirror.resolve_cache.plain.clear(); page_mirror.resolve_cache.ensured.clear(); page_mirror.resolve_cache.space_generation = 0; } page_mirror.mirror.reset(); page_mirror.tracking.reset(); page_mirror.filter_page_cache.reset(); page_mirror.filter_page_cache_in_use = false; page_mirror.out_scratch.reset(); page_mirror.out_scratch_in_use = false; page_mirror.batch_page_work.clear(); page_mirror.batch_out_bufs.clear(); page_mirror.batch_work_in_use = false; destroy_readback_locked(); for (VkBuffer chunk : page_mirror.chunks) context->vk.vkDestroyBuffer(info.device, chunk, nullptr); page_mirror.chunks.clear(); if (page_mirror.zero_page) context->vk.vkFreeMemory(info.device, page_mirror.zero_page, nullptr); page_mirror.zero_page = VK_NULL_HANDLE; if (page_mirror.timeline) context->vk.vkDestroySemaphore(info.device, page_mirror.timeline, nullptr); page_mirror.timeline = VK_NULL_HANDLE; } // Before every submission (the before-execute hook, after write_back_titles): the reservations placed since get // chunks, xmem's changes are bound, the pages written since are filled again, and the binds go in one batch that // every queue's next submission waits for (VulkanContext::note_mirror_bind). A page is armed before its home is // filled, so a write after the fill faults and is in the next refresh. void refresh_page_mirror() { auto& m = page_mirror; if (!m.mirror) return; const auto start = std::chrono::steady_clock::now(); const std::int64_t start_ns = std::chrono::duration_cast(start.time_since_epoch()).count(); // O(1) lock-free clean-submission fast-path: skip locking page_mirror.mutex when no reservations, feeds, // releases, hot/dirty pages, retired homes, or in-place heap slot changes are pending and the 10 s log is not // due. { const bool log_due = (start_ns - m.since_ns_atomic.load(std::memory_order_acquire)) >= 10'000'000'000ll; const bool in_place_dirty = in_place_heaps.load(std::memory_order_acquire) != 0 && (slot_change_count.load(std::memory_order_acquire) != 0 || m.in_place_pending.load(std::memory_order_acquire)); if (!log_due && !in_place_dirty && leonida::title_mirror_space::generation() == m.space_gen_atomic.load(std::memory_order_acquire) && !m.feed_pending.load(std::memory_order_acquire) && !leonida::geometry_writes::has_released(m.released) && !m.tracking->has_pending_work() && !m.mirror->has_dirty() && !m.mirror->has_retired_homes() && m.refresh_in_flight.load(std::memory_order_seq_cst) == 0) { m.fast_refreshes.fetch_add(1, std::memory_order_relaxed); return; } } const std::int64_t t_start = leonida::submit_phases::now_ns(); std::unique_lock lock(m.mutex, std::defer_lock); leonida::submit_phases::lock_timed(lock); const std::int64_t t_lock = leonida::submit_phases::now_ns(); m.refresh_in_flight.fetch_add(1, std::memory_order_seq_cst); struct RefreshGuard { std::atomic& n; ~RefreshGuard() { n.fetch_sub(1, std::memory_order_release); } } in_flight{m.refresh_in_flight}; sync_mirror_space_locked(); m.taken.clear(); AcquireSRWLockExclusive(&m.feed_lock); for (auto& change : m.feed) m.taken.push_back(std::move(change)); m.feed.clear(); m.feed_pending.store(false, std::memory_order_release); ReleaseSRWLockExclusive(&m.feed_lock); m.fed_now.clear(); if (!m.taken.empty()) { m.fed += m.taken.size(); // 1. Invalidate readback_in_flight frames across ALL raw m.taken entries BEFORE collapsing. if (m.readback_in_flight) { for (const auto& change : m.taken) { note_readback_frame_invalidated_locked(m.mirror->frame_at(change.page)); note_readback_frame_invalidated_locked(change.frame); } } if (m.taken.size() == 1) { auto& change = m.taken[0]; m.fed_now.push_back(change.page); if (!change.frame) m.tracking->unwatch(change.page); else if (m.mirror->covers(change.page)) m.tracking->watch(change.page); m.mirror->map(change.page, change.frame, std::move(change.keep), leonida::TitleMirror::kUnstamped, true); } else { // 2. Collapse m.taken by change.page keeping only the final entry per page (avoiding redundant // unwatch+watch churn on xmem unmap+remap pairs), then batch unwatch/watch under single lock holds // and execute map() in final chronological order. m.feed_order.resize(m.taken.size()); for (std::size_t idx = 0; idx < m.taken.size(); ++idx) m.feed_order[idx] = {m.taken[idx].page, static_cast(idx)}; std::sort(m.feed_order.begin(), m.feed_order.end(), [](const auto& a, const auto& b) { return a.page != b.page ? (a.page < b.page) : (a.seq < b.seq); }); m.feed_collapsed.clear(); m.feed_unwatch.clear(); m.feed_watch.clear(); m.fed_now.reserve(m.taken.size()); for (std::size_t r = 0; r < m.feed_order.size();) { std::size_t r_end = r + 1; while (r_end < m.feed_order.size() && m.feed_order[r_end].page == m.feed_order[r].page) ++r_end; const std::uint32_t last_seq = m.feed_order[r_end - 1].seq; const bool had_prior = (r_end - r) > 1; const auto& final_change = m.taken[last_seq]; m.fed_now.push_back(final_change.page); m.feed_collapsed.push_back({last_seq, had_prior}); if (!final_change.frame) m.feed_unwatch.push_back(final_change.page); else if (m.mirror->covers(final_change.page)) m.feed_watch.push_back(final_change.page); r = r_end; } if (!m.feed_unwatch.empty()) m.tracking->unwatch_batch(m.feed_unwatch.data(), m.feed_unwatch.size()); if (!m.feed_watch.empty()) m.tracking->watch_batch(m.feed_watch.data(), m.feed_watch.size()); std::sort(m.feed_collapsed.begin(), m.feed_collapsed.end(), [](const auto& a, const auto& b) { return a.seq < b.seq; }); for (const auto& entry : m.feed_collapsed) { auto& change = m.taken[entry.seq]; // Guardrail: if {p, nullptr} was followed by {p, same_old_frame}, map() would see // old_frame == change.frame and return early; still mark dirty(p) so changed bytes upload. const bool same_frame_after_churn = entry.had_prior && change.frame && m.mirror->frame_at(change.page) == change.frame; m.mirror->map(change.page, change.frame, std::move(change.keep), leonida::TitleMirror::kUnstamped, true); if (same_frame_after_churn && m.mirror->dirty(change.page)) ++m.dirty; } } } m.taken.clear(); // Ordinary memory released or decommitted: its mirrored pages leave (named again, they are mirrored again). leonida::geometry_writes::take_released(m.released, m.released_ranges); bool ensured_changed = false; // Only pages the range holds whole: a freed heap block leaves the rest of its page to the blocks around it. for (const auto& [from, to] : m.released_ranges) { constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; for (auto page = m.identity.lower_bound((from + kPage - 1) & ~(kPage - 1)); page != m.identity.end() && *page + kPage <= to;) { if (m.readback_in_flight) note_readback_frame_invalidated_locked(m.mirror->frame_at(*page)); m.tracking->unwatch(*page); m.mirror->map(*page, nullptr, nullptr); ++m.identity_released; page = m.identity.erase(page); } if (to - from >= kPage) // a run that lost a page is named again (pages still there map to themselves) for (auto run = m.ensured.begin(); run != m.ensured.end();) { if (run->first < to && from < run->second) { run = m.ensured.erase(run); ensured_changed = true; } else { ++run; } } } if (ensured_changed) { std::unique_lock rc_lock(m.resolve_cache.mutex); m.resolve_cache.ensured = m.ensured; } const std::int64_t t_feed = leonida::submit_phases::now_ns(); m.tracking->collect(m.written); // re-watched before the copies below const bool have_fed = !m.fed_now.empty(); for (const std::uint64_t page : m.written) if ((!have_fed || !std::binary_search(m.fed_now.begin(), m.fed_now.end(), std::uintptr_t(page))) && m.mirror->dirty(page)) { ++m.dirty; } m.arm_failures += m.tracking->take_refused(); const std::int64_t t_collect = leonida::submit_phases::now_ns(); // The changes noted since (a buffer released, a texture come): the slots of heaps read in place they touch are // filtered again into their homes now, before the pages written since are. for (ConsoleHeap* heap : m.in_place) apply_in_place_changes(*heap); m.in_place_pending.store(false, std::memory_order_release); const std::int64_t t_in_place = leonida::submit_phases::now_ns(); std::uint64_t filter_batch_ns = 0; const auto filter_batch = [&](leonida::TitleMirror::AliasedPageJob* jobs, std::size_t count, leonida::TitleMirror::WorkerPool* pool, std::uint8_t* ok_out) { const std::int64_t fb0 = leonida::submit_phases::now_ns(); filter_heap_pages_batch_locked(jobs, count, pool, ok_out); const std::int64_t fb1 = leonida::submit_phases::now_ns(); if (fb1 > fb0) filter_batch_ns += std::uint64_t(fb1 - fb0); }; if (m.readback_in_flight && !m.readback_slice_frames.empty()) { m.uploads += m.mirror->upload( [&](std::uint8_t* frame, const std::array& changed_pieces) { note_readback_pieces_uploaded_locked(frame, changed_pieces); }, filter_batch); } else { m.uploads += m.mirror->upload([](std::uint8_t*, const std::array&) {}, filter_batch); } const std::int64_t t_upload = leonida::submit_phases::now_ns(); if (m.mirror->last_upload_bytes() != 0 || !m.fed_now.empty()) leonida::submit_phases::note_change(leonida::submit_phases::change_pages); if (m.mirror->has_retired_homes() && !m.readback_in_flight) { std::uint64_t completed = context->cached_completed_retire_ticket(); if (m.mirror->has_retired_homes(completed)) { m.mirror->retire(completed); m.retire_poll_skip = 0; } else if (++m.retire_poll_skip >= 16) { completed = context->completed_retire_ticket(); m.mirror->retire(completed); m.retire_poll_skip = 0; } } const std::int64_t t_end = leonida::submit_phases::now_ns(); { const auto arm_s = m.tracking->last_arm_stats(); const std::uint64_t lock_ns = std::uint64_t((std::max)(std::int64_t(0), t_lock - t_start)); const std::uint64_t feed_ns = std::uint64_t((std::max)(std::int64_t(0), t_feed - t_lock)); const std::uint64_t collect_total_ns = std::uint64_t((std::max)(std::int64_t(0), t_collect - t_feed)); const std::uint64_t arm_ns = (std::min)(arm_s.ns, collect_total_ns); const std::uint64_t collect_ns = collect_total_ns - arm_ns; const std::uint64_t in_place_ns = std::uint64_t((std::max)(std::int64_t(0), t_in_place - t_collect)); const std::uint64_t upload_total_ns = std::uint64_t((std::max)(std::int64_t(0), t_upload - t_in_place)); const std::uint64_t fb_clamped = (std::min)(filter_batch_ns, upload_total_ns); const std::uint64_t filter_ns = in_place_ns + fb_clamped; const std::uint64_t upload_ns = upload_total_ns - fb_clamped; const std::uint64_t other_ns = std::uint64_t((std::max)(std::int64_t(0), t_end - t_upload)); m.split_lock_ns += lock_ns; m.split_feed_ns += feed_ns; m.split_collect_ns += collect_ns; m.split_arm_ns += arm_ns; m.split_upload_ns += upload_ns; m.split_filter_ns += filter_ns; m.split_other_ns += other_ns; m.split_vp_calls += arm_s.vp_calls; m.split_vq_calls += arm_s.vq_calls; m.split_fast_tiles += arm_s.fast_tiles; m.split_slow_tiles += arm_s.slow_tiles; m.split_skip_tiles += arm_s.skip_tiles; m.split_bridged_runs += arm_s.bridged_runs; m.split_wc_tiles += arm_s.wc_tiles; m.split_whole_pages += m.mirror->last_whole_pages(); m.split_inc_pages += m.mirror->last_inc_pages(); m.split_alias_pages += m.mirror->last_aliased_pages(); } ++m.refreshes; const auto now = std::chrono::steady_clock::now(); m.ms += std::chrono::duration(now - start).count(); if (now - m.since >= std::chrono::seconds(10)) { m.refreshes += m.fast_refreshes.exchange(0, std::memory_order_relaxed); m.resolved += m.resolved_fast.exchange(0, std::memory_order_relaxed); m.clipped += m.clipped_fast.exchange(0, std::memory_order_relaxed); const auto c = m.mirror->counters(); const auto policy = m.tracking->stats(); const std::uint64_t presents = leonida::submit_phases::totals().present_serial.load(std::memory_order_relaxed); const std::uint64_t frames = presents - m.presents; std::fprintf(stderr, "[rt] d3d12: page mirror: %llu pages mirrored, %llu homes in %llu units (%llu MiB), %llu chunks " "(%llu not placed); in %.0f s: %llu refreshes, %llu changes fed, %llu pages written, %llu " "uploads, %llu binds (%llu unbinds, %llu homes freed) in %llu batches, %llu arms refused, " "%.3f ms a refresh; changes outside the chunks %llu; readers: %llu ranges resolved into it, " "%llu refused, %llu ordinary pages mirrored and %llu released, %llu buffer bindings cut at a " "chunk's end; %llu slot-133 buffers made on it, %llu KiB of GPU writes copied back (%llu KiB " "total); homes in device-local memory %llu units, in host memory %llu; tracking: %zu pages " "hot, %zu cold, %llu write faults, %llu hot and %llu cold copies; uploaded %.1f KiB a " "submission and %.1f KiB a frame; written back %.1f KiB a submission and %.1f KiB a frame; " "%llu pieces written on both sides (the title's kept); write-back: %llu calls, %.3f ms each " "(%.3f of it the GPU's copy of the homes and its wait), %.3f ms the longest, %.1f MiB of " "homes copied out\n", static_cast(c.pages), static_cast(c.homes), static_cast(c.units), static_cast(c.units * (leonida::TitleMirror::kUnitBytes >> 20)), static_cast(c.chunks), static_cast(c.chunk_failures), std::chrono::duration(now - m.since).count(), static_cast(m.refreshes), static_cast(m.fed), static_cast(m.dirty), static_cast(m.uploads), static_cast(m.binds), static_cast(c.unbinds - m.unbinds_seen), static_cast(c.homes_freed - m.homes_freed_seen), static_cast(m.batches), static_cast(m.arm_failures), m.refreshes ? m.ms / double(m.refreshes) : 0.0, static_cast(c.unmirrored_changes), static_cast(m.resolved), static_cast(m.resolve_refused), static_cast(m.identity_mapped), static_cast(m.identity_released), static_cast(m.clipped), static_cast(m.buffers), static_cast(m.written_back >> 10), static_cast(c.written_back_bytes >> 10), static_cast(m.units_local), static_cast(m.units_host), policy.hot, policy.cold, static_cast(policy.faults - m.faults_seen), static_cast(policy.hot_copies - m.hot_seen), static_cast(policy.cold_copies - m.cold_seen), m.refreshes ? double(c.uploaded_bytes - m.uploaded_seen) / 1024.0 / double(m.refreshes) : 0.0, frames ? double(c.uploaded_bytes - m.uploaded_seen) / 1024.0 / double(frames) : 0.0, m.refreshes ? double(m.written_back) / 1024.0 / double(m.refreshes) : 0.0, frames ? double(m.written_back) / 1024.0 / double(frames) : 0.0, static_cast(c.conflicts - m.conflicts_seen), static_cast(m.write_back_calls), m.write_back_calls ? m.write_back_ms / double(m.write_back_calls) : 0.0, m.write_back_calls ? m.write_back_wait_ms / double(m.write_back_calls) : 0.0, m.write_back_max_ms, double(m.read_back_bytes) / double(1 << 20)); const double denom = m.refreshes ? double(m.refreshes) : 1.0; const double ns_to_ms = m.refreshes ? (1.0 / (1e6 * double(m.refreshes))) : 0.0; const double split_total_ms = double(m.split_lock_ns + m.split_feed_ns + m.split_collect_ns + m.split_arm_ns + m.split_upload_ns + m.split_filter_ns + m.split_other_ns) * ns_to_ms; std::fprintf(stderr, "[rt] d3d12: page mirror split (ms/refresh): total %.3f = lock %.3f + feed %.3f + collect " "%.3f + arm %.3f + upload %.3f + filter %.3f + other %.3f; arm: %.1f VP, %.1f VQ, %.1f fast/" "%.1f slow/%.1f skip, %.1f bridged, %.1f WC; upload: %.1f whole + %.1f inc (%.1f alias) " "pages\n", split_total_ms, double(m.split_lock_ns) * ns_to_ms, double(m.split_feed_ns) * ns_to_ms, double(m.split_collect_ns) * ns_to_ms, double(m.split_arm_ns) * ns_to_ms, double(m.split_upload_ns) * ns_to_ms, double(m.split_filter_ns) * ns_to_ms, double(m.split_other_ns) * ns_to_ms, m.refreshes ? double(m.split_vp_calls) / denom : 0.0, m.refreshes ? double(m.split_vq_calls) / denom : 0.0, m.refreshes ? double(m.split_fast_tiles) / denom : 0.0, m.refreshes ? double(m.split_slow_tiles) / denom : 0.0, m.refreshes ? double(m.split_skip_tiles) / denom : 0.0, m.refreshes ? double(m.split_bridged_runs) / denom : 0.0, m.refreshes ? double(m.split_wc_tiles) / denom : 0.0, m.refreshes ? double(m.split_whole_pages) / denom : 0.0, m.refreshes ? double(m.split_inc_pages) / denom : 0.0, m.refreshes ? double(m.split_alias_pages) / denom : 0.0); m.split_lock_ns = m.split_feed_ns = m.split_collect_ns = 0; m.split_arm_ns = m.split_upload_ns = m.split_filter_ns = m.split_other_ns = 0; m.split_vp_calls = m.split_vq_calls = 0; m.split_fast_tiles = m.split_slow_tiles = m.split_skip_tiles = 0; m.split_bridged_runs = m.split_wc_tiles = 0; m.split_whole_pages = m.split_inc_pages = m.split_alias_pages = 0; m.write_back_calls = m.read_back_bytes = 0; m.write_back_ms = m.write_back_wait_ms = m.write_back_max_ms = 0; m.uploaded_seen = c.uploaded_bytes; m.conflicts_seen = c.conflicts; m.unbinds_seen = c.unbinds; m.homes_freed_seen = c.homes_freed; m.faults_seen = policy.faults; m.hot_seen = policy.hot_copies; m.cold_seen = policy.cold_copies; m.presents = presents; m.refreshes = m.fed = m.dirty = m.uploads = m.batches = m.binds = m.arm_failures = 0; m.resolved = m.resolve_refused = m.identity_mapped = m.identity_released = m.clipped = 0; m.written_back = m.buffers = 0; m.ms = 0; m.since = now; m.since_ns_atomic.store( std::chrono::duration_cast(now.time_since_epoch()).count(), std::memory_order_release); } } // What an arena range holds, for the high-water report (D3D-55). enum ArenaUse { arena_buffer, arena_descriptor_heap, arena_shader, arena_heap, arena_window, arena_use_count }; static_assert(arena_use_count == 5); static constexpr const char* kArenaUseNames[arena_use_count] = { "buffer", "descriptor heap", "shader", "heap", "title window/shadow"}; // A fault line about the arena is rate-limited to this interval: the walk behind it costs a pass over every // free block, and a persistent fault would otherwise print on every allocation of a streaming frame. static constexpr ULONGLONG kArenaReportMs = 5000; // One arena line per interval, so a fault that persists does not flood the log and a second, different fault // still gets its own line later (a one-shot flag would have hidden it). The count of suppressed lines is // printed with the next one. bool arena_report_due() { const ULONGLONG now = GetTickCount64(); if (arena.fault_report_ms && now - arena.fault_report_ms < kArenaReportMs) { ++arena.faults_suppressed; return false; } arena.fault_report_ms = now; return true; } void arena_report_suppressed(const char* what) { if (!arena.faults_suppressed) return; std::fprintf(stderr, "[rt] d3d12: GPU address arena: %llu earlier line(s) about %s were rate-limited\n", static_cast(arena.faults_suppressed), what); arena.faults_suppressed = 0; } // The free bytes and the live bytes must add up to the arena: a range released twice, or released without ever // having been allocated, breaks it. That check is O(1) and runs on every call; the whole block map is walked // only when it fails or LEONIDA_ARENA_CHECK=1 asks for it, since a walk costs a pass over every free block. void check_arena(const char* what) { const bool consistent = arena.blocks.consistent(arena.in_use); if (consistent && !arena.check_all) return; const auto fault = arena.blocks.check(); if (fault == leonida::ArenaBlocks::Fault::none && consistent) return; if (!arena_report_due()) return; const char* why = fault != leonida::ArenaBlocks::Fault::none ? leonida::ArenaBlocks::kFaultNames[static_cast(fault)] : "free + live does not add up to the arena"; std::fprintf(stderr, "[rt] d3d12: GPU address arena: %s left %llu KiB free and %llu KiB live of %llu the arena has " "minus %llu reserved (%s; %zu free blocks, %llu faults so far)\n", what, static_cast(arena.blocks.free_bytes() >> 10), static_cast(arena.in_use >> 10), static_cast(arena.size >> 10), static_cast(arena.blocks.reserved() >> 10), why, arena.blocks.count(), static_cast(arena.blocks.faults())); arena_report_suppressed(what); } bool arena_ready() const { return arena.backing.ready(); } // How the shaders read a V#'s 48-bit base: signed, a buffer outside the arena may lie on either side of heap_base // within 2^47 (TitleBufferWindows::allocate); unsigned, only above it. bool vsharp_offsets_signed() const { return signed_vsharp_offsets(); } // The device could bind the arena's memory as it is used (create_arena): sparse binding and residency, strict // non-resident reads, and a queue of its own for the binds. bool arena_sparse_capable = false; // The CPU address of [offset, offset + bytes) of the arena, inside an allocation the caller holds (its unit // cannot go while it lives), in constant time (src/arena_backing.h). Null, with a rate-limited line, when no // memory is behind that range or it crosses a backing unit: a caller's bug, never a silent write elsewhere. std::uint8_t* arena_host(VkDeviceSize offset, VkDeviceSize bytes) { std::uint8_t* host = arena.backing.host(offset, bytes); if (!host) note_unbacked_arena(offset, bytes); return host; } void note_unbacked_arena(VkDeviceSize offset, VkDeviceSize bytes) { static std::atomic refusals{0}; const std::uint64_t n = refusals.fetch_add(1, std::memory_order_relaxed); if (n < 16 || !(n & (n - 1))) std::fprintf(stderr, "[rt] d3d12: GPU address arena: no memory behind VA 0x%llx + 0x%llx; refused (%llu " "so far)\n", static_cast(offset), static_cast(bytes), static_cast(n + 1)); } // Unbinds and frees the arena's backing units whose last allocation is gone and whose release ticket the GPU has // passed (src/arena_backing.h). Called at the start of every ExecuteCommandLists, holding nothing: the completed // ticket is read first (it takes the submit lock), then the arena's lock is taken. void reclaim_arena() { if (!context || !arena.backing.sparse()) return; { // Non-blocking fast path: skip reclaiming on this submission if arena.mutex is currently held by another // thread's allocation or sparse bind, and return immediately when no backing units are pending. std::unique_lock lock(arena.mutex, std::try_to_lock); if (!lock.owns_lock() || !arena.backing.has_pending()) return; } const std::uint64_t completed = context->completed_retire_ticket(); std::lock_guard lock(arena.mutex); arena.backing.reclaim(completed); } // A zero-size range is refused: it would share its offset with the next range, and its release would collide // with that range's free entry. The fit test cannot wrap: free blocks lie inside the arena (below 4 GiB). bool arena_allocate(VkDeviceSize asked, VkDeviceSize alignment, VkDeviceSize& out, ArenaUse use) { if (!asked || asked > arena.size) return false; std::lock_guard lock(arena.mutex); // With sparse binding no allocation crosses a backing unit: one larger than a block takes whole blocks of its // own (src/arena_backing.h). arena_release rounds the same way. const VkDeviceSize bytes = arena.backing.footprint(asked); alignment = arena.backing.alignment(asked, alignment); // Not over a range of the title's own memory: the title's heap can lie below the arena's size, and a view // that names an address there must mean the title's bytes (TitleVaAliases::want_buffer). The walk holds no // iterator across this call, so a cut made under it cannot invalidate it (src/arena_blocks.h). bool found = arena.blocks.allocate( bytes, alignment, [this](std::uint64_t lo, std::uint64_t hi) { const std::uint64_t title = leonida::title_va_aliases().title_overlap_end(lo, hi); const std::uint64_t unit = arena.backing.keep_out(lo, hi); return std::max(title, unit); }, out); // Memory behind it before anyone can name it: bound now if its block has none. if (found && !arena.backing.acquire(out, bytes)) { arena.blocks.release(out, bytes); found = false; if (arena_report_due()) std::fprintf(stderr, "[rt] d3d12: GPU address arena: no memory could be bound for a %llu KiB " "allocation (%llu MiB bound)\n", static_cast(bytes >> 10), static_cast(arena.backing.stats().bound >> 20)); } if (!found) { ++arena.failures; if (arena.log) std::fprintf(stderr, "[rt] d3d12: arena %s: no room for 0x%llx bytes\n", kArenaUseNames[use], (unsigned long long)bytes); // The search restarted to its limit: say so, since the request may have been refusable anyway. if (arena.blocks.interrupted() && arena_report_due()) std::fprintf(stderr, "[rt] d3d12: GPU address arena: the block map was cut under a search %d times; " "a %llu KiB request was refused (live %llu KiB, free %llu KiB)\n", leonida::ArenaBlocks::kAttempts, static_cast(bytes >> 10), static_cast(arena.in_use >> 10), static_cast(arena.blocks.free_bytes() >> 10)); return false; } // The V# writers look this range up by device address (vsharp_address): an allocation registers its backing. backing(arena.address + out, bytes, out, true); ++arena.allocations; arena.in_use += bytes; arena.peak_in_use = std::max(arena.peak_in_use, arena.in_use); arena.peak_end = std::max(arena.peak_end, out + bytes); arena.use_in_use[use] += bytes; arena.use_peak[use] = std::max(arena.use_peak[use], arena.use_in_use[use]); if (arena.log) std::fprintf(stderr, "[rt] d3d12: arena %s VA 0x%llx + 0x%llx\n", kArenaUseNames[use], (unsigned long long)out, (unsigned long long)bytes); check_arena("an allocation"); return true; } // A console VA outside the arena (an upload or readback buffer: its device address minus heap_base). void log_va(const char* what, std::uint64_t va, VkDeviceSize bytes) { if (arena.log) std::fprintf(stderr, "[rt] d3d12: %s VA 0x%llx + 0x%llx (outside the arena)\n", what, (unsigned long long)va, (unsigned long long)bytes); } // Printed once at device release, so a run reports the size the arena needs; the arena line also about once a // minute with a console heap's log (report_arena_peak), since a run cut short never releases its device. void report_arena() { report_arena_peak(); report_title_memory(); } void report_arena_peak() { std::lock_guard lock(arena.mutex); if (!arena.size) return; const double mib = 1.0 / (1 << 20); const auto bound = arena.backing.stats(); std::fprintf(stderr, "[rt] d3d12: GPU address arena: bound %.1f MiB now (peak %.1f, %llu units of %.0f MiB blocks, %s), " "%llu binds, %llu unbind batches, %llu bind failures\n", bound.bound * mib, bound.peak_bound * mib, static_cast(bound.units), arena.backing.block() * mib, arena.backing.sparse() ? "sparse" : "one allocation", static_cast(bound.binds), static_cast(bound.unbinds), static_cast(bound.bind_failures)); std::fprintf(stderr, "[rt] d3d12: GPU address arena: peak end %.1f of %.1f MiB (%.1f%%), peak live %.1f MiB " "(buffers %.1f, descriptor heaps %.1f of which null guards %.1f now, shaders %.1f, heaps %.1f, " "windows/shadows %.1f), %llu allocations, %llu refused; %zu free blocks (largest %.1f MiB, %.1f " "MiB free)\n", arena.peak_end * mib, arena.size * mib, 100.0 * double(arena.peak_end) / double(arena.size), arena.peak_in_use * mib, arena.use_peak[arena_buffer] * mib, arena.use_peak[arena_descriptor_heap] * mib, double(arena_guard_bytes.load(std::memory_order_relaxed)) * mib, arena.use_peak[arena_shader] * mib, arena.use_peak[arena_heap] * mib, arena.use_peak[arena_window] * mib, (unsigned long long)arena.allocations, (unsigned long long)arena.failures, arena.blocks.count(), arena.blocks.largest().size * mib, arena.blocks.free_bytes() * mib); if (arena.staged) { const auto st = arena.staging.stats(); std::fprintf(stderr, "[rt] d3d12: GPU address arena staging (DEVICE_LOCAL VRAM): %llu flushes (%llu regions, %.1f " "MiB uploaded), %llu readbacks (%llu regions, %.1f MiB read back)\n", static_cast(st.flushes), static_cast(st.regions), double(st.bytes) * mib, static_cast(st.readbacks), static_cast(st.readback_regions), double(st.readback_bytes) * mib); if (external_windows.staged()) { const auto est = external_windows.staging_stats(); if (est.flushes || est.readbacks) std::fprintf(stderr, "[rt] d3d12: overflow VRAM slabs staging: %llu flushes (%llu regions, %.1f MiB " "uploaded), %llu readbacks (%llu regions, %.1f MiB read back)\n", static_cast(est.flushes), static_cast(est.regions), double(est.bytes) * mib, static_cast(est.readbacks), static_cast(est.readback_regions), double(est.readback_bytes) * mib); } } } void report_title_memory() { { std::lock_guard windows(title_window_mutex); const auto geometry_spans = std::count_if(pool_spans.begin(), pool_spans.end(), [](const PoolSpan& span) { return span.geometry; }); std::fprintf(stderr, "[rt] d3d12: title memory: %zu windows (%llu KiB of a %llu MiB budget, %llu refused, %llu " "retired once nothing reached them), %zu stream-pool extents (one mapping each, %llu KiB; " "%lld by geometry copy, %llu retired with their copy or window), %llu addresses given a " "zero-size view\n", title_windows.size(), static_cast(title_window_bytes >> 10), static_cast(title_window_cap >> 20), static_cast(title_window_refusals), static_cast(title_windows_retired), pool_spans.size(), static_cast(pool_span_bytes >> 10), static_cast(geometry_spans), static_cast(pool_spans_retired), static_cast(unbacked_requests)); } } void arena_release(VkDeviceSize offset, VkDeviceSize asked, ArenaUse use) { if (!asked) return; // Every submission made so far, and the one being recorded now, may name the range: its block is unbound only // once the GPU is past the next ticket (as VulkanContext::defer_destroy). An atomic read: no lock is taken. const std::uint64_t ticket = context ? context->submitted_retire_ticket() + 1 : 0; std::lock_guard lock(arena.mutex); const VkDeviceSize bytes = arena.backing.footprint(asked); // The range is validated and merged before the live-byte counters move: a release of a range the arena never // had must not change them, and a double free must not count the bytes twice. const auto fault = arena.blocks.release(offset, bytes); if (fault == leonida::ArenaBlocks::Fault::none) arena.backing.release(offset, bytes, ticket); if (fault != leonida::ArenaBlocks::Fault::outside_arena) { backing(arena.address + offset, bytes, offset, false); arena.in_use -= bytes; arena.use_in_use[use] -= bytes; // A heap copy re-fixes the slots that named a backing that has gone (slot_changes): the range is no view's. backing(arena.address + offset, bytes, offset, false); } if (fault != leonida::ArenaBlocks::Fault::none && arena_report_due()) { std::fprintf(stderr, "[rt] d3d12: GPU address arena: %s at VA 0x%llx + 0x%llx (live %llu KiB, free %llu KiB, " "%llu faults so far)\n", leonida::ArenaBlocks::kFaultNames[static_cast(fault)], static_cast(offset), static_cast(bytes), static_cast(arena.in_use >> 10), static_cast(arena.blocks.free_bytes() >> 10), static_cast(arena.blocks.faults())); arena_report_suppressed("arena releases"); } check_arena("a release"); } // Console descriptor heaps (Xbox slot 14, docs/d3d12_vulkan.md section 3.4). The title gives the heap's address // itself: memory of its own, at a console VA the shaders would reach as heap_base + VA, past the arena. It fills // the heap through Create*View and CopyDescriptors, and also by writing 32-byte descriptor records into that // memory itself and copying them with its own memcpy, which no API call sees. So shaders must read the title's // pages, not a copy the API keeps. Two ways, in this order: // - import: the heap's pages are imported as host memory (VK_EXT_external_memory_host, as a slot-133 buffer // on the title's pages is), so the GPU reads them as they are, with no copy. Shaders reach them at the // import's device address minus heap_base, which must stay below 4 GiB: most shaders keep only 32 bits of a // descriptor-table pointer (section 3.3). The title's own records are then read as written; T#s among them // that no Create*View registered are found by a scan that walks a part of the heap before every submission; // - copy: an arena range of the heap's size (at the console VA itself when the arena reaches that far), brought // up to date before every submission from the pages the title wrote since the last one (ShadowPages, the // slot-133 shadow's tracker); each slot copied is fixed up: a buffer V# whose base is the title's memory gets // the console VA of a GPU copy (rebase_title_vsharp), and an unregistered T# is bound (bind_title_image). // The tracker copies into a host mirror of the title's bytes, and only the slots whose bytes differ from what // their arena slot was made from (a second host copy) are fixed and written there again; a T# that found no // texture and a V# that found no backing are recorded as waiting (ConsoleHeap::records) and fixed again when a // texture, backing, alias or room comes for them (apply_slot_changes), never by looking again. Pages xmem // maps at two addresses are copied at every submission, and fixing all their slots each time, reading the // arena (uncached device memory) to do it, cost more than a frame (295 ms a submission for the 4 MiB of the // retail heap in use, RTX 4070 Ti). // A copy must not watch pages another import pins (a slot-133 buffer placed over the heap, as the retail // title does): it is only the fallback. // Descriptor tables bound at a console VA inside the heap, and the heap's base for SetDescriptorHeaps, are moved // to where shaders read it (console_heap_ranges). The copy is one way, as for slot 133. struct FreeConsoleScratch { void operator()(std::uint8_t* p) const { VirtualFree(p, 0, MEM_RELEASE); } }; struct ConsoleHeap { std::uint64_t console_va = 0; VkDeviceSize bytes = 0; std::uint64_t shader_va = 0; // where shaders read it VkDeviceSize guard = 0; // null bytes after the GPU copy (heap_guard_bytes/heap_guard_for), its allocation bool resource_heap = false; // a CBV/SRV/UAV heap; a sampler heap's S#s are copied as written bool imported = false; std::uint8_t* copy = nullptr; // writable GPU mirror of the console heap // Keep large scratch allocations out of the low addresses the title can use for its heap. std::unique_ptr scratch; std::uint8_t* input{}; std::uint8_t* previous{}; // import VkBuffer buffer = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; std::uint64_t pin = 0; // the imported pages' leonida::kernel_writes pin while `memory` lives std::size_t scan_at = 0; // the next slot the T# scan reads // copy bool identity = false; ShadowPagesPtr pages; std::vector mirror; // the title's bytes as the tracker last copied them std::vector made; // the title's bytes each arena slot was last made from // Per slot: in `retries`. On the CPU path a slot LEONIDA_CONSOLE_FIX_US deferred (fix_deferred_slots); in the // GPU mode (refresh_console_heap_gpu) also a T# whose texture is still to come (retry_console_tsharps). std::vector retry; // A resource heap's V# halves and T#s: what each resolved to or waits for (fix_console_slot), so a change of // the address space or of the textures re-fixes the slots it touches (apply_slot_changes), and a V# whose // buffer or a T# whose texture comes later is fixed when it does. leonida::ConsoleHeapSlotRecords records; std::vector retries; std::size_t retry_at = 0; // where retry_console_tsharps goes on (GPU mode) // Since the last log line: T# fixes left waiting (for a texture at their address, or room), and T#s that // waited and are bound now. std::uint64_t texture_waits = 0, texture_refills = 0; // V# halves answered by a waiting half of the same range (fix_vsharp), and how many of slot_changes this // heap has applied since refresh_console_heaps took the list (sync_slot_changes). std::uint64_t vsharps_answered = 0, vsharps_answered_resolved = 0; std::size_t changes_seen = 0; // Since the last log line: the full resolutions of its V# halves and their time, the classes of those that // resolved to nothing, and the longest refresh with its parts (pages, changes applied, slots fixed). std::uint64_t resolutions = 0; double resolution_ms = 0; std::uint64_t nothing[nothing_classes] = {}; // For the arena-offset and not-title-memory classes: what the host has at the base as an address // (nothing_where_kind), so a log names the memory a V# resolved to nothing names. std::uint64_t nothing_where[2][5] = {}; double max_ms = 0, max_pages_ms = 0, max_changes_ms = 0, max_fix_ms = 0; // Read in place (add_heap_in_place): the page mirror holds the title's heap pages, bound a second time into the // arena at shader_va, and fills their home through filter_heap_page. No copy, no page tracker of its own. // Under page_mirror.mutex, not console_heap_mutex (the filter runs inside the mirror's fills): `previous` (the // title's bytes each slot was last filtered from), the records, `deferred` (the slots whose V#s the mirror does // not hold or whose T# is to be bound: done outside the mirror's lock, finish_in_place), the title ranges its // V#s name in the mirror (for the write-back), `pending_changes` (noted after the mirror's last look at the // change list) and the counters since the last log line: pages filtered, slots that changed, the time, V# // halves read as written and halves deferred, and the presents in between (per-frame figures). bool in_place = false; std::atomic in_place_work_pending{false}; // lock-free hint: deferred, mirror_ranges, or pending_changes std::vector deferred; std::vector deferred_mark; std::vector> mirror_ranges; std::vector pending_changes; std::vector touched_scratch; std::uint64_t pages_filtered = 0, slots_filtered = 0, present_mark = 0; std::uint64_t vsharps_as_written = 0, vsharps_deferred = 0, vsharps_rejected = 0; double filter_ms = 0, deferred_ms = 0; // fix_console_slots' budget, for the current refresh, and the slots it nulled since the last log line std::chrono::steady_clock::time_point fix_start{}; bool fix_over = false; std::uint32_t fix_count = 0; std::uint64_t deferred_fixes = 0; std::uint64_t refreshes = 0, logged = 0; std::chrono::steady_clock::time_point log_time{}; // Since the last log line. std::uint64_t copied = 0, vsharps = 0, unbacked = 0, retried = 0; std::uint64_t images[5] = {}; // by TitleImage struct ReasonLess { bool operator()(const char* a, const char* b) const noexcept { return a != b && std::strcmp(a, b) < 0; } }; std::map refused_reasons; double ms = 0, pages_ms = 0, fix_ms = 0, retry_ms = 0; // ms: all; the others its parts // Changed slots by class (before the fix budget), since the last log line: all-zero, V# pair, T#, other // words; V# halves whose 16 bytes were seen before (a direct-mapped memo of 65536 keys, so a lower bound of // how often an exact-key translation would be found again); the slot records' work: changes applied, index // entries looked at, slots fixed again, and its time. std::uint64_t changed[4] = {}, vsharp_halves = 0, vsharp_repeats = 0; std::uint64_t record_changes = 0, record_looked = 0, record_refixed = 0; double record_ms = 0; std::vector> seen_keys; // LEONIDA_CONSOLE_HEAP_GPU (DeviceState::attach_console_heap_gpu): the translation pass's index of this heap // (-1: fixed on the CPU), the import of `input` the pass reads, the slots holding a V# pair (translated again // when a backing goes), and the slots queued for the pass since the last log line. int gpu = -1; VkBuffer input_buffer = VK_NULL_HANDLE; VkDeviceMemory input_memory = VK_NULL_HANDLE; std::vector vsharp_bits; std::uint64_t gpu_queued = 0; std::uint32_t gpu_high = 0; // one past the highest slot the title has written (a rescan's range) }; std::mutex console_heap_mutex; // taken before title_window_mutex, shadow_mutex and descriptor_mutex std::vector> console_heaps; std::atomic console_heap_signature{0xcbf29ce484222325ull}; void update_console_heap_signature_locked() { // console_heap_mutex held std::uint64_t sig = 0xcbf29ce484222325ull; for (const auto& h : console_heaps) { if (!h || !h->bytes) continue; const std::uint64_t begin = h->shader_va, end = h->shader_va + h->bytes + h->guard; sig = (sig ^ begin) * 0x100000001b3ull; sig = (sig ^ end) * 0x100000001b3ull; } console_heap_signature.store(sig, std::memory_order_release); } // Null slots after a shader-visible resource heap's GPU copy. A directly indexed heap is read at // heap VA + index * 32 with the index from data (docs/d3d12_vulkan.md section 3.4), and nothing bounds it: an // index past the heap read whatever the arena held after it, and a buffer V# made of those bytes sent loads and // stores to heap_base + garbage (GPU MMU faults at world start). With the guard such an index reads a null // descriptor instead (loads 0, stores dropped). As VIctory does for its host heaps (crates/victory-shader/src/emit // "Heap indices": at least 2^21 slots, those past the title's own null). // Two shapes: `heap_guard_bytes` is the fixed reach a directly indexed heap is given (2^21 slots, bounded so the // heap and its guard stay inside a 32-bit shader offset, LEONIDA_HEAP_GUARD_MB overrides), and `heap_guard_for` // is the per-heap guard a console heap's copy takes - as large as the heap, at least 1 MiB, at most // `heap_guard_cap()` (64 MiB by default, 0: no guard). Either comes out of the arena every default-heap buffer is // placed in; a heap the arena has no room for with its guard is made without one (logged). static constexpr VkDeviceSize kHeapGuardFloor = VkDeviceSize(1) << 20; static VkDeviceSize heap_guard_cap() { static const VkDeviceSize bytes = [] { constexpr VkDeviceSize fallback = VkDeviceSize(64) << 20; char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_HEAP_GUARD_MB", text, sizeof(text)); if (n == 0 || n >= sizeof(text)) return fallback; for (DWORD i = 0; i < n; ++i) if (text[i] < '0' || text[i] > '9') return fallback; // "-1" and the like: the default return VkDeviceSize(std::min(std::strtoull(text, nullptr, 10), 1024)) << 20; }(); return bytes; } static constexpr VkDeviceSize kHeapIndexReach = VkDeviceSize(1) << 26; // 2^21 slots of 32 bytes static VkDeviceSize heap_guard_bytes() { static const VkDeviceSize bytes = [] { char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_HEAP_GUARD_MB", text, sizeof(text)); if (n == 0 || n >= sizeof(text)) return kHeapIndexReach; return VkDeviceSize(std::min(std::strtoull(text, nullptr, 10), 1024)) << 20; }(); return bytes; } // The null bytes after a heap of `bytes`: as many as the heap, at least `floor`, at most heap_guard_cap(); grown so // heap and guard together end on a multiple of `align`. 0 with no cap. static VkDeviceSize heap_guard_for(VkDeviceSize bytes, VkDeviceSize floor, VkDeviceSize align) { const VkDeviceSize cap = heap_guard_cap(); if (!cap || !bytes) return 0; VkDeviceSize guard = std::min(std::max(bytes, floor), cap); if (align > 1) guard = (bytes + guard + align - 1) / align * align - bytes; return guard; } std::atomic arena_guard_bytes{0}; // the heap guards in the arena now (report_arena) // [start, start + bytes) of the arena, exactly. False when any of it is taken or past the arena. bool arena_allocate_at(VkDeviceSize start, VkDeviceSize asked, ArenaUse use) { if (!asked || start > arena.size || asked > arena.size - start) return false; std::lock_guard lock(arena.mutex); // At `start` exactly, rounded as arena_allocate rounds (so arena_release gives back the same bytes): it must lie // in one unit, or over blocks that have none yet. const VkDeviceSize bytes = arena.backing.footprint(asked); if (bytes > arena.size - start) return false; if (!arena.backing.placeable(start, bytes) || !arena.blocks.allocate_at(start, bytes)) return false; if (!arena.backing.acquire(start, bytes)) { arena.blocks.release(start, bytes); return false; } backing(arena.address + start, bytes, start, true); ++arena.allocations; arena.in_use += bytes; arena.peak_in_use = std::max(arena.peak_in_use, arena.in_use); arena.peak_end = std::max(arena.peak_end, start + bytes); arena.use_in_use[use] += bytes; arena.use_peak[use] = std::max(arena.use_peak[use], arena.use_in_use[use]); return true; } // Slot `slot` of a heap copy, as the title wrote it, fixed up as described above, and the only writer of a // resource heap's slot records. A T# that found no texture, or one that does not fit it, is recorded as waiting // for the texture at its address (or for room in its bindless array): a texture registered, replaced or gone there // fixes the slot again (apply_slot_changes), and nothing looks at it before. A sampler heap holds S#s: copied as // written. // `answers`: the title rewrote the slot (fix_console_slots), so a waiting V# of the same range may answer for it // (fix_vsharp). A slot fixed again because a change touched it is always resolved anew. // `out`: where the fixed slot goes, the heap's copy by default; for a heap read in place, its page's home in the // page mirror (filter_heap_page, refilter_slot). void fix_console_slot(ConsoleHeap& heap, std::size_t slot, bool answers = false, std::uint8_t* out = nullptr, bool mark_dirty = true) { std::uint32_t w[kDescriptorSize / 4]; std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize); bool vsharp = false; using Records = leonida::ConsoleHeapSlotRecords; Records::State texture = Records::none; std::uint64_t texture_address = 0; VsharpRecord halves[2]; const VsharpPath path = (heap.scratch || heap.in_place) ? VsharpPath::scratch : VsharpPath::shadow; if (!heap.resource_heap || !(w[0] | w[1] | w[2] | w[3])) { // A sampler heap holds S#s (copied as written); an all-zero slot stays null. } else if (!(w[3] >> 30)) { // A buffer V#: rewritten to the address its bytes are backed at (fix_vsharp: the console shadow, or the // console scratch an imported heap rewrites). A base nothing backs is written with no base and no records // and recorded as waiting: a backing, alias range or title memory added over it fixes the slot again // (apply_slot_changes). vsharp = true; const VsharpResult result = fix_vsharp(w, path, &halves[0], &heap, answers); if (result == VsharpResult::rebased) ++heap.vsharps; // Only the GPU copy changes; the title's bytes (heap.previous) stay as written. if (result == VsharpResult::empty) ++heap.unbacked; // The slot's second V# is a UAV counter (raw, 4 bytes, in the descriptor's upper 16 bytes): a store to it at // heap_base + a raw title address loses the device just as one through the buffer V# does. A counter with // no backing is nulled and waits as the buffer V# does. if (fix_vsharp(w + 4, path, &halves[1], &heap, answers) == VsharpResult::empty) ++heap.unbacked; } else { leonida::gfx10::ImageWords words; std::memcpy(words.data(), w, sizeof(words)); if (leonida::gfx10::is_image(words)) { const char* why = nullptr; std::uint32_t index_word = 0; std::uint64_t bound_address = 0; const TitleImage result = bind_title_image(*this, words, &why, tsharp_index_words ? &index_word : nullptr, &bound_address); const bool unbound = result == TitleImage::unknown || result == TitleImage::refused; // A pending_stream texture (or top-only partial view with last_mip < filled_from) returns // TitleImage::bound while deferring its bindless entry, leaving index_word == 0 (black fallback). // Record it as texture_waiting so SlotChange::texture_added always refills dword 6 once pages land. const bool waiting_index = tsharp_index_words && !unbound && result != TitleImage::not_tsharp && index_word == 0; if (unbound) { note_refused_tsharp(heap, slot * kDescriptorSize, words, why); ++heap.refused_reasons[why ? why : "?"]; } ++heap.images[unsigned(result)]; if (result == TitleImage::not_tsharp) { std::memset(w, 0, 16); } else { leonida::gfx10::Image image{}; leonida::gfx10::decode(words, image); // Waits under the address its texture is registered and announced at (note_texture_change). texture_address = bound_address ? bound_address : tsharp_texture_key(image.address); texture = (!unbound && !waiting_index) ? Records::texture_bound : (unbound && (why == kTsharpArrayFull || why == kTsharpStorageFull)) ? Records::texture_waiting_room : Records::texture_waiting; if (unbound || waiting_index) ++heap.texture_waits; else if (Records::is_waiting(heap.records.state(slot, 0)) && heap.records.base(slot, 0) == texture_address) ++heap.texture_refills; // the T# waited for this address and is bound now // The copy's dword 6 is the index shaders take (gfx10_descriptors.h, tsharp_index_word), or 0 while // the T# waits: a texture coming, going or being replaced at its address fixes the slot again // (apply_slot_changes), so the word follows the texture the T# names. The title's bytes and the // T#'s key keep the title's dword 6. if (tsharp_index_words) w[leonida::gfx10::kTsharpIndexDword] = (unbound || waiting_index) ? 0u : index_word; } } else { // Neither a buffer V# (TYPE is not 0) nor a T# the layer can decode: data the title keeps in the slot. // No image is found by these words (the bindless lookup misses, as for a null T#), but a shader that // takes the slot as a V# (an index from data, or one past what the title filled) adds heap_base to // words that name nothing: in the GPU copy the slot is null. ++heap.images[unsigned(TitleImage::not_tsharp)]; std::memset(w, 0, 16); } } auto* const dst = out ? out : heap.copy + slot * kDescriptorSize; std::memcpy(dst, w, kDescriptorSize); if (mark_dirty) arena_mark_dirty_ptr(dst, kDescriptorSize); if (heap.resource_heap) { if (vsharp) for (unsigned half = 0; half < 2; ++half) heap.records.set(slot, half, halves[half].state, halves[half].base, halves[half].span, halves[half].target, halves[half].geometry); else if (texture != Records::none) heap.records.set_texture(slot, texture, texture_address); else heap.records.clear(slot); } } static constexpr std::size_t kSeenKeysMask = 511u; // 512 entries (8 KiB): fits in L1d instead of thrashing 1 MiB L2/L3 static bool slots_equal_32(const std::uint8_t* a, const std::uint8_t* b) noexcept { #if defined(__AVX2__) const __m256i va = _mm256_loadu_si256(reinterpret_cast(a)); const __m256i vb = _mm256_loadu_si256(reinterpret_cast(b)); const __m256i diff = _mm256_xor_si256(va, vb); return _mm256_testz_si256(diff, diff) != 0; #else std::uint64_t a0 = 0, a1 = 0, a2 = 0, a3 = 0; std::uint64_t b0 = 0, b1 = 0, b2 = 0, b3 = 0; std::memcpy(&a0, a + 0, 8); std::memcpy(&a1, a + 8, 8); std::memcpy(&a2, a + 16, 8); std::memcpy(&a3, a + 24, 8); std::memcpy(&b0, b + 0, 8); std::memcpy(&b1, b + 8, 8); std::memcpy(&b2, b + 16, 8); std::memcpy(&b3, b + 24, 8); return ((a0 ^ b0) | (a1 ^ b1) | (a2 ^ b2) | (a3 ^ b3)) == 0; #endif } static void note_changed_vsharp_words(ConsoleHeap& heap, const std::uint32_t* w) { ++heap.changed[1]; if (heap.seen_keys.size() != kSeenKeysMask + 1) heap.seen_keys.assign(kSeenKeysMask + 1, {}); for (int half = 0; half < 2; ++half) { const std::uint32_t* k = w + 4 * half; if (!k[2]) continue; // no records: nothing to translate ++heap.vsharp_halves; std::uint32_t h = 2166136261u; for (int i = 0; i < 4; ++i) h = (h ^ k[i]) * 16777619u; auto& entry = heap.seen_keys[h & kSeenKeysMask]; if (entry[0] == k[0] && entry[1] == k[1] && entry[2] == k[2] && entry[3] == k[3]) ++heap.vsharp_repeats; else entry = {k[0], k[1], k[2], k[3]}; } } // Diagnostics only: the class of a changed slot, and whether its V# halves were seen before (ConsoleHeap::changed). static void note_changed_slot(ConsoleHeap& heap, const std::uint8_t* bytes) { std::uint32_t w[8]; std::memcpy(w, bytes, sizeof(w)); if (!(w[0] | w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7])) { ++heap.changed[0]; return; } if (w[3] >> 30) { leonida::gfx10::ImageWords words; std::memcpy(words.data(), w, sizeof(words)); ++heap.changed[leonida::gfx10::is_image(words) ? 2 : 3]; return; } note_changed_vsharp_words(heap, w); } // The slots on [offset, offset + bytes) of a heap copy's mirror, just brought up to date: each that differs from // what its arena slot was made from is written there and fixed up. // LEONIDA_CONSOLE_FIX_US limits the fixing in one submission (0, the default: no limit). Past it a changed slot is // written as a null descriptor and fixed at a later submission (fix_deferred_slots): after the story load the title rewrote up to // 3.7 MiB of its heap at once and one submission spent 28 s fixing it (speed-8). A shader reads such a slot as // empty until its turn comes, so a limit changes results: at the first world frame lib_cs_01144 read the size it // divides by from a nulled buffer slot and its loops never ended, which lost the device. void fix_console_slots(ConsoleHeap& heap, std::size_t offset, std::size_t bytes) { static const std::uint64_t budget_us = [] { char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_FIX_US", text, sizeof(text)); return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 0ull; }(); const std::size_t end = std::min(offset + bytes, std::size_t(heap.bytes)); if (!heap.resource_heap) { std::memcpy(heap.copy + offset, heap.input + offset, end - offset); arena_mark_dirty_ptr(heap.copy + offset, end - offset); return; } std::size_t dirty_lo = end, dirty_hi = 0; for (std::size_t at = offset & ~std::size_t(kDescriptorSize - 1); at + kDescriptorSize <= end; at += kDescriptorSize) { const std::size_t slot = at / kDescriptorSize; if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue; std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize); note_changed_slot(heap, heap.previous + at); if (budget_us && !heap.fix_over && !(++heap.fix_count & 15) && std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us)) heap.fix_over = true; // Buffer V#s (!(w3 >> 30)) only rebase address offsets, so they are fast and must never be // deferred or nulled: at the first world frame lib_cs_01144 reads its loop bound from a buffer // slot; nulling it causes an infinite loop and device loss. Only image T#s are deferred past budget. std::uint32_t w3 = 0; std::memcpy(&w3, heap.previous + at + 12, sizeof(w3)); const bool is_buffer_vsharp = !(w3 >> 30); if (at < dirty_lo) dirty_lo = at; dirty_hi = at + kDescriptorSize; if (heap.fix_over && !is_buffer_vsharp) { std::memset(heap.copy + at, 0, kDescriptorSize); heap.records.clear(slot); ++heap.deferred_fixes; if (!heap.retry[slot]) { heap.retry[slot] = 1; heap.retries.push_back(std::uint32_t(slot)); } continue; } heap.retry[slot] = 0; fix_console_slot(heap, slot, true, nullptr, /*mark_dirty=*/false); } if (dirty_hi > dirty_lo) arena_mark_dirty_ptr(heap.copy + dirty_lo, dirty_hi - dirty_lo); } // The slots LEONIDA_CONSOLE_FIX_US deferred at an earlier submission (null in the copy meanwhile): fixed first, // under the same budget; those past it wait for the next submission. Nothing else is in the list on this path. void fix_deferred_slots(ConsoleHeap& heap) { static const std::uint64_t budget_us = [] { char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_FIX_US", text, sizeof(text)); return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 0ull; }(); std::size_t done = 0; for (; done < heap.retries.size(); ++done) { if (budget_us && !(++heap.fix_count & 15) && std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us)) { heap.fix_over = true; break; } const std::uint32_t slot = heap.retries[done]; if (!heap.retry[slot]) continue; // rewritten or zeroed since heap.retry[slot] = 0; fix_console_slot(heap, slot); ++heap.retried; } heap.retries.erase(heap.retries.begin(), heap.retries.begin() + std::ptrdiff_t(done)); } // The changes since the last submission (slot_changes), applied to a resource heap's copy: each slot whose record // a change touches is fixed again - a V# whose backing, copy or alias range went, so the copy never names freed // memory, a waiting V# over which a backing, alias range or title memory was added or for which geometry room was // made, and a T# whose texture was registered, replaced or went at its address, or that waited for room in its // bindless array when entries were freed. Only the slots the changes name are looked at // (ConsoleHeapSlotRecords::touched); nothing reads the copy. std::vector slot_change_scratch; // console_heap_mutex std::uint64_t geometry_room_seen = 0; // geometry.free_generation() at the last refresh (console_heap_mutex) void apply_slot_changes(ConsoleHeap& heap, const std::vector& changes) { if (!heap.resource_heap || changes.empty()) return; const auto start = std::chrono::steady_clock::now(); const std::uint64_t looked = heap.records.looked_at(); heap.records.touched(changes.data(), changes.size(), slot_change_scratch); heap.record_changes += changes.size(); heap.record_looked += heap.records.looked_at() - looked; heap.record_refixed += slot_change_scratch.size(); // A slot deferred by the fix budget (null in the copy) is fixed from its list, not here. for (const std::uint32_t slot : slot_change_scratch) if (!heap.retry[slot]) fix_console_slot(heap, slot); heap.record_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); } // ---- Console heaps read in place (add_heap_in_place) ---- // Lock order: console_heap_mutex, then page_mirror.mutex, then slot_change_mutex. The filter runs inside the // mirror's fills (page_mirror.mutex held, console_heap_mutex not), so under the mirror's lock it does only what // needs no other lock of ours: reachability (reachable_as_written), nulls, and the list of slots to finish. The rest // - a V# the mirror does not hold resolved as before, a T# bound - is finish_in_place's, in the heap's refresh // (console_heap_mutex held), outside the mirror's lock, its result written into the home under it. // Acquires the hoisted FilterPageCache for this DeviceState under page_mirror.mutex. A re-entrant fill triggered // by page_mirror_resolve_locked() -> map() reuses the live batch cache without resetting it. struct FilterCacheScope { FilterPageCache* cache = nullptr; bool* in_use = nullptr; explicit FilterCacheScope(DeviceState& dev) { if (!dev.page_mirror.filter_page_cache) dev.page_mirror.filter_page_cache = std::make_unique(); cache = dev.page_mirror.filter_page_cache.get(); if (dev.page_mirror.filter_page_cache_in_use) return; dev.page_mirror.filter_page_cache_in_use = true; in_use = &dev.page_mirror.filter_page_cache_in_use; cache->reset(); cache->signed_vsharp = signed_vsharp_offsets(); cache->has_mirror = dev.page_mirror.mirror != nullptr; cache->has_geometry = dev.geometry.cap() != 0; cache->arena_size = dev.arena.size; if (cache->has_mirror) dev.sync_mirror_space_locked(); } ~FilterCacheScope() { if (in_use) *in_use = false; } FilterCacheScope(const FilterCacheScope&) = delete; FilterCacheScope& operator=(const FilterCacheScope&) = delete; }; // Coalesces contiguous changed 32-byte descriptor slots across a 64 KiB page (2048 slots = 32 x 64-bit mask words) // from cached host RAM `out_buf` into WC PCIe BAR VRAM `to`. Never reads from `to` and never overwrites unchanged // slots (preserving previously bound T#s / resolved V#s in untouched slots). static void flush_written_slot_runs(std::uint8_t* to, const std::uint8_t* out_buf, const std::array& written_slots, std::size_t written_count) noexcept { constexpr std::size_t kSlotsPerPage = leonida::TitleMirror::kPage / kDescriptorSize; if (!written_count) return; if (written_count == kSlotsPerPage) { std::memcpy(to, out_buf, leonida::TitleMirror::kPage); return; } std::size_t run_start = kSlotsPerPage; for (std::size_t w = 0; w < 32; ++w) { const std::uint64_t word = written_slots[w]; if (!word) { if (run_start < kSlotsPerPage) { const std::size_t run_end = w * 64; std::memcpy(to + run_start * kDescriptorSize, out_buf + run_start * kDescriptorSize, (run_end - run_start) * kDescriptorSize); run_start = kSlotsPerPage; } continue; } if (word == ~std::uint64_t(0)) { if (run_start == kSlotsPerPage) run_start = w * 64; continue; } std::size_t bit = 0; while (bit < 64) { const std::uint64_t rem = word >> bit; if (!rem) { if (run_start < kSlotsPerPage) { const std::size_t run_end = w * 64 + bit; std::memcpy(to + run_start * kDescriptorSize, out_buf + run_start * kDescriptorSize, (run_end - run_start) * kDescriptorSize); run_start = kSlotsPerPage; } break; } const std::size_t zeros = std::size_t(std::countr_zero(rem)); if (zeros > 0) { if (run_start < kSlotsPerPage) { const std::size_t run_end = w * 64 + bit; std::memcpy(to + run_start * kDescriptorSize, out_buf + run_start * kDescriptorSize, (run_end - run_start) * kDescriptorSize); run_start = kSlotsPerPage; } bit += zeros; } const std::size_t ones = std::size_t(std::countr_one(word >> bit)); if (run_start == kSlotsPerPage) run_start = w * 64 + bit; bit += ones; } } if (run_start < kSlotsPerPage) { std::memcpy(to + run_start * kDescriptorSize, out_buf + run_start * kDescriptorSize, (kSlotsPerPage - run_start) * kDescriptorSize); } } // Pure read-only check equivalent to page_mirror_resolve_locked(va, bytes, /*make=*/false) after // sync_mirror_space_locked(). Safe to call concurrently from parallel Phase A workers while page_mirror.mutex is // held continuously by the calling thread (zero mutations to chunks_, homes_, plain, ensured, or counters). bool page_mirror_is_resolved_readonly(std::uint64_t va, std::uint64_t bytes) const noexcept { if (!bytes || va + bytes < va) return false; constexpr std::uint64_t kChunk = leonida::TitleMirror::kChunk; constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; const std::uint64_t end = va + bytes; for (std::uint64_t c = va & ~(kChunk - 1); c < end; c += kChunk) { if (!page_mirror.mirror->covers(c)) return false; if (c > UINT64_MAX - kChunk) break; } auto it = page_mirror.plain.upper_bound(va); if (it != page_mirror.plain.begin() && std::prev(it)->second > va) --it; for (; it != page_mirror.plain.end() && it->first < end; ++it) { const std::uint64_t from = (std::max)(it->first, va) & ~(kPage - 1); const std::uint64_t to = ((std::min)(it->second, end) + kPage - 1) & ~(kPage - 1); if (!ensured_covers(from, to)) return false; } return true; } // Reusable cached 64 KiB host scratch buffer for single-page filter writes under page_mirror.mutex (avoids // scattered 32B WC BAR writes and avoids putting a 64 KiB array on a Windows/Wine thread stack). Falls back to // heap allocation on re-entry. struct OutScratchGuard { std::uint8_t* ptr = nullptr; std::unique_ptr overflow; bool* in_use = nullptr; explicit OutScratchGuard(DeviceState& dev) { if (!dev.page_mirror.out_scratch_in_use) { if (!dev.page_mirror.out_scratch) dev.page_mirror.out_scratch.reset(new std::uint8_t[leonida::TitleMirror::kPage]); dev.page_mirror.out_scratch_in_use = true; in_use = &dev.page_mirror.out_scratch_in_use; ptr = dev.page_mirror.out_scratch.get(); } else { overflow.reset(new std::uint8_t[leonida::TitleMirror::kPage]); ptr = overflow.get(); } } ~OutScratchGuard() { if (in_use) *in_use = false; } OutScratchGuard(const OutScratchGuard&) = delete; OutScratchGuard& operator=(const OutScratchGuard&) = delete; }; // Slot `slot` of a heap read in place, from its title bytes as last filtered (`previous`), into `out` (either a // cached 64 KiB scratch buffer or its place in the page's home). page_mirror.mutex held. void filter_slot_locked(ConsoleHeap& heap, std::size_t slot, std::uint8_t* out, FilterPageCache* cache = nullptr, bool count_changed = false) { using Records = leonida::ConsoleHeapSlotRecords; std::uint32_t w[kDescriptorSize / 4]; std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize); bool defer = false; bool added_mirror_range = false; if (!(w[0] | w[1] | w[2] | w[3])) { if (count_changed) ++heap.changed[(w[4] | w[5] | w[6] | w[7]) ? 1 : 0]; heap.records.clear(slot); // a null slot stays null } else if (!(w[3] >> 30)) { if (count_changed) note_changed_vsharp_words(heap, w); const bool signed_vsharp = cache ? cache->signed_vsharp : signed_vsharp_offsets(); const std::uint64_t arena_size = cache ? cache->arena_size : arena.size; const bool has_geometry = cache ? cache->has_geometry : (geometry.cap() != 0); // A buffer V# and its UAV counter: each read as written when heap_base + its base holds its bytes, else // null until finish_in_place resolves it (recorded as waiting meanwhile, so a change finds it). for (unsigned half = 0; half < 2; ++half) { std::uint32_t* h = w + 4 * half; if ((h[3] >> 30) || !h[2]) { heap.records.set(slot, half, Records::none, 0, 0, 0); continue; } const std::uint64_t base = std::uint64_t(h[0]) | (std::uint64_t(h[1] & 0xffff) << 32); const std::uint32_t stride = (h[1] >> 16) & 0x3fffu; const std::uint64_t span = std::uint64_t(h[2]) * (stride ? stride : 1); // Fast inline arena hit: skips reachable_as_written(), mirror lookups, and cache hashing. if (base && (!signed_vsharp || !(base & (1ull << 47))) && base < arena_size && (span ? span : 1) <= arena_size - base) { heap.records.set(slot, half, Records::none, 0, 0, 0); ++heap.vsharps_as_written; continue; } if (cache) { if (FilterPageCache::Entry* cached = cache->find(base, span)) { switch (cached->outcome) { case FilterPageCache::Outcome::mirrored: heap.records.set(slot, half, Records::none, 0, 0, 0); if (cached->mirror_range_heap != &heap) { heap.mirror_ranges.emplace_back(base, span); cached->mirror_range_heap = &heap; added_mirror_range = true; } ++heap.vsharps_as_written; continue; case FilterPageCache::Outcome::backed: heap.records.set(slot, half, Records::resolved, base, span, cached->target, false); ++heap.vsharps_as_written; continue; case FilterPageCache::Outcome::waiting: heap.records.set(slot, half, Records::waiting, base, span, 0, true); h[0] = h[1] = h[2] = h[3] = 0; ++heap.vsharps_rejected; continue; case FilterPageCache::Outcome::defer: heap.records.set(slot, half, Records::none, 0, 0, 0); h[0] = h[1] = h[2] = h[3] = 0; ++heap.vsharps_deferred; defer = true; continue; default: break; } } } bool mirrored = false; std::uint64_t target = 0; if (reachable_as_written(base, span, mirrored, &target)) { if (target) { heap.records.set(slot, half, Records::resolved, base, span, target, false); if (cache) cache->put(base, span, FilterPageCache::Outcome::backed, target); } else { heap.records.set(slot, half, Records::none, 0, 0, 0); if (mirrored) { heap.mirror_ranges.emplace_back(base, span); added_mirror_range = true; if (cache) cache->put(base, span, FilterPageCache::Outcome::mirrored, 0, &heap); } } ++heap.vsharps_as_written; continue; } // Classify V# halves that reachable_as_written did not accept, maintaining exact semantic parity with // finish_in_place -> vsharp_address (VsharpPath::scratch): // - permanently impossible (null base, unbacked bit-47, or arena offset whose span exceeds arena.size // and is neither in title_memory, aliased, nor a stream-pool GPU view): null with Records::none; // - unresolvable right now (base >= arena.size, not in title_memory within span, no alias, and no // stream-pool GPU view): null and record Records::waiting directly without deferring, so a later // SlotChange::source_added (backing, alias, or title_memory) still wakes and re-filters it; // - otherwise: clear any stale record, null temporarily, and defer to finish_in_place. auto& aliases = leonida::title_va_aliases(); bool permanent_impossible = !base || (base & (1ull << 47)) != 0; bool in_title = false, has_alias = false, is_gpu_view = false; if (!permanent_impossible) { std::uint64_t lo = 0, hi = 0; in_title = aliases.title_memory(base, lo, hi) && span <= hi - base; if (!in_title) { std::uint64_t alias_to = 0, alias_room = 0; has_alias = aliases.range_of(base, alias_to, alias_room); if (!has_alias) { is_gpu_view = has_geometry && leonida::title_gpu_views::to_cpu(base, span) != base; if (!is_gpu_view && base < arena_size) permanent_impossible = true; } } } if (permanent_impossible) { heap.records.set(slot, half, Records::none, 0, 0, 0); h[0] = h[1] = h[2] = h[3] = 0; // null whole: no three words of four ++heap.vsharps_rejected; continue; } if (!in_title && !has_alias && !is_gpu_view) { // `!in_title && !has_alias && !is_gpu_view` proves geometry_va cannot succeed either, so // `geometry = true` is exact and lets answer() serve both geometry=true/false queries until a // SlotChange::source_added refilters this slot. heap.records.set(slot, half, Records::waiting, base, span, 0, true); if (cache) cache->put(base, span, FilterPageCache::Outcome::waiting); h[0] = h[1] = h[2] = h[3] = 0; // null whole: no three words of four ++heap.vsharps_rejected; continue; } // Clear any stale record before deferring so finish_in_place's record-answer lookup never mistakes a // placeholder for a resolved or settled waiting record. heap.records.set(slot, half, Records::none, 0, 0, 0); if (cache) cache->put(base, span, FilterPageCache::Outcome::defer); h[0] = h[1] = h[2] = h[3] = 0; // null whole: no three words of four (a stride or format left over) ++heap.vsharps_deferred; defer = true; } } else { leonida::gfx10::ImageWords words; std::memcpy(words.data(), w, sizeof(words)); leonida::gfx10::Image image{}; const bool is_img = leonida::gfx10::is_image(words); if (count_changed) ++heap.changed[is_img ? 2 : 3]; if (is_img && leonida::gfx10::decode(words, image)) { // As the title wrote it, bound by finish_in_place, which writes its bindless index into dword 6 // (gfx10_descriptors.h, tsharp_index_word; the entry's index needs descriptor_mutex, not taken under // the mirror's lock). Until then dword 6 is 0, the fallback: the title's own dword 6 (compression // metadata) is never read as an index. The title's bytes keep it. if (tsharp_index_words) w[leonida::gfx10::kTsharpIndexDword] = 0; defer = true; } else { heap.records.clear(slot); std::memset(w, 0, 16); // data where a V# or T# is read: null } } std::memcpy(out, w, kDescriptorSize); if (defer && !heap.deferred_mark[slot]) { heap.deferred_mark[slot] = 1; heap.deferred.push_back(std::uint32_t(slot)); } if (defer || added_mirror_range) heap.in_place_work_pending.store(true, std::memory_order_release); } // The changes noted since the mirror last looked (and those refresh_console_heaps kept for it): the slots they // touch are filtered again straight into their homes. page_mirror.mutex held (refresh_page_mirror). void apply_in_place_changes(ConsoleHeap& heap) { { std::lock_guard taken(slot_change_mutex); if (heap.changes_seen < slot_changes.size()) heap.pending_changes.insert(heap.pending_changes.end(), slot_changes.begin() + std::ptrdiff_t(heap.changes_seen), slot_changes.end()); heap.changes_seen = slot_changes.size(); } if (heap.pending_changes.empty()) return; if (bindless && bindless->total_free_images() == 0) { // No free bindless slot in any dimension: waking room_[1] (texture_waiting_room) cannot succeed and would // only re-refuse every waiting slot on this submission. std::erase_if(heap.pending_changes, [](const leonida::SlotChange& c) { return c.kind == leonida::SlotChange::texture_room; }); if (heap.pending_changes.empty()) return; } const auto start = std::chrono::steady_clock::now(); const std::uint64_t looked = heap.records.looked_at(); heap.records.touched(heap.pending_changes.data(), heap.pending_changes.size(), heap.touched_scratch); heap.record_changes += heap.pending_changes.size(); heap.record_looked += heap.records.looked_at() - looked; heap.record_refixed += heap.touched_scratch.size(); heap.pending_changes.clear(); if (!heap.touched_scratch.empty()) { FilterCacheScope cache_scope(*this); OutScratchGuard out_guard(*this); std::array written_slots{}; std::size_t written_count = 0; constexpr std::uint64_t kPageMask = ~(leonida::TitleMirror::kPage - 1); constexpr std::uint64_t kOffMask = leonida::TitleMirror::kPage - 1; std::uint64_t last_page = UINT64_MAX; std::uint8_t* last_copy = nullptr; std::uint8_t* last_frame = nullptr; const bool readback = page_mirror.readback_in_flight; const auto flush_page = [&] { if (last_copy && written_count) { flush_written_slot_runs(last_copy, out_guard.ptr, written_slots, written_count); written_slots = {}; written_count = 0; } }; for (const std::uint32_t slot : heap.touched_scratch) { const std::uint64_t va = heap.console_va + std::uint64_t(slot) * kDescriptorSize; const std::uint64_t page_va = va & kPageMask; if (page_va != last_page) { flush_page(); last_page = page_va; last_copy = page_mirror.mirror->copy_bytes(page_va); last_frame = (last_copy && readback) ? page_mirror.mirror->frame_at(page_va) : nullptr; if (last_frame) note_readback_frame_invalidated_locked(last_frame); } if (last_copy) { using Records = leonida::ConsoleHeapSlotRecords; const auto st = heap.records.state(slot, 0); if (st == Records::texture_waiting || st == Records::texture_waiting_room) { std::uint32_t w[kDescriptorSize / 4]; std::memcpy(w, heap.previous + std::size_t(slot) * kDescriptorSize, kDescriptorSize); if ((w[0] | w[1] | w[2] | w[3]) && (w[3] >> 30)) { leonida::gfx10::ImageWords words; std::memcpy(words.data(), w, sizeof(words)); leonida::gfx10::Image image{}; if (leonida::gfx10::is_image(words) && leonida::gfx10::decode(words, image)) { // Waiting T# already has filtered dword 6 == 0 in `last_copy`: enqueue directly for // finish_in_place() without rewriting identical bytes to WC BAR VRAM. if (!heap.deferred_mark[slot]) { heap.deferred_mark[slot] = 1; heap.deferred.push_back(slot); } heap.in_place_work_pending.store(true, std::memory_order_release); continue; } } } const std::size_t at = std::size_t(va & kOffMask); const std::size_t page_slot = at >> 5; filter_slot_locked(heap, slot, out_guard.ptr + at, cache_scope.cache, false); const std::uint64_t bit = std::uint64_t(1) << (page_slot & 63); if (!(written_slots[page_slot >> 6] & bit)) { written_slots[page_slot >> 6] |= bit; ++written_count; } } // A page not mapped is filtered whole when it is. } flush_page(); } heap.record_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); } // TitleMirrorHooks::filter for the pages of console heaps read in place: the title's page at `from` (shown at // `va`) in, the home `to` out. Each slot whose title bytes differ from what it was last filtered from (all of them // on a fresh fill) is filtered (filter_slot_locked) into a cached host scratch buffer and bulk-flushed to WC BAR // VRAM in contiguous runs; the others keep what the home holds. page_mirror.mutex held. bool filter_heap_page(std::uint64_t va, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool fresh) { ConsoleHeap* heap = nullptr; for (ConsoleHeap* h : page_mirror.in_place) if (va - h->console_va < h->bytes) heap = h; if (!heap) return copy_guarded_host(to, from, bytes, false); const auto start = std::chrono::steady_clock::now(); std::unique_ptr overflow; std::uint8_t* title = nullptr; struct ScratchGuard { bool* in_use = nullptr; ~ScratchGuard() { if (in_use) *in_use = false; } } scratch_guard; if (!page_mirror.filter_scratch_in_use && bytes <= page_mirror.filter_scratch.size()) { page_mirror.filter_scratch_in_use = true; scratch_guard.in_use = &page_mirror.filter_scratch_in_use; title = page_mirror.filter_scratch.data(); } else { overflow.reset(new std::uint8_t[bytes]); // a fill may come inside another title = overflow.get(); } if (!copy_guarded_host(title, from, bytes, false)) return false; FilterCacheScope cache_scope(*this); std::size_t changed = 0; const std::uint64_t heap_base_va = heap->console_va; const std::uint64_t heap_bytes = heap->bytes; std::uint8_t* const heap_prev = heap->previous; const bool use_scratch_flush = bytes <= leonida::TitleMirror::kPage; OutScratchGuard out_guard(*this); std::array written_slots{}; std::size_t written_count = 0; for (std::size_t at = 0; at + kDescriptorSize <= bytes; at += kDescriptorSize) { const std::uint64_t slot_va = va + at; const std::size_t page_slot = at >> 5; if (slot_va - heap_base_va >= heap_bytes) { // past the heap's end on its last page: as it is if (use_scratch_flush) { std::memcpy(out_guard.ptr + at, title + at, kDescriptorSize); written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); ++written_count; } else { std::memcpy(to + at, title + at, kDescriptorSize); } continue; } const std::size_t slot = std::size_t((slot_va - heap_base_va) / kDescriptorSize); std::uint8_t* previous = heap_prev + slot * kDescriptorSize; const bool same = slots_equal_32(previous, title + at); if (same && !fresh) continue; if (!same) { std::memcpy(previous, title + at, kDescriptorSize); ++changed; } if (use_scratch_flush) { filter_slot_locked(*heap, slot, out_guard.ptr + at, cache_scope.cache, !same); written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); ++written_count; } else { filter_slot_locked(*heap, slot, to + at, cache_scope.cache, !same); } } if (use_scratch_flush && written_count) flush_written_slot_runs(to, out_guard.ptr, written_slots, written_count); heap->slots_filtered += changed; ++heap->pages_filtered; heap->copied += changed * kDescriptorSize; heap->filter_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); return true; } // Fast path for TitleMirrorHooks::filter_pieces: `scratch` already holds the title's 64 KiB page copied by // TitleMirror::fill(), and `changed_pieces` (256 bits, one per 256-byte piece = 8 descriptor slots) marks the // pieces that changed. Pass 1 reads `scratch` and snapshots changed slots into `heap->previous` BEFORE Pass 2 // calls filter_slot_locked(), so a re-entrant TitleMirror::fill() triggered by page_mirror_resolve_locked() // cannot overwrite `scratch` while we are still reading it. Filtered outputs go to a cached 64 KiB host scratch // buffer and flush in coalesced runs to WC BAR VRAM `to`. page_mirror.mutex held. bool filter_heap_page_pieces(std::uint64_t va, std::uint8_t* to, const std::uint8_t* scratch, std::size_t bytes, bool fresh, const std::array& changed_pieces) { if (bytes > leonida::TitleMirror::kPage) return filter_heap_page(va, to, scratch, bytes, fresh); ConsoleHeap* heap = nullptr; for (ConsoleHeap* h : page_mirror.in_place) if (va - h->console_va < h->bytes) heap = h; if (!heap) { std::memcpy(to, scratch, bytes); return true; } const auto start = std::chrono::steady_clock::now(); constexpr std::size_t kPiece = 256; // Pack offset (bits 0..14) + changed flag (bit 15): kPage = 65536 is 32-byte aligned, so `at >> 5` fits in 11 bits. std::array to_filter; std::size_t to_filter_count = 0; std::size_t changed = 0; const std::uint64_t heap_base_va = heap->console_va; const std::uint64_t heap_bytes = heap->bytes; std::uint8_t* const heap_prev = heap->previous; OutScratchGuard out_guard(*this); std::array written_slots{}; std::size_t written_count = 0; for (std::size_t word = 0; word < 4; ++word) { std::uint64_t mask = fresh ? ~std::uint64_t(0) : changed_pieces[word]; while (mask) { const unsigned bit = static_cast(std::countr_zero(mask)); mask &= mask - 1; const std::size_t piece_begin = (word * 64 + bit) * kPiece; if (piece_begin >= bytes) break; const std::size_t piece_end = (std::min)(piece_begin + kPiece, bytes); for (std::size_t at = piece_begin; at + kDescriptorSize <= piece_end; at += kDescriptorSize) { const std::uint64_t slot_va = va + at; if (slot_va - heap_base_va >= heap_bytes) { // past the heap's end on its last page: as it is const std::size_t page_slot = at >> 5; std::memcpy(out_guard.ptr + at, scratch + at, kDescriptorSize); written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); ++written_count; continue; } const std::size_t slot = std::size_t((slot_va - heap_base_va) / kDescriptorSize); std::uint8_t* previous = heap_prev + slot * kDescriptorSize; const bool same = slots_equal_32(previous, scratch + at); if (same && !fresh) continue; if (!same) { std::memcpy(previous, scratch + at, kDescriptorSize); ++changed; } to_filter[to_filter_count++] = static_cast((at >> 5) | (same ? 0u : 0x8000u)); } } } if (to_filter_count) { FilterCacheScope cache_scope(*this); for (std::size_t i = 0; i < to_filter_count; ++i) { const std::uint16_t packed = to_filter[i]; const std::size_t page_slot = std::size_t(packed & 0x7fffu); const std::size_t at = page_slot << 5; const bool slot_changed = (packed & 0x8000u) != 0; const std::size_t slot = std::size_t((va + at - heap_base_va) / kDescriptorSize); filter_slot_locked(*heap, slot, out_guard.ptr + at, cache_scope.cache, slot_changed); written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); ++written_count; } } if (written_count) flush_written_slot_runs(to, out_guard.ptr, written_slots, written_count); heap->slots_filtered += changed; ++heap->pages_filtered; heap->copied += changed * kDescriptorSize; heap->filter_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); return true; } // Batched filtered-heap refresh invoked once per TitleMirror::upload() under page_mirror.mutex: // - Hoists one 1024-entry FilterPageCache across all pages in the batch (deduping V# lookups and mirror_ranges). // - Phase A (parallel across TitleMirror::WorkerPool, 100% READ-ONLY on shared page_mirror, homes_, heap.records, // heap.deferred, heap.mirror_ranges, and heap.seen_keys): diffs disjoint 64 KiB page slices of heap->previous, // classifies null slots, T# decodes, inline arena V#s, and already-resolved read-only mirror V#s into cached // host 64 KiB scratch buffers, and flushes pages with zero Phase B misses directly to WC BAR VRAM in parallel. // - Phase B (sequential on calling thread under page_mirror.mutex): commits records/deferred/mirror_ranges, runs // filter_slot_locked() for cache misses into the same host scratch buffer, and bulk-flushes changed slot runs. void filter_heap_pages_batch_locked(leonida::TitleMirror::AliasedPageJob* jobs, std::size_t count, leonida::TitleMirror::WorkerPool* pool, std::uint8_t* ok_out) { if (!count) return; FilterCacheScope cache_scope(*this); constexpr std::size_t kPage = leonida::TitleMirror::kPage; constexpr std::size_t kPiece = 256; constexpr std::size_t kMaxBufferedPages = 64; if (count == 1) { ok_out[0] = filter_heap_page_pieces(jobs[0].va, jobs[0].to, jobs[0].scratch, kPage, jobs[0].fresh, jobs[0].mask) ? 1 : 0; return; } const auto batch_start = std::chrono::steady_clock::now(); using ClearOp = FilterClearOp; using PageWork = FilterPageWork; // Pre-Phase A (sequential under page_mirror.mutex): reuse DeviceState::page_mirror PageWork & scratch storage // (keeping inner vector capacities warm across batches; falls back to stack vectors on re-entry), resolve // heaps and confirm disjoint page VAs. std::vector fallback_page_work; std::vector fallback_batch_bufs; struct PageWorkGuard { bool* in_use = nullptr; ~PageWorkGuard() { if (in_use) *in_use = false; } } work_guard; std::vector* work_ptr = &fallback_page_work; std::vector* bufs_ptr = &fallback_batch_bufs; if (!page_mirror.batch_work_in_use) { page_mirror.batch_work_in_use = true; work_guard.in_use = &page_mirror.batch_work_in_use; work_ptr = &page_mirror.batch_page_work; bufs_ptr = &page_mirror.batch_out_bufs; } std::vector& work = *work_ptr; if (work.size() < count) work.resize(count); for (std::size_t p = 0; p < count; ++p) work[p].reset(); bool duplicate_va = false; for (std::size_t p = 0; p < count; ++p) { ConsoleHeap* heap = nullptr; for (ConsoleHeap* h : page_mirror.in_place) if (jobs[p].va - h->console_va < h->bytes) heap = h; work[p].heap = heap; for (std::size_t q = 0; q < p && !duplicate_va; ++q) if (jobs[q].va == jobs[p].va) duplicate_va = true; } if (duplicate_va) { for (std::size_t p = 0; p < count; ++p) { ok_out[p] = filter_heap_page_pieces(jobs[p].va, jobs[p].to, jobs[p].scratch, kPage, jobs[p].fresh, jobs[p].mask) ? 1 : 0; } return; } // Reusable per-page host scratch buffers (up to kMaxBufferedPages = 4 MiB) so Phase A + Phase B merge into one // coalesced WC BAR VRAM write burst per page. std::vector& batch_bufs = *bufs_ptr; const std::size_t buffered_pages = (std::min)(count, kMaxBufferedPages); if (batch_bufs.size() < buffered_pages * kPage) batch_bufs.resize(buffered_pages * kPage); for (std::size_t p = 0; p < buffered_pages; ++p) { work[p].out_buf = batch_bufs.data() + p * kPage; work[p].persistent_buf = true; } const bool signed_vsharp = cache_scope.cache->signed_vsharp; const bool has_mirror = cache_scope.cache->has_mirror; const std::uint64_t arena_size = cache_scope.cache->arena_size; const bool has_tsharp_index = tsharp_index_words; // Phase A (parallel when pool != nullptr, strictly read-only on all shared page_mirror / heap structures). const auto run_phase_a = [&](std::size_t b, std::size_t e, std::size_t tid) { using Records = leonida::ConsoleHeapSlotRecords; struct LocalMirrorEntry { std::uint64_t base = 0; std::uint64_t span = 0; std::uint32_t gen = 0; }; std::array local_mirror{}; std::uint32_t local_gen = 0; ConsoleHeap* prev_heap = nullptr; std::uint8_t* const worker_fallback_buf = pool ? pool->scratch(tid) : nullptr; std::unique_ptr serial_fallback_buf; for (std::size_t p = b; p < e; ++p) { const auto& job = jobs[p]; PageWork& pw = work[p]; ConsoleHeap* const heap = pw.heap; if (!heap) { std::memcpy(job.to, job.scratch, kPage); pw.flushed = true; continue; } std::uint8_t* out_buf = pw.out_buf; if (!out_buf) { if (worker_fallback_buf) { out_buf = worker_fallback_buf; } else { if (!serial_fallback_buf) serial_fallback_buf.reset(new std::uint8_t[kPage]); out_buf = serial_fallback_buf.get(); } } // Persist `local_mirror` across consecutive pages of the same ConsoleHeap* so repeated mirror V#s // avoid redundant page_mirror_is_resolved_readonly() walks and duplicate mirror_ranges pushes; reset // immediately when ConsoleHeap* changes so each heap receives all of its own mirror_ranges. if (heap != prev_heap) { prev_heap = heap; if (++local_gen == 0) { local_mirror = {}; local_gen = 1; } } const std::uint64_t heap_base_va = heap->console_va; const std::uint64_t heap_bytes = heap->bytes; std::uint8_t* const heap_prev = heap->previous; const auto& records = heap->records; for (std::size_t word = 0; word < 4; ++word) { std::uint64_t mask = job.fresh ? ~std::uint64_t(0) : job.mask[word]; while (mask) { const unsigned bit = static_cast(std::countr_zero(mask)); mask &= mask - 1; const std::size_t piece_begin = (word * 64 + bit) * kPiece; const std::size_t piece_end = piece_begin + kPiece; for (std::size_t at = piece_begin; at < piece_end; at += kDescriptorSize) { const std::uint64_t slot_va = job.va + at; const std::size_t page_slot = at >> 5; if (slot_va - heap_base_va >= heap_bytes) { std::memcpy(out_buf + at, job.scratch + at, kDescriptorSize); pw.written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); ++pw.written_count; continue; } const std::size_t slot = std::size_t((slot_va - heap_base_va) / kDescriptorSize); std::uint8_t* const previous = heap_prev + slot * kDescriptorSize; const bool same = slots_equal_32(previous, job.scratch + at); if (same && !job.fresh) continue; if (!same) { std::memcpy(previous, job.scratch + at, kDescriptorSize); ++pw.changed; } std::uint32_t w[kDescriptorSize / 4]; std::memcpy(w, job.scratch + at, kDescriptorSize); if (!(w[0] | w[1] | w[2] | w[3])) { if (!same) ++pw.changed_class[(w[4] | w[5] | w[6] | w[7]) ? 1 : 0]; std::memcpy(out_buf + at, w, kDescriptorSize); pw.written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); ++pw.written_count; const std::uint8_t clr = (records.state(slot, 0) != Records::none ? 1u : 0u) | (records.state(slot, 1) != Records::none ? 2u : 0u); if (clr) pw.clear_ops.push_back({std::uint32_t(slot), clr}); } else if (!(w[3] >> 30)) { // Pure read-only check for both V# halves; commit Phase A only if BOTH halves resolve. const bool has_h0 = (w[2] != 0); const bool has_h1 = (w[6] != 0); bool half_ok[2] = {false, false}; bool half_as_written[2] = {false, false}; bool half_rejected[2] = {false, false}; bool half_mirrored[2] = {false, false}; bool half_resolved_new[2] = {false, false}; std::uint64_t half_base[2] = {0, 0}; std::uint64_t half_span[2] = {0, 0}; std::uint8_t clr = 0; for (unsigned half = 0; half < 2; ++half) { std::uint32_t* const h = w + 4 * half; if ((h[3] >> 30) || !h[2]) { half_ok[half] = true; if (records.state(slot, half) != Records::none) clr |= static_cast(1u << half); continue; } const std::uint64_t base = std::uint64_t(h[0]) | (std::uint64_t(h[1] & 0xffff) << 32); const std::uint32_t stride = (h[1] >> 16) & 0x3fffu; const std::uint64_t span = std::uint64_t(h[2]) * (stride ? stride : 1); if (!base) { h[0] = h[1] = h[2] = h[3] = 0; half_ok[half] = true; half_rejected[half] = true; if (records.state(slot, half) != Records::none) clr |= static_cast(1u << half); continue; } if (!signed_vsharp || !(base & (1ull << 47))) { if (base < arena_size && (span ? span : 1) <= arena_size - base) { half_ok[half] = true; half_as_written[half] = true; if (records.state(slot, half) != Records::none) clr |= static_cast(1u << half); continue; } if (has_mirror) { const std::size_t lb = static_cast(((base >> 4) ^ (span * 0x9e3779b97f4a7c15ull)) & 1023u); LocalMirrorEntry& le = local_mirror[lb]; if (le.gen == local_gen && le.base == base && le.span == span) { half_ok[half] = true; half_as_written[half] = true; if (records.state(slot, half) != Records::none) clr |= static_cast(1u << half); continue; } if (page_mirror_is_resolved_readonly(base, span ? span : 1)) { le = {base, span, local_gen}; half_ok[half] = true; half_as_written[half] = true; half_mirrored[half] = true; half_resolved_new[half] = true; half_base[half] = base; half_span[half] = span; if (records.state(slot, half) != Records::none) clr |= static_cast(1u << half); continue; } } } break; // half missed Phase A -> defer entire slot to Phase B } if (half_ok[0] && half_ok[1]) { if (!same) { ++pw.changed_class[1]; if (has_h0) ++pw.vsharp_halves; if (has_h1) ++pw.vsharp_halves; } for (unsigned half = 0; half < 2; ++half) { if (half_as_written[half]) ++pw.vsharps_as_written; if (half_rejected[half]) ++pw.vsharps_rejected; if (half_resolved_new[half]) ++pw.resolved; if (half_mirrored[half]) pw.mirror_ranges.emplace_back(half_base[half], half_span[half]); } if (clr) pw.clear_ops.push_back({std::uint32_t(slot), clr}); std::memcpy(out_buf + at, w, kDescriptorSize); pw.written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); ++pw.written_count; } else { pw.phase_b_full.push_back( static_cast(page_slot | (same ? 0u : 0x8000u))); } } else { leonida::gfx10::ImageWords words; std::memcpy(words.data(), w, sizeof(words)); leonida::gfx10::Image image{}; const bool is_img = leonida::gfx10::is_image(words); if (!same) ++pw.changed_class[is_img ? 2 : 3]; if (is_img && leonida::gfx10::decode(words, image)) { if (has_tsharp_index) w[leonida::gfx10::kTsharpIndexDword] = 0; pw.defer_slots.push_back(std::uint32_t(slot)); } else { const std::uint8_t clr = (records.state(slot, 0) != Records::none ? 1u : 0u) | (records.state(slot, 1) != Records::none ? 2u : 0u); if (clr) pw.clear_ops.push_back({std::uint32_t(slot), clr}); std::memset(w, 0, 16); } std::memcpy(out_buf + at, w, kDescriptorSize); pw.written_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); ++pw.written_count; } } } } // Always flush Phase A's own written_slots to WC BAR VRAM in parallel (disjoint from phase_b_full) and // reset them so Phase B flushes only the few remaining phase_b_full slots. if (pw.written_count) { flush_written_slot_runs(job.to, out_buf, pw.written_slots, pw.written_count); pw.written_slots = {}; pw.written_count = 0; } if (pw.phase_b_full.empty()) pw.flushed = true; } }; if (pool) { const std::size_t workers = pool->worker_count(); const std::size_t chunk = (std::max)(std::size_t(1), (std::min)(std::size_t(4), count / (workers * 2))); pool->run(count, chunk, run_phase_a); } else { run_phase_a(0, count, 0); } // Phase B (sequential on calling thread under page_mirror.mutex, in exact page order). using Records = leonida::ConsoleHeapSlotRecords; OutScratchGuard overflow_phase_b_guard(*this); for (std::size_t p = 0; p < count; ++p) { const auto& job = jobs[p]; PageWork& pw = work[p]; ConsoleHeap* const heap = pw.heap; if (!heap) { ok_out[p] = 1; continue; } heap->slots_filtered += pw.changed; ++heap->pages_filtered; heap->copied += pw.changed * kDescriptorSize; heap->vsharps_as_written += pw.vsharps_as_written; heap->vsharps_rejected += pw.vsharps_rejected; heap->vsharp_halves += pw.vsharp_halves; for (int c = 0; c < 4; ++c) heap->changed[c] += pw.changed_class[c]; page_mirror.resolved += pw.resolved; bool work_pending = false; for (const auto& [base, span] : pw.mirror_ranges) { FilterPageCache::Entry* cached = cache_scope.cache->find(base, span); if (cached && cached->outcome == FilterPageCache::Outcome::mirrored) { if (cached->mirror_range_heap != heap) { heap->mirror_ranges.emplace_back(base, span); cached->mirror_range_heap = heap; work_pending = true; } } else { heap->mirror_ranges.emplace_back(base, span); cache_scope.cache->put(base, span, FilterPageCache::Outcome::mirrored, 0, heap); work_pending = true; } } for (const ClearOp& op : pw.clear_ops) { if (op.halves == 3u) { heap->records.clear(op.slot); } else { if (op.halves & 1u) heap->records.set(op.slot, 0, Records::none, 0, 0, 0); if (op.halves & 2u) heap->records.set(op.slot, 1, Records::none, 0, 0, 0); } } for (const std::uint32_t slot : pw.defer_slots) { if (!heap->deferred_mark[slot]) { heap->deferred_mark[slot] = 1; heap->deferred.push_back(slot); } work_pending = true; } if (work_pending) heap->in_place_work_pending.store(true, std::memory_order_release); if (!pw.phase_b_full.empty()) { const std::uint64_t heap_base_va = heap->console_va; std::uint8_t* const phase_b_buf = pw.persistent_buf ? pw.out_buf : overflow_phase_b_guard.ptr; std::array phase_b_slots{}; std::size_t phase_b_written = 0; for (const std::uint16_t packed : pw.phase_b_full) { const std::size_t page_slot = std::size_t(packed & 0x7fffu); const std::size_t at = page_slot << 5; const bool slot_changed = (packed & 0x8000u) != 0; const std::size_t slot = std::size_t((job.va + at - heap_base_va) / kDescriptorSize); filter_slot_locked(*heap, slot, phase_b_buf + at, cache_scope.cache, slot_changed); phase_b_slots[page_slot >> 6] |= std::uint64_t(1) << (page_slot & 63); ++phase_b_written; } if (phase_b_written) flush_written_slot_runs(job.to, phase_b_buf, phase_b_slots, phase_b_written); pw.flushed = true; } ok_out[p] = 1; } const double total_ms = std::chrono::duration(std::chrono::steady_clock::now() - batch_start).count(); ConsoleHeap* first_heap = nullptr; for (std::size_t p = 0; p < count; ++p) { if (work[p].heap) { first_heap = work[p].heap; break; } } if (first_heap) first_heap->filter_ms += total_ms; } // Reusable finish_in_place() scratch storage (guarded by console_heap_mutex). struct InPlaceJob { std::uint32_t slot = 0; std::uint32_t words[kDescriptorSize / 4]{}; bool reachable[2] = {false, false}; std::uint64_t reachable_target[2] = {0, 0}; bool answered[2] = {false, false}; VsharpRecord answer[2]{}; }; struct InPlaceDone { std::uint32_t out[kDescriptorSize / 4]{}; VsharpRecord halves[2]{}; leonida::ConsoleHeapSlotRecords::State texture = leonida::ConsoleHeapSlotRecords::none; std::uint64_t texture_address = 0; }; struct InPlaceVsharpKey { std::uint64_t base = 0, span = 0; bool geometry = false; bool operator==(const InPlaceVsharpKey&) const = default; }; struct InPlaceVsharpKeyHash { std::size_t operator()(const InPlaceVsharpKey& k) const noexcept { std::size_t h = std::hash{}(k.base); h ^= std::hash{}(k.span) + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2); return h ^ std::size_t(k.geometry); } }; struct InPlaceTsharpKeyHash { std::size_t operator()(const leonida::gfx10::ImageWords& w) const noexcept { std::uint64_t h = 14695981039346656037ull; for (const std::uint32_t x : w) h = (h ^ x) * 1099511628211ull; return static_cast(h); } }; struct InPlaceTsharpCached { TitleImage result = TitleImage::not_tsharp; const char* why = nullptr; std::uint64_t texture_address = 0; std::uint32_t index_word = 0; std::uint64_t capped_hits = 0; }; std::vector in_place_jobs_scratch; std::vector in_place_done_scratch; std::vector> in_place_ranges_scratch; std::unordered_map in_place_vsharp_cache; std::unordered_map in_place_tsharp_cache; // What the filter left to do, done outside the mirror's lock: the V#s the mirror does not hold resolved as a // copied slot's were (an interim, until every title allocation is in the mirror; they read null meanwhile), the // T#s bound, and the write-back noted for the mirror ranges the heap's V#s name. Each result goes into the home // under the lock, unless the title rewrote the slot since (then the filter has it again). console_heap_mutex held, // page_mirror.mutex not. void finish_in_place(ConsoleHeap& heap) { // O(1) lock-free skip when no filter work, mirror ranges, pending_changes, or new slot_changes exist: // avoids contending on page_mirror.mutex while holding console_heap_mutex on clean submissions. if (!heap.in_place_work_pending.load(std::memory_order_acquire) && slot_change_count.load(std::memory_order_acquire) == 0) return; using Records = leonida::ConsoleHeapSlotRecords; const VsharpPath path = (heap.scratch || heap.in_place) ? VsharpPath::scratch : VsharpPath::shadow; const auto wants_geometry = [path](const std::uint32_t* h, std::uint64_t span) { const leonida::gfx10::BufferWords words{h[0], h[1], h[2], h[3]}; leonida::gfx10::Buffer desc{}; return leonida::gfx10::decode(words, desc) && (path != VsharpPath::scratch || span <= kTitleWindowMax || (desc.format && leonida::gfx10::encode(desc) == words)); }; auto& jobs = in_place_jobs_scratch; auto& ranges = in_place_ranges_scratch; jobs.clear(); ranges.clear(); { std::unique_lock lock(page_mirror.mutex, std::defer_lock); leonida::submit_phases::lock_timed(lock); // Apply any pending slot changes first under page_mirror.mutex so heap.records is current before // consulting heap.records.answer() for repeated V# halves. apply_in_place_changes(heap); const std::uint64_t room_gen = geometry.free_generation(); if (!heap.deferred.empty()) { FilterCacheScope reach_scope(*this); FilterPageCache& reach_cache = *reach_scope.cache; jobs.reserve(heap.deferred.size()); for (const std::uint32_t slot : heap.deferred) { heap.deferred_mark[slot] = 0; InPlaceJob& job = jobs.emplace_back(); job.slot = slot; std::memcpy(job.words, heap.previous + std::size_t(slot) * kDescriptorSize, kDescriptorSize); if (!(job.words[3] >> 30)) { // Batch-check reachability and existing slot records under the single mirror lock acquisition. for (unsigned half = 0; half < 2; ++half) { const std::uint32_t* h = job.words + 4 * half; if ((h[3] >> 30) || !h[2]) continue; const std::uint64_t base = std::uint64_t(h[0]) | (std::uint64_t(h[1] & 0xffff) << 32); const std::uint32_t stride = (h[1] >> 16) & 0x3fffu; const std::uint64_t span = std::uint64_t(h[2]) * (stride ? stride : 1); if (const FilterPageCache::Entry* cached = reach_cache.find(base, span)) { if (cached->outcome == FilterPageCache::Outcome::mirrored) { job.reachable[half] = true; job.reachable_target[half] = 0; heap.mirror_ranges.emplace_back(base, span); continue; } if (cached->outcome == FilterPageCache::Outcome::backed) { job.reachable[half] = true; job.reachable_target[half] = cached->target; continue; } } else { bool mirrored = false; std::uint64_t reach_target = 0; if (reachable_as_written(base, span, mirrored, &reach_target)) { job.reachable[half] = true; job.reachable_target[half] = reach_target; if (mirrored) { heap.mirror_ranges.emplace_back(base, span); reach_cache.put(base, span, FilterPageCache::Outcome::mirrored); } else { reach_cache.put(base, span, FilterPageCache::Outcome::backed, reach_target); } continue; } reach_cache.put(base, span, FilterPageCache::Outcome::defer); } const bool copy_geometry = wants_geometry(h, span); Records::State state{}; std::uint64_t target = 0; if (heap.records.answer(base, span, copy_geometry, state, target) && !(state == Records::waiting_room && room_gen != geometry_room_seen)) { job.answered[half] = true; job.answer[half] = {state, base, span, target, copy_geometry}; ++(state == Records::resolved ? heap.vsharps_answered_resolved : heap.vsharps_answered); } } } } heap.deferred.clear(); } ranges.swap(heap.mirror_ranges); heap.in_place_work_pending.store(false, std::memory_order_release); } if (ranges.size() > 1) { // Deduplicate identical-base mirrored V# ranges (keeping the largest span per base) so repeated // descriptors do not hammer title_va_aliases() and title_write_back_mutex; never merge across distinct // bases because note_passive_title_write() clamps each call to the single title_memory region at `base`. std::sort(ranges.begin(), ranges.end()); std::size_t write = 0; for (std::size_t i = 0; i < ranges.size(); ++i) { if (write && ranges[write - 1].first == ranges[i].first) { ranges[write - 1].second = (std::max)(ranges[write - 1].second, ranges[i].second); } else { if (write != i) ranges[write] = ranges[i]; ++write; } } ranges.resize(write); } if (!ranges.empty()) { if (!writes_buffer_meta_complete.load(std::memory_order_acquire)) { for (const auto& [base, span] : ranges) note_title_write(base, span); } else if (title_write_back_enabled()) { // Clamp each range against title_memory outside title_write_back_mutex, then batch all notes under one // lock hold. auto& aliases = leonida::title_va_aliases(); std::size_t valid = 0; for (const auto& [base, span] : ranges) { if (!base || !span) continue; std::uint64_t lo = 0, hi = 0; if (!aliases.title_memory(base, lo, hi) || base >= hi) continue; ranges[valid++] = {base, base + (std::min)(span, hi - base)}; } if (valid) { std::lock_guard wb_lock(title_write_back_mutex); for (std::size_t i = 0; i < valid; ++i) passive_write_back.note(ranges[i].first, ranges[i].second); has_passive_title_write_back.store(!passive_write_back.empty(), std::memory_order_release); } } } if (jobs.empty()) return; const auto start = std::chrono::steady_clock::now(); auto& batch_answers = in_place_vsharp_cache; auto& tsharp_cache = in_place_tsharp_cache; if (!batch_answers.empty()) batch_answers.clear(); if (!tsharp_cache.empty()) tsharp_cache.clear(); const auto apply_answer = [&](std::uint32_t* h, const VsharpRecord& rec, VsharpRecord& out_rec) { out_rec = rec; if (rec.state == Records::resolved) { const std::uint64_t to = rec.target - arena.address; // mod 2^64, as recorded if ((to & ((1ull << 48) - 1)) != rec.base) { h[0] = std::uint32_t(to); h[1] = (h[1] & 0xffff0000u) | std::uint32_t((to >> 32) & 0xffff); ++heap.vsharps; } else if (page_mirror.mirror && to == rec.base && rec.base >= arena.size) { note_passive_title_write(rec.base, rec.span); } } else { const std::uint32_t stride = (h[1] >> 16) & 0x3fffu; note_unbacked_vsharp(rec.base, rec.span, stride, h); h[0] = h[1] = h[2] = h[3] = 0; ++heap.unbacked; } }; auto& done = in_place_done_scratch; done.assign(jobs.size(), InPlaceDone{}); auto& refusal_tracker = unbound_tsharp_tracker(); bool any_capped_hits = false; for (std::size_t i = 0; i < jobs.size(); ++i) { std::uint32_t* w = done[i].out; std::memcpy(w, jobs[i].words, kDescriptorSize); if (!(w[3] >> 30)) { for (unsigned half = 0; half < 2; ++half) { std::uint32_t* h = w + 4 * half; if ((h[3] >> 30) || !h[2] || jobs[i].reachable[half]) continue; if (jobs[i].answered[half]) { apply_answer(h, jobs[i].answer[half], done[i].halves[half]); continue; } const std::uint64_t base = std::uint64_t(h[0]) | (std::uint64_t(h[1] & 0xffff) << 32); const std::uint32_t stride = (h[1] >> 16) & 0x3fffu; const std::uint64_t span = std::uint64_t(h[2]) * (stride ? stride : 1); const InPlaceVsharpKey key{base, span, wants_geometry(h, span)}; if (const auto it = batch_answers.find(key); it != batch_answers.end()) { ++(it->second.state == Records::resolved ? heap.vsharps_answered_resolved : heap.vsharps_answered); apply_answer(h, it->second, done[i].halves[half]); continue; } const VsharpResult result = fix_vsharp(h, path, &done[i].halves[half], &heap, false); if (done[i].halves[half].state != Records::none) batch_answers.emplace(key, done[i].halves[half]); if (result == VsharpResult::rebased) ++heap.vsharps; if (result == VsharpResult::empty) { ++heap.unbacked; h[3] = 0; // null whole in the filtered copy, never three words of four } } } else { leonida::gfx10::ImageWords words; std::memcpy(words.data(), w, sizeof(words)); if (const auto cached = tsharp_cache.find(words); cached != tsharp_cache.end()) { InPlaceTsharpCached& entry = cached->second; const bool unbound = entry.result == TitleImage::unknown || entry.result == TitleImage::refused; const bool waiting_index = tsharp_index_words && !unbound && entry.result != TitleImage::not_tsharp && entry.index_word == 0; if (unbound) { if (refusal_tracker.is_capped()) { ++entry.capped_hits; any_capped_hits = true; } else { note_refused_tsharp(heap, std::size_t(jobs[i].slot) * kDescriptorSize, words, entry.why); } ++heap.refused_reasons[entry.why ? entry.why : "?"]; ++heap.texture_waits; } else if (waiting_index) { ++heap.texture_waits; } ++heap.images[unsigned(entry.result)]; if (entry.result == TitleImage::not_tsharp) { std::memset(w, 0, 16); } else { done[i].texture_address = entry.texture_address; done[i].texture = (!unbound && !waiting_index) ? Records::texture_bound : (unbound && (entry.why == kTsharpArrayFull || entry.why == kTsharpStorageFull)) ? Records::texture_waiting_room : Records::texture_waiting; if (tsharp_index_words) w[leonida::gfx10::kTsharpIndexDword] = entry.index_word; } continue; } if (leonida::gfx10::is_image(words)) { const char* why = nullptr; std::uint32_t index_word = 0; std::uint64_t bound_address = 0; const TitleImage result = bind_title_image( *this, words, &why, tsharp_index_words ? &index_word : nullptr, &bound_address); const bool unbound = result == TitleImage::unknown || result == TitleImage::refused; const bool waiting_index = tsharp_index_words && !unbound && result != TitleImage::not_tsharp && index_word == 0; bool counted_capped = false; if (unbound) { if (refusal_tracker.is_capped()) { counted_capped = true; any_capped_hits = true; } else { note_refused_tsharp(heap, std::size_t(jobs[i].slot) * kDescriptorSize, words, why); } ++heap.refused_reasons[why ? why : "?"]; ++heap.texture_waits; } else if (waiting_index) { ++heap.texture_waits; } ++heap.images[unsigned(result)]; InPlaceTsharpCached entry{result, why, 0, 0, counted_capped ? 1ull : 0ull}; if (result == TitleImage::not_tsharp) { std::memset(w, 0, 16); } else { leonida::gfx10::Image image{}; leonida::gfx10::decode(words, image); entry.texture_address = bound_address ? bound_address : tsharp_texture_key(image.address); done[i].texture_address = entry.texture_address; done[i].texture = (!unbound && !waiting_index) ? Records::texture_bound : (unbound && (why == kTsharpArrayFull || why == kTsharpStorageFull)) ? Records::texture_waiting_room : Records::texture_waiting; // The home's dword 6 is the index shaders take (tsharp_index_word), 0 while the T# waits; a // texture coming, going or replaced at its address touches the slot (apply_in_place_changes), // which is filtered and finished again, so the word follows the texture the T# names. The heap // copy's write (fix_console_slot) is for heaps not read in place. if (tsharp_index_words) { entry.index_word = (unbound || waiting_index) ? 0u : index_word; w[leonida::gfx10::kTsharpIndexDword] = entry.index_word; } } tsharp_cache.emplace(words, entry); } else { ++heap.images[unsigned(TitleImage::not_tsharp)]; std::memset(w, 0, 16); tsharp_cache.emplace(words, InPlaceTsharpCached{TitleImage::not_tsharp, nullptr, 0, 0, 0}); } } } if (any_capped_hits) { for (const auto& kv : tsharp_cache) { if (kv.second.capped_hits) refusal_tracker.note_capped(kv.second.why, kv.second.capped_hits); } } std::unique_lock lock(page_mirror.mutex, std::defer_lock); leonida::submit_phases::lock_timed(lock); OutScratchGuard out_guard(*this); std::array written_slots{}; std::size_t written_count = 0; constexpr std::uint64_t kPageMask = ~(leonida::TitleMirror::kPage - 1); constexpr std::uint64_t kOffMask = leonida::TitleMirror::kPage - 1; std::uint64_t last_page = UINT64_MAX; std::uint8_t* last_home = nullptr; const bool has_mirror = page_mirror.mirror != nullptr; const bool readback = page_mirror.readback_in_flight; const auto flush_page = [&] { if (last_home && written_count) { flush_written_slot_runs(last_home, out_guard.ptr, written_slots, written_count); written_slots = {}; written_count = 0; } }; for (std::size_t i = 0; i < jobs.size(); ++i) { const std::uint32_t slot = jobs[i].slot; if (!slots_equal_32(heap.previous + std::size_t(slot) * kDescriptorSize, reinterpret_cast(jobs[i].words))) continue; // rewritten since: filtered again, and deferred again if it needs this const std::uint64_t va = heap.console_va + std::uint64_t(slot) * kDescriptorSize; const std::uint64_t page_va = va & kPageMask; if (page_va != last_page) { flush_page(); last_page = page_va; last_home = has_mirror ? page_mirror.mirror->copy_bytes(page_va) : nullptr; if (last_home && readback) { if (std::uint8_t* frame = page_mirror.mirror->frame_at(page_va)) note_readback_frame_invalidated_locked(frame); } } if (!last_home) continue; const InPlaceDone& d = done[i]; if (d.texture != Records::none) { if (Records::is_waiting(heap.records.state(slot, 0)) && heap.records.base(slot, 0) == d.texture_address && d.texture == Records::texture_bound) ++heap.texture_refills; heap.records.set_texture(slot, d.texture, d.texture_address); } else if (jobs[i].words[3] >> 30) { heap.records.clear(slot); } else { for (unsigned half = 0; half < 2; ++half) { const std::uint32_t* h = jobs[i].words + 4 * half; if (jobs[i].reachable[half]) { if (jobs[i].reachable_target[half]) { const std::uint64_t base = std::uint64_t(h[0]) | (std::uint64_t(h[1] & 0xffff) << 32); const std::uint32_t stride = (h[1] >> 16) & 0x3fffu; const std::uint64_t span = std::uint64_t(h[2]) * (stride ? stride : 1); heap.records.set(slot, half, Records::resolved, base, span, jobs[i].reachable_target[half], false); } else { heap.records.set(slot, half, Records::none, 0, 0, 0); } } else if (d.halves[half].state != Records::none) { heap.records.set(slot, half, d.halves[half].state, d.halves[half].base, d.halves[half].span, d.halves[half].target, d.halves[half].geometry); } else if ((h[3] >> 30) || !h[2]) { heap.records.set(slot, half, Records::none, 0, 0, 0); } } } // filter_slot_locked / Phase A already wrote every deferred T# slot to the home with dword 6 = 0 (when // tsharp_index_words) or raw words (otherwise). Skip the WC BAR write when d.out matches those bytes // (e.g. repeated zero-index refusal or !tsharp_index_words). if (d.texture != Records::none && (!tsharp_index_words || d.out[leonida::gfx10::kTsharpIndexDword] == 0)) continue; const std::size_t at = std::size_t(va & kOffMask); const std::size_t page_slot = at >> 5; std::memcpy(out_guard.ptr + at, d.out, kDescriptorSize); const std::uint64_t bit = std::uint64_t(1) << (page_slot & 63); if (!(written_slots[page_slot >> 6] & bit)) { written_slots[page_slot >> 6] |= bit; ++written_count; } } flush_page(); heap.deferred_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); } // The changes noted since refresh_console_heaps took the list (a window this pass made, a buffer another thread // released), applied to `heap` now: they stay in the list for the next submission too (applying one twice only // fixes its slots twice). std::vector slot_change_tail; // console_heap_mutex void sync_slot_changes(ConsoleHeap& heap) { if (slot_change_count.load(std::memory_order_acquire) == heap.changes_seen) return; { std::lock_guard lock(slot_change_mutex); slot_change_tail.assign(slot_changes.begin() + std::ptrdiff_t(std::min(heap.changes_seen, slot_changes.size())), slot_changes.end()); heap.changes_seen = slot_changes.size(); } apply_slot_changes(heap, slot_change_tail); } // fix_vsharp's answer from a record of the same range in `heap`, current with every change noted so far. bool answered_by_record(ConsoleHeap& heap, std::uint64_t base, std::uint64_t span, bool copy_geometry, VsharpRecord& record) { if (heap.in_place) return false; // in-place heaps answer under page_mirror.mutex in finish_in_place sync_slot_changes(heap); using Records = leonida::ConsoleHeapSlotRecords; Records::State state{}; std::uint64_t target = 0; if (!heap.records.answer(base, span, copy_geometry, state, target)) return false; // Room for geometry copies is seen once a refresh (refresh_console_heaps): freed since, resolve anew. if (state == Records::waiting_room && geometry.free_generation() != geometry_room_seen) return false; record = {state, base, span, target, copy_geometry}; ++(state == Records::resolved ? heap.vsharps_answered_resolved : heap.vsharps_answered); return true; } // A console heap's full resolution of a V# half (fix_vsharp): counted, timed, and for an answer of nothing, its // class. void note_resolution(ConsoleHeap& heap, std::chrono::steady_clock::time_point start, std::uint64_t base, std::uint64_t to, std::uint64_t refused, bool copy_geometry, NoCopy no_copy) { ++heap.resolutions; heap.resolution_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); if (to) return; Nothing kind = nothing_other; if (refused) kind = nothing_refused; else if (base < arena.size) kind = nothing_arena; else if (base & (1ull << 47)) kind = nothing_negative; else if (!copy_geometry) kind = nothing_no_copy; else switch (no_copy) { case NoCopy::not_title: kind = nothing_not_title; break; case NoCopy::past_range: kind = nothing_past_range; break; case NoCopy::known_buffer: kind = nothing_known_buffer; break; case NoCopy::private_pages: kind = nothing_private; break; case NoCopy::refused: kind = nothing_room; break; case NoCopy::pool_alias: kind = nothing_pool_alias; break; default: break; } ++heap.nothing[kind]; if (kind == nothing_arena || kind == nothing_not_title) { static const bool detail = [] { const char* v = std::getenv("LEONIDA_VSHARP_NOTHING_DETAIL"); return v && v[0] == '1'; }(); if (detail) ++heap.nothing_where[kind == nothing_not_title][nothing_where_kind(base)]; } } // What the host has at `base` taken as an address: 0 image, 1 mapped, 2 private committed, 3 reserved, 4 free. static unsigned nothing_where_kind(std::uint64_t base) { MEMORY_BASIC_INFORMATION info{}; if (!VirtualQuery(reinterpret_cast(static_cast(base)), &info, sizeof(info)) || info.State == MEM_FREE) return 4; if (info.State != MEM_COMMIT) return 3; return info.Type == MEM_IMAGE ? 0 : info.Type == MEM_MAPPED ? 1 : 2; } void note_refused_tsharp(ConsoleHeap& heap, std::size_t offset, const leonida::gfx10::ImageWords& words, const char* why) { unbound_tsharp_tracker().note(heap.console_va, offset, words, why); } // `changes`: what changed since the last submission (refresh_console_heaps took it from slot_changes), or null for // a heap's first refresh, which has no records yet. void refresh_console_heap(ConsoleHeap& heap, const std::vector* changes) { // console_heap_mutex held if (heap.imported) return; // directly imported sampler heap if (heap.gpu >= 0) return refresh_console_heap_gpu(heap, changes); // Read in place: filtered as the page mirror fills its pages (refresh_page_mirror, before this); what the filter // left (V#s the mirror does not hold, T#s to bind) is finished here, outside the mirror's lock. if (heap.in_place) { const auto start = std::chrono::steady_clock::now(); finish_in_place(heap); heap.fix_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); return; } using clock = std::chrono::steady_clock; const auto ms = [](clock::time_point a, clock::time_point b) { return std::chrono::duration(b - a).count(); }; const auto t0 = clock::now(); heap.copied += heap.pages->refresh(); heap.pages->for_each_zeroed([&](std::size_t offset, std::size_t bytes) { std::memset(heap.copy + offset, 0, bytes); arena_mark_dirty_ptr(heap.copy + offset, bytes); std::memset(heap.previous + offset, 0, bytes); if (heap.resource_heap) { const auto first = std::uint32_t(offset / kDescriptorSize); const auto end = std::uint32_t((offset + bytes) / kDescriptorSize); for (auto slot = first; slot < end; ++slot) heap.retry[slot] = 0; heap.records.clear_range(first, end); } }); const auto t1 = clock::now(); heap.fix_start = t1; heap.fix_over = false; heap.fix_count = 0; // Even an unchanged title slot may name a buffer released since the last submission, or wait for a buffer or // texture that came: the slots the changes touch are fixed again, found by their records. First, so the // records the rewritten slots below are answered by are current (answered_by_record). if (changes) apply_slot_changes(heap, *changes); const auto t2 = clock::now(); // Slots the fix budget deferred at an earlier submission (LEONIDA_CONSOLE_FIX_US; none without it). if (!heap.retries.empty()) fix_deferred_slots(heap); const auto t3 = clock::now(); heap.pages->for_each_copied([&](std::size_t offset, std::size_t bytes) { fix_console_slots(heap, offset, bytes); }); const auto t4 = clock::now(); heap.pages_ms += ms(t0, t1); heap.retry_ms += ms(t2, t3); heap.fix_ms += ms(t1, t2) + ms(t3, t4); if (ms(t0, t4) > heap.max_ms) { heap.max_ms = ms(t0, t4); heap.max_pages_ms = ms(t0, t1); heap.max_changes_ms = ms(t1, t2); heap.max_fix_ms = ms(t2, t4); } } // Before every submission, ahead of the slot-133 shadows. // The time a submission waited for console_heap_mutex (another queue's refresh holds it), since the last log line. double heap_lock_wait_ms = 0, heap_lock_wait_max_ms = 0; // console_heap_mutex std::uint64_t heap_lock_waits = 0; void refresh_console_heaps() { const auto asked = std::chrono::steady_clock::now(); std::unique_lock lock(console_heap_mutex, std::defer_lock); leonida::submit_phases::lock_timed(lock); { const double waited = std::chrono::duration(std::chrono::steady_clock::now() - asked).count(); heap_lock_wait_ms += waited; heap_lock_wait_max_ms = (std::max)(heap_lock_wait_max_ms, waited); ++heap_lock_waits; } const bool heap_pass = heap_gpu && console_heap_gpu_enabled(); if (heap_pass) console_heap_gpu_begin(); else if (heap_gpu) heap_gpu->drain(context->completed_retire_ticket(), [](int, std::uint32_t, std::uint32_t) {}, [](int) {}); struct GpuEnd { // after every heap's slots are queued, however the loop ends DeviceState& state; bool on; ~GpuEnd() { if (on) state.console_heap_gpu_end(); } } gpu_end{*this, heap_pass}; // Every change since the last submission, for every heap; one made from now on (by another thread, or by a // fix below making a window) is applied at the next submission. std::vector changes; const bool have_slot_changes = slot_change_count.load(std::memory_order_acquire) != 0; const std::uint64_t freed_gen = geometry.free_generation(); if (have_slot_changes || freed_gen != geometry_room_seen) { // A heap read in place reads the list in the mirror's refresh (apply_in_place_changes, under the mirror's // lock): the list is taken under that lock too, so the entries it has not read yet are kept for it. // Always swap slot_changes whenever entering this block so heap->changes_seen = 0 stays consistent with // slot_changes and never skips a trailing geometry_room change. std::unique_lock mirror(page_mirror.mutex, std::defer_lock); if (in_place_heaps.load(std::memory_order_acquire)) leonida::submit_phases::lock_timed(mirror); { std::lock_guard taken(slot_change_mutex); changes.swap(slot_changes); slot_change_count.store(0, std::memory_order_release); } // Geometry copies freed since (GeometryViews::reap): the V# halves refused a copy for lack of room ask // again. if (freed_gen != geometry_room_seen) { geometry_room_seen = freed_gen; changes.push_back({leonida::SlotChange::geometry_room, 0, 1}); } bool pushed_in_place = false; for (const auto& heap : console_heaps) { if (heap->in_place && mirror.owns_lock()) { const std::size_t from = (std::min)(heap->changes_seen, changes.size()); if (from < changes.size()) { heap->pending_changes.insert(heap->pending_changes.end(), changes.begin() + std::ptrdiff_t(from), changes.end()); heap->in_place_work_pending.store(true, std::memory_order_release); pushed_in_place = true; } } heap->changes_seen = 0; // of the list noted from now on } if (pushed_in_place) page_mirror.in_place_pending.store(true, std::memory_order_release); if (mirror.owns_lock()) mirror.unlock(); } for (const auto& heap : console_heaps) { const auto start = std::chrono::steady_clock::now(); const std::uint64_t copied_before = heap->copied, retried_before = heap->retried; refresh_console_heap(*heap, &changes); // A heap slot or page brought up to date: this submission is not one of the "submit floor" line's. if (heap->copied != copied_before || heap->retried != retried_before || !changes.empty()) leonida::submit_phases::note_change(leonida::submit_phases::change_slots); heap->ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); ++heap->refreshes; // A line at the first and 64th submission, then every 10 s (a crawl logs as often as a fast run). const bool logged = heap->refreshes == 1 || heap->refreshes == 64 || (heap->refreshes > 64 && start - heap->log_time >= std::chrono::seconds(10)); if (!logged) continue; // A heap read in place has its filter's counters under the mirror's lock (console_heap_mutex, then it). std::unique_lock in_place_counters(page_mirror.mutex, std::defer_lock); if (heap->in_place) leonida::submit_phases::lock_timed(in_place_counters); const double count = double(std::max(1, heap->refreshes - heap->logged)); heap->logged = heap->refreshes; heap->log_time = start; std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx (%s): submissions up to %llu %s %.1f KiB each " "in %.3f ms on average (pages %.3f, fixing slots %.3f, %llu deferred past the budget, " "deferred ones %.3f: %.1f slots a submission, %zu left), %llu write faults; %llu title V#s " "rebased, %llu with no copy given no records (%zu V# halves waiting for a backing), T#s %llu " "known, %llu bound, %llu naming no texture, %llu refused, %llu words that are no V# or T# " "(data, null in the copy)\n", static_cast(heap->console_va), heap->in_place ? "in place" : heap->imported ? "imported" : "copy", static_cast(heap->refreshes), "copied", double(heap->copied) / 1024.0 / count, heap->ms / count, heap->pages_ms / count, heap->fix_ms / count, static_cast(heap->deferred_fixes), heap->retry_ms / count, double(heap->retried) / count, heap->retries.size(), static_cast(heap->pages ? heap->pages->faults() : 0), static_cast(heap->vsharps), static_cast(heap->unbacked), heap->records.waiting_count(), static_cast(heap->images[unsigned(TitleImage::known)]), static_cast(heap->images[unsigned(TitleImage::bound)]), static_cast(heap->images[unsigned(TitleImage::unknown)]), static_cast(heap->images[unsigned(TitleImage::refused)]), static_cast(heap->images[unsigned(TitleImage::not_tsharp)])); if (heap->resource_heap) { std::uint64_t paths[kVsharpPathCount]; for (unsigned i = 0; i < kVsharpPathCount; ++i) paths[i] = vsharp_paths[i].exchange(0, std::memory_order_relaxed); std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx changed slots per submission: %.1f zero, %.1f " "V# pairs, %.1f T#s, %.1f other; V# halves %.1f, %.1f%% seen before; V# resolutions since " "the last line: alias %llu, alias refused %llu, arena %llu, geometry %llu, window %llu, " "none %llu, page mirror %llu\n", static_cast(heap->console_va), double(heap->changed[0]) / count, double(heap->changed[1]) / count, double(heap->changed[2]) / count, double(heap->changed[3]) / count, double(heap->vsharp_halves) / count, heap->vsharp_halves ? 100.0 * double(heap->vsharp_repeats) / double(heap->vsharp_halves) : 0.0, static_cast(paths[0]), static_cast(paths[1]), static_cast(paths[2]), static_cast(paths[3]), static_cast(paths[4]), static_cast(paths[5]), static_cast(paths[6])); // What releases, alias changes and additions cost: per submission, the changes taken, the record // entries looked at to find their slots, and the slots fixed again (apply_slot_changes). // T#s: those in the heap now, those of them waiting (for a texture at their address, or room), and // since the last line the T# fixes that left one waiting and the waiting ones bound by a texture that // came (refills). std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx slot records per submission: %.1f changes, " "%.1f slots looked at, %.1f fixed again, %.3f ms; %zu V# halves recorded; T#s %zu " "recorded, %zu waiting for a texture; since the last line %llu T# fixes left waiting, " "%llu refills, %llu V# halves answered by a waiting one of their range\n", static_cast(heap->console_va), double(heap->record_changes) / count, double(heap->record_looked) / count, double(heap->record_refixed) / count, heap->record_ms / count, heap->records.recorded(), heap->records.textures(), heap->records.textures_waiting(), static_cast(heap->texture_waits), static_cast(heap->texture_refills), static_cast(heap->vsharps_answered)); // Where a submission's V# fixing goes: halves answered by a current record of their range (resolved // or waiting) and halves resolved anew with their time; the classes of those that resolved to // nothing; the longest refresh and its parts; the waits for the heap lock (in the heaps phase too). std::string classes; for (unsigned i = 0; i < nothing_classes; ++i) if (heap->nothing[i]) classes += (classes.empty() ? "" : ", ") + std::string(kNothingNames[i]) + " " + std::to_string(heap->nothing[i]); // Where the host has those bases (nothing_where_kind). for (unsigned c = 0; c < 2; ++c) { const std::uint64_t* w = heap->nothing_where[c]; if (!(w[0] | w[1] | w[2] | w[3] | w[4])) continue; char text[200]; std::snprintf(text, sizeof(text), " (%s bases as host addresses: image %llu, mapped %llu, private %llu, reserved " "%llu, free %llu)", c ? "not title memory" : "arena offset", static_cast(w[0]), static_cast(w[1]), static_cast(w[2]), static_cast(w[3]), static_cast(w[4])); classes += text; } std::memset(heap->nothing_where, 0, sizeof(heap->nothing_where)); std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx V# halves per submission: %.1f answered by a " "resolved record of their range, %.1f by a waiting one, %.1f resolved anew (%.3f ms, %.2f " "us each); resolved to nothing since the last line: %s; longest refresh %.3f ms (pages " "%.3f, changes %.3f, slots %.3f); heap lock waited %.3f ms on average, %.3f the longest\n", static_cast(heap->console_va), double(heap->vsharps_answered_resolved) / count, double(heap->vsharps_answered) / count, double(heap->resolutions) / count, heap->resolution_ms / count, heap->resolutions ? 1000.0 * heap->resolution_ms / double(heap->resolutions) : 0.0, classes.empty() ? "none" : classes.c_str(), heap->max_ms, heap->max_pages_ms, heap->max_changes_ms, heap->max_fix_ms, heap_lock_waits ? heap_lock_wait_ms / double(heap_lock_waits) : 0.0, heap_lock_wait_max_ms); heap_lock_wait_ms = heap_lock_wait_max_ms = 0; heap_lock_waits = 0; heap->vsharps_answered_resolved = heap->resolutions = 0; heap->resolution_ms = 0; for (auto& n : heap->nothing) n = 0; heap->max_ms = heap->max_pages_ms = heap->max_changes_ms = heap->max_fix_ms = 0; for (auto& n : heap->changed) n = 0; heap->texture_waits = heap->texture_refills = heap->vsharps_answered = 0; heap->vsharp_halves = heap->vsharp_repeats = 0; heap->record_changes = heap->record_looked = heap->record_refixed = 0; heap->record_ms = 0; } if (heap->gpu >= 0) log_console_heap_gpu(*heap, count); if (heap->in_place) { // What filtering its pages cost (filter_heap_page): pages and changed slots, per submission and per // frame (presents since the last line), and the V# halves read as the title wrote them. const std::uint64_t presents = phases_present_serial(); const double frames = double(std::max(1, presents - heap->present_mark)); std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx read in place: per submission %.1f pages " "filtered, %.1f slots changed, %.3f ms, and %.3f ms finishing what the filter left; per " "frame %.1f pages, %.3f ms (%llu frames); V# halves a submission: %.1f read as the title " "wrote them, %.1f rejected in filter, %.1f resolved outside the mirror\n", static_cast(heap->console_va), double(heap->pages_filtered) / count, double(heap->slots_filtered) / count, heap->filter_ms / count, heap->deferred_ms / count, double(heap->pages_filtered) / frames, (heap->filter_ms + heap->deferred_ms) / frames, static_cast(presents - heap->present_mark), double(heap->vsharps_as_written) / count, double(heap->vsharps_rejected) / count, double(heap->vsharps_deferred) / count); heap->present_mark = presents; heap->pages_filtered = heap->slots_filtered = heap->vsharps_as_written = heap->vsharps_deferred = heap->vsharps_rejected = 0; heap->filter_ms = heap->deferred_ms = 0; } std::string refused_breakdown; for (const auto& [reason, count] : heap->refused_reasons) refused_breakdown += (refused_breakdown.empty() ? "" : "; ") + std::string(reason) + " " + std::to_string(count); if (!refused_breakdown.empty()) std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx unbound T#s by reason: %s\n", static_cast(heap->console_va), refused_breakdown.c_str()); heap->refused_reasons.clear(); heap->copied = heap->vsharps = heap->unbacked = heap->retried = heap->deferred_fixes = 0; for (auto& n : heap->images) n = 0; heap->ms = heap->pages_ms = heap->fix_ms = heap->retry_ms = 0; if (start - arena_log_time >= std::chrono::seconds(60)) { arena_log_time = start; report_arena_peak(); } } } std::chrono::steady_clock::time_point arena_log_time{}; // console_heap_mutex held // The heap's pages imported as host memory (see above): true with `heap` filled in, false when they cannot be // (no VK_EXT_external_memory_host, a page not committed or write-combined, a driver refusal, or a device address // shaders could not reach with 32 bits). // `span`: the bytes to import from host_va (0: the heap's), its copy and null guard for a scratch backing. bool import_console_heap(ConsoleHeap& heap, std::uintptr_t host_va, VkDeviceSize span = 0) { auto& vk = context->vk; const VkDeviceSize alignment = info.host_pointer_alignment; if (!span) span = heap.bytes; if (!get_host_pointer_properties || !alignment || !arena.address || (host_va % alignment) || (span % alignment)) return false; const auto* pages = reinterpret_cast(static_cast(host_va)); for (VkDeviceSize at = 0; at < span;) { MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(pages + at, ®ion, sizeof(region)) || region.State != MEM_COMMIT || (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE | PAGE_GUARD))) return false; at = reinterpret_cast(region.BaseAddress) + region.RegionSize - host_va; } VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; VkBufferCreateInfo create{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external}; create.size = span; create.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; share(create); if (vk.vkCreateBuffer(info.device, &create, nullptr, &heap.buffer) != VK_SUCCESS) return false; const auto fail = [&] { if (heap.buffer) vk.vkDestroyBuffer(info.device, heap.buffer, nullptr); if (heap.memory) vk.vkFreeMemory(info.device, heap.memory, nullptr); leonida::kernel_writes::release(std::exchange(heap.pin, 0)); heap.buffer = VK_NULL_HANDLE; heap.memory = VK_NULL_HANDLE; return false; }; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(info.device, heap.buffer, &requirements); VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; if (get_host_pointer_properties(info.device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, const_cast(pages), &host) != VK_SUCCESS) return fail(); const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits; if (!types || span < requirements.size) return fail(); VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; import.pHostPointer = const_cast(pages); VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; heap.pin = leonida::kernel_writes::hold(pages, std::size_t(heap.bytes)); // as create_host_buffer's for (const VkMemoryPropertyFlags want : {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), VkMemoryPropertyFlags(0)}) { for (std::uint32_t i = 0; i < memory.memoryTypeCount && !heap.memory; ++i) { if (!(types & (1u << i)) || (memory.memoryTypes[i].propertyFlags & want) != want) continue; VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; allocate.allocationSize = span; allocate.memoryTypeIndex = i; if (vk.vkAllocateMemory(info.device, &allocate, nullptr, &heap.memory) != VK_SUCCESS) heap.memory = VK_NULL_HANDLE; } if (heap.memory) break; } if (!heap.memory || vk.vkBindBufferMemory(info.device, heap.buffer, heap.memory, 0) != VK_SUCCESS) return fail(); VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bda.buffer = heap.buffer; const VkDeviceAddress address = vk.vkGetBufferDeviceAddress(info.device, &bda); const std::uint64_t shader_va = address - arena.address; // mod 2^64, as for an imported slot-133 buffer if (!address || shader_va > (std::uint64_t(1) << 32) - span) { std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx: its import lies at heap_base + 0x%llx, which " "32-bit descriptor-table pointers cannot reach; copied instead\n", static_cast(heap.console_va), static_cast(shader_va)); return fail(); } heap.shader_va = shader_va; heap.imported = true; return true; } // A console resource heap read in place (stage 2 of the CPU plan): when the page mirror holds every page of it, // shaders read the title's heap through the mirror's homes, with no copy and no page tracker of the heap's own. // 25,865 of the corpus's 26,503 shaders keep 32 bits of a descriptor-table pointer, so the pages are bound a second // time into the arena below 4 GiB (TitleMirror::alias), at a range of whole blocks with no arena memory behind it; // the guard after them is that range's rest, unbound, which reads zero. The homes are filled through the filter // (filter_heap_page): the title's bytes in, the GPU's bytes out, never the other way. False (with `heap` given back) // when the mirror does not hold the heap, or the arena has no room: it is copied as before. Never under // console_heap_mutex (takes page_mirror.mutex). std::atomic in_place_heaps{0}; static std::uint64_t phases_present_serial() { return leonida::submit_phases::totals().present_serial.load(std::memory_order_relaxed); } bool add_heap_in_place(std::unique_ptr&& heap, VkDeviceSize guard, std::uint64_t& shader_va) { constexpr std::uint64_t page = leonida::TitleMirror::kPage; const std::uint64_t console_va = heap->console_va, bytes = heap->bytes; if (!page_mirror.mirror || (heap_gpu && console_heap_gpu_enabled()) || (console_va % page) || (bytes % page) || !page_mirror_covers(console_va, bytes)) return false; VkDeviceSize offset = 0, reserved = 0; if (!arena_reserve_unbacked(bytes + guard, offset, reserved)) return false; auto owned = std::move(heap); ConsoleHeap& h = *owned; h.in_place = true; h.imported = false; h.shader_va = offset; h.guard = reserved - bytes; h.made.assign(std::size_t(bytes), 0); h.previous = h.made.data(); h.retry.assign(std::size_t(bytes / kDescriptorSize), 0); h.deferred_mark.assign(std::size_t(bytes / kDescriptorSize), 0); h.records.set_texture_live_callback(&DeviceState::on_console_texture_live, this); h.records.reset(std::size_t(bytes / kDescriptorSize)); h.present_mark = phases_present_serial(); slot_records_live.store(true, std::memory_order_release); shader_va = offset; console_heap_ranges().add(console_va, bytes, offset); arena_guard_bytes.fetch_add(h.guard, std::memory_order_relaxed); { std::lock_guard lock(console_heap_mutex); { std::unique_lock ranges(console_copy_ranges_mutex); // views keep the title's addresses there too console_copy_ranges.emplace_back(console_va, bytes); } in_place_heaps.fetch_add(1, std::memory_order_release); // Its pages keep the title's bytes at the title's address; at the table address in the arena each has a // filtered copy of its own (TitleMirror::alias), bound with the mirror's next batch. std::lock_guard mirror(page_mirror.mutex); page_mirror.in_place.push_back(&h); page_mirror.mirror->alias(console_va, console_va + bytes, arena.buffer, offset); page_mirror_resolve_locked(console_va, bytes, true); console_heaps.push_back(std::move(owned)); console_heap_count.fetch_add(1, std::memory_order_release); update_console_heap_signature_locked(); } std::fprintf(stderr, "[rt] d3d12: console CBV/SRV/UAV descriptor heap 0x%llx (%llu KiB): read in place, its pages the " "title's bytes in the page mirror and a filtered copy of each at heap_base + 0x%llx (the table " "address), refilled as they change; %llu KiB of null slots after it with nothing bound\n", static_cast(console_va), static_cast(bytes >> 10), static_cast(offset), static_cast((reserved - bytes) >> 10)); return true; } // [out, out + reserved) of the arena, whole blocks, with no memory of the arena's behind it: for binds of other // memory there (TitleMirror::alias). Its pages read zero where nothing is bound. False without room. bool arena_reserve_unbacked(VkDeviceSize asked, VkDeviceSize& out, VkDeviceSize& reserved) { if (!asked || !arena.backing.sparse()) return false; const VkDeviceSize block = leonida::kArenaBlockBytes; reserved = (asked + block - 1) & ~(block - 1); if (reserved > arena.size) return false; std::lock_guard lock(arena.mutex); // Whole blocks no unit has (keep_out), so the arena never binds its own memory over them. return arena.blocks.allocate( reserved, block, [this](std::uint64_t lo, std::uint64_t hi) { const std::uint64_t title = leonida::title_va_aliases().title_overlap_end(lo, hi); const std::uint64_t unit = arena.backing.keep_out(lo, hi); return std::max(title, unit); }, out); } void arena_release_unbacked(VkDeviceSize offset, VkDeviceSize reserved) { std::lock_guard lock(arena.mutex); arena.blocks.release(offset, reserved); } // Gives the console heap at `console_va` a GPU view: `shader_va` is where shaders read it. False when there is // none (the heap then stays where only the CPU sees it, as without this). bool add_console_heap(std::uint64_t console_va, VkDeviceSize bytes, std::uint64_t& shader_va, bool resource_heap) { if (!arena_ready() || !context || !bytes || console_va > UINTPTR_MAX - bytes) return false; auto heap = std::make_unique(); heap->console_va = console_va; heap->bytes = bytes; // Self-written V#s must be rebased without changing the title's descriptor bytes. // A directly indexed heap can lie outside the main arena and still fit in a 32-bit shader offset. // A resource heap's copy is followed by null slots (heap_guard_bytes), rounded so the whole stays 64 KiB // aligned for an import. heap->resource_heap = resource_heap; // Round the guarded import up to Wine's allocation granularity. if (bytes > (1ull << 32)) return false; const VkDeviceSize requested = resource_heap ? heap_guard_bytes() : 0; const VkDeviceSize guard = requested && bytes + requested <= (1ull << 32) ? ((bytes + requested + 65535) & ~VkDeviceSize(65535)) - bytes : 0; // Read in place when the page mirror holds the heap's pages: no copy (add_heap_in_place). if (resource_heap && add_heap_in_place(std::move(heap), guard, shader_va)) return true; if (!heap) return false; // LEONIDA_CONSOLE_HEAP_ARENA=1 (with LEONIDA_CONSOLE_HEAP_GPU): the copy and its guard in the arena, which is // device-local where the device has it (ReBAR), not in an import of host memory: every draw's descriptor // fetch and the pass's writes stay on the card. The CPU never writes the copy then (the pass does); [input | // previous] stay in host memory. No room in the arena: the import, as without the switch. bool in_arena = false; if (resource_heap && heap_gpu && console_heap_gpu_enabled() && console_heap_arena_enabled() && bytes <= SIZE_MAX / 2) { VkDeviceSize offset = 0; const VkDeviceSize size = bytes + guard; if (arena_allocate(size, 65536, offset, arena_descriptor_heap)) { heap->scratch.reset(static_cast( VirtualAlloc(nullptr, bytes * 2, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))); if (heap->scratch) { heap->input = heap->scratch.get(); heap->previous = heap->scratch.get() + bytes; heap->shader_va = offset; heap->copy = arena_host(offset, size); heap->guard = guard; heap->imported = false; in_arena = true; std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_ARENA: console descriptor heap 0x%llx's " "copy and %llu MiB guard in the arena at 0x%llx (memory type %u)\n", static_cast(console_va), static_cast(guard >> 20), static_cast(offset), unsigned(arena.memory_type)); } else { arena_release(offset, size, arena_descriptor_heap); } } } if (in_arena) { } else if (resource_heap && geometry.cap()) { if (bytes > (SIZE_MAX - guard) / 3) return false; // [copy | guard | input | previous]: the import covers the copy and its guard. heap->scratch.reset(static_cast(VirtualAlloc(nullptr, bytes * 3 + guard, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))); if (heap->scratch) { auto* backing = heap->scratch.get(); if (import_console_heap(*heap, reinterpret_cast(backing), bytes + guard)) { heap->copy = backing; heap->guard = guard; } heap->input = backing + bytes + guard; heap->previous = backing + 2 * bytes + guard; } heap->imported = false; // the imported storage holds the rewritten descriptors } else if (!resource_heap) { import_console_heap(*heap, console_va); } if (!heap->imported) { if (!heap->copy) { VkDeviceSize offset = 0; // At the console VA itself when the arena reaches that far, else anywhere: with the guard first. bool placed = false; for (int attempt = 0; attempt < (guard ? 2 : 1) && !placed; ++attempt) { const VkDeviceSize size = attempt ? bytes : bytes + guard; heap->identity = arena_allocate_at(console_va, size, arena_descriptor_heap); if (heap->identity) { offset = console_va; } else if (!arena_allocate(size, 65536, offset, arena_descriptor_heap)) { continue; } heap->guard = size - bytes; placed = true; } if (!placed) { log_once("GPU address arena full (raise LEONIDA_ARENA_MB): console descriptor heap left in title " "memory only; KiB", int(std::min(bytes >> 10, INT_MAX))); return false; } if (guard && !heap->guard) log_once("GPU address arena has no room for a console heap's null guard (raise LEONIDA_ARENA_MB): " "a heap index past it reads the arena's next bytes; guard MiB", int(guard >> 20)); heap->shader_va = offset; heap->copy = arena_host(offset, bytes + heap->guard); if (!heap->copy) return false; } std::memset(heap->copy, 0, std::size_t(bytes + heap->guard)); arena_mark_dirty_ptr(heap->copy, std::size_t(bytes + heap->guard)); if (!heap->input) { heap->mirror.assign(std::size_t(bytes), 0); heap->made.assign(std::size_t(bytes), 0); heap->input = heap->mirror.data(); heap->previous = heap->made.data(); } if (resource_heap) { heap->retry.assign(std::size_t(bytes / kDescriptorSize), 0); heap->records.set_texture_live_callback(&DeviceState::on_console_texture_live, this); heap->records.reset(std::size_t(bytes / kDescriptorSize)); // Changes are kept from now on, before the first refresh writes a record. slot_records_live.store(true, std::memory_order_release); } } shader_va = heap->shader_va; if (shader_va != console_va) console_heap_ranges().add(console_va, bytes, shader_va); const bool imported = heap->imported; const VkDeviceSize guarded = heap->guard; arena_guard_bytes.fetch_add(guarded, std::memory_order_relaxed); if (heap_gpu && console_heap_gpu_enabled() && heap->scratch && resource_heap && !imported) { attach_console_heap_gpu(*heap); } if (!imported) { // With tsharp_index_words on the GPU pass, ShadowPages copies raw title bytes into heap->mirror so // unchanged slots in heap->input (which holds patched T# index words) are never clobbered on page re-copy. std::uint8_t* shadow_dst = heap->input; if (heap->gpu >= 0 && tsharp_index_words) { heap->mirror.assign(std::size_t(bytes), 0); shadow_dst = heap->mirror.data(); } heap->pages = make_shadow_pages(reinterpret_cast(static_cast(console_va)), shadow_dst, std::size_t(bytes)); } { std::lock_guard lock(console_heap_mutex); if (heap->gpu >= 0) gpu_heaps[std::size_t(heap->gpu)] = heap.get(); if (!imported) refresh_console_heap(*heap, nullptr); if (heap->copy) { std::unique_lock ranges(console_copy_ranges_mutex); console_copy_ranges.emplace_back(heap->console_va, heap->bytes); } const bool is_resource_heap = heap->resource_heap; console_heaps.push_back(std::move(heap)); if (is_resource_heap) console_heap_count.fetch_add(1, std::memory_order_release); update_console_heap_signature_locked(); } std::fprintf(stderr, "[rt] d3d12: console %s descriptor heap 0x%llx (%llu KiB): shaders read it at heap_base + 0x%llx, " "%s; %llu KiB of null slots after it%s\n", resource_heap ? "CBV/SRV/UAV" : "sampler", static_cast(console_va), static_cast(bytes >> 10), static_cast(shader_va), imported ? "the title's pages imported as host memory" : "a descriptor copy brought up to date before every submission", static_cast(guarded >> 10), imported && resource_heap ? " (imported pages have no guard)" : ""); return true; } // Called by the title's threads as they write buffer views (the Subrender workers among them). Not under // console_heap_mutex, which the submit thread holds for every refresh of the heaps (3-7 ms a submission after the // load, speed-27): the heaps with a copy, as ranges, under a lock of their own. std::shared_mutex console_copy_ranges_mutex; std::vector> console_copy_ranges; // console VA, bytes bool has_console_descriptor_copy(std::uintptr_t destination) { std::shared_lock lock(console_copy_ranges_mutex); for (const auto& [va, bytes] : console_copy_ranges) if (destination - va < bytes) return true; return false; } void remove_console_heap(std::uint64_t console_va) { std::unique_ptr heap; { std::lock_guard lock(console_heap_mutex); const auto it = std::find_if(console_heaps.begin(), console_heaps.end(), [console_va](const auto& h) { return h->console_va == console_va; }); if (it == console_heaps.end()) return; heap = std::move(*it); console_heaps.erase(it); if (heap->resource_heap) console_heap_count.fetch_sub(1, std::memory_order_acq_rel); update_console_heap_signature_locked(); std::unique_lock ranges(console_copy_ranges_mutex); std::erase_if(console_copy_ranges, [console_va](const auto& r) { return r.first == console_va; }); if (heap->gpu >= 0) { heap_gpu->remove_heap(heap->gpu); gpu_heaps[std::size_t(heap->gpu)] = nullptr; } } console_heap_ranges().remove(console_va); heap->pages.reset(); if (heap->in_place) { // Its pages leave the arena (unbound in the mirror's next batch, flushed here) and their filtered copies are // freed; the arena range is free once what was submitted, which may read it, has retired. in_place_heaps.fetch_sub(1, std::memory_order_acq_rel); { std::lock_guard lock(page_mirror.mutex); std::erase(page_mirror.in_place, heap.get()); if (page_mirror.mirror) page_mirror.mirror->unalias(console_va); } refresh_page_mirror(); flush_page_mirror(); context->wait_retire_ticket(context->submitted_retire_ticket()); arena_release_unbacked(heap->shader_va, heap->bytes + heap->guard); arena_guard_bytes.fetch_sub(heap->guard, std::memory_order_relaxed); return; } if (heap->gpu >= 0) { // A pass recorded before remove_heap may still be on its way to the queue, and then reads `input` and // writes the copy: wait for it to be submitted, then for everything submitted. while (heap_gpu->uncommitted()) Sleep(0); context->wait_retire_ticket(context->submitted_retire_ticket()); if (heap->input_buffer) context->vk.vkDestroyBuffer(info.device, heap->input_buffer, nullptr); if (heap->input_memory) context->vk.vkFreeMemory(info.device, heap->input_memory, nullptr); } if (heap->buffer) { // As for an imported slot-133 buffer: the title may free its pages right after, so the memory goes once // what was submitted retires, not through the deferred queue. context->wait_retire_ticket(context->submitted_retire_ticket()); context->vk.vkDestroyBuffer(info.device, heap->buffer, nullptr); context->vk.vkFreeMemory(info.device, heap->memory, nullptr); leonida::kernel_writes::release(std::exchange(heap->pin, 0)); } else { arena_release(heap->shader_va, heap->bytes + heap->guard, arena_descriptor_heap); } arena_guard_bytes.fetch_sub(heap->guard, std::memory_order_relaxed); } // ---- LEONIDA_CONSOLE_HEAP_GPU=1: the console heaps' V#s rebased by a compute pass (src/console_heap_gpu.h) ---- // Before every submission the CPU still finds the changed slots (the heap's ShadowPages, then a compare with the // bytes each slot was last made from) and registers the T#s, as fix_console_slot does; every changed slot is then // queued for the pass, which writes it into the copy at the start of the submission (the context's prelude). A // V# half the pass's tables cannot answer is written with no records and comes back as a miss once its submission // is done: resolved here with vsharp_address (which may make a geometry copy) within LEONIDA_CONSOLE_GPU_RESOLVE_US // a refresh (2000 by default), its answer entered in the key table and its slots queued again. Words that got no // backing are asked again every LEONIDA_CONSOLE_GPU_RETRY_MS (500), on a timer to bound the per-submission cost. // When a backing or an alias range goes, the key entries that answered into it are dropped and every V# slot of // the heap is translated again (on the GPU: a list of slot indices). std::unique_ptr heap_gpu; std::array gpu_heaps{}; // console_heap_mutex std::vector> released_ranges; // (shader VA, bytes); backing_mutex struct GpuKeyHash { std::size_t operator()(const leonida::ConsoleHeapKeys::Key& k) const { return leonida::ConsoleHeapKeys::hash(k); } }; // The rest: console_heap_mutex. Unresolved words with the slots that missed on them (heap << 28 | slot), and // whether the resolver has them. struct GpuUnresolved { std::vector slots; bool asked = false; }; std::unordered_map gpu_unresolved; // The resolver: a thread of ours that answers missed words with vsharp_address, off the submitting thread (one // answer can wait milliseconds for the geometry worker's lock). // Requests and answers pass under its own mutex; the refresh hands words over and takes answers, never waits. struct GpuAnswer { leonida::ConsoleHeapKeys::Key key; std::uint64_t to, span; bool retry; }; struct GpuResolver { std::mutex mutex; std::condition_variable wake; bool stop = false; std::vector> requests; // (words, a retry of no backing) std::vector answers; // T#s to register (bind_title_image), the slot's words: the refresh only decodes them. Resolver-only state: // the words registered recently (not asked again) and those whose texture is still to come (asked again). std::vector tsharps; std::unordered_set registered; std::deque> waiting; std::thread thread; ~GpuResolver() { halt(); } void halt() { { std::lock_guard lock(mutex); stop = true; } wake.notify_all(); if (thread.joinable()) thread.join(); } }; std::unique_ptr gpu_resolver; std::array, 5> gpu_tsharps{}; // the resolver's T# registrations, by TitleImage std::size_t gpu_asked = 0; // requests handed over and not answered yet struct GpuUnbacked { std::chrono::steady_clock::time_point at; // when it may be asked again leonida::ConsoleHeapKeys::Key key; std::uint32_t tries = 0; // asked again so far: the wait doubles each time, up to 64x retry_ms }; std::deque gpu_unbacked; // words answered "no backing", by when they may be asked again (roughly) std::unordered_map gpu_unbacked_tries; // being asked std::uint64_t gpu_alias_generation = ~0ull; std::chrono::steady_clock::time_point gpu_ranges_at{}; std::vector gpu_ranges; leonida::ConsoleHeapSpans gpu_backed, gpu_ask; std::uint64_t gpu_backed_generation = ~0ull, gpu_ask_generation = ~0ull; std::uint64_t gpu_backed_blocks = ~0ull; // the title-window blocks' layout generations at the last rebuild std::chrono::steady_clock::time_point gpu_backed_at{}; std::vector gpu_queue_scratch; bool gpu_rescan = false, gpu_rescan_after_resolve = false; std::chrono::steady_clock::time_point gpu_rescan_asked{}; // LEONIDA_CONSOLE_GPU_FILTER=1 (default off): a release, an alias range that went or a word answered since asks // for a rescan of the slots it touches (an interval rule, 8a22e92c8) instead of every V# slot: the GPU passes over // the rest on its device-local metadata. // gpu_filter_shader: shader-VA spans (released backings, alias copies that went); gpu_filter_title: title VAs // (words backed since). Overflows and key resets still rescan everything. static bool gpu_filter_enabled() { static const bool on = [] { char text[8] = {}; return GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_FILTER", text, sizeof(text)) && text[0] == '1'; }(); return on; } bool gpu_rescan_filtered = false; leonida::ConsoleHeapSpans gpu_filter_shader, gpu_filter_title; void request_rescan_after_resolve() { if (!gpu_rescan_after_resolve) gpu_rescan_asked = std::chrono::steady_clock::now(); gpu_rescan_after_resolve = true; } struct GpuMiss { leonida::ConsoleHeapKeys::Key key; std::uint32_t code; // heap << 28 | slot; UINT32_MAX once handled }; std::vector gpu_miss_scratch; struct GpuCounts { std::uint64_t misses = 0, resolved = 0, none = 0, flips = 0, rescans = 0, dropped = 0, released = 0; std::uint64_t known_misses = 0, put_failed = 0, backed_rebuilds = 0, backed_cuts = 0, key_resets = 0; std::uint64_t retried = 0, filtered_rescans = 0; double backed_ms = 0; double resolve_ms = 0, begin_ms = 0; double part_ms[5] = {}; // before: alias probes, drain + releases, range table, backed table, ask table } gpu_counts; // LEONIDA_SHADOW_GPU=1 copies aliased shadow pages on the GPU at the start of the submission. // The source uses VK_EXT_external_memory_host to import the mapped title section. An import is // made per 2 MiB-aligned window of the view, kept while xmem's map journal shows no change over it, and lives until // the last pass that copies from it retires. Destinations outside the arena, and pages that will not import, are // copied by the CPU as before. static bool shadow_gpu_enabled() { static const bool on = [] { char value[4] = {}; return GetEnvironmentVariableA("LEONIDA_SHADOW_GPU", value, sizeof(value)) == 1 && value[0] == '1'; }(); return on; } struct ShadowImport { DeviceState* device = nullptr; std::uintptr_t base = 0; std::size_t bytes = 0; VkBuffer buffer = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; std::uint64_t generation = 0; // title_memory_map's, when last found unchanged ~ShadowImport() { if (buffer) device->context->vk.vkDestroyBuffer(device->info.device, buffer, nullptr); if (memory) device->context->vk.vkFreeMemory(device->info.device, memory, nullptr); } }; std::mutex shadow_import_mutex; std::map> shadow_imports; // by base std::uint64_t shadow_import_bytes = 0; struct ShadowGpuCounts { std::uint64_t copies = 0, bytes = 0, imports = 0, imported = 0, dropped = 0, refused = 0, outside = 0; } shadow_gpu_counts; // shadow_import_mutex static bool shadow_gpu_copy(void* context, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { return static_cast(context)->gpu_copy_shadow(to, from, bytes); } // Shadows with memory of their own (no room in the arena): their mapping and buffer, for gpu_copy_shadow. struct CopyTarget { std::size_t bytes; VkBuffer buffer; }; std::map copy_targets; // shadow_import_mutex void add_copy_target(const std::uint8_t* mapped, std::size_t bytes, VkBuffer buffer) { if (!shadow_gpu_enabled() || !mapped || !buffer) return; std::lock_guard lock(shadow_import_mutex); copy_targets[mapped] = {bytes, buffer}; } // Before the buffer goes: no copy into it is recorded after this (one already recorded runs before it is freed: // the buffer goes to the deferred queue, behind the submission that recorded it). void remove_copy_target(const std::uint8_t* mapped) { if (!shadow_gpu_enabled() || !mapped) return; VkBuffer buffer = VK_NULL_HANDLE; { std::lock_guard lock(shadow_import_mutex); const auto it = copy_targets.find(mapped); if (it == copy_targets.end()) return; buffer = it->second.buffer; copy_targets.erase(it); } if (heap_gpu) heap_gpu->drop_copies_to(buffer); } // Where [to, to + n) is on the GPU: the arena, a title-window block outside it, or a shadow's own buffer. bool copy_destination(const std::uint8_t* to, std::size_t n, VkBuffer& buffer, VkDeviceSize& offset) { if (std::uint64_t at = 0; arena.backing.offset_of(to, n, at)) { buffer = arena.buffer; offset = at; return true; } if (external_windows.find_mapped(to, n, buffer, offset)) return true; auto it = copy_targets.upper_bound(to); // shadow_import_mutex held if (it == copy_targets.begin()) return false; --it; if (to < it->first || n > it->second.bytes || std::size_t(to - it->first) > it->second.bytes - n) return false; buffer = it->second.buffer; offset = VkDeviceSize(to - it->first); return true; } bool gpu_copy_shadow(std::uint8_t* to, const std::uint8_t* from, std::size_t n) { if (!heap_gpu || !n) return false; std::lock_guard lock(shadow_import_mutex); VkBuffer dst_buffer = VK_NULL_HANDLE; VkDeviceSize dst_offset = 0; if (!copy_destination(to, n, dst_buffer, dst_offset)) { ++shadow_gpu_counts.outside; return false; } const auto src = reinterpret_cast(from); std::shared_ptr found; auto it = shadow_imports.upper_bound(src); if (it != shadow_imports.begin()) { --it; ShadowImport& cand = *it->second; if (src >= cand.base && src + n <= cand.base + cand.bytes) { std::uint64_t now = 0; bool moved = false; if (!leonida::title_memory_map::changes_since(cand.generation, now, cand.base, cand.base + cand.bytes, [&](std::uintptr_t, std::uintptr_t) { moved = true; })) moved = true; if (moved) { shadow_import_bytes -= cand.bytes; shadow_imports.erase(it); ++shadow_gpu_counts.dropped; } else { cand.generation = now; found = it->second; } } } if (!found && !(found = make_shadow_import(src, n))) { ++shadow_gpu_counts.refused; return false; } heap_gpu->queue_copy(found->buffer, src - found->base, dst_buffer, dst_offset, n, found); ++shadow_gpu_counts.copies; shadow_gpu_counts.bytes += n; return true; } // An import of the committed, readable view region around [src, src + n): its 2 MiB-aligned window, inside the // region. Null when it does not hold all of it, the budget (LEONIDA_SHADOW_GPU_MB, 1024) is spent, or the driver // refuses. shadow_import_mutex held. std::shared_ptr make_shadow_import(std::uintptr_t src, std::size_t n) { static const std::uint64_t budget = [] { char text[16] = {}; const DWORD c = GetEnvironmentVariableA("LEONIDA_SHADOW_GPU_MB", text, sizeof(text)); return (c > 0 && c < sizeof(text) ? std::strtoull(text, nullptr, 10) : 1024ull) << 20; }(); const std::uint64_t generation = leonida::title_memory_map::generation(); MEMORY_BASIC_INFORMATION region{}; const auto refuse = [&](const char* why) -> std::shared_ptr { static std::atomic logged{0}; if (logged.fetch_add(1, std::memory_order_relaxed) < 8) std::fprintf(stderr, "[rt] d3d12: LEONIDA_SHADOW_GPU: no import of 0x%llx (+%zu; state 0x%lx protect 0x%lx " "type 0x%lx): %s; copied by the CPU\n", static_cast(src), n, static_cast(region.State), static_cast(region.Protect), static_cast(region.Type), why); return nullptr; }; if (!VirtualQuery(reinterpret_cast(src), ®ion, sizeof(region))) return refuse("no region"); if (region.State != MEM_COMMIT || !region.Protect || (region.Protect & (PAGE_NOACCESS | PAGE_GUARD | PAGE_WRITECOMBINE | PAGE_NOCACHE))) return refuse("not committed and readable"); // This import path supports mapped section views. if (region.Type != MEM_MAPPED) return refuse("not a section view"); constexpr std::uintptr_t kWindow = 2u << 20; const auto region_base = reinterpret_cast(region.BaseAddress); const std::uintptr_t region_end = region_base + region.RegionSize; const std::uintptr_t base = std::max(region_base, src & ~(kWindow - 1)); const std::uintptr_t end = std::min(region_end, (src + n + kWindow - 1) & ~(kWindow - 1)); if (src + n > end) return refuse("the run crosses the view's end"); if (shadow_import_bytes + (end - base) > budget) return refuse("LEONIDA_SHADOW_GPU_MB spent"); auto imp = std::make_shared(); imp->device = this; imp->base = base; imp->bytes = end - base; imp->generation = generation; VkDeviceAddress address = 0; if (!import_host_range(reinterpret_cast(base), imp->bytes, imp->buffer, imp->memory, address)) return refuse("the driver refused the import"); // Older imports over these pages are stale or redundant. for (auto it = shadow_imports.lower_bound(base > (64ull << 20) ? base - (64ull << 20) : 0); it != shadow_imports.end() && it->first < end;) { if (it->first + it->second->bytes > base) { shadow_import_bytes -= it->second->bytes; it = shadow_imports.erase(it); } else { ++it; } } shadow_imports[base] = imp; shadow_import_bytes += imp->bytes; ++shadow_gpu_counts.imports; shadow_gpu_counts.imported += imp->bytes; return imp; } static bool console_heap_gpu_enabled() { static const bool on = [] { char value[4] = {}; return GetEnvironmentVariableA("LEONIDA_CONSOLE_HEAP_GPU", value, sizeof(value)) == 1 && value[0] == '1'; }(); return on; } static bool console_heap_arena_enabled() { static const bool on = [] { char value[4] = {}; return GetEnvironmentVariableA("LEONIDA_CONSOLE_HEAP_ARENA", value, sizeof(value)) == 1 && value[0] == '1'; }(); return on; } void setup_console_heap_gpu(PFN_vkGetDeviceProcAddr get_device) { if ((!console_heap_gpu_enabled() && !shadow_gpu_enabled()) || !context || !get_device) return; auto gpu = std::make_unique(get_device, info.device, memory); if (!gpu->init()) { std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: the translation pass could not be made; the " "console heaps are fixed on the CPU\n"); return; } heap_gpu = std::move(gpu); heap_gpu->set_signed_offsets(signed_vsharp_offsets()); leonida::title_va_aliases().record_removals(true); context->set_prelude([this](VkCommandBuffer cb) { return heap_gpu->record(cb); }, [this](bool submitted, std::uint64_t ticket) { heap_gpu->commit(submitted, ticket); }); gpu_resolver = std::make_unique(); gpu_resolver->thread = std::thread([this, r = gpu_resolver.get()] { SetThreadDescription(GetCurrentThread(), L"leonida console heap resolver"); const auto words_hash = [](const leonida::gfx10::ImageWords& w) { std::uint64_t h = 1469598103934665603ull; for (const std::uint32_t x : w) h = (h ^ x) * 1099511628211ull; return h; }; const auto bind = [&](const leonida::gfx10::ImageWords& w) { const TitleImage result = bind_title_image(*this, w); gpu_tsharps[unsigned(result)].fetch_add(1, std::memory_order_relaxed); if (result == TitleImage::unknown || result == TitleImage::refused) { if (r->waiting.size() < 65536) r->waiting.emplace_back(std::chrono::steady_clock::now(), w); } else { if (r->registered.size() > (1u << 20)) r->registered.clear(); r->registered.insert(words_hash(w)); } }; for (;;) { std::vector> batch; std::vector tsharps; { std::unique_lock lock(r->mutex); // Woken for work, or every 100 ms for the T#s whose texture is still to come. r->wake.wait_for(lock, std::chrono::milliseconds(100), [r] { return r->stop || !r->requests.empty() || !r->tsharps.empty(); }); if (r->stop) return; batch.swap(r->requests); tsharps.swap(r->tsharps); } const leonida::submit_phases::WorkerScope busy(leonida::submit_phases::worker_heap_resolver); for (const auto& w : tsharps) if (!r->registered.count(words_hash(w))) bind(w); // Those still waiting for a texture, again every 500 ms, at most 256 a round. const auto now = std::chrono::steady_clock::now(); for (int n = 0; n < 256 && !r->waiting.empty() && now - r->waiting.front().first >= std::chrono::milliseconds(500); ++n) { const auto w = r->waiting.front().second; r->waiting.pop_front(); bind(w); } for (const auto& [key, retry] : batch) { std::uint64_t span = 0; const std::uint64_t to = resolve_vsharp_words(key, span); std::lock_guard lock(r->mutex); if (r->stop) return; r->answers.push_back({key, to, span, retry}); } } }); if (shadow_gpu_enabled()) { ShadowPages::gpu_copy_context = this; ShadowPages::gpu_copy = &shadow_gpu_copy; std::fprintf(stderr, "[rt] d3d12: LEONIDA_SHADOW_GPU=1: slot-133 shadows' aliased pages are copied by the " "GPU from imports of the title's pages\n"); } if (console_heap_gpu_enabled()) std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU=1: console heap V#s are rebased by a compute pass " "at the start of each submission\n"); } // `bytes` of host memory at `host` as a buffer the GPU reads by its device address. False: not importable. bool import_host_range(void* host, VkDeviceSize bytes, VkBuffer& buffer, VkDeviceMemory& out, VkDeviceAddress& address) { auto& vk = context->vk; const VkDeviceSize alignment = info.host_pointer_alignment; if (!get_host_pointer_properties || !alignment || (reinterpret_cast(host) % alignment) || (bytes % alignment)) return false; VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; VkBufferCreateInfo create{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external}; create.size = bytes; create.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT; share(create); buffer = VK_NULL_HANDLE; out = VK_NULL_HANDLE; if (vk.vkCreateBuffer(info.device, &create, nullptr, &buffer) != VK_SUCCESS) return false; const auto fail = [&] { if (buffer) vk.vkDestroyBuffer(info.device, buffer, nullptr); if (out) vk.vkFreeMemory(info.device, out, nullptr); buffer = VK_NULL_HANDLE; out = VK_NULL_HANDLE; return false; }; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(info.device, buffer, &requirements); VkMemoryHostPointerPropertiesEXT pointer{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; if (get_host_pointer_properties(info.device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, host, &pointer) != VK_SUCCESS) return fail(); const std::uint32_t types = pointer.memoryTypeBits & requirements.memoryTypeBits; if (!types || bytes < requirements.size) return fail(); VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; import.pHostPointer = host; VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; for (const VkMemoryPropertyFlags want : {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), VkMemoryPropertyFlags(0)}) { for (std::uint32_t i = 0; i < memory.memoryTypeCount && !out; ++i) { if (!(types & (1u << i)) || (memory.memoryTypes[i].propertyFlags & want) != want) continue; VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; allocate.allocationSize = bytes; allocate.memoryTypeIndex = i; if (vk.vkAllocateMemory(info.device, &allocate, nullptr, &out) != VK_SUCCESS) out = VK_NULL_HANDLE; } if (out) break; } if (!out || vk.vkBindBufferMemory(info.device, buffer, out, 0) != VK_SUCCESS) return fail(); VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bda.buffer = buffer; address = vk.vkGetBufferDeviceAddress(info.device, &bda); if (!address) return fail(); return true; } // A resource heap with its 3x scratch (copy, input, previous) goes to the pass: `input` imported, the copy // written by the pass where shaders read it (arena.address + shader_va: the scratch import or the arena range). void attach_console_heap_gpu(ConsoleHeap& heap) { VkDeviceAddress input = 0; if (!import_host_range(heap.input, heap.bytes, heap.input_buffer, heap.input_memory, input)) { std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: console descriptor heap 0x%llx: its mirror " "could not be imported; fixed on the CPU\n", static_cast(heap.console_va)); return; } const int index = heap_gpu->add_heap(input, arena.address + heap.shader_va, std::uint32_t(heap.bytes / kDescriptorSize)); if (index < 0) { context->vk.vkDestroyBuffer(info.device, heap.input_buffer, nullptr); context->vk.vkFreeMemory(info.device, heap.input_memory, nullptr); heap.input_buffer = VK_NULL_HANDLE; heap.input_memory = VK_NULL_HANDLE; return; } heap.gpu = index; heap.vsharp_bits.assign((heap.bytes / kDescriptorSize + 63) / 64, 0); std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: console descriptor heap 0x%llx (%llu slots) is " "translated by the pass (heap %d)\n", static_cast(heap.console_va), static_cast(heap.bytes / kDescriptorSize), index); } static void set_vsharp_bit(ConsoleHeap& heap, std::size_t slot, bool on) { const std::uint64_t bit = 1ull << (slot & 63); auto& word = heap.vsharp_bits[slot >> 6]; word = on ? word | bit : word & ~bit; } // The T# in a slot's title bytes, registered as fix_console_slot does (no write: the pass copies it). 0: not // settled (a T# whose texture is still to come); 1: settled; 2: settled, and the slot holds words that are no // buffer pair and no T# that decodes, whose dwords 0-3 the pass writes as zeros, as fix_console_slot does. int console_tsharp_check(ConsoleHeap& heap, std::size_t slot) { leonida::gfx10::ImageWords words; std::memcpy(words.data(), heap.previous + slot * kDescriptorSize, sizeof(words)); if (!(words[3] >> 30)) return 1; if (!leonida::gfx10::is_image(words)) { ++heap.images[unsigned(TitleImage::not_tsharp)]; return 2; } const char* why = nullptr; const TitleImage result = bind_title_image(*this, words, &why); if (result == TitleImage::unknown || result == TitleImage::refused) { note_refused_tsharp(heap, slot * kDescriptorSize, words, why); if (result == TitleImage::refused) ++heap.refused_reasons[why ? why : "?"]; } ++heap.images[unsigned(result)]; if (result == TitleImage::not_tsharp) return 2; return result != TitleImage::unknown && result != TitleImage::refused ? 1 : 0; } // LEONIDA_CONSOLE_GPU_TSHARPS=0 keeps T# registration on the submitting thread (fix_console_slot's way, under the // fix budget); by default the resolver does it and the refresh only decodes. static bool tsharps_off_thread_enabled() { static const bool on = [] { char value[4] = {}; return !(GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_TSHARPS", value, sizeof(value)) == 1 && value[0] == '0'); }(); return on; } void fix_gpu_tsharp_slot(ConsoleHeap& heap, std::size_t slot, std::vector& queued) { using Records = leonida::ConsoleHeapSlotRecords; leonida::gfx10::ImageWords words; std::memcpy(words.data(), heap.previous + slot * kDescriptorSize, sizeof(words)); if (!(words[3] >> 30)) { if (heap.records.state(slot, 0) != Records::none) heap.records.clear(slot); return; } if (!leonida::gfx10::is_image(words)) { ++heap.images[unsigned(TitleImage::not_tsharp)]; if (heap.records.state(slot, 0) != Records::none) heap.records.clear(slot); std::memcpy(heap.input + slot * kDescriptorSize, words.data(), kDescriptorSize); queued.push_back(std::uint32_t(slot) | leonida::ConsoleHeapGpu::kZeroFirst); return; } const char* why = nullptr; std::uint32_t index_word = 0; std::uint64_t bound_address = 0; const TitleImage result = bind_title_image(*this, words, &why, &index_word, &bound_address); const bool unbound = result == TitleImage::unknown || result == TitleImage::refused; const bool waiting_index = !unbound && result != TitleImage::not_tsharp && index_word == 0; if (unbound) { note_refused_tsharp(heap, slot * kDescriptorSize, words, why); ++heap.refused_reasons[why ? why : "?"]; } ++heap.images[unsigned(result)]; if (result == TitleImage::not_tsharp) { if (heap.records.state(slot, 0) != Records::none) heap.records.clear(slot); std::memcpy(heap.input + slot * kDescriptorSize, words.data(), kDescriptorSize); queued.push_back(std::uint32_t(slot) | leonida::ConsoleHeapGpu::kZeroFirst); return; } leonida::gfx10::Image image{}; leonida::gfx10::decode(words, image); const std::uint64_t texture_address = bound_address ? bound_address : tsharp_texture_key(image.address); const Records::State texture = (!unbound && !waiting_index) ? Records::texture_bound : (unbound && (why == kTsharpArrayFull || why == kTsharpStorageFull)) ? Records::texture_waiting_room : Records::texture_waiting; if (unbound || waiting_index) ++heap.texture_waits; else if (Records::is_waiting(heap.records.state(slot, 0)) && heap.records.base(slot, 0) == texture_address) ++heap.texture_refills; words[leonida::gfx10::kTsharpIndexDword] = (unbound || waiting_index) ? 0u : index_word; std::memcpy(heap.input + slot * kDescriptorSize, words.data(), kDescriptorSize); heap.records.set_texture(slot, texture, texture_address); queued.push_back(std::uint32_t(slot)); } std::vector tsharp_jobs; // console_heap_mutex void refresh_console_heap_gpu(ConsoleHeap& heap, const std::vector* changes) { // console_heap_mutex held const bool tsharps_off_thread = !tsharp_index_words && tsharps_off_thread_enabled() && gpu_resolver; static const std::uint64_t budget_us = [] { char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_FIX_US", text, sizeof(text)); return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 4000ull; }(); using clock = std::chrono::steady_clock; using Records = leonida::ConsoleHeapSlotRecords; const auto ms = [](clock::time_point a, clock::time_point b) { return std::chrono::duration(b - a).count(); }; const auto t0 = clock::now(); heap.copied += heap.pages->refresh(); auto& queued = gpu_queue_scratch; queued.clear(); const bool separate_mirror = !heap.mirror.empty(); const std::uint8_t* raw = separate_mirror ? heap.mirror.data() : heap.input; // The tracker zeroed these in `raw` too: mirror into `input` when separate, then queue. heap.pages->for_each_zeroed([&](std::size_t offset, std::size_t bytes) { std::memset(heap.previous + offset, 0, bytes); if (separate_mirror) std::memset(heap.input + offset, 0, bytes); for (std::size_t slot = offset / kDescriptorSize; slot * kDescriptorSize < offset + bytes && slot < heap.retry.size(); ++slot) { heap.retry[slot] = 0; set_vsharp_bit(heap, slot, false); if (tsharp_index_words && heap.records.state(slot, 0) != Records::none) heap.records.clear(slot); queued.push_back(std::uint32_t(slot)); } }); const auto t1 = clock::now(); std::uint32_t binds = 0; bool over = false; heap.pages->for_each_copied([&](std::size_t offset, std::size_t bytes) { const std::size_t end = std::min(offset + bytes, std::size_t(heap.bytes)); for (std::size_t at = offset & ~std::size_t(kDescriptorSize - 1); at + kDescriptorSize <= end; at += kDescriptorSize) { if (!std::memcmp(heap.previous + at, raw + at, kDescriptorSize)) continue; std::memcpy(heap.previous + at, raw + at, kDescriptorSize); note_changed_slot(heap, heap.previous + at); const std::size_t slot = at / kDescriptorSize; heap.gpu_high = std::max(heap.gpu_high, std::uint32_t(slot + 1)); const auto* w = reinterpret_cast(heap.previous + at); if (!(w[3] >> 30)) { if (separate_mirror) std::memcpy(heap.input + at, raw + at, kDescriptorSize); queued.push_back(std::uint32_t(slot)); set_vsharp_bit(heap, slot, w[2] || w[6]); heap.retry[slot] = 0; if (tsharp_index_words && heap.records.state(slot, 0) != Records::none) heap.records.clear(slot); continue; } set_vsharp_bit(heap, slot, false); if (tsharp_index_words) { heap.retry[slot] = 0; fix_gpu_tsharp_slot(heap, slot, queued); continue; } if (tsharps_off_thread) { // Only decoded here: words that are no T# are zeroed by the pass; a T# goes to the resolver to // be registered (shaders find it by its words; until then they get the fallback). leonida::gfx10::ImageWords words; std::memcpy(words.data(), w, sizeof(words)); leonida::gfx10::Image image{}; const bool tsharp = leonida::gfx10::is_image(words) && leonida::gfx10::decode(words, image); queued.push_back(std::uint32_t(slot) | (tsharp ? 0u : leonida::ConsoleHeapGpu::kZeroFirst)); if (tsharp) tsharp_jobs.push_back(words); else ++heap.images[unsigned(TitleImage::not_tsharp)]; heap.retry[slot] = 0; continue; } // Past LEONIDA_CONSOLE_FIX_US of registering T#s, the rest wait for retry_console_tsharps (copied as // they are meanwhile). if (budget_us && !over && !(++binds & 15) && clock::now() - t1 >= std::chrono::microseconds(budget_us)) over = true; const int check = over ? 0 : console_tsharp_check(heap, slot); queued.push_back(std::uint32_t(slot) | (check == 2 ? leonida::ConsoleHeapGpu::kZeroFirst : 0u)); if (check) { heap.retry[slot] = 0; } else { if (over) ++heap.deferred_fixes; if (!heap.retry[slot]) { heap.retry[slot] = 1; heap.retries.push_back(std::uint32_t(slot)); } } } }); if (tsharp_index_words && changes && !changes->empty()) { std::vector tex_changes; for (const auto& c : *changes) if (c.kind == leonida::SlotChange::texture_gone || c.kind == leonida::SlotChange::texture_added || c.kind == leonida::SlotChange::texture_room) tex_changes.push_back(c); if (!tex_changes.empty()) { heap.records.touched(tex_changes.data(), tex_changes.size(), slot_change_scratch); for (const std::uint32_t slot : slot_change_scratch) fix_gpu_tsharp_slot(heap, slot, queued); } } heap_gpu->queue(heap.gpu, queued.begin(), queued.end()); heap.gpu_queued += queued.size(); if (!tsharp_jobs.empty()) { { std::lock_guard lock(gpu_resolver->mutex); gpu_resolver->tsharps.insert(gpu_resolver->tsharps.end(), tsharp_jobs.begin(), tsharp_jobs.end()); } gpu_resolver->wake.notify_one(); tsharp_jobs.clear(); } const auto t2 = clock::now(); if (!heap.retries.empty()) retry_console_tsharps(heap); const auto t3 = clock::now(); heap.pages_ms += ms(t0, t1); heap.fix_ms += ms(t1, t2); heap.retry_ms += ms(t2, t3); } // retry_console_slots for the GPU mode: only T#s wait there, and nothing is written. void retry_console_tsharps(ConsoleHeap& heap) { static const std::uint64_t budget_us = [] { char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_RETRY_US", text, sizeof(text)); return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 500ull; }(); const auto start = std::chrono::steady_clock::now(); std::size_t i = heap.retry_at, visited = 0; const std::size_t total = heap.retries.size(); while (visited < total && !heap.retries.empty()) { if (i >= heap.retries.size()) i = 0; const std::uint32_t slot = heap.retries[i]; ++visited; const int check = heap.retry[slot] ? console_tsharp_check(heap, slot) : 1; if (check == 2) heap_gpu->queue(heap.gpu, slot | leonida::ConsoleHeapGpu::kZeroFirst); if (check) { heap.retry[slot] = 0; heap.retries[i] = heap.retries.back(); heap.retries.pop_back(); } else { ++i; } if (budget_us && !(visited & 31) && std::chrono::steady_clock::now() - start >= std::chrono::microseconds(budget_us)) break; } heap.retry_at = i; heap.retried += visited; } // What fix_vsharp's console path (VsharpPath::scratch) answers for the four words of a V# half: the shader VA, or 0 // (no backing). `span` gets the V#'s span. std::uint64_t resolve_vsharp_words(const leonida::ConsoleHeapKeys::Key& k, std::uint64_t& span) { const std::uint64_t base = std::uint64_t(k[0]) | (std::uint64_t(k[1] & 0xffff) << 32); const std::uint32_t stride = (k[1] >> 16) & 0x3fffu; span = std::uint64_t(k[2]) * (stride ? stride : 1); const leonida::gfx10::BufferWords words{k[0], k[1], k[2], k[3]}; leonida::gfx10::Buffer desc{}; const bool copy_geometry = leonida::gfx10::decode(words, desc) && (span <= kTitleWindowMax || (desc.format && leonida::gfx10::encode(desc) == words)); return vsharp_address(base, span, leonida::TitleVaAliases::table_view, !geometry.cap(), copy_geometry); } // vsharp_address's backed(): [offset, offset + bytes) of the shader VAs is a live allocation or geometry copy. bool shader_range_backed(std::uint64_t offset, std::uint64_t bytes) { constexpr std::uint64_t mask = (1ull << 48) - 1; if (!bytes) return false; const std::uint64_t limit = signed_vsharp_offsets() ? mask / 2 : mask; const bool encodable = offset <= limit ? bytes - 1 <= limit - offset : signed_vsharp_offsets() && offset >= UINT64_MAX - limit && bytes - 1 <= limit - offset; if (!encodable) return false; const auto bda = arena.address + offset; { std::lock_guard lock(backing_mutex); if (gpu_backings.covers(bda, bytes)) return true; } std::uint64_t host{}, room{}; return geometry.cap() && geometry.lookup(bda, host, room) && room >= bytes; } // The range table from the alias table: a range keeps its check while it and its backing stay; `gone` (shader // VA ranges released since the last one) clears it. True when a checked range lost its backing. bool rebuild_gpu_ranges(const std::vector>& gone) { std::vector mappings; leonida::title_va_aliases().mappings(mappings); const auto overlaps_gone = [&](std::uint64_t start, std::uint64_t end) { for (const auto& [s, n] : gone) if (s < end && start < s + n) return true; return false; }; bool lost = false; std::vector ranges; ranges.reserve(mappings.size()); for (const auto& m : mappings) { const std::uint64_t bytes = m.end - m.title_va; const bool released = !gone.empty() && overlaps_gone(m.shader_va, m.shader_va + bytes); auto it = std::lower_bound(gpu_ranges.begin(), gpu_ranges.end(), m.title_va, [](const leonida::ConsoleHeapRange& r, std::uint64_t va) { return r.title_va < va; }); bool checked; if (it != gpu_ranges.end() && it->title_va == m.title_va && it->end == m.end && it->shader_va == m.shader_va && !released) { checked = it->checked; } else { checked = shader_range_backed(m.shader_va, bytes); if (released && it != gpu_ranges.end() && it->title_va == m.title_va && it->checked) lost = true; } ranges.push_back({m.title_va, m.end, m.shader_va, checked}); } // A checked range that is gone from the table altogether had its slots answered from it. if (!lost) { for (const auto& r : gpu_ranges) { if (!r.checked) continue; auto it = std::lower_bound(ranges.begin(), ranges.end(), r.title_va, [](const leonida::ConsoleHeapRange& a, std::uint64_t va) { return a.title_va < va; }); if (it == ranges.end() || it->title_va != r.title_va || it->shader_va != r.shader_va || !it->checked) { lost = true; break; } } } gpu_ranges = ranges; heap_gpu->set_ranges(std::move(ranges)); return lost; } // The backed table (src/console_heap_gpu.h): every live allocation's shader VAs and the geometry copies' blocks, // merged, and clipped to what a V# can name. Rebuilt from gpu_backings when allocations changed, at most every // 100 ms (one made since is a miss the CPU answers meanwhile); a release in between is cut out of it at once, so // the pass never leaves a V# on memory that is going (an overlapping allocation that stays is then a miss too // until the next rebuild). void update_gpu_backed(const std::vector>& gone) { const auto start = std::chrono::steady_clock::now(); const std::uint64_t generation = backing_generation.load(std::memory_order_relaxed); const std::uint64_t blocks = geometry.pool().layout_generation() + external_windows.layout_generation(); const bool changed = generation != gpu_backed_generation || blocks != gpu_backed_blocks; if (changed && (gpu_backed_generation == ~0ull || start - gpu_backed_at >= std::chrono::milliseconds(100))) { gpu_backed_generation = generation; gpu_backed_blocks = blocks; gpu_backed_at = start; gpu_backed.clear(); { std::lock_guard lock(backing_mutex); gpu_backings.for_each([&](std::uint64_t va, std::uint64_t bytes) { const std::uint64_t offset = va - arena.address; if (bytes && offset <= UINT64_MAX - bytes) gpu_backed.emplace_back(offset, offset + bytes); }); } const auto block = [&](VkDeviceAddress address, VkDeviceSize bytes) { const std::uint64_t offset = address - arena.address; if (address && bytes && offset <= UINT64_MAX - bytes) gpu_backed.emplace_back(offset, offset + bytes); }; geometry.pool().for_each_block(block); external_windows.for_each_block(block); leonida::merge_console_heap_spans(gpu_backed); // What a V# can name: 48 bits, or +-2^47 around heap_base with signed offsets. constexpr std::uint64_t k47 = 1ull << 47, k48 = 1ull << 48; leonida::ConsoleHeapSpans clipped; for (const auto& [a, b] : gpu_backed) { if (signed_vsharp_offsets()) { if (a < k47) clipped.emplace_back(a, std::min(b, k47)); else if (a >= 0ull - k47) clipped.emplace_back(a, b); } else if (a < k48) { clipped.emplace_back(a, std::min(b, k48)); } } gpu_backed.swap(clipped); heap_gpu->set_spans(leonida::ConsoleHeapGpu::backed_table, gpu_backed); ++gpu_counts.backed_rebuilds; } else if (!gone.empty() && !gpu_backed.empty()) { leonida::ConsoleHeapSpans out; for (const auto& [s0, bytes] : gone) { const std::uint64_t e0 = bytes > UINT64_MAX - s0 ? UINT64_MAX : s0 + bytes; out.clear(); for (const auto& [a, b] : gpu_backed) { if (b <= s0 || a >= e0) { out.emplace_back(a, b); continue; } if (a < s0) out.emplace_back(a, s0); if (b > e0) out.emplace_back(e0, b); } gpu_backed.swap(out); } heap_gpu->set_spans(leonida::ConsoleHeapGpu::backed_table, gpu_backed); ++gpu_counts.backed_cuts; } gpu_counts.backed_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); } // LEONIDA_ADDRESS_GUARD=1 (docs/d3d12_vulkan.md, "Address guard"): the page table the guarded shaders read, a // host-visible buffer of its own whose address minus heap_base is in the guard header at arena offset // kGuardHeader. Built from the same backings as the console heap pass's backed table (gpu_backings, the // geometry copies' blocks and the separate window buffers), but whole and at once: a backing made since the last // submission must not read 0. struct AddressGuard { VkBuffer buffer = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; std::uint32_t* words = nullptr; std::unique_ptr table; std::uint64_t generation = ~0ull, blocks = ~0ull, heaps = ~0ull; // heaps: the console heaps' ranges, hashed std::uint32_t refused_logged = 0, overflow_logged = 0; std::uint64_t updates = 0, words_written = 0; std::chrono::steady_clock::time_point logged{}; std::mutex mutex; } guard; // Make the page table and write the header (called once the arena is mapped). False leaves the guard off: the // header keeps no magic, so guarded shaders check nothing. bool create_address_guard() { namespace ag = leonida::address_guard; if (!context || !arena_ready() || arena.size < ag::kGuardEnd) return false; auto& vk = context->vk; guard.table = std::make_unique(); // Read by guarded shaders on every queue: shared by the device's queue families. const VkBufferCreateInfo create = ag::table_buffer_info(guard.table->bytes(), families); if (vk.vkCreateBuffer(info.device, &create, nullptr, &guard.buffer) != VK_SUCCESS) { guard.buffer = VK_NULL_HANDLE; return false; } VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(info.device, guard.buffer, &requirements); guard.memory = allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, true); void* mapped = nullptr; if (!guard.memory || vk.vkBindBufferMemory(info.device, guard.buffer, guard.memory, 0) != VK_SUCCESS || vk.vkMapMemory(info.device, guard.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { destroy_address_guard(); return false; } guard.words = static_cast(mapped); std::memcpy(guard.words, guard.table->words().data(), guard.table->bytes()); VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = guard.buffer; const VkDeviceAddress table = vk.vkGetBufferDeviceAddress(info.device, &address); // Below arena.first: the arena's permanent head, always backed. std::uint8_t* const guard_page = arena_host(ag::kGuardHeader, ag::kGuardEnd - ag::kGuardHeader); if (!guard_page) return false; auto* header = reinterpret_cast(guard_page); std::memset(guard_page, 0, std::size_t(ag::kGuardEnd - ag::kGuardHeader)); header->limit = arena.size; header->table = table - arena.address; std::atomic_thread_fence(std::memory_order_release); header->magic = ag::magic(); // last: a shader that sees it sees the rest arena_mark_dirty(ag::kGuardHeader, ag::kGuardEnd - ag::kGuardHeader); std::fprintf(stderr, "[rt] d3d12: address guard on (LEONIDA_ADDRESS_GUARD): %llu KiB page table, header at " "heap_base + 0x%llx; shaders translated with --address-guard read 0 from memory nothing " "backs and drop their stores there\n", static_cast(guard.table->bytes() >> 10), static_cast(ag::kGuardHeader)); return true; } void destroy_address_guard() { if (!context) return; auto& vk = context->vk; if (guard.buffer) vk.vkDestroyBuffer(info.device, guard.buffer, nullptr); if (guard.memory) vk.vkFreeMemory(info.device, guard.memory, nullptr); guard.buffer = VK_NULL_HANDLE; guard.memory = VK_NULL_HANDLE; guard.words = nullptr; } // Before each submission: the page table says exactly what is backed now, and refusals since the last line are // logged (at most once a second). Rebuilt only when a backing came or went; only changed words are written. void update_address_guard() { namespace ag = leonida::address_guard; if (!guard.words) return; const std::uint64_t generation = backing_generation.load(std::memory_order_acquire); const std::uint64_t blocks = geometry.pool().layout_generation() + external_windows.layout_generation(); std::uint64_t heap_signature = console_heap_signature.load(std::memory_order_acquire); // Lock-free clean fast path: skip console_heap_mutex, heap_spans allocation, and guard.mutex when backings, // blocks, console heaps, and refusal counter are unchanged. if (generation == std::atomic_ref(guard.generation).load(std::memory_order_acquire) && blocks == std::atomic_ref(guard.blocks).load(std::memory_order_acquire) && heap_signature == std::atomic_ref(guard.heaps).load(std::memory_order_acquire)) { auto* header = reinterpret_cast(arena_host(ag::kGuardHeader, sizeof(ag::AddressGuardHeader))); if (!header || std::atomic_ref(header->refused).load(std::memory_order_relaxed) == 0) return; } // A console descriptor heap whose GPU copy lies outside the arena (an import of the title's pages, which // shaders read at shader_va = its device address minus heap_base) is read through heap_base + VA like a // buffer, but no gpu_backing names it: its bytes and the null guard after them are entered here. Without // this the guard refused every descriptor-table load from such a heap (run 28: a 38 MB imported heap at // shader VA 0x87e00000, past a 2 GiB arena). Collected before guard.mutex, in console_heap_mutex's order. std::vector> heap_spans; const bool need_table_update = generation != std::atomic_ref(guard.generation).load(std::memory_order_acquire) || blocks != std::atomic_ref(guard.blocks).load(std::memory_order_acquire) || heap_signature != std::atomic_ref(guard.heaps).load(std::memory_order_acquire); if (need_table_update) { heap_signature = 0xcbf29ce484222325ull; std::lock_guard heaps(console_heap_mutex); for (const auto& h : console_heaps) { if (!h || !h->bytes) continue; const std::uint64_t begin = h->shader_va, end = h->shader_va + h->bytes + h->guard; heap_signature = (heap_signature ^ begin) * 0x100000001b3ull; heap_signature = (heap_signature ^ end) * 0x100000001b3ull; if (!(begin < arena.size && end <= arena.size)) heap_spans.emplace_back(begin, end); } } std::lock_guard lock(guard.mutex); if (need_table_update && (generation != std::atomic_ref(guard.generation).load(std::memory_order_relaxed) || blocks != std::atomic_ref(guard.blocks).load(std::memory_order_relaxed) || heap_signature != std::atomic_ref(guard.heaps).load(std::memory_order_relaxed))) { std::vector> spans = heap_spans; { std::lock_guard backing_lock(backing_mutex); gpu_backings.for_each([&](std::uint64_t va, std::uint64_t bytes) { const std::uint64_t offset = va - arena.address; // The arena's own ranges pass on the limit compare; only what lies outside needs pages. if (bytes && !(offset < arena.size && bytes <= arena.size - offset)) spans.emplace_back(offset, offset + bytes); }); } const auto block = [&](VkDeviceAddress address, VkDeviceSize bytes) { const std::uint64_t offset = address - arena.address; if (address && bytes) spans.emplace_back(offset, offset + bytes); }; geometry.pool().for_each_block(block); external_windows.for_each_block(block); guard.words_written += guard.table->assign(spans, [&](std::size_t i, std::uint32_t v) { std::atomic_ref(guard.words[i]).store(v, std::memory_order_relaxed); }); ++guard.updates; // Publish updated generation/blocks/heaps with release semantics AFTER guard.words is updated so // concurrent threads taking the lock-free fast path never observe stale page-table words. std::atomic_ref(guard.generation).store(generation, std::memory_order_release); std::atomic_ref(guard.blocks).store(blocks, std::memory_order_release); std::atomic_ref(guard.heaps).store(heap_signature, std::memory_order_release); if (guard.table->overflowed() != guard.overflow_logged) { guard.overflow_logged = guard.table->overflowed(); std::fprintf(stderr, "[rt] d3d12: address guard: %u 4 GiB chunk(s) of backings past the page table's " "%u blocks are not checked\n", guard.overflow_logged, guard.table->blocks_used()); } } const auto now = std::chrono::steady_clock::now(); if (arena.staged) { if (now - guard.logged < std::chrono::seconds(1)) return; sync_arena_to_host(ag::kGuardHeader, sizeof(ag::AddressGuardHeader)); } auto* header = reinterpret_cast(arena_host(ag::kGuardHeader, sizeof(ag::AddressGuardHeader))); if (!header) return; const std::uint32_t refused = std::atomic_ref(header->refused).load(std::memory_order_relaxed); if (refused != guard.refused_logged && now - guard.logged >= std::chrono::seconds(1)) { guard.logged = now; std::fprintf(stderr, "[rt] d3d12: address guard: %u access(es) refused so far (+%u), the last at heap " "offset 0x%llx by module 0x%08x; %llu table update(s), %llu word(s) written\n", refused, refused - guard.refused_logged, static_cast(header->last_refused), std::atomic_ref(header->last_module).load(std::memory_order_relaxed), static_cast(guard.updates), static_cast(guard.words_written)); guard.refused_logged = refused; } else if (arena.staged) { guard.logged = now; } } // The ask table: the title's memory and both addresses of its GPU-window pairs. A V# base outside them that the // other tables do not answer is one vsharp_address could only answer 0 for. void update_gpu_ask() { auto& aliases = leonida::title_va_aliases(); const std::uint64_t generation = aliases.memory_generation() * 1000003ull + std::uint64_t(leonida::title_gpu_views::count()); if (generation == gpu_ask_generation) return; gpu_ask_generation = generation; gpu_ask = aliases.title_memory_ranges(); leonida::ConsoleHeapSpans views; leonida::title_gpu_views::spans(views); gpu_ask.insert(gpu_ask.end(), views.begin(), views.end()); leonida::merge_console_heap_spans(gpu_ask); heap_gpu->set_spans(leonida::ConsoleHeapGpu::ask_table, gpu_ask); } // Once, when xmem's aliased pages are many: can they be imported as host memory (VK_EXT_external_memory_host)? // A successful import lets the GPU copy the section. Release the diagnostic import after the check. void probe_alias_imports() { static bool probed = false; if (probed) return; std::vector pages; const std::size_t total = leonida::title_page_aliases::sample(pages, 8); if (total < 256) return; probed = true; int ok = 0; for (const std::uintptr_t va : pages) { if (leonida::title_frames::backed(va)) continue; // a table page has no host view to import VkBuffer buffer = VK_NULL_HANDLE; VkDeviceMemory imported = VK_NULL_HANDLE; VkDeviceAddress address = 0; MEMORY_BASIC_INFORMATION region{}; VirtualQuery(reinterpret_cast(va), ®ion, sizeof(region)); const bool done = import_host_range(reinterpret_cast(va), leonida::title_page_aliases::kPageSize, buffer, imported, address); ok += done; std::fprintf(stderr, "[rt] d3d12: alias import probe: page 0x%llx (state 0x%lx protect 0x%lx type 0x%lx): %s, " "device address 0x%llx\n", static_cast(va), static_cast(region.State), static_cast(region.Protect), static_cast(region.Type), done ? "imported" : "refused", static_cast(address)); if (buffer) context->vk.vkDestroyBuffer(info.device, buffer, nullptr); if (imported) context->vk.vkFreeMemory(info.device, imported, nullptr); } std::fprintf(stderr, "[rt] d3d12: alias import probe: %d of %zu sampled pages imported (%zu aliased pages)\n", ok, pages.size(), total); } // Before the heaps of a refresh: the misses of the passes that are done, the backings and alias ranges gone, the // range table. console_heap_mutex held. void console_heap_gpu_begin() { const auto start = std::chrono::steady_clock::now(); auto lap = [last = start](double& to) mutable { const auto now = std::chrono::steady_clock::now(); to += std::chrono::duration(now - last).count(); last = now; }; probe_alias_imports(); lap(gpu_counts.part_ms[0]); auto& misses = gpu_miss_scratch; misses.clear(); heap_gpu->drain( context->completed_retire_ticket(), [&](int h, std::uint32_t slot, std::uint32_t half) { ConsoleHeap* heap = h >= 0 && unsigned(h) < gpu_heaps.size() ? gpu_heaps[std::size_t(h)] : nullptr; ++gpu_counts.misses; if (!heap || slot >= heap->retry.size()) return; const auto* k = reinterpret_cast(heap->previous + slot * kDescriptorSize) + 4 * half; if ((k[3] >> 30) || !k[2]) return; // rewritten since: queued by its change misses.push_back({{k[0], k[1], k[2], k[3]}, (std::uint32_t(h) << 28) | slot}); }, // A list that ran over: every V# slot again once what it did hold is resolved (at once would only // overflow it again with the same words). [&](int) { request_rescan_after_resolve(); }); if (!misses.empty()) { // Words the table has now (entered after that pass was recorded): only the slot again. The rest wait to // be resolved. std::vector again; heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) { for (auto& m : misses) if (keys.find(m.key) >= 0) again.push_back(m.code), m.code = UINT32_MAX; return 0; }); for (const std::uint32_t code : again) if (gpu_heaps[code >> 28]) heap_gpu->queue(int(code >> 28), code & ((1u << 28) - 1)); gpu_counts.known_misses += again.size(); for (const auto& m : misses) { if (m.code == UINT32_MAX) continue; auto& slots = gpu_unresolved[m.key].slots; // Words shared by very many slots: the rest are found by the rescan after the answer. if (slots.size() < 4096) slots.push_back(m.code); else request_rescan_after_resolve(); } } std::vector> gone, removed; { std::lock_guard lock(backing_mutex); gone.swap(released_ranges); } auto& aliases = leonida::title_va_aliases(); aliases.take_removed(removed); gpu_counts.released += gone.size() + removed.size(); std::size_t dropped = 0; if (!gone.empty() || !removed.empty()) dropped = heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) { std::size_t n = 0; for (const auto& [s, bytes] : gone) n += keys.erase_overlapping(s, s + bytes); for (const auto& [s, bytes] : removed) n += keys.erase_overlapping(s, s + bytes); return n; }); gpu_counts.dropped += dropped; lap(gpu_counts.part_ms[1]); bool lost = false; const std::uint64_t generation = aliases.generation(); // At once when something went (the pass must not answer from it), else at most every 50 ms: a range added // since is a miss the resolver answers meanwhile (the alias table changes at most submissions). if ((generation != gpu_alias_generation && (!removed.empty() || start - gpu_ranges_at >= std::chrono::milliseconds(50))) || !gone.empty()) { gpu_alias_generation = generation; gpu_ranges_at = start; lost = rebuild_gpu_ranges(gone); } lap(gpu_counts.part_ms[2]); if (dropped || lost) { if (gpu_filter_enabled()) { gpu_rescan_filtered = true; for (const auto& [s, bytes] : gone) gpu_filter_shader.emplace_back(s, s + bytes); for (const auto& [s, bytes] : removed) gpu_filter_shader.emplace_back(s, s + bytes); } else { gpu_rescan = true; } } update_gpu_backed(gone); lap(gpu_counts.part_ms[3]); update_gpu_ask(); lap(gpu_counts.part_ms[4]); gpu_counts.begin_ms += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); } // After the heaps: hand the missed words to the resolver, take its answers (entered in the key table, their slots // queued again), ask again for words that got no backing, and translate every V# slot again when something they // were answered from went. Nothing here waits for an answer. void console_heap_gpu_end() { static const std::uint64_t retry_ms = [] { char text[16] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_RETRY_MS", text, sizeof(text)); return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 2000ull; }(); using clock = std::chrono::steady_clock; const auto start = clock::now(); std::vector answers; std::vector> requests; for (auto& [key, u] : gpu_unresolved) if (!u.asked) { u.asked = true; requests.emplace_back(key, false); } // Words with no backing, asked again once retry_ms old: at most 256 a refresh, and while the resolver has // fewer than 4096 waiting. const auto now = clock::now(); for (int n = 0; n < 256 && !gpu_unbacked.empty() && gpu_asked + requests.size() < 4096 && now >= gpu_unbacked.front().at; ++n) { requests.emplace_back(gpu_unbacked.front().key, true); gpu_unbacked_tries[gpu_unbacked.front().key] = gpu_unbacked.front().tries + 1; gpu_unbacked.pop_front(); ++gpu_counts.retried; } { std::lock_guard lock(gpu_resolver->mutex); answers.swap(gpu_resolver->answers); gpu_resolver->requests.insert(gpu_resolver->requests.end(), requests.begin(), requests.end()); } if (!requests.empty()) gpu_resolver->wake.notify_one(); gpu_asked += requests.size(); gpu_asked -= std::min(gpu_asked, answers.size()); const auto queue_slots = [&](const std::vector& slots) { for (const std::uint32_t code : slots) { const std::uint32_t h = code >> 28; if (h < gpu_heaps.size() && gpu_heaps[h]) heap_gpu->queue(int(h), code & ((1u << 28) - 1)); } }; for (const GpuAnswer& a : answers) { if (a.retry) { if (!a.to) { // Still no backing: asked again after twice the wait, at most 64x retry_ms. const auto t = gpu_unbacked_tries.find(a.key); const std::uint32_t tries = t == gpu_unbacked_tries.end() ? 1 : t->second; if (t != gpu_unbacked_tries.end()) gpu_unbacked_tries.erase(t); const auto wait = std::chrono::milliseconds(retry_ms << std::min(tries, 6)); gpu_unbacked.push_back({clock::now() + wait, a.key, tries}); continue; } gpu_unbacked_tries.erase(a.key); // Backed now: every slot that read "no backing" for these words, once all are in. const bool entered = heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) { std::uint64_t to = 0; bool none = false; return keys.lookup(a.key, to, none) && none && keys.put(a.key, a.to, a.span, false); }); if (entered) { ++gpu_counts.flips; if (gpu_filter_enabled()) { // The slots that read "no backing" for these words: those with this title base. const std::uint64_t base = a.key[0] | (std::uint64_t(a.key[1] & 0xffff) << 32); gpu_filter_title.emplace_back(base, base + 1); gpu_rescan_filtered = true; } else { gpu_rescan = true; } } continue; } ++gpu_counts.resolved; const auto it = gpu_unresolved.find(a.key); if (!heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) { return keys.put(a.key, a.to, a.span, !a.to); })) ++gpu_counts.put_failed; // every probe slot holds other words: these slots stay without records else if (it != gpu_unresolved.end()) queue_slots(it->second.slots); if (it != gpu_unresolved.end()) gpu_unresolved.erase(it); if (!a.to) { ++gpu_counts.none; gpu_unbacked.push_back({clock::now() + std::chrono::milliseconds(retry_ms), a.key, 0}); } } while (gpu_unbacked.size() > 65536) gpu_unbacked.pop_front(); // those stay "no backing" until a rescan // A key table past 60 % full: emptied at once (the next pass clears the GPU's), and every V# slot again. const auto [key_count, key_capacity] = heap_gpu->with_keys( [](leonida::ConsoleHeapKeys& k) { return std::pair(k.size(), k.capacity()); }); if (key_count * 10 > key_capacity * 6) { heap_gpu->reset_keys(); gpu_unbacked.clear(); gpu_unresolved.clear(); ++gpu_counts.key_resets; gpu_rescan = true; } // Asked for after an overflow: once the misses are resolved, or a second later if new ones keep coming. if (gpu_rescan_after_resolve && (gpu_unresolved.empty() || clock::now() - gpu_rescan_asked >= std::chrono::seconds(1))) { gpu_rescan_after_resolve = false; gpu_rescan = true; } if (gpu_rescan) { gpu_rescan = false; ++gpu_counts.rescans; // On the GPU: one dispatch over the slots the title has written, pairs only (ConsoleHeapGpu::rescan). for (unsigned h = 0; h < gpu_heaps.size(); ++h) if (ConsoleHeap* heap = gpu_heaps[h]) heap_gpu->rescan(int(h), heap->gpu_high); gpu_rescan_filtered = false; // the full one covers it gpu_filter_shader.clear(); gpu_filter_title.clear(); } else if (gpu_rescan_filtered) { gpu_rescan_filtered = false; ++gpu_counts.filtered_rescans; // The spans go to the pass once (its change tables serve every heap). bool first = true; const leonida::ConsoleHeapSpans none; for (unsigned h = 0; h < gpu_heaps.size(); ++h) if (ConsoleHeap* heap = gpu_heaps[h]) { heap_gpu->rescan_filtered(int(h), heap->gpu_high, first ? gpu_filter_shader : none, first ? gpu_filter_title : none); first = false; } gpu_filter_shader.clear(); gpu_filter_title.clear(); } gpu_counts.resolve_ms += std::chrono::duration(clock::now() - start).count(); } void log_console_heap_gpu(ConsoleHeap& heap, double count) { const auto stats = heap_gpu->take_stats(); const std::size_t keys = heap_gpu->with_keys([](leonida::ConsoleHeapKeys& k) { return k.size(); }); std::size_t checked = 0; for (const auto& r : gpu_ranges) checked += r.checked; std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx on the GPU: %.1f slots queued a submission; passes " "%llu (%llu slots, %llu key updates, %llu misses, %llu overflowed, %llu not submitted); resolved " "%llu words (%llu with no backing, %llu asked again, %llu answered later, %llu not entered), %llu " "misses already " "entered, %zu waiting (%zu with the resolver), %zu unbacked; %llu rescans (%llu slots), " "%llu filtered rescans (%llu slots looked at), %llu key entries dropped for %llu releases; %zu keys (%llu resets), %zu ranges (%zu checked), %zu " "backed spans (%llu rebuilds, %llu cuts, %.3f ms a submission), %zu ask spans; %.3f ms before " "and %.3f ms resolving a submission\n", static_cast(heap.console_va), double(heap.gpu_queued) / count, static_cast(stats.passes), static_cast(stats.slots), static_cast(stats.updates), static_cast(stats.misses), static_cast(stats.overflows), static_cast(stats.failed), static_cast(gpu_counts.resolved), static_cast(gpu_counts.none), static_cast(gpu_counts.retried), static_cast(gpu_counts.flips), static_cast(gpu_counts.put_failed), static_cast(gpu_counts.known_misses), gpu_unresolved.size(), gpu_asked, gpu_unbacked.size(), static_cast(gpu_counts.rescans), static_cast(stats.rescanned), static_cast(gpu_counts.filtered_rescans), static_cast(stats.filtered), static_cast(gpu_counts.dropped), static_cast(gpu_counts.released), keys, static_cast(gpu_counts.key_resets), gpu_ranges.size(), checked, gpu_backed.size(), static_cast(gpu_counts.backed_rebuilds), static_cast(gpu_counts.backed_cuts), gpu_counts.backed_ms / count, gpu_ask.size(), gpu_counts.begin_ms / count, gpu_counts.resolve_ms / count); std::fprintf(stderr, "[rt] d3d12: console heap pass, before the heaps, ms a submission: alias probes %.3f, misses and " "releases %.3f, range table %.3f, backed table %.3f, ask table %.3f\n", gpu_counts.part_ms[0] / count, gpu_counts.part_ms[1] / count, gpu_counts.part_ms[2] / count, gpu_counts.part_ms[3] / count, gpu_counts.part_ms[4] / count); if (tsharps_off_thread_enabled()) { std::uint64_t t[5]; for (unsigned i = 0; i < 5; ++i) t[i] = gpu_tsharps[i].exchange(0, std::memory_order_relaxed); std::fprintf(stderr, "[rt] d3d12: console heap T#s registered by the resolver: %llu known, %llu bound, %llu naming no " "texture, %llu refused\n", static_cast(t[0]), static_cast(t[1]), static_cast(t[2]), static_cast(t[3])); } if (shadow_gpu_enabled()) { ShadowGpuCounts c; std::size_t imports = 0; std::uint64_t imported_bytes = 0; { std::lock_guard lock(shadow_import_mutex); c = std::exchange(shadow_gpu_counts, ShadowGpuCounts{}); imports = shadow_imports.size(); imported_bytes = shadow_import_bytes; } std::fprintf(stderr, "[rt] d3d12: slot-133 shadows on the GPU: %llu copies (%.1f KiB a submission), %llu imports made " "(%llu MiB), %llu dropped after a map change, %llu refused, %llu with no GPU destination; %zu imports " "live (%llu MiB); passes copied %llu regions\n", static_cast(c.copies), double(c.bytes) / 1024.0 / count, static_cast(c.imports), static_cast(c.imported >> 20), static_cast(c.dropped), static_cast(c.refused), static_cast(c.outside), imports, static_cast(imported_bytes >> 20), static_cast(stats.copies)); } heap.gpu_queued = 0; gpu_counts = {}; } // LOCAL DIAGNOSTIC (desc-probe): which console-heap slots our API wrote and which the title wrote itself, what // the title's own records decode to, and whether the GPU can see them. Title data: the log stays local. struct HeapProbe { std::uint64_t console_va = 0, shader_va = 0; std::size_t slots = 0; bool shadowed = false; std::vector api; // hash of what our API last wrote to the slot; 0: never std::vector writer; // optional input-probe API origin by slot std::vector seen; // hash at the last census std::uint64_t api_writes = 0, censuses = 0; int table_dumps = 0, census_dumps = 0; bool told_table = false; // bound tables, since the last census std::uint64_t tables = 0, t_slots = 0, t_zero = 0, t_api = 0, t_title = 0, t_kind[8] = {}; int table_logs = 0; std::size_t recent[8] = {}; // the last bound slots, read again at each census unsigned recent_count = 0; }; std::mutex probe_mutex; // never under console_heap_mutex' callees; takes descriptor_mutex inside // LEONIDA_DESC_PROBE=1 turns the diagnostic on (so does the compute input probe, which reads these records). Off // by default: at every submission it hashes each slot of every bound table, and formats a line under // descriptor_mutex for each slot the title wrote itself. static bool probe_enabled() { static const bool on = [] { const char* v = std::getenv("LEONIDA_DESC_PROBE"); return (v && *v == '1') || rt::compute_probe::enabled(); }(); return on; } std::vector> probes; std::uint64_t probe_submissions = 0; static constexpr const char* kProbeKinds[8] = {"V# in arena", "V# title memory", "V# other", "T# key known", "T# texture by address", "T# no texture", "other", "free-list link (dword 0 only)"}; std::atomic probe_view_logs{0}; // Where a Create*View / CopyDescriptors* write landed, for the first ones. void probe_view(const char* what, SIZE_T ptr, UINT count) { if (!probe_enabled() || probe_view_logs.fetch_add(1) >= 48) return; std::lock_guard lock(probe_mutex); for (const auto& p : probes) if (ptr >= p->console_va && ptr < p->console_va + p->slots * kDescriptorSize) { char text[512]; probe_kind(reinterpret_cast(ptr), text, sizeof(text)); std::fprintf(stderr, "[rt] desc-probe: %s x%u -> console heap slot %llu: %s\n", what, count, static_cast((ptr - p->console_va) / kDescriptorSize), text); return; } std::fprintf(stderr, "[rt] desc-probe: %s x%u -> 0x%llx, outside the console heaps\n", what, count, static_cast(ptr)); } static std::uint64_t probe_hash(const std::uint8_t* p) { std::uint64_t h = 1469598103934665603ull; for (unsigned i = 0; i < kDescriptorSize; ++i) h = (h ^ p[i]) * 1099511628211ull; return h ? h : 1; } static bool probe_zero(const std::uint8_t* p) { std::uint64_t q[4]; std::memcpy(q, p, sizeof(q)); return !(q[0] | q[1] | q[2] | q[3]); } void probe_add(std::uint64_t console_va, std::uint64_t shader_va, std::size_t slots, bool shadowed) { if (!probe_enabled() && !rt::compute_probe::enabled()) return; auto probe = std::make_unique(); probe->console_va = console_va; probe->shader_va = shader_va; probe->slots = slots; probe->shadowed = shadowed; probe->api.assign(slots, 0); if (rt::compute_probe::enabled()) probe->writer.resize(slots); probe->seen.assign(slots, 0); std::lock_guard lock(probe_mutex); probes.push_back(std::move(probe)); std::fprintf(stderr, "[rt] desc-probe: console heap 0x%llx, %zu slots, shaders read it at VA 0x%llx (%s); arena size " "0x%llx: heap_base + VA is %s the arena\n", static_cast(console_va), slots, static_cast(shader_va), !shadowed ? "no GPU view" : shader_va + slots * kDescriptorSize <= arena.size ? "arena copy" : "import", static_cast(arena.size), shader_va + slots * kDescriptorSize <= arena.size ? "inside" : "PAST"); } void probe_remove(std::uint64_t console_va) { if (!probe_enabled()) return; std::lock_guard lock(probe_mutex); std::erase_if(probes, [console_va](const std::unique_ptr& p) { return p->console_va == console_va; }); } void probe_api(SIZE_T ptr, UINT count, const char* what = "CopyDescriptors") { if (!ptr || !count || !probe_enabled()) return; std::lock_guard lock(probe_mutex); for (const auto& p : probes) { if (ptr < p->console_va || ptr >= p->console_va + p->slots * kDescriptorSize) continue; const std::size_t first = std::size_t((ptr - p->console_va) / kDescriptorSize); for (std::size_t i = first; i < first + count && i < p->slots; ++i) { p->api[i] = probe_hash(reinterpret_cast( static_cast(p->console_va + i * kDescriptorSize))); if (!p->writer.empty()) p->writer[i] = rt::compute_probe::writer_code(what); ++p->api_writes; } } } // What a slot the title wrote holds (an index into kProbeKinds) and a line saying so. int probe_kind(const std::uint8_t* bytes, char* text, std::size_t size) { namespace g = leonida::gfx10; std::uint32_t w[8]; std::memcpy(w, bytes, sizeof(w)); int n = std::snprintf(text, size, "%08x %08x %08x %08x %08x %08x %08x %08x |", w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]); if (!(w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7]) && w[0] < 0x200000u) { if (n > 0 && std::size_t(n) < size) std::snprintf(text + n, size - n, " free-list link to slot %u?", w[0]); return 7; } if (n < 0) n = 0; char* rest = text + std::min(std::size_t(n), size); const std::size_t left = size - std::min(std::size_t(n), size); if (!(w[3] >> 30)) { g::BufferWords words{w[0], w[1], w[2], w[3]}; g::Buffer b{}; const bool ok = g::decode(words, b); std::uint64_t lo = 0, hi = 0; const bool title = leonida::title_va_aliases().title_memory(b.address, lo, hi); const std::uint64_t to = leonida::title_va_aliases().shader_va(b.address); const int kind = b.address < arena.size ? 0 : title ? 1 : 2; std::snprintf(rest, left, " V#%s base 0x%llx stride %u records %u fmt %u dst %u%u%u%u oob %u -> %s%s (upper 16 B %s)", ok ? "" : "(bad dst)", static_cast(b.address), b.stride, b.num_records, b.format, b.swizzle[0], b.swizzle[1], b.swizzle[2], b.swizzle[3], unsigned(b.oob_select), kProbeKinds[kind], to != b.address ? " (has a GPU copy)" : "", (w[4] | w[5] | w[6] | w[7]) ? "set" : "zero"); return kind; } g::ImageWords words{w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]}; g::Image image{}; if (!g::is_image(words) || !g::decode(words, image)) { std::snprintf(rest, left, " neither V# nor valid T# (type %u)", w[3] >> 28); return 6; } int kind = 5; char what[96] = "no texture at that address"; { std::lock_guard lock(descriptor_mutex); if (image_entries.count(words) || image_entries.count(g::tsharp_key(words))) { kind = 3; std::snprintf(what, sizeof(what), "key registered"); } else if (const auto it = images_by_address.find(image.address); it != images_by_address.end()) { kind = 4; std::snprintf(what, sizeof(what), "texture known, this key not registered"); } } std::snprintf(rest, left, " T# base 0x%llx fmt %u type %u %ux%u depth %u mips %u+%u of %u layers %u+%u samples %u dst " "%u%u%u%u minlod %.2f -> %s", static_cast(image.address), image.format, unsigned(image.type), image.width, image.height, image.depth, image.first_mip, image.mip_count, image.resource_mips, image.first_layer, image.layer_count, image.samples, image.swizzle[0], image.swizzle[1], image.swizzle[2], image.swizzle[3], double(image.min_lod), what); return kind; } // At a descriptor-table scan (ExecuteCommandLists): the slots a bound table in a console heap declares. void probe_table(std::uint64_t table_va, std::uint32_t descriptors) { if (!probe_enabled()) return; std::lock_guard lock(probe_mutex); for (const auto& p : probes) { const std::uint64_t span = p->slots * kDescriptorSize; std::uint64_t at = 0; if (table_va >= p->shader_va && table_va - p->shader_va < span) at = table_va - p->shader_va; else if (table_va >= p->console_va && table_va - p->console_va < span) at = table_va - p->console_va; else continue; const std::size_t first = std::size_t(at / kDescriptorSize); const std::size_t count = std::min(std::min(descriptors, 1024), p->slots - first); if (!p->told_table) { p->told_table = true; std::fprintf(stderr, "[rt] desc-probe: first bound table in console heap 0x%llx: VA 0x%llx = slot %zu, %zu " "slots declared; shaders load it at heap_base + 0x%llx, %s the arena (size 0x%llx)\n", static_cast(p->console_va), static_cast(table_va), first, count, static_cast(table_va), table_va + count * kDescriptorSize <= arena.size ? "inside" : "PAST", static_cast(arena.size)); } ++p->tables; p->recent[p->recent_count++ % 8] = first; if (p->table_logs < 40) { ++p->table_logs; char text[512] = ""; probe_kind(reinterpret_cast( static_cast(p->console_va + first * kDescriptorSize)), text, sizeof(text)); std::fprintf(stderr, "[rt] desc-probe: table %llu VA 0x%llx slot %zu (%zu declared) at execute: %s\n", static_cast(p->tables), static_cast(table_va), first, count, text); } for (std::size_t i = first; i < first + count; ++i) { const auto* bytes = reinterpret_cast(static_cast(p->console_va + i * kDescriptorSize)); ++p->t_slots; if (probe_zero(bytes)) { ++p->t_zero; continue; } if (p->api[i] && p->api[i] == probe_hash(bytes)) { ++p->t_api; continue; } ++p->t_title; char text[512]; const int kind = probe_kind(bytes, text, sizeof(text)); ++p->t_kind[kind]; if (p->table_dumps < 24) { ++p->table_dumps; std::fprintf(stderr, "[rt] desc-probe: table slot %zu (table VA 0x%llx +%zu) %s-written: %s\n", i, static_cast(table_va), i - first, p->api[i] ? "API-then-title" : "title", text); } } } } // Before a submission, after the console heaps' copies are refreshed: the whole heap, now and then. void probe_census() { if (!probe_enabled()) return; const std::uint64_t n = ++probe_submissions; if (n != 1 && n != 64 && n != 512 && n != 2048 && n % 4096) return; std::lock_guard lock(probe_mutex); for (const auto& p : probes) { ++p->censuses; std::uint64_t zero = 0, api = 0, title_new = 0, title_over = 0, changed_no_api = 0, kinds[8] = {}; std::uint64_t copy_differs = 0, copy_differs_unrebased = 0; // A copy lies in the arena; an import never does (its device address is outside the arena's). const std::uint8_t* copy = p->shadowed ? arena.backing.host(p->shader_va, p->slots * kDescriptorSize) : nullptr; for (std::size_t i = 0; i < p->slots; ++i) { const auto* bytes = reinterpret_cast(static_cast(p->console_va + i * kDescriptorSize)); if (copy && std::memcmp(copy + i * kDescriptorSize, bytes, kDescriptorSize)) { ++copy_differs; // A rebased V# differs in its base only (dwords 0 and 1 low half). std::uint32_t a[8], b[8]; std::memcpy(a, bytes, 32); std::memcpy(b, copy + i * kDescriptorSize, 32); const bool rebased = !(a[3] >> 30) && a[2] == b[2] && a[3] == b[3] && (a[1] & 0xFFFF0000u) == (b[1] & 0xFFFF0000u) && !std::memcmp(a + 4, b + 4, 16); copy_differs_unrebased += !rebased; } const bool is_zero = probe_zero(bytes); const std::uint64_t h = is_zero ? 0 : probe_hash(bytes); if (p->seen[i] != h && p->censuses > 1 && h != p->api[i]) ++changed_no_api; p->seen[i] = h; if (is_zero) { ++zero; continue; } if (p->api[i] == h) { ++api; continue; } ++(p->api[i] ? title_over : title_new); char text[512]; const int kind = probe_kind(bytes, text, sizeof(text)); ++kinds[kind]; if (p->census_dumps < 40 && kind != 7 && kind != 0) { ++p->census_dumps; std::fprintf(stderr, "[rt] desc-probe: census %llu slot %zu %s-written: %s\n", static_cast(p->censuses), i, p->api[i] ? "API-then-title" : "title", text); } } std::fprintf(stderr, "[rt] desc-probe: census %llu at submission %llu, heap 0x%llx (%zu slots, %llu API writes so " "far): zero %llu, as our API wrote them %llu, title-written %llu (never API %llu, over an API " "write %llu), changed since the last census with no API write %llu; title kinds: %s %llu, %s " "%llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu; arena copy differs %llu (not a rebased V# " "%llu)\n", static_cast(p->censuses), static_cast(n), static_cast(p->console_va), p->slots, static_cast(p->api_writes), static_cast(zero), static_cast(api), static_cast(title_new + title_over), static_cast(title_new), static_cast(title_over), static_cast(changed_no_api), kProbeKinds[0], static_cast(kinds[0]), kProbeKinds[1], static_cast(kinds[1]), kProbeKinds[2], static_cast(kinds[2]), kProbeKinds[3], static_cast(kinds[3]), kProbeKinds[4], static_cast(kinds[4]), kProbeKinds[5], static_cast(kinds[5]), kProbeKinds[6], static_cast(kinds[6]), kProbeKinds[7], static_cast(kinds[7]), static_cast(copy_differs), static_cast(copy_differs_unrebased)); std::fprintf(stderr, "[rt] desc-probe: bound tables since the last census: %llu tables, %llu slots: zero %llu, API " "%llu, title-written %llu (%s %llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu, %s %llu)\n", static_cast(p->tables), static_cast(p->t_slots), static_cast(p->t_zero), static_cast(p->t_api), static_cast(p->t_title), kProbeKinds[0], static_cast(p->t_kind[0]), kProbeKinds[1], static_cast(p->t_kind[1]), kProbeKinds[2], static_cast(p->t_kind[2]), kProbeKinds[3], static_cast(p->t_kind[3]), kProbeKinds[4], static_cast(p->t_kind[4]), kProbeKinds[5], static_cast(p->t_kind[5]), kProbeKinds[6], static_cast(p->t_kind[6]), kProbeKinds[7], static_cast(p->t_kind[7])); for (unsigned r = 0; r < std::min(p->recent_count, 8u); ++r) { char text[512] = ""; const std::size_t slot = p->recent[r]; probe_kind(reinterpret_cast( static_cast(p->console_va + slot * kDescriptorSize)), text, sizeof(text)); std::fprintf(stderr, "[rt] desc-probe: census %llu: recently bound slot %zu now: %s\n", static_cast(p->censuses), slot, text); } p->tables = p->t_slots = p->t_zero = p->t_api = p->t_title = 0; for (auto& k : p->t_kind) k = 0; } } // The translator's output, loaded on first use. std::mutex library_mutex; bool library_tried = false; leonida::ShaderLibrary shader_library; leonida::GraphicsShaderModules graphics_modules; rt::d3d12_xs::NativeGraphicsPipelines native_graphics; const leonida::ShaderLibrary* library() { std::lock_guard lock(library_mutex); if (!library_tried) { library_tried = true; // Nothing may leave here into Create*PipelineState: a path the STL cannot convert throws std::system_error // under MSVC, which is not a filesystem_error, so every std::exception gives the message. try { std::string error; const std::filesystem::path dir = info.shader_dir.empty() ? configured_shader_directory(&error) : std::filesystem::path(info.shader_dir); if (!error.empty()) std::fprintf(stderr, "[rt] d3d12: invalid translated shader path: %s\n", error.c_str()); else if (dir.empty()) std::fprintf(stderr, "[rt] d3d12: no translated shaders: set LEONIDA_SHADERS to /shaders/spirv\n"); else if (!shader_library.load(dir, &error)) std::fprintf(stderr, "[rt] d3d12: %s\n", error.c_str()); else { writes_buffer_meta_complete.store(shader_library.all_have_writes_buffer_meta(), std::memory_order_release); const auto path = shader_library.directory().u8string(); // fspx counts library/ too (shader_library.h, load()). std::fprintf(stderr, "[rt] d3d12: %zu translated shaders (%zu fspx, %zu fspx_compute, " "%zu fspx_gfx, %zu bvh, %zu exe) from %s\n", shader_library.size(), shader_library.fspx_size(), shader_library.fspx_compute_size(), shader_library.fspx_gfx_size(), shader_library.bvh_size(), shader_library.exe_size(), reinterpret_cast(path.c_str())); } } catch (const std::exception& e) { std::fprintf(stderr, "[rt] d3d12: invalid translated shader path: %s\n", e.what()); } } return shader_library.loaded() ? &shader_library : nullptr; } VkFormat depth_backing(VkFormat logical) const { if(logical!=VK_FORMAT_D16_UNORM_S8_UINT)return logical; for(const auto candidate : {VK_FORMAT_D16_UNORM_S8_UINT,VK_FORMAT_D32_SFLOAT_S8_UINT,VK_FORMAT_D24_UNORM_S8_UINT}) if(depth_usable(candidate))return candidate; return VK_FORMAT_UNDEFINED; } bool depth_usable(VkFormat format) const { VkFormatProperties properties{}; format_properties(info.physical, format, &properties); return properties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT; } bool color_attachment_usable(VkFormat format) const { VkFormatProperties properties{}; format_properties(info.physical, format, &properties); return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0; } bool storage_usable(VkFormat format) const { VkFormatProperties properties{}; format_properties(info.physical, format, &properties); return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) != 0; } bool sampled_usable(VkFormat format) const { VkFormatProperties properties{}; format_properties(info.physical, format, &properties); return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0; } // Whether the GPU needs and supports backing UAV textures of `logical` (no storage support) with a mutable image of // the unsigned format `backing` of the same size. bool probe_uint_backed_uav(VkFormat logical, VkFormat backing) const { if (storage_usable(logical)) return false; if (!image_format_properties2 || !storage_usable(backing) || !sampled_usable(logical)) return false; const VkFormat view_formats[2] = {backing, logical}; VkImageFormatListCreateInfo list{VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO}; list.viewFormatCount = 2; list.pViewFormats = view_formats; VkPhysicalDeviceImageFormatInfo2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2, &list}; query.format = backing; query.type = VK_IMAGE_TYPE_2D; query.tiling = VK_IMAGE_TILING_OPTIMAL; query.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; query.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT; VkImageFormatProperties2 props{VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2}; return image_format_properties2(info.physical, &query, &props) == VK_SUCCESS; } // The limits apply to this exact combination of format, type, tiling, usage, create flags and pNext format list. HRESULT check_image_support(const VkImageCreateInfo& create) const { VkImageFormatProperties limits{}; VkResult result = VK_ERROR_FORMAT_NOT_SUPPORTED; if (image_format_properties2) { VkPhysicalDeviceImageFormatInfo2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2}; query.pNext = create.pNext; query.format = create.format; query.type = create.imageType; query.tiling = create.tiling; query.usage = create.usage; query.flags = create.flags; VkImageFormatProperties2 props{VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2}; result = image_format_properties2(info.physical, &query, &props); limits = props.imageFormatProperties; } else { result = image_format_properties(info.physical, create.format, create.imageType, create.tiling, create.usage, create.flags, &limits); } if (result == VK_ERROR_FORMAT_NOT_SUPPORTED) return E_INVALIDARG; if (result == VK_ERROR_OUT_OF_HOST_MEMORY || result == VK_ERROR_OUT_OF_DEVICE_MEMORY) return E_OUTOFMEMORY; if (result != VK_SUCCESS) return E_FAIL; if (create.extent.width > limits.maxExtent.width || create.extent.height > limits.maxExtent.height || create.extent.depth > limits.maxExtent.depth || create.mipLevels > limits.maxMipLevels || create.arrayLayers > limits.maxArrayLayers || !(limits.sampleCounts & create.samples)) return E_INVALIDARG; return S_OK; } VkFormatFeatureFlags2 optimal_features(VkFormat format) const { if (!format_properties2) return 0; VkFormatProperties3 features{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; VkFormatProperties2 properties{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &features}; format_properties2(info.physical, format, &properties); return features.optimalTilingFeatures; } // D3D12_OPTIONS1's wave facts, from the physical device: which subgroup operations exist and what wave sizes it // can run. Zeros and false when the device cannot be asked, which the query then reports as unsupported. // Read once: std::call_once makes a concurrent first caller wait until the facts are complete. const SubgroupFacts& subgroup_facts() { std::call_once(subgroups_once, [this] { read_subgroup_facts(); }); return subgroups; } void read_subgroup_facts() { const auto properties2 = reinterpret_cast( info.get_instance_proc ? info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2") : nullptr); if (!properties2 || !info.physical) return; VkPhysicalDeviceSubgroupSizeControlProperties size_control{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES}; VkPhysicalDeviceSubgroupProperties subgroup{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES, &size_control}; VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &subgroup}; properties2(info.physical, &properties); // Every group the wave intrinsics map to, because D3D12 promises them all behind the one bool. constexpr VkSubgroupFeatureFlags kD3D12WaveOps = VK_SUBGROUP_FEATURE_BASIC_BIT | VK_SUBGROUP_FEATURE_VOTE_BIT | VK_SUBGROUP_FEATURE_BALLOT_BIT | VK_SUBGROUP_FEATURE_SHUFFLE_BIT | VK_SUBGROUP_FEATURE_ARITHMETIC_BIT; subgroups.wave_ops = (subgroup.supportedOperations & kD3D12WaveOps) == kD3D12WaveOps; subgroups.lane_min = size_control.minSubgroupSize ? size_control.minSubgroupSize : subgroup.subgroupSize; subgroups.lane_max = size_control.maxSubgroupSize ? size_control.maxSubgroupSize : subgroups.lane_min; if (subgroups.lane_max < subgroups.lane_min) subgroups.lane_max = subgroups.lane_min; // D3D-121: Intel's D3D12 driver answers a fixed 16..16 on its older integrated GPUs, where Vulkan reports // the compiler's whole 8..32 choice. Measured on Xe-LP: UHD 770 (32.0.101.6129), Raptor Lake-S Mobile // (101.7092) and Tiger Lake 0x9a78 (101.7088). Discrete Arc is not measured yet (TEST-57), so it keeps the // Vulkan range. D3D-280: from Xe-LPG on the driver answers what Vulkan reports (Meteor Lake 0x7d55, // 32.0.101.6127: 8..32 on both sides), so there is no fixed answer to mirror and those lines keep the // Vulkan range too. constexpr uint32_t kIntelVendorId = 0x8086; constexpr UINT kIntelD3D12Lanes = 16; const uint32_t intel_device_id = properties.properties.deviceID; // The Xe-core integrated lines from Xe-LPG on. Device IDs are not generation-ordered (Tiger Lake's 0x9a78 // sorts above Meteor Lake's), so the ranges are listed out, not compared as a cutoff. const bool intel_xe_lpg_or_later = (intel_device_id >= 0x7d40 && intel_device_id <= 0x7dc5) || // Meteor Lake, Arrow Lake (intel_device_id >= 0x64a0 && intel_device_id <= 0x64b6); // Lunar Lake if (properties.properties.vendorID == kIntelVendorId && properties.properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU && !intel_xe_lpg_or_later && subgroups.lane_min <= kIntelD3D12Lanes && kIntelD3D12Lanes <= subgroups.lane_max) subgroups.lane_min = subgroups.lane_max = kIntelD3D12Lanes; } // The device's mesh-shader limits (output vertices and primitives, workgroup size), for mesh PSO creation. const VkPhysicalDeviceMeshShaderPropertiesEXT& mesh_limits() { std::lock_guard lock(mesh_properties_mutex); if (mesh_properties_read) return mesh_properties; mesh_properties_read = true; const auto properties2 = reinterpret_cast( info.get_instance_proc ? info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2") : nullptr); if (!properties2 || !info.physical || !info.mesh_shader) return mesh_properties; VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &mesh_properties}; properties2(info.physical, &properties); mesh_properties.pNext = nullptr; return mesh_properties; } // Integer sampled images need not support multisampling. Pick a supported count for the // zero image in the corresponding set-0 bindings; one means that class is unavailable. VkSampleCountFlagBits ms_fallback_samples(VkFormat format) const { VkImageFormatProperties props{}; constexpr VkImageUsageFlags usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; if (image_format_properties(info.physical, format, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usage, 0, &props) == VK_SUCCESS) { for (UINT count = D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT; count > 1; count >>= 1) if (props.sampleCounts & count) return VkSampleCountFlagBits(count); } return VK_SAMPLE_COUNT_1_BIT; } // The format a texture description is created with, D24S8 and R9G9B9E5 UAV fallbacks included. Format texture_format(const D3D12_RESOURCE_DESC& desc) const { if (!xr_bias_compatible(desc)) return {}; if (desc.Format == DXGI_FORMAT_A8_UNORM) { // Sampled A8: an R8 image read through the alpha swizzle, in 1D, 2D or 3D as the host runtime makes // them (d3d12_a8_dimensions_test); A8 render targets stay 2D. if ((desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) || ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) || desc.SampleDesc.Count != 1 || (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) return {}; if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) { if (!info.a8_render_target) { log_once("A8_UNORM render targets need VK_FORMAT_A8_UNORM_KHR (VK_KHR_maintenance5); format", desc.Format); return {}; } Format alpha{kA8UnormFormat, VK_IMAGE_ASPECT_COLOR_BIT}; alpha.a8_as_alpha = true; return alpha; } } if (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) { if ((desc.SampleDesc.Count != 1 && (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) || (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE))) return {}; if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && r9g9b9e5_target_stand_in) { log_once("R9G9B9E5_SHAREDEXP render target unavailable natively, using B10G11R11_UFLOAT; format", desc.Format); return Format{VK_FORMAT_B10G11R11_UFLOAT_PACK32, VK_IMAGE_ASPECT_COLOR_BIT}; } if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && (!color_attachment_usable(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32) || ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !storage_usable(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32)))) return {}; if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && r9g9b9e5_uav_emulated) { log_once("R9G9B9E5_SHAREDEXP UAV unavailable natively, using mutable R32_UINT; format", desc.Format); Format backed{VK_FORMAT_R32_UINT, VK_IMAGE_ASPECT_COLOR_BIT}; backed.uint_backed = VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; return backed; } } if (rgb96_refused(desc)) { if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) log_once("96-bit (R32G32B32) render targets not supported; format", desc.Format); return {}; } // The host runtime refuses typed B8G8R8X8 with unordered access (its typeless family is accepted): the // BGRA8 image could take storage writes, but D3D12 has no typed UAV for these formats. if (alpha_unused(desc.Format) && desc.Format != DXGI_FORMAT_B8G8R8X8_TYPELESS && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { log_once("B8G8R8X8 textures cannot allow unordered access; format", desc.Format); return {}; } // A B5G5R5A1 UAV texture where VK_FORMAT_A1R5G5B5_UNORM_PACK16 has no storage support: a mutable R16_UINT image // (Format::uint_backed). Its RTVs and SRVs view it as A1R5G5B5; shaders store the packed 16 bits. if (desc.Format == DXGI_FORMAT_B5G5R5A1_UNORM && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !storage_usable(VK_FORMAT_A1R5G5B5_UNORM_PACK16)) { if (!b5g5r5a1_uav_emulated || desc.SampleDesc.Count > 1 || ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && !color_attachment_usable(VK_FORMAT_A1R5G5B5_UNORM_PACK16))) return {}; log_once("B5G5R5A1_UNORM UAV unavailable natively, using mutable R16_UINT; format", desc.Format); Format backed{VK_FORMAT_R16_UINT, VK_IMAGE_ASPECT_COLOR_BIT}; backed.uint_backed = VK_FORMAT_A1R5G5B5_UNORM_PACK16; return backed; } // A B4G4R4A4 render target where no 4444 format is a colour attachment (NVIDIA has none, sampled only): an // RGBA8 image, which holds every 4-bit value exactly. RTVs and PSOs follow the image's format; the 4_4_4_4 T#s // read it with the 4444 view's channels (bind_image). Not covered: a copy between it and a buffer footprint // moves 4-byte RGBA8 texels, not packed 16-bit ones (replay's footprint bounds checks still hold). if (desc.Format == DXGI_FORMAT_B4G4R4A4_UNORM && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && !color_attachment_usable(VK_FORMAT_A4R4G4B4_UNORM_PACK16) && color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM)) { log_once("B4G4R4A4_UNORM render targets unavailable natively, using RGBA8; format", desc.Format); Format backed{VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT}; backed.rgba4_render_fallback = true; // clears are quantised to 4 bits a channel, as its draws are return backed; } // An 8-bit sRGB UAV texture where the sRGB format has no storage support: the host runtime makes it (RTX 4090 // and WARP; a retail title sizes a 2048x2048 R8G8B8A8_UNORM_SRGB render target with unordered access), but no // typed UAV is sRGB in D3D12, so shaders write the raw bytes. A mutable image of the UNORM format of the same // channel order (Format::uint_backed): its storage view is UNORM, its SRVs and RTVs are sRGB, so sampling // decodes and rendering encodes as on the host. if ((desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB) && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { const bool rgba = desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; const VkFormat srgb = rgba ? VK_FORMAT_R8G8B8A8_SRGB : VK_FORMAT_B8G8R8A8_SRGB; if (!storage_usable(srgb)) { if (!(rgba ? rgba8_srgb_uav_emulated : bgra8_srgb_uav_emulated) || desc.SampleDesc.Count > 1 || ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && !color_attachment_usable(srgb))) return {}; log_once("8-bit sRGB UAV unavailable natively, using a mutable UNORM image; format", desc.Format); Format backed{rgba ? VK_FORMAT_R8G8B8A8_UNORM : VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT}; backed.uint_backed = srgb; return backed; } } Format format = texture_storage_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) return {}; if(desc.Format==DXGI_FORMAT_B4G4R4A4_UNORM && (desc.Flags&D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && !color_attachment_usable(format.format)) { if(!color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM))return {}; format.format=VK_FORMAT_R8G8B8A8_UNORM;format.rgba4_render_fallback=true; return format; } if(format.format==VK_FORMAT_D16_UNORM_S8_UINT) { format.xbox_depth16_stencil8=true;format.format=depth_backing(format.format); return format; } format.d24 = format.format == VK_FORMAT_D24_UNORM_S8_UINT; // native or not: clears are quantised if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !depth_usable(format.format)) { log_once("D24_UNORM_S8_UINT unavailable, using D32_SFLOAT_S8_UINT; format", desc.Format); format.format = VK_FORMAT_D32_SFLOAT_S8_UINT; format.d24_as_float = true; } return format; } // The memory an image made from `create` needs, or false if the device can't make that image. bool memory_requirements(const VkImageCreateInfo& create, VkMemoryRequirements& out) const { if (FAILED(check_image_support(create))) return false; if (image_requirements) { VkDeviceImageMemoryRequirements query{VK_STRUCTURE_TYPE_DEVICE_IMAGE_MEMORY_REQUIREMENTS}; query.pCreateInfo = &create; VkMemoryRequirements2 result{VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; image_requirements(info.device, &query, &result); out = result.memoryRequirements; return true; } auto& vk = context->vk; // without the query, a throwaway image VkImage image = VK_NULL_HANDLE; VkImageCreateInfo shared = create; share(shared); if (vk.vkCreateImage(info.device, &shared, nullptr, &image) != VK_SUCCESS) return false; vk.vkGetImageMemoryRequirements(info.device, image, &out); vk.vkDestroyImage(info.device, image, nullptr); return true; } // Set 0 of the translated shaders (vulkan_bindless.h, docs section 3.4) and what has been put in it. A shader // finds a T# or S# by its bytes (the descriptor hash table), so one entry serves every heap slot that holds // those bytes: a copied descriptor needs nothing more. An image's entries live until its texture is // destroyed, samplers until the device is. struct ImageEntry { leonida::ImageDimension dimension; std::uint32_t index; VkImageView sampled; VkImageView storage; // the same range without a component mapping, for the storage bindings; or null std::uint64_t address; // A 2D view of the first layer in the 2D arrays (a 2D-array image's slice 0, BindlessSet::MirrorViews); or null VkImageView mirror_sampled = VK_NULL_HANDLE; VkImageView mirror_storage = VK_NULL_HANDLE; // 2D R64_UINT storage alias for 64-bit image atomics (binding 29); null unless distinct from storage/mirror_storage. VkImageView storage_r64ui = VK_NULL_HANDLE; VkImageView mirror_storage_r64ui = VK_NULL_HANDLE; }; std::unique_ptr bindless; // True when the loaded library's modules read the table's kind word (create_bindless, descriptor_table.h): the // image inserts then record which arrays each index is bound in. bool descriptor_table_tagged = false; // True when the loaded library's modules read a T#'s bindless index from its dword 6 (create_bindless, // gfx10_descriptors.h tsharp_index_word): every T# the layer writes into a heap shaders read then carries it, in // the console heaps' copies (fix_console_slot) and in its own heaps (write_image_descriptor, scan_title_table). bool tsharp_index_words = false; std::mutex descriptor_mutex; // the set and the containers below // vkDeviceWaitIdle calls made for the bindless set (none, unless LEONIDA_BINDLESS_IDLE_WAIT restores the old wait). std::atomic bindless_idle_waits{0}; bool bindless_legacy_idle = false; std::atomic bindless_cap_logged{false}; std::size_t bindless_logged_table_bytes = 0; // descriptor_mutex: the table size last logged bool bindless_host_logged = false; // descriptor_mutex struct DescriptorKeyHash { std::size_t operator()(const leonida::DescriptorKey& k) const noexcept { std::uint64_t h = 14695981039346656037ull; for (const std::uint32_t x : k) h = (h ^ x) * 1099511628211ull; return static_cast(h); } }; // Deduplication key for Vulkan image views + bindless slots across distinct T# keys whose post-pending_image_keys // Vulkan view state is identical (differing only in non-semantic T# metadata, CPU/GPU alias addresses, or shared // zero_sampled_image for pending streams). struct ViewKey { VkImage vk_image = VK_NULL_HANDLE; leonida::ImageDimension dimension = leonida::ImageDimension::dim_2d; VkImageViewType view_type = VK_IMAGE_VIEW_TYPE_2D; VkFormat view_format = VK_FORMAT_UNDEFINED; VkFormat storage_format = VK_FORMAT_UNDEFINED; std::uint32_t sampled_class = 0; VkComponentSwizzle swizzle_r = VK_COMPONENT_SWIZZLE_IDENTITY; VkComponentSwizzle swizzle_g = VK_COMPONENT_SWIZZLE_IDENTITY; VkComponentSwizzle swizzle_b = VK_COMPONENT_SWIZZLE_IDENTITY; VkComponentSwizzle swizzle_a = VK_COMPONENT_SWIZZLE_IDENTITY; VkImageAspectFlags aspect_mask = 0; std::uint32_t base_mip = 0; std::uint32_t mip_count = 0; std::uint32_t base_layer = 0; std::uint32_t layer_count = 0; std::uint32_t min_lod_bits = 0; std::uint32_t slice_first = 0; std::uint32_t slice_count = 0; std::uint32_t mirror_layer = 0; std::uint64_t api_owner_address = 0; // distinguishes D3D12 API views on shared deferred/placeholder images bool sampled_only = false; bool sampled = false; bool storage = false; bool has_min_lod = false; bool operator==(const ViewKey&) const = default; }; struct ViewKeyHash { std::size_t operator()(const ViewKey& k) const noexcept { auto mix = [](std::uint64_t h, std::uint64_t v) noexcept { h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2); return h; }; std::uint64_t h = static_cast(std::hash{}(k.vk_image)); h = mix(h, k.api_owner_address); h = mix(h, (std::uint64_t(k.dimension) << 32) | std::uint64_t(k.view_type)); h = mix(h, (std::uint64_t(k.view_format) << 32) | std::uint64_t(k.storage_format)); h = mix(h, (std::uint64_t(k.sampled_class) << 32) | std::uint64_t(k.aspect_mask)); h = mix(h, (std::uint64_t(k.swizzle_r) << 48) | (std::uint64_t(k.swizzle_g) << 32) | (std::uint64_t(k.swizzle_b) << 16) | std::uint64_t(k.swizzle_a)); h = mix(h, (std::uint64_t(k.base_mip) << 32) | std::uint64_t(k.mip_count)); h = mix(h, (std::uint64_t(k.base_layer) << 32) | std::uint64_t(k.layer_count)); h = mix(h, (std::uint64_t(k.min_lod_bits) << 32) | std::uint64_t(k.mirror_layer)); h = mix(h, (std::uint64_t(k.slice_first) << 32) | std::uint64_t(k.slice_count)); const std::uint64_t flags = (k.sampled_only ? 1ull : 0ull) | (k.sampled ? 2ull : 0ull) | (k.storage ? 4ull : 0ull) | (k.has_min_lod ? 8ull : 0ull); h = mix(h, flags); return static_cast(h); } }; struct SharedViewEntry { ImageEntry entry{}; std::uint32_t refcount = 0; std::uint32_t api_refcount = 0; // pinned keys (API / known_heap / UAV / MS); never GC-evicted std::uint64_t last_seen_gen = 0; std::uint64_t last_touch_ticket = 0; // submitted_retire_ticket() + 1 when last created or hit bool pinned_by_upgrade = false; // kept in replaced_images when refcount hits 0 until texture goes std::uint64_t pinned_address = 0; bool is_zero_view = false; // shared pending_image_keys->zero fallback view std::vector keys; }; struct ImageKeyEntry : ImageEntry { ViewKey view_key{}; std::size_t sv_key_pos = 0; bool from_title_heap = false; // true when evictable (bind_title_image or eligible !known_heap console view) bool in_known_heap = false; // true when written into a layer-owned visible_heaps / cpu_view_heaps slot std::uint64_t last_seen_gen = 0; }; std::unordered_map image_entries; std::unordered_map shared_views; bool binding_from_title_heap = false; // descriptor_mutex: true while inside bind_title_image() std::uint64_t tsharp_use_gen = 0; // descriptor_mutex: monotonic LRU touch counter std::size_t title_heap_image_keys = 0; // descriptor_mutex: count of image_entries with from_title_heap == true std::atomic console_heap_count{0}; // live console resource heaps (add/remove_console_heap) // Pure leaf mutex tracking live kTexture kSettled addresses across console resource heaps (NEVER takes another lock). std::mutex live_console_textures_mutex; std::unordered_map live_console_textures; static void on_console_texture_live(void* user, std::uint64_t addr, bool bound) { auto* self = static_cast(user); std::lock_guard lock(self->live_console_textures_mutex); if (bound) { ++self->live_console_textures[addr]; } else { const auto it = self->live_console_textures.find(addr); if (it != self->live_console_textures.end()) { if (it->second <= 1) self->live_console_textures.erase(it); else --it->second; } } } // Declared after live_console_textures[_mutex] so ~DeviceState() detaches callbacks before destroying them, // even if a ConsoleHeap remains in console_heaps (declared earlier in DeviceState). struct LiveConsoleTexturesDetach { DeviceState* owner = nullptr; ~LiveConsoleTexturesDetach() { if (!owner) return; for (auto& h : owner->console_heaps) if (h) h->records.set_texture_live_callback(nullptr, nullptr); } } live_console_textures_detach{this}; std::array evictable_views_in_dim{}; // descriptor_mutex: SharedViewEntrys with is_evictable_sv std::array gc_last_submit_ticket{}; // descriptor_mutex std::array gc_last_attempt_ns{}; // descriptor_mutex std::array gc_cooldown_ns{}; // descriptor_mutex std::vector> gc_candidates_scratch; // descriptor_mutex std::vector gc_winners_scratch; // descriptor_mutex std::vector gc_touched_addrs_scratch; // descriptor_mutex std::vector gc_live_addrs_scratch; // descriptor_mutex std::uint64_t gc_runs = 0, gc_evicted_slots = 0, gc_evicted_keys = 0; // descriptor_mutex // 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 PendingImageKey { leonida::gfx10::Image image{}; bool evictable = false; bool in_known_heap = false; }; struct PendingImage { VkImage zero = VK_NULL_HANDLE; std::uint32_t first_mip = UINT32_MAX; std::map keys; }; std::unordered_map pending_image_keys; using ZeroShape = std::tuple; std::mutex zero_image_mutex; std::map zero_images; std::atomic zero_image_bytes{0}; VkImage zero_sampled_image(const D3D12_RESOURCE_DESC&, const Format&, VkDeviceSize); std::multimap image_keys; // by the texture's address std::vector replaced_images; // kept until their texture goes: work in flight may still use them struct SamplerEntry { VkSampler sampler = VK_NULL_HANDLE; std::uint32_t index = 0; }; std::map sampler_entries; struct CustomBorderColor { bool is_int = false; VkClearColorValue value{}; bool operator==(const CustomBorderColor& o) const { return is_int == o.is_int && std::memcmp(&value, &o.value, sizeof(value)) == 0; } }; std::vector border_color_table; std::uint32_t register_border_color(bool is_int, const void* components) { std::lock_guard lock(descriptor_mutex); CustomBorderColor entry{}; entry.is_int = is_int; std::memcpy(&entry.value, components, sizeof(entry.value)); for (std::size_t i = 0; i < border_color_table.size(); ++i) { if (border_color_table[i] == entry) return std::uint32_t(i); } if (border_color_table.size() >= 4000) { log_once("custom sampler border colour table is full (4000 entries); clamping index", int(border_color_table.size())); return 3999; } const std::uint32_t idx = std::uint32_t(border_color_table.size()); border_color_table.push_back(entry); return idx; } // A T# names a texture by an address of its own: above 4 GiB, which the GPU address arena for buffers (docs // section 3.3) stays below, and 256 bytes apart (the T# keeps addresses in 256-byte units). Nothing // dereferences it. std::atomic next_image_address{std::uint64_t(1) << 32}; // 0 float, 1 unsigned integer, 2 signed integer: which of the three storage-image arrays a view belongs in. static int numeric_class(VkFormat format) { switch (format) { case VK_FORMAT_R8_UINT: case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_R16_UINT: case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16G16B16A16_UINT: case VK_FORMAT_R32_UINT: case VK_FORMAT_R32G32_UINT: case VK_FORMAT_R32G32B32A32_UINT: case VK_FORMAT_A2B10G10R10_UINT_PACK32: return 1; case VK_FORMAT_R8_SINT: case VK_FORMAT_R8G8_SINT: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_R16_SINT: case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R32_SINT: case VK_FORMAT_R32G32_SINT: case VK_FORMAT_R32G32B32A32_SINT: return 2; default: return 0; } } void release(const ImageEntry& entry) { // descriptor_mutex held const std::uint64_t slot_handle = (static_cast(entry.dimension) << 32) | static_cast(entry.index); context->defer_destroy(leonida::DeferredDeletionQueue::Kind::bindless_slot, slot_handle); if (entry.sampled) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.sampled); if (entry.storage) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.storage); if (entry.mirror_sampled) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.mirror_sampled); if (entry.mirror_storage) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.mirror_storage); if (entry.storage_r64ui) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.storage_r64ui); if (entry.mirror_storage_r64ui) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.mirror_storage_r64ui); } static bool is_evictable_sv(const SharedViewEntry& sv) noexcept { return sv.api_refcount == 0 && !sv.pinned_by_upgrade && !sv.is_zero_view; } void adjust_evictable_sv_locked(leonida::ImageDimension dim, bool was, bool now) noexcept { if (was == now) return; const std::uint32_t d = std::uint32_t(dim); if (d >= evictable_views_in_dim.size()) return; if (now) ++evictable_views_in_dim[d]; else if (evictable_views_in_dim[d] > 0) --evictable_views_in_dim[d]; } // Detaches one T# key from its refcounted SharedViewEntry (descriptor_mutex held). Releases the VkImageViews and // bindless slot ONLY when refcount drops to 0; if the SharedViewEntry was replaced by a storage upgrade, moves it // to replaced_images instead so already-recorded command lists keep valid descriptors until the texture goes. void detach_view_key_locked(const ViewKey& vk_key, std::size_t key_pos, bool was_from_title_heap, bool upgrading, std::uint64_t upgrade_address) { const auto sv_it = shared_views.find(vk_key); if (sv_it == shared_views.end()) return; SharedViewEntry& sv = sv_it->second; const bool was_evictable = is_evictable_sv(sv); if (key_pos < sv.keys.size()) { const leonida::DescriptorKey back_key = sv.keys.back(); sv.keys[key_pos] = back_key; sv.keys.pop_back(); if (key_pos < sv.keys.size()) { if (const auto moved = image_entries.find(back_key); moved != image_entries.end()) moved->second.sv_key_pos = key_pos; } } if (upgrading && !sv.pinned_by_upgrade) { sv.pinned_by_upgrade = true; sv.pinned_address = upgrade_address; } if (!was_from_title_heap && sv.api_refcount > 0) --sv.api_refcount; if (sv.refcount > 0) --sv.refcount; if (sv.refcount == 0) { adjust_evictable_sv_locked(sv.entry.dimension, was_evictable, false); if (sv.pinned_by_upgrade && images_by_address.count(sv.pinned_address)) { ImageEntry kept = sv.entry; kept.address = sv.pinned_address; replaced_images.push_back(kept); } else { release(sv.entry); } shared_views.erase(sv_it); } else { adjust_evictable_sv_locked(sv.entry.dimension, was_evictable, is_evictable_sv(sv)); } } // Diagnostic breakdown of dim-2D live slots, shared ViewKeys, and evictable vs pinned keys (descriptor_mutex held). std::string bindless_diag_summary_locked() const { if (!bindless) return {}; const std::uint32_t cap_2d = bindless->image_capacity(leonida::ImageDimension::dim_2d); const std::uint32_t free_2d = bindless->free_images(leonida::ImageDimension::dim_2d); const std::uint32_t live_2d = cap_2d > 1 + free_2d ? cap_2d - 1 - free_2d : 0; const std::size_t api_keys = image_entries.size() >= title_heap_image_keys ? image_entries.size() - title_heap_image_keys : 0; return std::to_string(live_2d) + "/" + std::to_string(cap_2d > 0 ? cap_2d - 1 : 0) + " dim2D live, " + std::to_string(shared_views.size()) + " ViewKeys (" + std::to_string(evictable_views_in_dim[0]) + " dim2D evictable; " + std::to_string(title_heap_image_keys) + " evictable, " + std::to_string(api_keys) + " pinned keys)"; } // Two-phase zero-churn pressure-triggered bindless GC (descriptor_mutex held): // Phase 1 (Dead-Key Sweep): evicts retired evictable SharedViewEntrys whose texture address is NOT live in any // console heap's ConsoleHeapSlotRecords (emits ZERO SlotChange::texture_gone -> zero filter/shadows churn). // Phase 2 (Emergency Live-LRU): ONLY when hard_full and Phase 1 found 0 (or heap_gpu active): evicts oldest // retired evictable entries, emitting texture_gone so live console heap slots re-bind cleanly on demand. void gc_bindless_title_views_locked(leonida::ImageDimension dimension, bool need_storage, std::uint32_t sampled_class, const ViewKey* skip_view_key = nullptr) { const std::uint32_t d = std::uint32_t(dimension); if (!bindless || d >= evictable_views_in_dim.size() || evictable_views_in_dim[d] == 0) return; const bool hard_full = !bindless->has_free_image(dimension, need_storage, sampled_class); constexpr std::uint64_t kNormalCooldownNs = 250ull * 1000000ull; constexpr std::uint64_t kBackoffCooldownNs = 1000ull * 1000000ull; const std::uint64_t now_ns = static_cast( std::chrono::duration_cast( std::chrono::steady_clock::now().time_since_epoch()) .count()); if (!hard_full && gc_last_attempt_ns[d] != 0) { const std::uint64_t cooldown = gc_cooldown_ns[d] ? gc_cooldown_ns[d] : kNormalCooldownNs; if (now_ns >= gc_last_attempt_ns[d] && (now_ns - gc_last_attempt_ns[d]) < cooldown) return; } const std::uint64_t submitted = context ? context->submitted_retire_ticket() : 0; const std::uint64_t wait_ticket = gc_last_submit_ticket[d]; // NEVER bypass wait_ticket even on hard_full: slots on DeferredDeletionQueue cannot return before retirement. if (wait_ticket != 0 && submitted < wait_ticket) return; const std::uint64_t completed = context ? context->completed_retire_ticket() : 0; if (wait_ticket != 0 && completed < wait_ticket) return; const std::uint32_t storage_cap = bindless->storage_capacity(dimension); const bool use_live_tracking = !(heap_gpu && console_heap_gpu_enabled()); bool phase2_live_lru = false; gc_candidates_scratch.clear(); if (use_live_tracking) { // Snapshot live console-heap texture addresses under the pure leaf mutex (no nested locks). gc_live_addrs_scratch.clear(); { std::lock_guard live_lock(live_console_textures_mutex); gc_live_addrs_scratch.reserve(live_console_textures.size()); for (const auto& [live_addr, cnt] : live_console_textures) if (cnt > 0) gc_live_addrs_scratch.push_back(live_addr); } std::sort(gc_live_addrs_scratch.begin(), gc_live_addrs_scratch.end()); const auto addr_is_live = [&](std::uint64_t addr) -> bool { if (gc_live_addrs_scratch.empty()) return false; if (std::binary_search(gc_live_addrs_scratch.begin(), gc_live_addrs_scratch.end(), addr)) return true; if (const std::uint64_t key = tsharp_texture_key(addr); key != addr && std::binary_search(gc_live_addrs_scratch.begin(), gc_live_addrs_scratch.end(), key)) return true; if (const std::uint64_t other = leonida::title_gpu_views::other_view(addr); other && std::binary_search(gc_live_addrs_scratch.begin(), gc_live_addrs_scratch.end(), other)) return true; return false; }; const auto sv_is_live = [&](const SharedViewEntry& sv) -> bool { if (gc_live_addrs_scratch.empty()) return false; if (addr_is_live(sv.entry.address)) return true; for (const auto& k : sv.keys) { if (const auto e_it = image_entries.find(k); e_it != image_entries.end()) { if (e_it->second.address != sv.entry.address && addr_is_live(e_it->second.address)) return true; } } return false; }; for (const auto& [vk_key, sv] : shared_views) { if (sv.entry.dimension != dimension) continue; if (!is_evictable_sv(sv)) continue; if (sv.last_touch_ticket > completed) continue; if (skip_view_key && vk_key == *skip_view_key) continue; if (need_storage && sv.entry.index >= storage_cap) continue; if (sv_is_live(sv)) continue; gc_candidates_scratch.emplace_back(&vk_key, sv.last_seen_gen); } } if (gc_candidates_scratch.empty() && hard_full) { phase2_live_lru = true; for (const auto& [vk_key, sv] : shared_views) { if (sv.entry.dimension != dimension) continue; if (!is_evictable_sv(sv)) continue; if (sv.last_touch_ticket > completed) continue; if (skip_view_key && vk_key == *skip_view_key) continue; if (need_storage && sv.entry.index >= storage_cap) continue; gc_candidates_scratch.emplace_back(&vk_key, sv.last_seen_gen); } } // ALWAYS stamp ticket + wall-clock cooldown even when candidates is empty (prevents repeat scan storms). gc_last_submit_ticket[d] = submitted + 1; gc_last_attempt_ns[d] = now_ns; if (gc_candidates_scratch.empty()) { gc_cooldown_ns[d] = kBackoffCooldownNs; return; } const std::size_t dim_cap = std::size_t(bindless->image_capacity(dimension)); const std::size_t batch_cap = (std::min)(std::size_t(8192), (std::max)(std::size_t(64), dim_cap / 8)); const std::size_t target = (std::min)(gc_candidates_scratch.size(), batch_cap); if (target < gc_candidates_scratch.size()) { std::nth_element( gc_candidates_scratch.begin(), gc_candidates_scratch.begin() + std::ptrdiff_t(target), gc_candidates_scratch.end(), [](const auto& a, const auto& b) { return a.second < b.second; }); } gc_winners_scratch.clear(); gc_winners_scratch.reserve(target); for (std::size_t i = 0; i < target; ++i) gc_winners_scratch.push_back(*gc_candidates_scratch[i].first); gc_candidates_scratch.clear(); if (phase2_live_lru) { gc_touched_addrs_scratch.clear(); gc_touched_addrs_scratch.reserve(target); } std::size_t evicted_slots = 0, evicted_keys = 0; for (const ViewKey& win_key : gc_winners_scratch) { const auto sv_it = shared_views.find(win_key); if (sv_it == shared_views.end()) continue; if (!is_evictable_sv(sv_it->second)) continue; adjust_evictable_sv_locked(sv_it->second.entry.dimension, true, false); const ImageEntry entry = sv_it->second.entry; const std::vector keys = std::move(sv_it->second.keys); shared_views.erase(sv_it); for (const auto& k : keys) { if (const auto e_it = image_entries.find(k); e_it != image_entries.end()) { const std::uint64_t addr = e_it->second.address; if (phase2_live_lru) gc_touched_addrs_scratch.push_back(addr); const auto [first, last] = image_keys.equal_range(addr); for (auto kit = first; kit != last; ++kit) { if (kit->second == k) { image_keys.erase(kit); break; } } if (e_it->second.from_title_heap && title_heap_image_keys > 0) --title_heap_image_keys; image_entries.erase(e_it); } bindless->erase_key(k); ++evicted_keys; } release(entry); ++evicted_slots; } gc_cooldown_ns[d] = evicted_slots < 64 ? kBackoffCooldownNs : kNormalCooldownNs; if (!evicted_slots) return; ++gc_runs; gc_evicted_slots += evicted_slots; gc_evicted_keys += evicted_keys; std::size_t notified_textures = 0; if (phase2_live_lru && !gc_touched_addrs_scratch.empty()) { std::sort(gc_touched_addrs_scratch.begin(), gc_touched_addrs_scratch.end()); gc_touched_addrs_scratch.erase( std::unique(gc_touched_addrs_scratch.begin(), gc_touched_addrs_scratch.end()), gc_touched_addrs_scratch.end()); notified_textures = gc_touched_addrs_scratch.size(); for (const std::uint64_t addr : gc_touched_addrs_scratch) { note_texture_change(leonida::SlotChange::texture_gone, addr); if (const std::uint64_t key = tsharp_texture_key(addr); key != addr) note_texture_change(leonida::SlotChange::texture_gone, key); } } if ((gc_runs & (gc_runs - 1)) == 0) { constexpr const char* names[] = {"2D", "2D array", "3D", "1D", "1D array", "2D MS", "2D MS array"}; std::fprintf(stderr, "[rt] d3d12: bindless GC #%llu [%s] dim %d (%s%s): evicted %zu slots (%zu keys, %zu " "textures notified); %s, %u free in dim\n", static_cast(gc_runs), phase2_live_lru ? "live-lru" : "dead-sweep", int(dimension), names[int(dimension)], need_storage ? " storage" : "", evicted_slots, evicted_keys, notified_textures, bindless_diag_summary_locked().c_str(), bindless->free_images(dimension)); } } struct PendingSample { Resource* owner = nullptr; leonida::gfx10::Image image{}; VkFormat view_format{}, channels_format{}; }; std::mutex pending_view_mutex; std::map pending_samples; std::atomic pending_sample_count{}; bool materialize_sample(const leonida::DescriptorKey& key); bool materialize_table(std::uint64_t address,std::uint32_t slots); void write_tsharp_index_words(const std::vector& keys); void remember_sample(const leonida::DescriptorKey& key, const PendingSample& sample) { std::lock_guard lock(pending_view_mutex); if (pending_samples.try_emplace(key,sample).second) { ++pending_sample_count; } } void retire_samples(Resource* owner) { std::lock_guard lock(pending_view_mutex); const auto removed=std::erase_if(pending_samples,[&](const auto& p){return p.second.owner==owner;}); pending_sample_count -= static_cast(removed); } struct VolumeSlices { UINT first = 0; UINT count = 0; // 0: no restriction (ordinary view of the whole mip) }; // Gives the T# `words` a view in set 0 and an entry in the hash table, unless it has them. `storage`: shaders // write through it too (an unordered-access view), so it also goes into the storage arrays, which are // shorter. False when set 0 cannot show the image; the descriptor then finds the fallback at index 0. `why`, when // given, is set to the reason when it is that set 0 has no room (or no array) for the image's dimension, and left // alone otherwise (no view could be made for the T#). bool bind_image(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, VkFormat image_format, VkImageAspectFlags aspects, bool storage, bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED, bool evictable = false) { std::lock_guard lock(descriptor_mutex); return bind_image_locked(words, image, vk_image, image_format, aspects, storage, allow_channel_cast, uint_backed, nullptr, evictable); } static bool supports_min_lod_clamp(leonida::gfx10::ImageType type) { using T = leonida::gfx10::ImageType; return type == T::image_1d || type == T::image_2d || type == T::image_2d_array || type == T::cube || type == T::image_3d; } bool bind_image_locked(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, VkFormat image_format, VkImageAspectFlags aspects, bool storage, bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED, const char** why = nullptr, bool evictable = false, bool in_known_heap = false) { namespace g = leonida::gfx10; if (!bindless) return false; const bool effective_evictable = evictable || binding_from_title_heap; bool is_zero_view = false; float partial_min_lod = 0.0f; auto pending = pending_image_keys.find(vk_image); if (pending != pending_image_keys.end()) { const std::uint32_t filled_from = pending->second.first_mip; const std::uint32_t view_min_mip = leonida::effective_min_mip(image.first_mip, g::image_min_lod(words)); if (view_min_mip < filled_from) { auto [it, inserted] = pending->second.keys.try_emplace( words, PendingImageKey{image, effective_evictable, in_known_heap}); if (!inserted) { if (!effective_evictable) it->second.evictable = false; if (in_known_heap) it->second.in_known_heap = true; } const std::uint32_t last_mip = image.mip_count ? image.first_mip + image.mip_count - 1 : image.first_mip; const bool can_partial_clamp = !pending->second.zero && filled_from != UINT32_MAX && info.image_view_min_lod && !storage && supports_min_lod_clamp(image.type) && (aspects & VK_IMAGE_ASPECT_COLOR_BIT) != 0 && image.mip_count > 0 && filled_from <= last_mip; if (can_partial_clamp) { partial_min_lod = float(filled_from); } else { if (!pending->second.zero) return true; vk_image = pending->second.zero; is_zero_view = true; } } } const bool depth_or_stencil = (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; // A T# of 8_UINT on a depth-stencil image is a view of its stencil plane (image_descriptor, D3D-75). Vulkan // views it in the image's own format with the stencil aspect, and returns the value in R, as a T# whose // format is 8_UINT reads it from X. const bool stencil = (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) && image.format == g::stencil_format; const VkFormat logical_format = uint_backed ? uint_backed : image_format; VkFormat view_format = stencil ? image_format : g::vulkan_view_format(logical_format, image.format, allow_channel_cast); VkFormat channels_format = view_format; // whose channels the T#'s swizzle selects from // A B4G4R4A4 render target stored as RGBA8 (no 4444 format renders on this device): a 16-bit view of the // 32-bit image is not allowed, so its 4_4_4_4 T# reads the RGBA8 image (which holds the logical R, G, B, A) // with the channels of A4R4G4B4, the format the texture has (DXGI_FORMAT_B4G4R4A4_UNORM). if (!stencil && image_format == VK_FORMAT_R8G8B8A8_UNORM && (view_format == VK_FORMAT_A4B4G4R4_UNORM_PACK16 || view_format == VK_FORMAT_A4R4G4B4_UNORM_PACK16)) { view_format = VK_FORMAT_R8G8B8A8_UNORM; channels_format = VK_FORMAT_A4R4G4B4_UNORM_PACK16; } if (view_format == VK_FORMAT_UNDEFINED) { // a 96-bit texture's T# names RGB32; its image is RGBA32 view_format = rgb96_view_format(image_format, image.format); channels_format = rgb96_named_format(view_format); } // A depth image can only be viewed in its own format, so a T# that names another format on it (the title's // T# of a console D16S8 target says 16-bit UNORM; the image is D24S8 or D32S8) is its depth plane, read as a // normalised value in X either way. if (depth_or_stencil && !stencil && (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) && (view_format == VK_FORMAT_UNDEFINED || !g::is_depth_stencil_format(view_format))) { log_once("a T# names another format on a depth image; viewed as its depth plane, GFX10 format", int(image.format)); view_format = image_format; channels_format = image_format; } // A sampled view only samples: a view in a cast format the image's storage usage does not support (an R32 // target viewed as E5B9G9R9) stays valid (VUID-VkImageViewCreateInfo-usage-02274). const bool sampled_only = uint_backed || (view_format != image_format && view_format != VK_FORMAT_UNDEFINED); return bind_image_views_locked(words, image, vk_image, view_format, channels_format, uint_backed ? image_format : view_format, aspects, true, storage, {}, sampled_only, why, effective_evictable, is_zero_view, partial_min_lod, in_known_heap); } // The same for a view whose formats the caller has worked out: `view_format` of the sampled view (made when // `sampled`), `channels_format` whose channels the T#'s swizzle selects from, `storage_format` of the storage view. bool bind_image(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, VkFormat view_format, VkFormat channels_format, VkFormat storage_format, VkImageAspectFlags aspects, bool sampled, bool storage, VolumeSlices slices, const void* evictable_owner = nullptr, bool in_known_heap = false) { std::lock_guard lock(descriptor_mutex); bool evictable = false; if (evictable_owner) { const auto it = images_by_address.find(image.address); evictable = (it != images_by_address.end() && it->second == evictable_owner); } return bind_image_views_locked(words, image, vk_image, view_format, channels_format, storage_format, aspects, sampled, storage, slices, true, nullptr, evictable, false, 0.0f, in_known_heap); } bool bind_image_views_locked(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, VkFormat view_format, VkFormat channels_format, VkFormat storage_format, VkImageAspectFlags aspects, bool sampled, bool storage, VolumeSlices slices, bool sampled_only, const char** why = nullptr, bool evictable = false, bool is_zero_view = false, float partial_min_lod = 0.0f, bool in_known_heap = false) { namespace g = leonida::gfx10; if (!bindless) { if (storage) log_once("unordered-access view needs the Vulkan bindless set; type", int(image.type)); return false; } const bool effective_evictable = evictable || binding_from_title_heap; if (!is_zero_view && partial_min_lod == 0.0f) { if (const auto pending = pending_image_keys.find(vk_image); pending != pending_image_keys.end()) { const std::uint32_t filled_from = pending->second.first_mip; const std::uint32_t view_min_mip = leonida::effective_min_mip(image.first_mip, g::image_min_lod(words)); if (view_min_mip < filled_from) { auto [it, inserted] = pending->second.keys.try_emplace( words, PendingImageKey{image, effective_evictable, in_known_heap}); if (!inserted) { if (!effective_evictable) it->second.evictable = false; if (in_known_heap) it->second.in_known_heap = true; } const std::uint32_t last_mip = image.mip_count ? image.first_mip + image.mip_count - 1 : image.first_mip; const bool can_partial_clamp = !pending->second.zero && filled_from != UINT32_MAX && info.image_view_min_lod && sampled && !storage && supports_min_lod_clamp(image.type) && (aspects & VK_IMAGE_ASPECT_COLOR_BIT) != 0 && image.mip_count > 0 && filled_from <= last_mip; if (can_partial_clamp) { partial_min_lod = float(filled_from); } else { if (!pending->second.zero) return true; vk_image = pending->second.zero; is_zero_view = true; } } } } VkImageViewMinLodCreateInfoEXT clamp{VK_STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT}; bool has_min_lod = false; std::uint32_t min_lod_bits = 0; bool empty_lod_range = false; if (!storage && supports_min_lod_clamp(image.type) && (aspects & VK_IMAGE_ASPECT_COLOR_BIT)) { // Use the clamp in the T# itself: views with identical keys must sample identically. // For a partially-filled streamed texture, raise minLod to filled_from until finer mips arrive. // Note: VkImageViewMinLodCreateInfoEXT::minLod is an absolute image mip index (not relative to // baseMipLevel), verified empirically against Khronos VVL (VUID-VkImageViewMinLodCreateInfoEXT-minLod-06456) // and RADV hardware sampling with baseMipLevel > 0. clamp.minLod = (std::max)(g::image_min_lod(words), partial_min_lod); if (clamp.minLod > float(image.first_mip + image.mip_count - 1)) { empty_lod_range = true; } else if (clamp.minLod > float(image.first_mip)) { if (!info.image_view_min_lod) { log_once("SRV requires VK_EXT_image_view_min_lod; first mip", int(image.first_mip)); return false; } has_min_lod = true; min_lod_bits = std::bit_cast(clamp.minLod); } } const auto existing = image_entries.find(words); if (existing != image_entries.end() && (existing->second.storage || !storage) && existing->second.view_key.vk_image == vk_image && existing->second.view_key.has_min_lod == has_min_lod && existing->second.view_key.min_lod_bits == min_lod_bits) { const std::uint64_t gen = ++tsharp_use_gen; existing->second.last_seen_gen = gen; if (in_known_heap) existing->second.in_known_heap = true; const auto sv_it = shared_views.find(existing->second.view_key); if (sv_it != shared_views.end()) { const bool was_evictable = is_evictable_sv(sv_it->second); if (!effective_evictable && existing->second.from_title_heap) { existing->second.from_title_heap = false; if (title_heap_image_keys > 0) --title_heap_image_keys; ++sv_it->second.api_refcount; } adjust_evictable_sv_locked(sv_it->second.entry.dimension, was_evictable, is_evictable_sv(sv_it->second)); sv_it->second.last_seen_gen = gen; sv_it->second.last_touch_ticket = context ? context->submitted_retire_ticket() + 1 : 0; } else if (!effective_evictable && existing->second.from_title_heap) { existing->second.from_title_heap = false; if (title_heap_image_keys > 0) --title_heap_image_keys; } return true; } leonida::ImageDimension dimension; switch (image.type) { case g::ImageType::image_2d: dimension = leonida::ImageDimension::dim_2d; break; case g::ImageType::image_2d_array: case g::ImageType::cube: dimension = leonida::ImageDimension::dim_2d_array; break; case g::ImageType::image_3d: dimension = leonida::ImageDimension::dim_3d; break; case g::ImageType::image_1d: dimension = leonida::ImageDimension::dim_1d; break; case g::ImageType::image_1d_array: dimension = leonida::ImageDimension::dim_1d_array; break; case g::ImageType::image_2d_msaa: dimension = leonida::ImageDimension::dim_2d_ms; break; case g::ImageType::image_2d_msaa_array: dimension = leonida::ImageDimension::dim_2d_ms_array; break; default: log_once("set 0 has no array for this image type:", int(image.type)); return false; } const bool depth_or_stencil = (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; if (storage && depth_or_stencil) { log_once("storage view not supported for depth-stencil image format:", int(view_format)); return false; } if (view_format == VK_FORMAT_UNDEFINED || (depth_or_stencil && !g::is_depth_stencil_format(view_format))) { log_once("no Vulkan view format for the GFX10 format of a view:", int(image.format)); return false; } // A T# of 8_UINT on a depth-stencil image is a view of its stencil plane (image_descriptor, D3D-75). Vulkan // views it in the image's own format with the stencil aspect, and returns the value in R, as a T# whose // format is 8_UINT reads it from X. const bool stencil = (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) && image.format == g::stencil_format; const unsigned sampled_class = g::multisampled(image.type) ? numeric_class(view_format) : 0; if (g::multisampled(image.type) && !bindless->supports_ms_class(sampled_class)) { log_once("set 0 has no multisample binding for this numeric class:", int(sampled_class)); return false; } auto& vk = context->vk; VkImageViewUsageCreateInfo view_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; view_usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT; VkImageViewCreateInfo view_info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; if (sampled_only) view_info.pNext = &view_usage; view_info.image = vk_image; view_info.viewType = g::vulkan_view_type(image.type); view_info.format = view_format; auto swizzle = image.swizzle; if (empty_lod_range) { // The accessible mip set is empty. Keep the dimensions and constant/missing channels. for (auto& channel : swizzle) if (channel != g::select_one) channel = g::select_zero; } else if (has_min_lod) { clamp.pNext = view_info.pNext; view_info.pNext = &clamp; } view_info.components = g::vulkan_swizzle(swizzle, channels_format); view_info.subresourceRange = g::vulkan_subresource_range( image, stencil ? VK_IMAGE_ASPECT_STENCIL_BIT : (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT); // Deduplicate identical Vulkan views across distinct T# keys via refcounted ViewKey sharing. ViewKey vk_key{}; vk_key.vk_image = vk_image; vk_key.dimension = dimension; vk_key.view_type = view_info.viewType; vk_key.view_format = view_info.format; vk_key.storage_format = storage ? storage_format : VK_FORMAT_UNDEFINED; vk_key.sampled_class = sampled_class; vk_key.swizzle_r = view_info.components.r; vk_key.swizzle_g = view_info.components.g; vk_key.swizzle_b = view_info.components.b; vk_key.swizzle_a = view_info.components.a; vk_key.aspect_mask = view_info.subresourceRange.aspectMask; vk_key.base_mip = view_info.subresourceRange.baseMipLevel; vk_key.mip_count = view_info.subresourceRange.levelCount; vk_key.base_layer = view_info.subresourceRange.baseArrayLayer; vk_key.layer_count = view_info.subresourceRange.layerCount; vk_key.min_lod_bits = min_lod_bits; vk_key.slice_first = storage ? slices.first : 0u; vk_key.slice_count = storage ? slices.count : 0u; vk_key.mirror_layer = dimension == leonida::ImageDimension::dim_2d_array ? image.first_layer : 0u; vk_key.api_owner_address = (is_zero_view && console_heap_count.load(std::memory_order_acquire) == 0) ? image.address : 0u; vk_key.sampled_only = sampled_only; vk_key.sampled = sampled; vk_key.storage = storage; vk_key.has_min_lod = has_min_lod; const auto commit_key_to_shared = [&](SharedViewEntry& sv, bool is_new) { const bool was_evictable = !is_new && is_evictable_sv(sv); const std::uint64_t gen = ++tsharp_use_gen; sv.last_seen_gen = gen; sv.last_touch_ticket = context ? context->submitted_retire_ticket() + 1 : 0; if (existing != image_entries.end()) { const bool old_from_title = existing->second.from_title_heap; const bool new_from_title = effective_evictable ? old_from_title : false; const ViewKey old_vk_key = existing->second.view_key; const std::size_t old_pos = existing->second.sv_key_pos; const std::uint64_t old_addr = existing->second.address; if (old_from_title && !new_from_title && title_heap_image_keys > 0) --title_heap_image_keys; ++sv.refcount; if (!new_from_title) ++sv.api_refcount; adjust_evictable_sv_locked(sv.entry.dimension, was_evictable, is_evictable_sv(sv)); const std::size_t new_pos = sv.keys.size(); sv.keys.push_back(words); static_cast(existing->second) = sv.entry; existing->second.address = old_addr; existing->second.view_key = vk_key; existing->second.sv_key_pos = new_pos; existing->second.from_title_heap = new_from_title; if (in_known_heap) existing->second.in_known_heap = true; existing->second.last_seen_gen = gen; detach_view_key_locked(old_vk_key, old_pos, old_from_title, /*upgrading=*/true, old_addr); // The console heap slots holding these words carry the read-only entry's index in their dword 6 // (tsharp_index_words): fixed again at the next submission (a texture_gone change re-fixes bound T#s, // under the address their records keep, tsharp_texture_key), they take this one, with its storage views. if (tsharp_index_words) note_texture_change(leonida::SlotChange::texture_gone, tsharp_texture_key(image.address)); } else { const bool from_title = effective_evictable; if (from_title) ++title_heap_image_keys; ++sv.refcount; if (!from_title) ++sv.api_refcount; adjust_evictable_sv_locked(sv.entry.dimension, was_evictable, is_evictable_sv(sv)); const std::size_t new_pos = sv.keys.size(); sv.keys.push_back(words); ImageKeyEntry key_entry{}; static_cast(key_entry) = sv.entry; key_entry.address = image.address; key_entry.view_key = vk_key; key_entry.sv_key_pos = new_pos; key_entry.from_title_heap = from_title; key_entry.in_known_heap = in_known_heap; key_entry.last_seen_gen = gen; image_entries.emplace(words, std::move(key_entry)); image_keys.emplace(image.address, words); } // The set derives the entry's kind from what it bound at this index (BindlessSet::image_kind_at); a plain // library's modules do not read it, so they get 0 as before. bindless->insert_key(words, sv.entry.index, descriptor_table_tagged ? bindless->image_kind_at(dimension, sv.entry.index) : 0u); leonida::fsdraw::note_tsharp(words.data()); // LOCAL DIAGNOSTIC }; if (const auto sv_it = shared_views.find(vk_key); sv_it != shared_views.end()) { commit_key_to_shared(sv_it->second, /*is_new=*/false); return true; } // Need a new bindless slot. Trigger safe pressure GC of stale evictable entries before checking room. const std::uint32_t dim_cap = bindless->image_capacity(dimension); const std::uint32_t gc_threshold = (std::min)(std::uint32_t(4096), dim_cap / 8); if (!bindless->has_free_image(dimension, storage, sampled_class) || bindless->free_images(dimension) < gc_threshold) { const ViewKey* skip_vk = existing != image_entries.end() ? &existing->second.view_key : nullptr; gc_bindless_title_views_locked(dimension, storage, sampled_class, skip_vk); } const auto report_bindless_refusal = [&](bool needed_storage) { using Refusal = leonida::BindlessSet::ImageRefusal; const Refusal refusal = bindless->image_refusal(dimension, needed_storage, sampled_class); if (why) *why = refusal == Refusal::no_array ? "set 0 has no array for the T#'s dimension" : refusal == Refusal::storage_full ? kTsharpStorageFull : kTsharpArrayFull; if (refusal != Refusal::no_array && first_diagnostic("a bindless image array is full; dimension", int(dimension))) { std::size_t entries = 0, replaced = 0, most = 0, registered = 0, dim_view_keys = 0; std::map per_texture; for (const auto& kv : image_entries) if (kv.second.dimension == dimension) { ++entries; most = (std::max)(most, ++per_texture[kv.second.address]); } for (const auto& kv : shared_views) if (kv.second.entry.dimension == dimension) ++dim_view_keys; for (const auto& texture : per_texture) registered += images_by_address.count(texture.first); for (const auto& held : replaced_images) replaced += held.dimension == dimension; constexpr const char* names[] = {"2D", "2D array", "3D", "1D", "1D array", "2D MS", "2D MS array"}; std::fprintf(stderr, "[rt] d3d12: a bindless image array is full; dimension %d (%s)%s: %u indices, %u in the " "storage arrays, %zu T#s (%zu shared ViewKeys) of %zu textures (%zu registered at their " "address, at most %zu T#s of one), %zu replaced views kept [%s]; further T#s of this " "dimension read the fallback\n", int(dimension), names[int(dimension)], refusal == Refusal::storage_full ? ", its storage range" : "", bindless->image_capacity(dimension), bindless->storage_capacity(dimension), entries, dim_view_keys, per_texture.size(), registered, most, replaced, bindless_diag_summary_locked().c_str()); } }; // Pre-check bindless room BEFORE vkCreateImageView so zero driver views are created/destroyed when full. if (!bindless->has_free_image(dimension, storage, sampled_class)) { report_bindless_refusal(storage); return false; } ImageEntry entry{dimension, 0, VK_NULL_HANDLE, VK_NULL_HANDLE, image.address}; if (sampled) { const VkResult result = vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled); if (result != VK_SUCCESS) { log_once("sampled image view creation failed:", result); return false; } } leonida::StorageViews views{}; VkImageViewCreateInfo storage_info{}; bool storage_info_valid = false; // storage_info's pNext chain: declared out here, since the 2D mirror below copies storage_info with its chain // after this block. Declared inside it, the chain dangled and the driver followed it into stale stack (the // 120 s hangs of d3d12_existing_heap, d3d12_r9g9b9e5_uav and the depth-storage tests). VkImageViewUsageCreateInfo storage_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; VkImageViewSlicedCreateInfoEXT sliced{VK_STRUCTURE_TYPE_IMAGE_VIEW_SLICED_CREATE_INFO_EXT}; if (storage) { storage_info = view_info; storage_info_valid = true; storage_info.components = {}; storage_info.format = storage_format; storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT; if (slices.count) { sliced.sliceOffset = slices.first; sliced.sliceCount = slices.count; storage_usage.pNext = &sliced; } storage_info.pNext = &storage_usage; const VkResult result = vk.vkCreateImageView(info.device, &storage_info, nullptr, &entry.storage); if (result != VK_SUCCESS) { log_once("storage image view creation failed:", result); if (entry.sampled) vk.vkDestroyImageView(info.device, entry.sampled, nullptr); return false; } const int numeric = numeric_class(storage_format); (numeric == 1 ? views.as_uint : numeric == 2 ? views.as_sint : views.as_float) = entry.storage; if (storage_format == VK_FORMAT_R32_UINT) views.r32ui = entry.storage; if (info.shader_image_int64_atomics && dimension == leonida::ImageDimension::dim_2d && (storage_format == VK_FORMAT_R64_UINT || is_r32g32_format(storage_format))) { if (storage_format == VK_FORMAT_R64_UINT) { views.r64ui = entry.storage; } else { VkImageViewCreateInfo r64_info = storage_info; r64_info.format = VK_FORMAT_R64_UINT; if (vk.vkCreateImageView(info.device, &r64_info, nullptr, &entry.storage_r64ui) == VK_SUCCESS) views.r64ui = entry.storage_r64ui; else log_once("R64_UINT storage image view creation failed; format", int(storage_format)); } } } // A 2D-array or cube image also gets a 2D view of its first layer, which the bindless set binds at the same // index in the 2D arrays: a 2D instruction reading this T# addresses slice 0 (BindlessSet::MirrorViews). leonida::BindlessSet::MirrorViews mirror{}; if (dimension == leonida::ImageDimension::dim_2d_array) { const auto make_mirror = [&](const VkImageViewCreateInfo& base, VkImageView* out) { VkImageViewCreateInfo layer = base; layer.viewType = VK_IMAGE_VIEW_TYPE_2D; layer.subresourceRange.baseArrayLayer = image.first_layer; layer.subresourceRange.layerCount = 1; return vk.vkCreateImageView(info.device, &layer, nullptr, out) == VK_SUCCESS; }; if (make_mirror(view_info, &entry.mirror_sampled)) { mirror.sampled = entry.mirror_sampled; mirror.sampled_layout = VK_IMAGE_LAYOUT_GENERAL; if (storage_info_valid && make_mirror(storage_info, &entry.mirror_storage)) { const int numeric = numeric_class(storage_info.format); (numeric == 1 ? mirror.storage.as_uint : numeric == 2 ? mirror.storage.as_sint : mirror.storage.as_float) = entry.mirror_storage; if (storage_info.format == VK_FORMAT_R32_UINT) mirror.storage.r32ui = entry.mirror_storage; if (info.shader_image_int64_atomics && (storage_info.format == VK_FORMAT_R64_UINT || is_r32g32_format(storage_info.format))) { if (storage_info.format == VK_FORMAT_R64_UINT) { mirror.storage.r64ui = entry.mirror_storage; } else { VkImageViewCreateInfo r64_info = storage_info; r64_info.format = VK_FORMAT_R64_UINT; if (make_mirror(r64_info, &entry.mirror_storage_r64ui)) mirror.storage.r64ui = entry.mirror_storage_r64ui; } } } } else { log_once("no 2D view of this image's first layer; a 2D instruction reading its T# reads the fallback", int(image.type)); } } // Every state a shader can read or write the texture in is GENERAL (ResourceBinding::sampled_in_general). // `kind` says which arrays the index is bound in; a tagged module reads it from the table (insert_key). entry.index = bindless->add_image(dimension, entry.sampled, VK_IMAGE_LAYOUT_GENERAL, views, sampled_class, mirror.sampled ? &mirror : nullptr); if (!entry.index) { if (entry.mirror_sampled) { vk.vkDestroyImageView(info.device, entry.mirror_sampled, nullptr); entry.mirror_sampled = VK_NULL_HANDLE; } if (entry.mirror_storage) { vk.vkDestroyImageView(info.device, entry.mirror_storage, nullptr); entry.mirror_storage = VK_NULL_HANDLE; } if (entry.mirror_storage_r64ui) { vk.vkDestroyImageView(info.device, entry.mirror_storage_r64ui, nullptr); entry.mirror_storage_r64ui = VK_NULL_HANDLE; } report_bindless_refusal(entry.storage != VK_NULL_HANDLE); if (entry.sampled) vk.vkDestroyImageView(info.device, entry.sampled, nullptr); if (entry.storage) vk.vkDestroyImageView(info.device, entry.storage, nullptr); if (entry.storage_r64ui) vk.vkDestroyImageView(info.device, entry.storage_r64ui, nullptr); return false; } SharedViewEntry& sv = shared_views[vk_key]; sv.entry = entry; sv.is_zero_view = is_zero_view; commit_key_to_shared(sv, /*is_new=*/true); return true; } // The dword 6 that the T# `words` (its key: the descriptor as the title or Create*View wrote it) gets in a heap // shaders read (gfx10_descriptors.h, tsharp_index_word): its entry's index and the arrays that index is bound in, // which the set derives from what it bound there (image_kind_at); 0, the fallback, while the T# has no entry (no // texture yet, a stream still pending, no room). descriptor_mutex held. std::uint32_t tsharp_index_word_locked(const leonida::gfx10::ImageWords& words) const { if (!bindless) return 0; const auto it = image_entries.find(words); if (it == image_entries.end()) return 0; return leonida::gfx10::tsharp_index_word(it->second.index, bindless->image_kind_at(it->second.dimension, it->second.index)); } std::uint32_t tsharp_index_word(const leonida::gfx10::ImageWords& words) { std::lock_guard lock(descriptor_mutex); return tsharp_index_word_locked(words); } // Textures by the address their T#s name them by (Resource::image_address), for the T#s a title writes into a // console descriptor heap itself (bind_title_image). Under descriptor_mutex: a texture leaves it in forget_image, // before its image goes. TitleGpuPlacements gpu_placements; // descriptor_mutex std::map images_by_address; // a Resource using TsharpRefusalKey = std::tuple; std::set logged_tsharp_refusals; // descriptor_mutex, dedup per tuple std::map logged_tsharp_refusals_by_reason; // descriptor_mutex, capped at 8/reason void note_image_address(std::uint64_t address, const void* resource) { std::lock_guard lock(descriptor_mutex); images_by_address[address] = resource; note_texture_change(leonida::SlotChange::texture_added, address); } // A texture registered, replaced or gone at `address`: the console heaps' T#s naming it (by that address or by // the other view of texture-pool memory, title_gpu_views) are fixed again at the next submission. void note_texture_change(leonida::SlotChange::Kind kind, std::uint64_t address) { if (!address) return; note_slot_change(kind, address, 1); if (const std::uint64_t other = leonida::title_gpu_views::other_view(address)) note_slot_change(kind, other, 1); } // Why no texture answers a T# (bind_title_image; descriptor_mutex held): the kTsharpNoTexture* reasons. const char* no_texture_reason_locked(const leonida::gfx10::Image& image); // The address a title-written T# names a texture by. The title rebuilds T#s of the layer's textures (1 << 32 and // up, 256 apart: Resource::image_address) from 32 bits: run 58's unbound T#s name 0x7f0000021400 for 0x100021400 // and 0x2ef600 for 0x1002ef600 (bits 32-39 clear, 0x7f or 0 in bits 40-47). Such an address outside the title's // memory is the layer's texture address with the same low 32 bits, before or after that texture exists, while the // layer has handed out fewer than 2^24 addresses (so the low bits name one); any other address is itself. std::uint64_t tsharp_texture_key(std::uint64_t address) const { constexpr std::uint64_t ours = std::uint64_t(1) << 32; const std::uint64_t high = address >> 40, mid = (address >> 32) & 0xff, low = address & 0xffffffffull; if (mid || !low || (high && high != 0x7f)) return address; if (next_image_address.load(std::memory_order_relaxed) >= ours + ours) return address; std::uint64_t lo = 0, hi = 0; if (leonida::title_va_aliases().title_memory(address, lo, hi)) return address; return ours | low; } // Fallback for rebuilt T#s of committed layer textures (1 << 32 and up) whose upper byte is 0x10 // (title_mirror_space::kLow >> 40) with bits 32-39 clear and non-zero low 32 bits. Only consulted by // bind_title_image() when no title texture (images_by_address or gpu_placements, at address or its other_view) // owns the address, because 0x100000000000..0x100400000000 is registered as title_memory. std::uint64_t tsharp_high10_low32_key(std::uint64_t address) const { constexpr std::uint64_t ours = std::uint64_t(1) << 32; const std::uint64_t high = address >> 40, mid = (address >> 32) & 0xff, low = address & 0xffffffffull; if (high != 0x10 || mid || !low) return address; if (next_image_address.load(std::memory_order_relaxed) >= ours + ours) return address; return ours | low; } // LEONIDA_TRACE_TEXTURE=
[,
...] (hex, the base a T# names): the resource id of an image registered // at that address, so a draw's T# can be followed to the passes that write it (fsdraw rt0, UAV views, copies). static void trace_image(std::uint64_t address, leonida::ResourceId id, const char* where) { static const std::vector traced = [] { std::vector out; const char* v = std::getenv("LEONIDA_TRACE_TEXTURE"); for (const char* p = v; p && *p;) { char* end = nullptr; const std::uint64_t a = std::strtoull(p, &end, 16); if (end == p) break; out.push_back(a); p = *end == ',' ? end + 1 : end; } return out; }(); if (traced.empty() || std::find(traced.begin(), traced.end(), address) == traced.end()) return; std::fprintf(stderr, "[rt] trace-texture: address 0x%llx is resource 0x%llx (%s)\n", static_cast(address), static_cast(id), where); leonida::fsdraw::note_target(id); // read back with the captures (numbers: mean, nonzero texels) } // The texture registered at `address` (a title-placed texture's address can be taken over by a later one). const void* image_owner(std::uint64_t address) { std::lock_guard lock(descriptor_mutex); const auto it = images_by_address.find(address); return it == images_by_address.end() ? nullptr : it->second; } // The texture at `address` is gone: its views leave set 0 and its T#s the hash table. void forget_image(std::uint64_t address) { std::lock_guard lock(descriptor_mutex); images_by_address.erase(address); forget_image_views_locked(address); } // The same for a texture that is going, only while `owner` is the texture registered at `address`: one that took // the address over since (a slot-133 texture placed where a slot-70 view had made one, place_at_title_address) // keeps it, and the views of the one going left with that takeover. void forget_image_of(std::uint64_t address, const void* owner) { std::lock_guard lock(descriptor_mutex); const auto it = images_by_address.find(address); if (it == images_by_address.end() || it->second != owner) return; images_by_address.erase(it); forget_image_views_locked(address); } // Its T#s stop naming it at once (a shader's lookup of their words misses from the next table flush on); the // console heap slots that held them wait for the next texture at the address (note_texture_change). Actual // SlotChange::texture_room is emitted only once the deferred slots actually return to free in set_bindless_release // or set_bindless_prepare (flush), avoiding premature wake storms while slots are still in flight. void forget_image_views_locked(std::uint64_t address) { note_texture_change(leonida::SlotChange::texture_gone, address); if (!bindless) return; const auto [first, last] = image_keys.equal_range(address); for (auto it = first; it != last; ++it) { const auto entry = image_entries.find(it->second); if (entry == image_entries.end()) continue; bindless->erase_key(it->second); const ViewKey vk_key = entry->second.view_key; const std::size_t key_pos = entry->second.sv_key_pos; const bool from_title = entry->second.from_title_heap; if (from_title && title_heap_image_keys > 0) --title_heap_image_keys; image_entries.erase(entry); detach_view_key_locked(vk_key, key_pos, from_title, /*upgrading=*/false, 0); } image_keys.erase(first, last); std::erase_if(replaced_images, [&](const ImageEntry& entry) { if (entry.address != address) return false; release(entry); return true; }); } // Gives the S# `words` a sampler in set 0 and an entry in the hash table, unless it has them. // When `out_index` is given, receives the bindless sampler index on success or 0xFFFFFFFFu on failure. bool bind_sampler(const leonida::gfx10::SamplerWords& words, std::uint32_t* out_index = nullptr) { if (out_index) *out_index = leonida::LiteralSamplerSpec::kFallbackIndex; namespace g = leonida::gfx10; std::lock_guard lock(descriptor_mutex); if (!bindless) return false; const leonida::DescriptorKey key = leonida::make_ssharp_key(words.data()); if (const auto it = sampler_entries.find(key); it != sampler_entries.end()) { if (out_index) *out_index = it->second.index; return true; } const g::Sampler sampler = g::decode(words); VkSamplerCreateInfo sampler_info = g::vulkan_sampler(sampler, max_sampler_lod_bias); // What vulkan_sampler leaves to its caller, and features this device may not have enabled. if (sampler_info.anisotropyEnable && !info.sampler_anisotropy) { log_once("anisotropic sampler without samplerAnisotropy; anisotropy", int(sampler.max_anisotropy)); sampler_info.anisotropyEnable = VK_FALSE; } for (VkSamplerAddressMode* mode : {&sampler_info.addressModeU, &sampler_info.addressModeV, &sampler_info.addressModeW}) { if (*mode != VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE || info.sampler_mirror_clamp_to_edge) continue; log_once("mirror-once sampler without samplerMirrorClampToEdge; clamped instead, mode", int(*mode)); *mode = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; } VkSamplerReductionModeCreateInfo reduction{VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO}; if (sampler.filter_mode != g::FilterMode::blend) { if (info.sampler_filter_minmax && !sampler_info.compareEnable) { reduction.reductionMode = g::vulkan_reduction_mode(sampler.filter_mode); reduction.pNext = sampler_info.pNext; sampler_info.pNext = &reduction; if (!info.sampler_filter_minmax_component_mapping) log_once("minimum/maximum filter sampler without filterMinmaxImageComponentMapping; only R is " "defined, mode", int(sampler.filter_mode)); } else { log_once("minimum/maximum filter sampler without samplerFilterMinmax; blended instead, mode", int(sampler.filter_mode)); } } VkSamplerCustomBorderColorCreateInfoEXT custom_border{ VK_STRUCTURE_TYPE_SAMPLER_CUSTOM_BORDER_COLOR_CREATE_INFO_EXT}; if (sampler.border_color == g::BorderColor::table) { const bool is_int = sampler.border_color_index < border_color_table.size() && border_color_table[sampler.border_color_index].is_int; if (info.custom_border_color && info.custom_border_color_without_format && sampler.border_color_index < border_color_table.size()) { const auto& entry = border_color_table[sampler.border_color_index]; custom_border.customBorderColor = entry.value; custom_border.format = VK_FORMAT_UNDEFINED; sampler_info.borderColor = entry.is_int ? VK_BORDER_COLOR_INT_CUSTOM_EXT : VK_BORDER_COLOR_FLOAT_CUSTOM_EXT; custom_border.pNext = sampler_info.pNext; sampler_info.pNext = &custom_border; } else { sampler_info.borderColor = is_int ? VK_BORDER_COLOR_INT_TRANSPARENT_BLACK : VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; log_once("custom sampler border colours without VK_EXT_custom_border_color; transparent black instead, index", int(sampler.border_color_index)); } } VkSampler vk_sampler = VK_NULL_HANDLE; if (!context->vk.vkCreateSampler || context->vk.vkCreateSampler(info.device, &sampler_info, nullptr, &vk_sampler) != VK_SUCCESS) return false; const std::uint32_t index = bindless->add_sampler(vk_sampler); if (!index) { log_once("the bindless sampler array is full; samplers", int(sampler_entries.size())); context->vk.vkDestroySampler(info.device, vk_sampler, nullptr); return false; } sampler_entries.emplace(key, SamplerEntry{vk_sampler, index}); bindless->insert_key(key, index); if (out_index) *out_index = index; return true; } // An optimal-tiling image of this format can take VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT. bool host_transfer_format(VkFormat format) const { if (!copy_memory_to_image || !format_properties2) return false; VkFormatProperties3 properties3{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; VkFormatProperties2 properties{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &properties3}; format_properties2(info.physical, format, &properties); return properties3.optimalTilingFeatures & VK_FORMAT_FEATURE_2_HOST_IMAGE_TRANSFER_BIT_EXT; } // A memory type with `required`, preferring one that also has `preferred`, in a heap large enough for the // allocation (leonida::memory_type_order). `chosen`, when given, receives the property flags of the type the // memory came from. // Held around every vkAllocateMemory of this device, host-pointer imports included (see allocate). static std::mutex& memory_mutex() { static std::mutex mutex; return mutex; } VkDeviceMemory allocate(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred, VkMemoryPropertyFlags* chosen = nullptr, bool device_address = false, std::uint32_t* chosen_type = nullptr, VkImage dedicated_image = VK_NULL_HANDLE) const { VkMemoryAllocateFlagsInfo flags_info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; flags_info.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; for (const std::uint32_t i : leonida::memory_type_order(memory, requirements.memoryTypeBits, required, preferred, requirements.size)) { VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; if (device_address) allocate.pNext = &flags_info; VkMemoryDedicatedAllocateInfo dedicated{VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO}; if (dedicated_image) { dedicated.image = dedicated_image; dedicated.pNext = allocate.pNext; allocate.pNext = &dedicated; } allocate.allocationSize = requirements.size; allocate.memoryTypeIndex = i; VkDeviceMemory out = VK_NULL_HANDLE; // The NVIDIA driver (620.73 under Wine) answers VK_ERROR_OUT_OF_HOST_MEMORY for a few-KiB allocation now // and then while other threads import host pointers that the kernel module cannot pin (journal: "Cannot // map memory with base addr ..."), with gigabytes free. The title asserts on the texture it loses. So // allocations and imports take turns (memory_mutex), and that answer is retried before it is believed. // // The retries are only worth their sleeps while some of them succeed: after the load a title placement // that fails this way failed every retry (speed-25/26: none recovered), and each failing memory type cost // the caller 15 ms of Sleep (the title's Subrender workers, slot 133), before the next type succeeded. So // while fewer than one in 16 of the recent retried allocations recovered (both counts are halved every 64 // retried allocations, so one recovery at boot does not keep them on), one attempt per type is made; one // failure in 64 still retries, to notice when they help again. static std::atomic retried{0}, recovered_total{0}, failures{0}; const std::uint32_t recent = retried.load(std::memory_order_relaxed); const bool retry = recent < 32 || recovered_total.load(std::memory_order_relaxed) * 16 >= recent || failures.load(std::memory_order_relaxed) % 64 == 0; VkResult allocated = VK_ERROR_OUT_OF_HOST_MEMORY; for (int attempt = 0; attempt < (retry ? 6 : 1) && allocated == VK_ERROR_OUT_OF_HOST_MEMORY; ++attempt) { if (attempt) Sleep(attempt); std::lock_guard serial(memory_mutex()); allocated = context->vk.vkAllocateMemory(info.device, &allocate, nullptr, &out); if (attempt == 1 && retried.fetch_add(1, std::memory_order_relaxed) + 1 >= 64) { retried.store(32, std::memory_order_relaxed); // halve both (racy, approximate is enough) recovered_total.store(recovered_total.load(std::memory_order_relaxed) / 2, std::memory_order_relaxed); } if (attempt && allocated == VK_SUCCESS) { recovered_total.fetch_add(1, std::memory_order_relaxed); static std::atomic recovered{0}; if (recovered.fetch_add(1, std::memory_order_relaxed) < 8) std::fprintf(stderr, "[rt] d3d12: vkAllocateMemory succeeded on retry %d after out-of-host-memory (%llu " "bytes, type %u)\n", attempt, static_cast(requirements.size), i); } } if (allocated == VK_ERROR_OUT_OF_HOST_MEMORY) failures.fetch_add(1, std::memory_order_relaxed); if (allocated != VK_SUCCESS) { static std::atomic logged{0}; if (logged.fetch_add(1, std::memory_order_relaxed) < 16) std::fprintf(stderr, "[rt] d3d12: vkAllocateMemory failed (%d): %llu bytes, memory type %u (flags 0x%x, heap " "%u of %llu MiB), device address %d\n", int(allocated), static_cast(requirements.size), i, unsigned(memory.memoryTypes[i].propertyFlags), memory.memoryTypes[i].heapIndex, static_cast(memory.memoryHeaps[memory.memoryTypes[i].heapIndex].size >> 20), int(device_address)); } if (allocated == VK_SUCCESS) { if (chosen) *chosen = memory.memoryTypes[i].propertyFlags; if (chosen_type) *chosen_type = i; if (leonida::spilled_to_host(required, preferred, memory.memoryTypes[i].propertyFlags)) std::call_once(spill_logged, [&] { const std::uint32_t heap = memory.memoryTypes[i].heapIndex; std::fprintf(stderr, "[rt] d3d12: a %llu-byte allocation did not fit in device-local memory and went " "to memory type %u (heap %u, %llu MiB); later ones are not logged\n", static_cast(requirements.size), i, heap, static_cast(memory.memoryHeaps[heap].size >> 20)); }); return out; } } return VK_NULL_HANDLE; } // A range of a device-local block for a texture, or null: the texture is too large to share one, or device-local // memory has no room for another block, and the caller makes its own allocation as it would without the blocks. std::unique_ptr allocate_image(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags& chosen) { for (const std::uint32_t i : leonida::memory_type_order(memory, requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, requirements.size)) { const VkDeviceSize block = leonida::image_block_bytes(memory.memoryHeaps[memory.memoryTypes[i].heapIndex].size); if (requirements.size > block / 8) continue; if (auto range = image_memory->allocate(i, requirements.size, requirements.alignment, block)) { chosen = memory.memoryTypes[i].propertyFlags; return range; } } return nullptr; } }; // TitleBufferWindows::system_memory_types reads the memory types through these (LEONIDA_GEOMETRY_HOST): without them // it would leave every type allowed, the BAR included. static_assert(requires(const DeviceState& d) { d.memory.memoryTypes[0].propertyFlags; d.memory.memoryTypeCount; }); // The Vulkan format for a texture this layer can create, with the D24 fallback; VK_FORMAT_UNDEFINED, after a log // line, when it cannot. Committed and placed textures share it so both refuse the same formats for the same reason. Format texture_format(const DeviceState& device, const D3D12_RESOURCE_DESC& desc) { Format format = vulkan_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); if(format.format==VK_FORMAT_D16_UNORM_S8_UINT) {format.xbox_depth16_stencil8=true;format.format=device.depth_backing(format.format);return format;} if(desc.Format==DXGI_FORMAT_B4G4R4A4_UNORM && (desc.Flags&D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && !device.color_attachment_usable(format.format)) { if(!device.color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM))return {}; format.format=VK_FORMAT_R8G8B8A8_UNORM;format.rgba4_render_fallback=true; } if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !device.depth_usable(format.format)) { log_once("D24_UNORM_S8_UINT unavailable, using D32_SFLOAT_S8_UINT; format", desc.Format); format.format = VK_FORMAT_D32_SFLOAT_S8_UINT; } if (format.format == VK_FORMAT_UNDEFINED) log_once("texture format not supported yet:", desc.Format); return format; } // The castable-format list a committed or placed texture was created with, mapped to Vulkan (D3D-85's committed // path, D3D-90's placed one). Each format must map and be the same texel size as the resource's: the host PC // runtime refuses other sizes, and a size-mismatched VkImageFormatListCreateInfo is a Vulkan validation error // (VUID-VkImageCreateInfo-pNext-06722). A nonzero count with a null list is no list. E_INVALIDARG on a bad format. // An A8_UNORM texture's own format is always viewable (create_texture adds the image's format), so naming it is a // no-op. An A8 render target's VK_FORMAT_A8_UNORM_KHR image (Format::a8_as_alpha) is in a class of its own: no // other format can be a view format of it, so any other castable format is refused here, before Vulkan. HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, UINT32 count, const DXGI_FORMAT* castable, std::vector& out, bool depth_uav_planes = false, bool console_d16s8 = false) { if (!count || !castable) return S_OK; const bool depth = (format.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; const leonida::BlockFormat own = leonida::block_format(format.format, format.aspects); for (UINT32 i = 0; i < count; ++i) { if (resource_format == DXGI_FORMAT_A8_UNORM && castable[i] == DXGI_FORMAT_A8_UNORM) continue; if (format.a8_as_alpha) { log_once("castable format of an A8_UNORM render target not supported (only A8_UNORM is):", castable[i]); return E_INVALIDARG; } if (depth_uav_planes) { // Attachment and sampled views use the original depth image's VkFormat. Each typed UAV // already has its own image; putting its colour format on the depth image is invalid. const DXGI_FORMAT view = castable[i]; const bool valid = format.format == VK_FORMAT_D16_UNORM ? view == DXGI_FORMAT_R16_TYPELESS || view == DXGI_FORMAT_D16_UNORM || view == DXGI_FORMAT_R16_UNORM || view == DXGI_FORMAT_R16_UINT : (format.xbox_depth16_stencil8 || console_d16s8) ? view == xbox_d16s8 || view == xbox_d16_plane || view == xbox_s8_plane || (format.d24 && (view == DXGI_FORMAT_D24_UNORM_S8_UINT || view == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || view == DXGI_FORMAT_X24_TYPELESS_G8_UINT)) || view == DXGI_FORMAT_R16_TYPELESS || view == DXGI_FORMAT_R16_UNORM || view == DXGI_FORMAT_R16_UINT || view == DXGI_FORMAT_R8_UINT : view == DXGI_FORMAT_R32G8X24_TYPELESS || view == DXGI_FORMAT_D32_FLOAT_S8X24_UINT || view == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS || view == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT || view == DXGI_FORMAT_R32_FLOAT || view == DXGI_FORMAT_R8_UINT; if (!valid) return E_INVALIDARG; continue; } const Format cast = vulkan_format(castable[i], depth); if (cast.format == VK_FORMAT_UNDEFINED) { log_once("castable format not supported yet:", castable[i]); return E_INVALIDARG; } const leonida::BlockFormat block = leonida::block_format(cast.format, cast.aspects); if (own.bytes && block.bytes && (block.bytes != own.bytes || block.block != own.block)) { log_once("castable format is a different texel size than the resource:", castable[i]); return E_INVALIDARG; } if (std::find(out.begin(), out.end(), cast.format) == out.end()) out.push_back(cast.format); } return S_OK; } // Argument checks the host PC runtime makes (without the debug layer) before it creates anything, so the layer // returns the same HRESULTs. Each rule was measured against the host runtime by d3d12_vulkan_device_test // (compare_invalid_arguments, D3D-49); the texture size, mip, sample-count and alignment rules are in // GetResourceAllocationInfo's allocation(), which CreateCommittedResource also applies. // The typeless format a DXGI format can be cast within, or the format itself when it has no such family. DXGI_FORMAT format_family(DXGI_FORMAT format) { if (format==xbox_d16s8 || format==xbox_d16_plane || format==xbox_s8_plane) return xbox_d16s8; const int f = int(format); const auto in = [f](int first, int last) { return f >= first && f <= last; }; if (in(1, 4)) return DXGI_FORMAT_R32G32B32A32_TYPELESS; if (in(5, 8)) return DXGI_FORMAT_R32G32B32_TYPELESS; if (in(9, 14)) return DXGI_FORMAT_R16G16B16A16_TYPELESS; if (in(15, 18)) return DXGI_FORMAT_R32G32_TYPELESS; if (in(19, 22)) return DXGI_FORMAT_R32G8X24_TYPELESS; if (in(23, 25)) return DXGI_FORMAT_R10G10B10A2_TYPELESS; if (in(27, 32)) return DXGI_FORMAT_R8G8B8A8_TYPELESS; if (in(33, 38)) return DXGI_FORMAT_R16G16_TYPELESS; if (in(39, 43)) return DXGI_FORMAT_R32_TYPELESS; if (in(44, 47)) return DXGI_FORMAT_R24G8_TYPELESS; if (in(48, 52)) return DXGI_FORMAT_R8G8_TYPELESS; if (in(53, 59)) return DXGI_FORMAT_R16_TYPELESS; if (in(60, 64)) return DXGI_FORMAT_R8_TYPELESS; if (in(70, 72)) return DXGI_FORMAT_BC1_TYPELESS; if (in(73, 75)) return DXGI_FORMAT_BC2_TYPELESS; if (in(76, 78)) return DXGI_FORMAT_BC3_TYPELESS; if (in(79, 81)) return DXGI_FORMAT_BC4_TYPELESS; if (in(82, 84)) return DXGI_FORMAT_BC5_TYPELESS; if (f == 87 || in(90, 91)) return DXGI_FORMAT_B8G8R8A8_TYPELESS; if (f == 88 || in(92, 93)) return DXGI_FORMAT_B8G8R8X8_TYPELESS; if (in(94, 96)) return DXGI_FORMAT_BC6H_TYPELESS; if (in(97, 99)) return DXGI_FORMAT_BC7_TYPELESS; return format; } // ALLOW_DEPTH_STENCIL: the host accepts every format of a family with a depth member (R32_FLOAT and R16_FLOAT // included) and nothing else. bool depth_stencil_family(DXGI_FORMAT format) { // The console's own D16S8 family (DXGI 118-120) counts as the D24S8 family it is made of here (pc_format). if (format_family(format) == xbox_d16s8) return true; const DXGI_FORMAT family = format_family(pc_format(format)); return family == DXGI_FORMAT_R32_TYPELESS || family == DXGI_FORMAT_R16_TYPELESS || family == DXGI_FORMAT_R24G8_TYPELESS || family == DXGI_FORMAT_R32G8X24_TYPELESS; } // ALLOW_RENDER_TARGET: the host refuses the families below and accepts the rest, D32_FLOAT, D16_UNORM, // R9G9B9E5_SHAREDEXP and NV12 among them. R32G32B32 is the driver's answer (refused by both AMD drivers measured, // accepted by WARP); it is refused here, since Vulkan drivers rarely render to it. bool render_target_family(DXGI_FORMAT format) { switch (format_family(format)) { case DXGI_FORMAT_R32G32B32_TYPELESS: case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_R24G8_TYPELESS: case DXGI_FORMAT_R1_UNORM: case DXGI_FORMAT_R8G8_B8G8_UNORM: case DXGI_FORMAT_G8R8_G8B8_UNORM: case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC6H_TYPELESS: case DXGI_FORMAT_BC7_TYPELESS: return false; default: return true; } } // Why the host would refuse these heap properties, or null if it accepts them. `uma` is the device's // D3D12_FEATURE_ARCHITECTURE answer: a UMA adapter has no MEMORY_POOL_L1, and the host refuses a custom heap in it // (measured on a Radeon 780M, AMD 32.0.13030.13001, and on WARP: E_INVALIDARG from CreateHeap and // CreateCommittedResource for every CPU page property). const char* heap_properties_refusal(const D3D12_HEAP_PROPERTIES& heap, bool uma) { if (heap.Type < D3D12_HEAP_TYPE_DEFAULT || heap.Type > D3D12_HEAP_TYPE_GPU_UPLOAD) return "heap type"; // CheckFeatureSupport reports OPTIONS16.GPUUploadHeapSupported FALSE, and a host runtime without GPU upload heaps // (Resizable BAR off) refuses the type. if (heap.Type == D3D12_HEAP_TYPE_GPU_UPLOAD) return "GPU upload heap, which OPTIONS16 reports unsupported"; const bool custom = heap.Type == D3D12_HEAP_TYPE_CUSTOM; const bool page_given = heap.CPUPageProperty != D3D12_CPU_PAGE_PROPERTY_UNKNOWN; const bool pool_given = heap.MemoryPoolPreference != D3D12_MEMORY_POOL_UNKNOWN; if (custom ? !(page_given && pool_given) : (page_given || pool_given)) return "CPU page property or memory pool (given only, and both, on custom heaps)"; if (heap.CreationNodeMask > 1 || heap.VisibleNodeMask > 1) return "node mask (one node)"; if (uma && custom && heap.MemoryPoolPreference == D3D12_MEMORY_POOL_L1) return "MEMORY_POOL_L1 on a UMA adapter"; return nullptr; } // Why the host would refuse this CreateHeap description, or null if these checks pass (D3D-238). A probe on an // RX 5700 and WARP refuses an alignment other than 0, 64 KiB and 4 MiB, the heap properties above (a type of 0, a // custom heap without a CPU page property), and a heap that denies buffers and both kinds of texture. ALLOW_DISPLAY // (CreateCommittedResource on a default heap only, per the D3D12_HEAP_FLAGS documentation) is refused too, confirmed // on an RTX 4070 SUPER and a UHD 770 host by @CowBoYdu76. Those hosts accept HARDWARE_PROTECTED, so it is not refused. const char* heap_desc_refusal(const D3D12_HEAP_DESC& desc, bool uma) { if (!desc.SizeInBytes) return "zero size"; if (desc.Alignment && desc.Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT && desc.Alignment != D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT) return "alignment (0, 64 KiB or 4 MiB)"; if (const char* why = heap_properties_refusal(desc.Properties, uma)) return why; constexpr UINT deny_all = D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES; if ((UINT(desc.Flags) & deny_all) == deny_all) return "heap flags denying every resource kind"; if (UINT(desc.Flags) & D3D12_HEAP_FLAG_ALLOW_DISPLAY) return "ALLOW_DISPLAY (committed resources only)"; return nullptr; } // Why the host would refuse this committed resource, or null if these checks pass. The flag and format tables were // measured on an RX 9070 XT, an integrated Radeon and WARP, which agree on all of them. Cross-adapter resources // (valid there only as a row-major texture on a SHARED | SHARED_CROSS_ADAPTER heap) are refused: this layer has no // cross-adapter sharing. // The initial state a committed, placed or reserved resource may start in, as the host runtime answers it // (d3d12_vulkan_device_test's compare_placed_reserved and its "committed: ... state" cases, RTX 3060 / 610.88). // A buffer takes any bits, unknown ones too, except RAYTRACING_ACCELERATION_STRUCTURE without UAV access, or at all // on a device without acceleration structures (the host refuses it where OPTIONS5 reports no ray tracing: an // integrated Radeon, measured by @aguedou-34 on #2462; here, a device with neither the KHR acceleration structures // nor the XDXR builds). A texture // takes exactly GENERIC_READ, or one write state alone (RENDER_TARGET, UNORDERED_ACCESS and DEPTH_WRITE need the // matching resource flag), or any mix of read states (DEPTH_READ needs ALLOW_DEPTH_STENCIL; the shader-resource // states are refused with DENY_SHADER_RESOURCE). The buffer-only bits (vertex/constant, index, indirect, stream // output, acceleration structure) and undefined bits are refused on a texture, also inside a mix. const char* initial_state_refusal(bool buffer, UINT flags, D3D12_RESOURCE_STATES state, bool acceleration_structures) { const UINT s = UINT(state); if (buffer) { if ((s & D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE) && !acceleration_structures) return "acceleration-structure state on a device without acceleration structures"; if ((s & D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE) && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return "acceleration-structure state on a buffer without UAV access"; return nullptr; } if (s == D3D12_RESOURCE_STATE_GENERIC_READ) return nullptr; constexpr UINT writes = D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_UNORDERED_ACCESS | D3D12_RESOURCE_STATE_DEPTH_WRITE | D3D12_RESOURCE_STATE_COPY_DEST | D3D12_RESOURCE_STATE_RESOLVE_DEST | D3D12_RESOURCE_STATE_VIDEO_DECODE_WRITE | D3D12_RESOURCE_STATE_VIDEO_PROCESS_WRITE | D3D12_RESOURCE_STATE_VIDEO_ENCODE_WRITE; constexpr UINT shader_reads = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; constexpr UINT reads = D3D12_RESOURCE_STATE_DEPTH_READ | shader_reads | D3D12_RESOURCE_STATE_COPY_SOURCE | D3D12_RESOURCE_STATE_RESOLVE_SOURCE | D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE | D3D12_RESOURCE_STATE_VIDEO_DECODE_READ | D3D12_RESOURCE_STATE_VIDEO_PROCESS_READ | D3D12_RESOURCE_STATE_VIDEO_ENCODE_READ; if (s & ~(writes | reads)) return "initial state of a texture (buffer-only or undefined bits)"; if (s & writes) { if (s & (s - 1)) return "initial state of a texture (a write state with another state)"; if (s == D3D12_RESOURCE_STATE_RENDER_TARGET && !(flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) return "RENDER_TARGET state without ALLOW_RENDER_TARGET"; if (s == D3D12_RESOURCE_STATE_UNORDERED_ACCESS && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return "UNORDERED_ACCESS state without ALLOW_UNORDERED_ACCESS"; if (s == D3D12_RESOURCE_STATE_DEPTH_WRITE && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) return "DEPTH_WRITE state without ALLOW_DEPTH_STENCIL"; return nullptr; } if ((s & D3D12_RESOURCE_STATE_DEPTH_READ) && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) return "DEPTH_READ state without ALLOW_DEPTH_STENCIL"; if ((s & shader_reads) && (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) return "shader-resource state with DENY_SHADER_RESOURCE"; return nullptr; } const char* committed_resource_refusal(const D3D12_HEAP_PROPERTIES& heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, bool acceleration_structures, bool uma) { if (const char* why = heap_properties_refusal(heap, uma)) return why; // The DENY flags of a committed resource's heap are the runtime's to choose; most other bits are refused too. constexpr UINT committed_heap_flags = D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_ALLOW_DISPLAY | D3D12_HEAP_FLAG_HARDWARE_PROTECTED | D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT | D3D12_HEAP_FLAG_CREATE_NOT_ZEROED | D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; if (UINT(heap_flags) & ~committed_heap_flags) return "heap flags of a committed resource"; const bool buffer = desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER; // 0x400 is not in this SDK's d3d12.h (10.0.26100), but the host accepts it on buffers and textures; 0x200 and // 0x800 it refuses. RAYTRACING_ACCELERATION_STRUCTURE is accepted on a texture too. constexpr UINT buffer_flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE | D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE | 0x400; constexpr UINT texture_flags = buffer_flags | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS; const UINT flags = UINT(desc.Flags); if (flags & ~(buffer ? buffer_flags : texture_flags)) return "resource flags"; const bool rt = flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; const bool ds = flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; const bool uav = flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; // ALLOW_SHADER_ATOMICS is for a resource shaders can write: RTX 4070 Laptop (621.24) and WARP refuse it without // ALLOW_UNORDERED_ACCESS, on buffers and textures alike. It changes nothing on one adapter; GetHeapProperties keeps it. if ((UINT(heap_flags) & D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS) && !uav) return "ALLOW_SHADER_ATOMICS without ALLOW_UNORDERED_ACCESS"; // Upload heaps start in (a part of) GENERIC_READ, readback heaps in COPY_DEST; COMMON on both; no UAVs. if (heap.Type == D3D12_HEAP_TYPE_UPLOAD && (uav || (UINT(state) & ~UINT(D3D12_RESOURCE_STATE_GENERIC_READ)))) return "upload heap state or UAV"; if (heap.Type == D3D12_HEAP_TYPE_READBACK && (uav || (UINT(state) & ~UINT(D3D12_RESOURCE_STATE_COPY_DEST)))) return "readback heap state or UAV"; if (const char* why = initial_state_refusal(buffer, flags, state, acceleration_structures)) return why; if (buffer) { if (!desc.Width || desc.Height != 1 || desc.DepthOrArraySize != 1 || desc.MipLevels != 1 || desc.Format != DXGI_FORMAT_UNKNOWN || desc.SampleDesc.Count != 1 || desc.SampleDesc.Quality != 0 || desc.Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return "buffer description"; if (desc.Alignment && desc.Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) return "buffer alignment"; if (clear) return "clear value on a buffer"; if (heap_flags & D3D12_HEAP_FLAG_ALLOW_DISPLAY) return "display heap for a buffer"; return nullptr; } if (desc.Dimension < D3D12_RESOURCE_DIMENSION_TEXTURE1D || desc.Dimension > D3D12_RESOURCE_DIMENSION_TEXTURE3D) return "resource dimension"; if ((rt && ds) || (ds && uav) || ((flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && !ds)) { return "resource flag combination"; } if (ds && !depth_stencil_family(desc.Format)) return "depth-stencil format"; if (rt && !render_target_family(desc.Format)) return "render-target format"; const UINT samples = desc.SampleDesc.Count; if (samples > 1 && !rt && !ds) return "multisampled texture that is not a render target or depth buffer"; // Every adapter measured reports one quality level; the two standard patterns are accepted too. They are spelled // with the DXGI names: D3D12_STANDARD/CENTER_MULTISAMPLE_PATTERN, the same values, are only in d3d12.h from // DirectX-Headers 1.613 on, and older Windows SDK 10.0.26100 headers lack them. if (samples > 1 && desc.SampleDesc.Quality && desc.SampleDesc.Quality != DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN && desc.SampleDesc.Quality != DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN) return "sample quality"; // A clear value is only for render targets and depth buffers, in the resource's format family. if (clear && (!(rt || ds) || clear->Format == DXGI_FORMAT_UNKNOWN || format_family(clear->Format) != format_family(desc.Format))) return "clear value"; return nullptr; } // Why the host refuses this enhanced-barrier initial layout for `desc`, or null when valid (measured on Windows D3D12). const char* barrier_layout_refusal(const D3D12_RESOURCE_DESC& desc, D3D12_BARRIER_LAYOUT layout) { if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return layout == D3D12_BARRIER_LAYOUT_UNDEFINED ? nullptr : "buffer barrier layout"; const UINT flags = UINT(desc.Flags); switch (layout) { case D3D12_BARRIER_LAYOUT_RENDER_TARGET: return (flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) ? nullptr : "RENDER_TARGET barrier layout"; case D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS: case D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS: case D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS: return (flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) ? nullptr : "UNORDERED_ACCESS barrier layout"; case D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE: case D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ: return (flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) ? nullptr : "DEPTH_STENCIL barrier layout"; case D3D12_BARRIER_LAYOUT_SHADER_RESOURCE: case D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE: case D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE: return (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) ? "SHADER_RESOURCE barrier layout" : nullptr; default: return nullptr; } } // Console Xbox D3D12 CreateDescriptorHeap (device slot 14) passes the PC description followed by the heap address // and size, as measured in the retail boot (issue #313 comment 7107265058): a 16-byte PC D3D12_DESCRIPTOR_HEAP_DESC, // then address at +0x10 and size at +0x18. The title asserts GetCPUDescriptorHandleForHeapStart() == address. // Backing this range with title memory / section 3.3 aliasing is tracked separately; this path only satisfies the // observed ABI contract and must not be inferred from normal PC 16-byte CreateDescriptorHeap calls. // LOCAL DIAGNOSTIC (desc-probe): records what a descriptor write through our API left in a console-heap slot. struct ProbeApiWrite { DeviceState& state; SIZE_T ptr; UINT count; const char* what; ~ProbeApiWrite() { state.arena_mark_dirty_ptr(reinterpret_cast(ptr), std::size_t(count) * kDescriptorSize); state.probe_api(ptr, count, what); state.probe_view(what, ptr, count); } }; struct ArenaDirtySlot { DeviceState& state; SIZE_T ptr; UINT count = 1; ~ArenaDirtySlot() { state.arena_mark_dirty_ptr(reinterpret_cast(ptr), std::size_t(count) * kDescriptorSize); } }; struct ConsoleDescriptorHeapDesc { D3D12_DESCRIPTOR_HEAP_DESC desc{}; std::uint64_t address = 0; std::uint64_t size = 0; }; class DescriptorHeap final : public Child { public: // {4a7d2c90-5e1b-4f63-8c0a-91d3b6e2f417} static constexpr GUID kTag{0x4a7d2c90, 0x5e1b, 0x4f63, {0x8c, 0x0a, 0x91, 0xd3, 0xb6, 0xe2, 0xf4, 0x17}}; // A shader-visible heap lives in the GPU address arena: its CPU handles point at the arena's host mapping and // its GPU handle is the console VA, so the bytes the game or Create*View writes are what shaders load. Other // heaps (RTV, DSV, non-visible staging heaps) stay in host memory. // A shader-visible heap that the arena cannot hold is not created (ok() is false, E_OUTOFMEMORY), as a // default-heap buffer is not: in host memory its GPU handle would be 0, and every table would read VA 0. DescriptorHeap(DeviceState& device, const D3D12_DESCRIPTOR_HEAP_DESC& desc, std::uint64_t console_address = 0, std::uint64_t console_size = 0) : device_(device), desc_(desc), console_address_(console_address), console_size_(console_size), console_addressed_(console_address != 0) { const VkDeviceSize bytes = VkDeviceSize(desc_.NumDescriptors) * descriptor_increment(desc_.Type); if (console_addressed_) { // The retail boot checks GetCPUDescriptorHandleForHeapStart() == address, so the CPU handles are the // title's memory and the GPU handles its console VA. A shader-visible heap there is read by shaders from // an arena copy the device keeps up to date (DeviceState::add_console_heap). cpu_ = reinterpret_cast(static_cast(console_address_)); in_arena_ = false; if ((desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && console_heap_shadow_enabled()) shadowed_ = device.add_console_heap(console_address_, bytes, console_shader_va_, desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); if (!shadowed_ && (desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) log_once("descriptor heap uses console address/size, which no shader reads (no GPU view); type", int(desc_.Type)); if (desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && // LOCAL DIAGNOSTIC (desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) device.probe_add(console_address_, shadowed_ ? console_shader_va_ : console_address_, desc_.NumDescriptors, shadowed_); return; } if ((desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && device.arena_ready()) { // A bindless-sized resource heap (64Ki slots or more: what a shader indexes directly) is followed by null // slots, as a console heap's copy is (DeviceState::heap_guard_bytes); a smaller one, or one the arena has // no room for with them, is not. const VkDeviceSize guard = desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && desc_.NumDescriptors >= 65536 ? DeviceState::heap_guard_bytes() : 0; if (guard && device.arena_allocate(bytes + guard, 256, arena_offset_, DeviceState::arena_descriptor_heap)) { guard_ = guard; device.arena_guard_bytes.fetch_add(guard, std::memory_order_relaxed); } else if (!device.arena_allocate(bytes, 256, arena_offset_, DeviceState::arena_descriptor_heap)) { log_once("GPU address arena full (raise LEONIDA_ARENA_MB); shader-visible heap size in KiB:", int(std::min(bytes / 1024, INT_MAX))); return; } in_arena_ = true; cpu_ = device.arena_host(arena_offset_, bytes + guard_); std::memset(cpu_, 0, std::size_t(bytes + guard_)); device.arena_mark_dirty(arena_offset_, bytes + guard_); if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) { std::lock_guard lock(device.visible_heap_mutex); device.visible_heaps[arena_offset_] = {arena_offset_ + bytes, desc.Type}; } } else { storage_.reset(new std::byte[std::size_t(bytes)]()); cpu_ = reinterpret_cast(storage_.get()); } if (cpu_ && !(desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { std::lock_guard lock(device_.visible_heap_mutex); const auto begin = reinterpret_cast(cpu_); device_.cpu_view_heaps[begin] = begin + bytes; registered_cpu_views_ = true; } } ~DescriptorHeap() override { if (console_addressed_) device_.probe_remove(console_address_); // LOCAL DIAGNOSTIC if (shadowed_) device_.remove_console_heap(console_address_); if (registered_cpu_views_) { std::lock_guard lock(device_.visible_heap_mutex); device_.cpu_view_heaps.erase(reinterpret_cast(cpu_)); } if (in_arena_) { std::lock_guard lock(device_.visible_heap_mutex); device_.visible_heaps.erase(arena_offset_); } const VkDeviceSize bytes = VkDeviceSize(desc_.NumDescriptors) * descriptor_increment(desc_.Type); if (in_arena_ && desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { device_.forget_nulled_table_slots(arena_offset_, bytes); } if (in_arena_) device_.arena_release(arena_offset_, bytes + guard_, DeviceState::arena_descriptor_heap); if (guard_) device_.arena_guard_bytes.fetch_sub(guard_, std::memory_order_relaxed); } bool ok() const { return cpu_ != nullptr; } // A node mask of 0 reads back as the one node of a single adapter, as on the PC runtime (d3d12_node_mask_test). D3D12_DESCRIPTOR_HEAP_DESC STDMETHODCALLTYPE GetDesc() override { D3D12_DESCRIPTOR_HEAP_DESC desc = desc_; if (!desc.NodeMask) desc.NodeMask = 1; return desc; } D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE GetCPUDescriptorHandleForHeapStart() override { return {reinterpret_cast(cpu_)}; } D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE GetGPUDescriptorHandleForHeapStart() override { if (!(desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) return {0}; if (console_addressed_) return {static_cast(console_address_)}; if (!in_arena_) log_once("shader-visible heap without a GPU address arena; flags", int(desc_.Flags)); return {in_arena_ ? UINT64(arena_offset_) : 0}; } bool owns_mapped_span(SIZE_T start, SIZE_T bytes) const { return in_arena_ && start == reinterpret_cast(cpu_) && bytes == SIZE_T(desc_.NumDescriptors) * descriptor_increment(desc_.Type); } const D3D12_DESCRIPTOR_HEAP_DESC& raw_desc() const { return desc_; } // Where shaders read the heap: its arena copy for a console heap that has one (SetDescriptorHeaps' base). D3D12_GPU_VIRTUAL_ADDRESS gpu_base() const { if (shadowed_) return UINT64(console_shader_va_); if (console_addressed_) return static_cast(console_address_); return in_arena_ ? UINT64(arena_offset_) : 0; } private: DeviceState& device_; D3D12_DESCRIPTOR_HEAP_DESC desc_; bool registered_cpu_views_ = false; std::unique_ptr storage_; std::uint8_t* cpu_ = nullptr; VkDeviceSize arena_offset_ = 0; VkDeviceSize guard_ = 0; // null bytes after the heap in its arena range bool in_arena_ = false; std::uint64_t console_address_ = 0; std::uint64_t console_size_ = 0; bool console_addressed_ = false; bool shadowed_ = false; // a console heap shaders read at console_shader_va_ (DeviceState::add_console_heap) std::uint64_t console_shader_va_ = 0; }; // Only Xbox depth resources have an alternate storage image. Barriers for other COM objects // can look it up without dereferencing the pointer or calling into another implementation. std::mutex depth_storage_mutex; std::map depth_storage_images; std::atomic depth_storage_count{0}; constexpr bool xbox_depth_storage_desc(const D3D12_RESOURCE_DESC& desc) { const unsigned usages = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; return (unsigned(desc.Flags) & ~unsigned(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) == usages && (desc.Format == DXGI_FORMAT_R16_TYPELESS || desc.Format == DXGI_FORMAT_R32_TYPELESS) && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1 && desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN; } D3D12_RESOURCE_DESC depth_storage_part(D3D12_RESOURCE_DESC desc, bool colour) { desc.Flags = colour ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAGS(unsigned(desc.Flags) & ~unsigned(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); return desc; } class Resource final : public Child { public: static constexpr GUID kTag = rt::d3d12_xs::kVulkanResourceTag; Resource(DeviceState& device, const D3D12_RESOURCE_DESC& desc, const D3D12_HEAP_PROPERTIES& heap, D3D12_HEAP_FLAGS heap_flags) : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags) {} // A placed resource lives inside a heap's arena range: the heap owns the range, so only the console VA is kept // here and nothing goes back to the arena when this object dies. Resource(DeviceState& device, const D3D12_RESOURCE_DESC& desc, const D3D12_HEAP_PROPERTIES& heap, D3D12_HEAP_FLAGS heap_flags, VkDeviceSize placed_va) : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags), placed_(true), va_(placed_va) {} void adopt_depth_storage(Resource* colour) { storage_ = colour; std::lock_guard lock(depth_storage_mutex); depth_storage_images.emplace(this, XboxDepthStorage{colour->id(), desc_.MipLevels, desc_.DepthOrArraySize}); ++depth_storage_count; } const Resource* storage_image() const { return storage_; } ~Resource() override { { std::lock_guard guard(device_.mapped_texture_mutex); if (device_.mapped_textures.erase(this)) --device_.map_count; } if (deferred_attachment_) device_.retire_samples(this); if (title_image_registered_) { std::lock_guard lock(device_.title_image_mutex); auto [begin,end] = device_.title_images.equal_range(va_); for (auto it = begin; it != end; ++it) if (it->second == this) { device_.title_images.erase(it); break; } } if (storage_) { { std::lock_guard lock(depth_storage_mutex); depth_storage_images.erase(this); --depth_storage_count; } storage_->Release(); } if (title_texture_) device_.title_texture_gone(this, reinterpret_cast(title_address_)); if (indexed_bda_) device_.backing(indexed_bda_, desc_.Width, id(), false); if (aliased_) leonida::title_va_aliases().remove(va_, title_alias_); if (accel_) { device_.context->unregister_acceleration_structure(gpu_va_); if (buffer_va_ && buffer_va_ != gpu_va_) device_.context->unregister_acceleration_structure(buffer_va_); device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::acceleration_structure, accel_); } if (deferred_stream_) { std::lock_guard lock(device_.descriptor_mutex); device_.pending_image_keys.erase(image_); } if (image_address_) device_.forget_image_of(image_address_, this); device_.context->remove_resource(id()); // Before the memory goes to the deferred queue: no submission copies into it after this. if (shadow_) device_.remove_shadow(shadow_); if (shadow_ && !in_arena_ && !in_external_window_) device_.remove_copy_target(shadow_); if (host_import_) { // VK_EXT_external_memory_host needs the caller's pages to stay valid for the imported memory's whole // lifetime, and a title may free them right after releasing the resource. So the memory is not left to // the deferred queue (freed after the *next* submission retires): wait for what was submitted, then // free it now (found in review). device_.context->wait_retire_ticket(device_.context->submitted_retire_ticket()); auto& vk = device_.context->vk; if (buffer_) vk.vkDestroyBuffer(device_.info.device, buffer_, nullptr); if (memory_) { vk.vkFreeMemory(device_.info.device, memory_, nullptr); device_.host_imports.fetch_sub(1, std::memory_order_relaxed); } leonida::kernel_writes::release(std::exchange(host_pin_, 0)); buffer_ = VK_NULL_HANDLE; memory_ = VK_NULL_HANDLE; } if (in_arena_) device_.arena_release(arena_offset_, desc_.Width, shadow_ ? DeviceState::arena_window : DeviceState::arena_buffer); if (in_external_window_) device_.external_windows_release_deferred(arena_offset_, desc_.Width); if (heap_range_ && device_.arena.staged) { for (std::uint32_t refs = arena_map_refs_.exchange(0, std::memory_order_relaxed); refs > 0; --refs) device_.arena.staging.untrack_mapped(va_, desc_.Width); } if (pooled_image_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::pooled_title_image, pooled_image_.release()); else if (image_ && !sparse_image_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image, image_); if (buffer_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::buffer, buffer_); if (memory_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::device_memory, memory_); if (image_range_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_memory, image_range_.release()); } VkDeviceAddress indexed_bda_{}; void index_shader_backing(VkDeviceAddress address) { if (address) { device_.backing(address, desc_.Width, id(), true); indexed_bda_ = address; } } leonida::ResourceId id() const { return resource_id(this); } VkImage image() const { return deferred_attachment_ && !deferred_attachment_->ensure() ? VK_NULL_HANDLE : image_; } // A sampled placement can publish views of its shared, correctly sized zero image while its own image is unbound. VkImage descriptor_image() const { return shared_zero_ ? image_ : image(); } bool host_initialized_image() const { return host_transfer_; } bool unbound_attachment() const { return deferred_attachment_ && !deferred_attachment_->bound(); } VkDeviceSize image_backing_bytes() const { return unbound_attachment() ? 0 : image_backing_bytes_; } // A placed image whose memory waits for its first use (create_texture) gets it here. bool ensure_texture_bound() const { return !deferred_attachment_ || deferred_attachment_->ensure(); } VkImage bound_image() const { return descriptor_image(); } // A deferred placed image with no memory yet, other than one that shows the shared zero image meanwhile. bool deferrable_sample() const { return !shared_zero_ && unbound_attachment(); } bool sparse_image() const { return sparse_image_; } VkBuffer buffer() const { return buffer_; } const D3D12_RESOURCE_DESC& desc() const { return desc_; } bool rgba4_render_backing() const {return desc_.Format==DXGI_FORMAT_B4G4R4A4_UNORM && format_==VK_FORMAT_R8G8B8A8_UNORM;} VkFormat format() const { return format_; } // of the image bool has_view_format_list() const { return !view_formats_.empty(); } bool allows_view_format(VkFormat format) const { return view_formats_.empty() || format == format_ || std::find(view_formats_.begin(), view_formats_.end(), format) != view_formats_.end(); } // The castable-format list in DXGI formats, which the Vulkan list can't tell apart where two families share a // VkFormat: B8G8R8X8 and B8G8R8A8 are both BGRA8 images. void keep_castable_formats(UINT32 count, const DXGI_FORMAT* formats) { if (count && formats) castable_formats_.assign(formats, formats + count); } bool lists_castable_format(DXGI_FORMAT format) const { return std::find(castable_formats_.begin(), castable_formats_.end(), format) != castable_formats_.end(); } bool has_castable_formats() const { return !castable_formats_.empty(); } VkFormat uint_backed() const { return uint_backed_; } // Format::uint_backed bool a8_as_alpha() const { return a8_as_alpha_; } VkImageAspectFlags aspects() const { return aspects_; } bool rgb96() const { return rgb96_; } // a 96-bit texture in an RGBA32 image std::uint64_t image_address() const { return image_address_; } // what a T# names the texture by const Resource* depth_stencil_uav(UINT plane) const { return plane < storage_planes_.size() ? storage_planes_[plane].get() : nullptr; } VkMemoryPropertyFlags memory_flags() const { return unbound_attachment() ? 0 : memory_flags_; } // of its backing bool is_shadow() const { return shadow_ != nullptr; } // create_shadow_buffer: a copy of title pages const DeviceState& device_state() const { return device_; } void* title_address() const { return title_address_; } // place_at_title_address, or null bool replay_seen() const { return replay_seen_.load(std::memory_order_relaxed); } bool staged_title() const { return staged_title_; } // The image as the title upload writes it (TitleImageUpload::reserve, fill and commit). const leonida::ResourceBinding& title_binding() const { return binding_; } bool upload_staged_title(const rt::xg_xs::Texture& layout, const std::uint8_t* tiled, std::vector& columns, bool inspect, bool& nonzero, unsigned from = 0) { std::lock_guard lock(device_.title_upload_mutex); 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; } // Every descriptor of the texture (a D3D12 view, a slot-70 view, a T# the title wrote into a console heap) comes // here. The first one of a title texture tells the registry, which fills it from memory only from then on; a // finer min_mip than previously seen notifies the registry so active_span expands before the next draw. void note_shader_view(std::uint32_t min_mip = 0) const { const std::uint32_t prev_count = shader_views_.fetch_add(1, std::memory_order_relaxed); std::uint32_t prev_mip = min_shader_view_mip_.load(std::memory_order_relaxed); bool lowered = false; while (min_mip < prev_mip) { if (min_shader_view_mip_.compare_exchange_weak(prev_mip, min_mip, std::memory_order_acq_rel, std::memory_order_relaxed)) { lowered = (prev_mip != UINT32_MAX); break; } } if (title_address_) { if (!prev_count && title_texture_) device_.title_texture_named(reinterpret_cast(title_address_)); if (lowered || (!prev_count && title_texture_)) device_.title_texture_view_mip(reinterpret_cast(title_address_), min_mip); } } std::uint32_t shader_views() const { return shader_views_.load(std::memory_order_relaxed); } std::uint32_t min_shader_view_mip() const { return min_shader_view_mip_.load(std::memory_order_acquire); } bool host_transfer() const { return host_transfer_; } // The element a CPU copy moves (a 4x4 block for block-compressed formats), as WriteToSubresource takes it. leonida::BlockFormat copy_element() const { return leonida::copy_block_format(binding_, VK_IMAGE_ASPECT_COLOR_BIT); } // Default-heap buffers are ranges of the GPU address arena: console VA = offset, zeroed through the arena's host // mapping. Upload and readback buffers keep their own host memory; with buffer device addresses their console // VA is their device address minus heap_base, so a shader's heap_base + VA still lands on them (section 3.3). HRESULT create_buffer(D3D12_RESOURCE_STATES initial_state = D3D12_RESOURCE_STATE_COMMON) { auto& vk = device_.context->vk; // A buffer has at least one byte, and its size must survive alignment to 64 KiB without wrapping. if (!desc_.Width || desc_.Width > ~UINT64(0) - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) return E_INVALIDARG; const bool host = cpu_visible(); leonida::ResourceBinding binding{}; // a buffer: no image binding.size = desc_.Width; const bool use_arena = !host && device_.arena_ready(); if (use_arena && desc_.Width > device_.arena.size) return E_OUTOFMEMORY; // An otherwise valid committed buffer can outgrow the largest free slice. Give it its own // addressable VkBuffer below, so the title can still use its arena-relative GPU VA. if (use_arena && device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, arena_offset_, DeviceState::arena_buffer)) { in_arena_ = true; std::memset(device_.arena_host(arena_offset_, desc_.Width), 0, std::size_t(desc_.Width)); device_.arena_mark_dirty(arena_offset_, desc_.Width); va_ = arena_offset_; binding.va = va_; binding.buffer = device_.arena.buffer; binding.indirect_arguments = device_.arena.indirect_arguments; binding.buffer_offset = arena_offset_; // No host pointer: this is DEFAULT-heap arena memory the GPU may write, so its mapped bytes can be // stale. host_at() must not treat it as a CPU-written instance pointer list. // A default-heap AS resource is one of these ranges: a GENERIC acceleration structure covers it where // it sits. It is named by its device address (heap base + offset, as the driver reports it), as instance // descriptors and BuildRaytracingAccelerationStructure hand that address to the driver, not a console VA. if (device_.info.ray_tracing && initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE && vk.vkCreateAccelerationStructureKHR) { VkAccelerationStructureCreateInfoKHR asci{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR}; asci.buffer = device_.arena.buffer; asci.offset = arena_offset_; asci.size = desc_.Width; asci.type = VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR; if (vk.vkCreateAccelerationStructureKHR(device_.info.device, &asci, nullptr, &accel_) == VK_SUCCESS) { gpu_va_ = device_.arena.address + va_; // An instance names its BLAS by a value obtained from vkGetAccelerationStructureDeviceAddressKHR // (VUID-vkCmdBuildAccelerationStructuresKHR-pInfos-12281), so ask for it, as the committed path // below does. For GENERIC the spec only promises that these addresses keep the offsets between // the structures of one buffer; drivers return buffer address + offset (vkd3d-proton checks the // same). If one ever does not, the driver's address is the one instances must hold. if (vk.vkGetAccelerationStructureDeviceAddressKHR) { VkAccelerationStructureDeviceAddressInfoKHR dai{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR}; dai.accelerationStructure = accel_; const std::uint64_t as_va = vk.vkGetAccelerationStructureDeviceAddressKHR(device_.info.device, &dai); if (as_va && as_va != gpu_va_) { log_once("GENERIC acceleration structure address is not its buffer address + offset; " "arena offset in KiB:", int(arena_offset_ / 1024)); buffer_va_ = gpu_va_; gpu_va_ = as_va; } } device_.context->register_acceleration_structure(gpu_va_, accel_); if (buffer_va_ && buffer_va_ != gpu_va_) device_.context->register_acceleration_structure(buffer_va_, accel_); } } device_.context->add_resource(id(), binding); return S_OK; } if (use_arena) log_once("GPU address arena full; using a dedicated default buffer, size in KiB:", int(desc_.Width / 1024)); const bool addressable = device_.arena.buffer != VK_NULL_HANDLE; const bool need_bda = device_.info.buffer_device_address || device_.info.ray_tracing; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; // The indexed quad pass loads 16-bit indices from aligned 32-bit words. Keep the final word inside the // Vulkan buffer while the D3D resource and views still use desc_.Width. info.size = addressable || need_bda ? align_up(desc_.Width, sizeof(std::uint32_t)) : desc_.Width; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; if (addressable || need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; if (device_.info.ray_tracing) { info.usage |= VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; } device_.share(info); if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); // Readback buffers prefer cached memory, which the CPU reads quickly. Upload buffers prefer VRAM the CPU // writes through Resizable BAR, where the GPU reads them quickly (D3D-96); without it, system memory. VkMemoryPropertyFlags host_preferred = 0; if (heap_.Type == D3D12_HEAP_TYPE_READBACK) host_preferred = VK_MEMORY_PROPERTY_HOST_CACHED_BIT; if (heap_.Type == D3D12_HEAP_TYPE_UPLOAD && device_.upload_in_vram) host_preferred = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; leonida::memory_breakdown::Owner owner(host ? leonida::memory_breakdown::Consumer::upload : leonida::memory_breakdown::current_owner()); memory_ = host ? device_.allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, host_preferred, &memory_flags_, addressable || need_bda) : device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_, addressable || need_bda); if (!memory_ || vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS) return E_OUTOFMEMORY; if (addressable) { VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = buffer_; va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &address) - device_.arena.address; const char* name = heap_.Type == D3D12_HEAP_TYPE_READBACK ? "readback buffer" : "upload buffer"; device_.log_va(host ? name : "default buffer", va_, desc_.Width); } if (host) { if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS) return E_OUTOFMEMORY; std::memset(mapped_, 0, std::size_t(info.size)); // committed resources and private padding start zeroed } if (need_bda && vk.vkGetBufferDeviceAddress) { VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bda.buffer = buffer_; buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda); gpu_va_ = buffer_va_; } if (device_.info.ray_tracing && initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE && vk.vkCreateAccelerationStructureKHR && vk.vkGetAccelerationStructureDeviceAddressKHR) { VkAccelerationStructureCreateInfoKHR asci{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR}; asci.buffer = buffer_; asci.offset = 0; asci.size = desc_.Width; asci.type = VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR; if (vk.vkCreateAccelerationStructureKHR(device_.info.device, &asci, nullptr, &accel_) == VK_SUCCESS) { VkAccelerationStructureDeviceAddressInfoKHR dai{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR}; dai.accelerationStructure = accel_; const std::uint64_t as_va = vk.vkGetAccelerationStructureDeviceAddressKHR(device_.info.device, &dai); if (as_va) gpu_va_ = as_va; device_.context->register_acceleration_structure(gpu_va_, accel_); if (buffer_va_ && buffer_va_ != gpu_va_) device_.context->register_acceleration_structure(buffer_va_, accel_); } } binding.buffer = buffer_; binding.indirect_arguments = (info.usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) != 0; binding.size = desc_.Width; binding.host = cpu_writable() ? static_cast(mapped_) : nullptr; binding.host_readable = (heap_.Type == D3D12_HEAP_TYPE_READBACK || (heap_.Type == D3D12_HEAP_TYPE_CUSTOM && heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK)); binding.va = va_; index_shader_backing(addressable ? device_.arena.address + va_ : buffer_va_); device_.context->add_resource(id(), binding); // Committed resources start zeroed unless the heap says otherwise; the host cannot reach device-local memory, // so the next submission fills it (D3D-71). if (!host && !(heap_flags_ & D3D12_HEAP_FLAG_CREATE_NOT_ZEROED)) device_.context->zero_on_next_submit(id(), buffer_); return S_OK; } // A buffer on the caller's own pages (Xbox device slot 133, create_buffer_at_host_address): `address` is imported // with VK_EXT_external_memory_host and the buffer bound to it at offset 0, so the CPU's writes there are the GPU's // reads with no copy. Its console VA is `address` itself, the VA the title chose, so vertex, index and immediate // writes the title names by that VA find this buffer (VulkanContext::buffer_at). A shader that adds heap_base to // that VA would not reach it, so the root views and V#s the layer writes for it name its device address minus // heap_base instead (alias_title_va, docs/d3d12_vulkan.md section 3.3 "Title-placed buffers"); V#s the title // writes into memory itself keep its VA. The pages stay the caller's: nothing is zeroed. HRESULT create_host_buffer(void* address) { // LEONIDA_SLOT133_IMPORT=0 (diagnostic): no title-placed buffer is imported; each takes the shadow fallback, // so no GPU store can reach title memory through an import. static const bool no_import = [] { const char* v = std::getenv("LEONIDA_SLOT133_IMPORT"); return v && std::strcmp(v, "0") == 0; }(); if (no_import) return E_NOTIMPL; auto& vk = device_.context->vk; const VkDeviceSize alignment = device_.info.host_pointer_alignment; if (!device_.get_host_pointer_properties || !alignment) return E_NOTIMPL; const auto start = reinterpret_cast(address); if (start & 3) return E_NOTIMPL; // byte-unaligned copies keep the ordinary-buffer fallback if (!address || !desc_.Width || alignment > UINT64_MAX / 2 || (alignment & (alignment - 1)) || desc_.Width > UINT64_MAX - 2 * alignment) return E_INVALIDARG; const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; // Keep the device-address word padding, and include the host page prefix in the backing buffer. const VkDeviceSize backing_size = need_bda ? align_up(desc_.Width, sizeof(std::uint32_t)) : desc_.Width; // Bind at zero; replay and device addresses carry the logical buffer's prefix instead. const std::uintptr_t base = start & ~static_cast(alignment - 1); void* const base_address = reinterpret_cast(base); const VkDeviceSize offset = start - base; const VkDeviceSize bytes = align_up(offset + backing_size, alignment); // An imported buffer's VA is its host address, and it joins the same BufferVaIndex as default-heap buffers, // whose VAs are offsets in [0, arena size). A host range that reaches into that window (low host addresses, // as under Wine) would shadow arena buffers in the index's nearest-start lookup, so it takes the fallback // (found in review). if (start < device_.arena.size) { log_once("a title-placed buffer's host address overlaps the arena's VA window; not imported, size", int(desc_.Width > INT_MAX ? INT_MAX : desc_.Width)); return E_NOTIMPL; } // A GPU-only range with pages of its own (title_gpu_views::independently_mapped): queue slot 31 remaps them // there, and an import would keep the GPU on the old physical pages. The shadow, copied from the pages before // every submission, follows the remap. Declined before anything is made, so nothing is left behind. if (leonida::title_gpu_views::independently_mapped(start, desc_.Width)) { log_once("a title-placed buffer over a GPU-only range slot 31 maps by itself is not imported, size", int(desc_.Width > INT_MAX ? INT_MAX : desc_.Width)); return E_NOTIMPL; } // The whole imported range must be committed, possibly across several allocations (the retail buffer spans // three mapped windows); a page not committed yet (xmem commits on first touch) or a write-combined one (on // an RTX 5090 such an import succeeded but GPU reads returned wrong bytes, found in review) is not imported, // and the ordinary-buffer fallback answers instead. bool importable = true; for (VkDeviceSize at = 0; at < bytes;) { MEMORY_BASIC_INFORMATION region{}; // A page that is not writable right now (a shadow buffer's write watch on the same page, say) cannot be // pinned for the GPU: the kernel module refuses it, loudly, and the shadow answers anyway. if (!VirtualQuery(static_cast(base_address) + at, ®ion, sizeof(region)) || region.State != MEM_COMMIT || (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE | PAGE_GUARD)) || !(region.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE))) { importable = false; break; } const auto region_end = reinterpret_cast(region.BaseAddress) + region.RegionSize; at = region_end - base; } if (!importable) return E_NOTIMPL; VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external}; info.size = offset + backing_size; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; if (need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; device_.share(info); if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; // An import not used is destroyed here, not left to the destructor's deferred queue: there it outlived the // next submission while the shadow the caller makes instead over the same pages guarded them, and RADV // rejects every submission once a page under a live import is read-only (the CS is rejected, then // VK_ERROR_DEVICE_LOST: found and measured by NateWeav, #14). Nothing was submitted with it: the resource is // registered only on success. const auto decline = [&](HRESULT hr) { if (buffer_) vk.vkDestroyBuffer(device_.info.device, buffer_, nullptr); if (memory_) { vk.vkFreeMemory(device_.info.device, memory_, nullptr); device_.host_imports.fetch_sub(1, std::memory_order_relaxed); } leonida::kernel_writes::release(std::exchange(host_pin_, 0)); buffer_ = VK_NULL_HANDLE; memory_ = VK_NULL_HANDLE; buffer_va_ = gpu_va_ = 0; return hr; }; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; if (device_.get_host_pointer_properties(device_.info.device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, base_address, &host) != VK_SUCCESS) return decline(E_NOTIMPL); const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits; // The binding is at zero; requirements cover the prefix as part of the buffer. if (!types || requirements.size > bytes) return decline(E_NOTIMPL); VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; import.pHostPointer = base_address; VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; // The imported pages are pinned before the import and until its memory is freed, so the shadow trackers // and the geometry watch never make them read-only meanwhile (leonida::kernel_writes::hold). Taken first, // so no guard lands between the writability check above and the import. host_pin_ = leonida::kernel_writes::hold(base_address, std::size_t(bytes)); // Host-visible and coherent first, as the caller's pages are; then any type both the import and the // buffer take. for (const VkMemoryPropertyFlags want : {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), VkMemoryPropertyFlags(0)}) { for (std::uint32_t i = 0; i < device_.memory.memoryTypeCount && !memory_; ++i) { if (!(types & (1u << i)) || (device_.memory.memoryTypes[i].propertyFlags & want) != want) continue; VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, need_bda ? static_cast(&flags) : &import}; allocate.allocationSize = bytes; allocate.memoryTypeIndex = i; std::lock_guard serial(DeviceState::memory_mutex()); if (vk.vkAllocateMemory(device_.info.device, &allocate, nullptr, &memory_) == VK_SUCCESS) { memory_flags_ = device_.memory.memoryTypes[i].propertyFlags; device_.host_imports.fetch_add(1, std::memory_order_relaxed); } else { memory_ = VK_NULL_HANDLE; } } if (memory_) break; } if (!memory_) return decline(E_OUTOFMEMORY); if (vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS) return decline(E_OUTOFMEMORY); if (need_bda && vk.vkGetBufferDeviceAddress) { VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bda.buffer = buffer_; buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda); if (buffer_va_) buffer_va_ += offset; gpu_va_ = buffer_va_; } // An import the driver put below the arena cannot be named by a V#: the V# keeps 48 bits of (device address // - heap_base), which is negative there, and the translated shaders zero-extend it, so they read 2^48 above // the buffer (found natively by plaaasma-agent: garbage constants, or VK_ERROR_DEVICE_LOST; this machine // logs the same wrap). Such an import is not used: the shadow buffer in the arena answers, as when the // import is refused. LEONIDA_IMPORT_BELOW_ARENA=1 keeps the import (for a shader library whose programs // sign-extend the address). if (buffer_va_ && buffer_va_ < device_.arena.address && !import_below_arena()) { static std::atomic logged{0}; if (logged.fetch_add(1, std::memory_order_relaxed) < 8) std::fprintf(stderr, "[rt] d3d12: an import of title memory at %p (%llu bytes) landed below the arena (device " "address 0x%llx, arena 0x%llx): a shadow in the arena is used instead\n", address, static_cast(desc_.Width), static_cast(buffer_va_), static_cast(device_.arena.address)); return decline(E_NOTIMPL); } mapped_ = address; host_import_ = true; va_ = start; device_.log_va("title-placed buffer", va_, desc_.Width); { // Which title ranges a GPU store can reach through an import (the first 256, then every 256th). static std::atomic imports{0}; const std::uint64_t n = imports.fetch_add(1, std::memory_order_relaxed) + 1; if (n <= 256 || n % 256 == 0) std::fprintf(stderr, "[rt] d3d12: slot-133 import #%llu: title 0x%llx-0x%llx (%llu bytes), device " "address 0x%llx, flags 0x%x\n", static_cast(n), static_cast(start), static_cast(start + desc_.Width), static_cast(desc_.Width), static_cast(buffer_va_), unsigned(desc_.Flags)); } leonida::ResourceBinding binding{}; binding.buffer = buffer_; binding.indirect_arguments = (info.usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) != 0; binding.buffer_offset = offset; binding.size = desc_.Width; binding.host = static_cast(address); binding.host_readable = true; binding.va = va_; index_shader_backing(buffer_va_); device_.context->add_resource(id(), binding); // Shaders reach the imported pages by their device address (src/title_va_alias.h). if (buffer_va_) alias_title_va(buffer_va_ - device_.arena.address); return S_OK; } // Registers [va_, va_ + width) as reached by shaders at `shader_va` (src/title_va_alias.h): the root views and // buffer V#s the layer writes for an address in it get the matching address of the buffer's GPU copy. void alias_title_va(std::uint64_t shader_va) { if (!leonida::title_va_aliases().add(va_, desc_.Width, shader_va)) return; title_alias_ = shader_va; aliased_ = true; } // The fallback of create_host_buffer, for pages the driver will not import: write-combined or uncached ones (in // retail 74 MiB of the title's 182 MiB range), pages not committed yet, a device without // VK_EXT_external_memory_host, or a driver past its import budget (an RTX 3070 Ti answers // VK_ERROR_OUT_OF_DEVICE_MEMORY after about 64 MiB of imports). The buffer has its own host-visible memory, a // shadow of the title's pages, but keeps the title's VA as its console VA, so the descriptors and views the title // builds from that VA still find it (an ordinary buffer here had another VA and none of the data: slot 70 wrote // a null SRV and the UI draws sampled nothing). It is filled from the pages now, and before every submission // of command lists the pages the title wrote since are copied again (ShadowPages, DeviceState::refresh_shadows). // One way only: what the GPU writes to the shadow is NOT copied back to the title's pages, and the next copy of // a page overwrites it. A title that reads GPU output at `address` needs the import. // A buffer on title memory the page mirror holds (step C): bound to the mirror's chunk at heap_base + the title's // address, so the GPU reads and writes the pages' homes, every view of the same pages shares them, and the // per-submission shadow copy, its walk and its guards go. Its VA is the title's address; V#s and root views naming // it keep that address (heap_base + it is the chunk). The CPU's Map answers the title's pages, as an import does; // the GPU's writes go back to them after the submission (DeviceState::page_mirror_write_back). E_NOTIMPL when the // mirror is off or does not hold the range in one chunk: an import or a shadow then answers, as before. HRESULT create_mirror_buffer(void* address) { const auto start = reinterpret_cast(address); if (!address || !desc_.Width || desc_.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) return E_NOTIMPL; VkBuffer chunk = VK_NULL_HANDLE; VkDeviceSize offset = 0; if (!device_.page_mirror_chunk(start, desc_.Width, chunk, offset)) return E_NOTIMPL; mapped_ = address; va_ = start; buffer_va_ = gpu_va_ = device_.page_mirror_address(start); leonida::ResourceBinding binding{}; binding.buffer = chunk; binding.indirect_arguments = true; // the chunks carry every buffer usage (sparse_buffer_info) binding.buffer_offset = offset; binding.size = desc_.Width; binding.host = static_cast(address); binding.host_readable = true; binding.va = va_; device_.context->add_resource(id(), binding); return S_OK; } HRESULT create_shadow_buffer(void* address) { auto& vk = device_.context->vk; if (!address || !desc_.Width || desc_.Width > ~UINT64(0) - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) return E_INVALIDARG; const auto* pages = static_cast(address); // The shadow is a range of the GPU address arena when it fits there (docs/d3d12_vulkan.md section 3.3). // The title's VA is a user-mode Windows address far above 4 GiB, past the arena, so a shader's heap_base + VA would miss // any buffer of the layer's; the root views and V#s the layer writes for that VA name the arena offset // instead (src/title_va_alias.h), a VA below 4 GiB that a root view and a V#'s 48 bits both hold. The arena // is host-visible, so the per-submission copy writes it in place. if (device_.arena_ready() && device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, arena_offset_, DeviceState::arena_window)) { in_arena_ = true; shadow_ = device_.arena_host(arena_offset_, desc_.Width); device_.add_shadow(pages, shadow_, std::size_t(desc_.Width)); mapped_ = address; va_ = reinterpret_cast(address); buffer_va_ = gpu_va_ = device_.arena.address + arena_offset_; device_.log_va("title-placed buffer (arena shadow)", va_, desc_.Width); leonida::ResourceBinding binding{}; binding.buffer = device_.arena.buffer; binding.indirect_arguments = device_.arena.indirect_arguments; binding.buffer_offset = arena_offset_; binding.size = desc_.Width; binding.host = shadow_; binding.va = va_; device_.context->add_resource(id(), binding); alias_title_va(arena_offset_); return S_OK; } if (device_.arena_ready() && device_.external_windows.staged()) { VkDeviceSize ext_offset = 0; std::uint8_t* ext_mapped = nullptr; VkBuffer ext_buffer = VK_NULL_HANDLE; VkDeviceSize ext_buf_offset = 0; VkDeviceAddress ext_bda = 0; leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::windows); if (device_.external_windows_allocate(desc_.Width, ext_offset, ext_mapped, &ext_buffer, &ext_buf_offset, &ext_bda)) { in_external_window_ = true; arena_offset_ = ext_offset; shadow_ = ext_mapped; device_.add_shadow(pages, shadow_, std::size_t(desc_.Width)); mapped_ = address; va_ = reinterpret_cast(address); buffer_va_ = gpu_va_ = ext_bda; device_.log_va("title-placed buffer (VRAM slab shadow)", va_, desc_.Width); leonida::ResourceBinding binding{}; binding.buffer = ext_buffer; binding.indirect_arguments = true; binding.buffer_offset = ext_buf_offset; binding.size = desc_.Width; binding.host = shadow_; binding.va = va_; index_shader_backing(buffer_va_); device_.context->add_resource(id(), binding); alias_title_va(ext_offset); return S_OK; } } log_once("a title-placed shadow buffer does not fit the GPU address arena (raise LEONIDA_ARENA_MB), so it " "has its own memory; size in KiB:", int(desc_.Width / 1024)); const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = desc_.Width; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; if (need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; device_.share(info); if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); // As an upload buffer (D3D-96): the CPU writes it at every submission and the GPU reads it, so VRAM through // Resizable BAR where there is one, system memory otherwise. leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::windows); memory_ = device_.allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, device_.upload_in_vram ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : 0, &memory_flags_, need_bda); void* shadow = nullptr; if (!memory_ || vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS || vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &shadow) != VK_SUCCESS) return E_OUTOFMEMORY; shadow_ = static_cast(shadow); device_.add_copy_target(shadow_, std::size_t(desc_.Width), buffer_); // LEONIDA_SHADOW_GPU device_.add_shadow(pages, shadow_, std::size_t(desc_.Width)); // Map() answers the title's own pages, as the imported buffer does: a write to the shadow's memory would be // overwritten by the next copy. mapped_ = address; va_ = reinterpret_cast(address); if (need_bda && vk.vkGetBufferDeviceAddress) { VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bda.buffer = buffer_; buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda); gpu_va_ = buffer_va_; } device_.log_va("title-placed buffer (shadow)", va_, desc_.Width); leonida::ResourceBinding binding{}; binding.buffer = buffer_; binding.indirect_arguments = (info.usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) != 0; binding.size = desc_.Width; // CPU-side reads take the shadow, not the title's pages: it is as fresh as what the GPU reads and every byte // of it can be read, which the pages do not promise. Not host_readable: GPU writes are not handed back. binding.host = shadow_; binding.va = va_; index_shader_backing(buffer_va_); device_.context->add_resource(id(), binding); if (buffer_va_) alias_title_va(buffer_va_ - device_.arena.address); return S_OK; } HRESULT create_sparse_buffer() { constexpr std::uint64_t tile_bytes = leonida::tile_size_in_bytes; if (!desc_.Width || desc_.Width > UINT64_MAX - tile_bytes || desc_.SampleDesc.Count != 1 || desc_.SampleDesc.Quality != 0) return E_INVALIDARG; auto& vk = device_.context->vk; auto sparse = std::make_shared(device_.info.device, vk); sparse->tile_count = (desc_.Width + tile_bytes - 1) / tile_bytes; const auto info = device_.sparse_buffer_info(sparse->tile_count * tile_bytes); if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &sparse->buffer) != VK_SUCCESS) return E_OUTOFMEMORY; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(device_.info.device, sparse->buffer, &requirements); sparse->memory_types = requirements.memoryTypeBits; if (tile_bytes % requirements.alignment || !(sparse->memory_types & device_.sparse_buffer_memory_types)) return E_NOTIMPL; VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = sparse->buffer; va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &address) - device_.arena.address; leonida::ResourceBinding binding{}; binding.buffer = sparse->buffer; binding.indirect_arguments = (info.usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) != 0; binding.size = desc_.Width; binding.va = va_; index_shader_backing(va_ + device_.arena.address); binding.sparse_buffer = true; device_.context->add_sparse_resource(id(), binding, std::move(sparse)); return S_OK; } HRESULT create_sparse_image() { auto& vk = device_.context->vk; const auto format = device_.texture_format(desc_); TextureCreateInfo create(desc_, format, false, device_.sample_grid_1, device_.info.shader_image_int64_atomics); create.info.flags |= VK_IMAGE_CREATE_SPARSE_BINDING_BIT | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT | VK_IMAGE_CREATE_SPARSE_ALIASED_BIT; HRESULT support = device_.check_image_support(create.info); if (FAILED(support)) return support == E_INVALIDARG ? E_NOTIMPL : support; device_.share(create.info); auto sparse = std::make_shared(device_.info.device, vk); const auto result = vk.vkCreateImage(device_.info.device, &create.info, nullptr, &sparse->image); if (result == VK_ERROR_FORMAT_NOT_SUPPORTED) return E_NOTIMPL; if (result != VK_SUCCESS) return E_OUTOFMEMORY; VkMemoryRequirements requirements{}; vk.vkGetImageMemoryRequirements(device_.info.device, sparse->image, &requirements); if (requirements.alignment != leonida::tile_size_in_bytes || leonida::memory_type_order(device_.memory, requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, leonida::tile_size_in_bytes).empty()) return E_NOTIMPL; std::uint32_t count = 0; vk.vkGetImageSparseMemoryRequirements(device_.info.device, sparse->image, &count, nullptr); if (count != 1) return E_NOTIMPL; // exactly one color aspect, with no separately bound metadata VkSparseImageMemoryRequirements image_requirements{}; vk.vkGetImageSparseMemoryRequirements(device_.info.device, sparse->image, &count, &image_requirements); constexpr auto shape = leonida::element_tile_shape(false, 4); const auto& properties = image_requirements.formatProperties; const auto granularity = properties.imageGranularity; if (properties.aspectMask != VK_IMAGE_ASPECT_COLOR_BIT || granularity.width != shape.width || granularity.height != shape.height || granularity.depth != 1 || !image_requirements.imageMipTailFirstLod || image_requirements.imageMipTailSize) return E_NOTIMPL; sparse->image_extent = {create.info.extent.width, create.info.extent.height}; sparse->tile_count = (1 + (sparse->image_extent.width - 1) / shape.width) * std::uint64_t(1 + (sparse->image_extent.height - 1) / shape.height); sparse->memory_types = requirements.memoryTypeBits; image_ = sparse->image; sparse_image_ = true; format_ = format.format; aspects_ = format.aspects; image_address_ = device_.next_image_address.fetch_add(256); device_.note_image_address(image_address_, this); DeviceState::trace_image(image_address_, id(), "registered"); binding_.image = image_; binding_.format = format_; binding_.aspects = aspects_; binding_.width = sparse->image_extent.width; binding_.height = sparse->image_extent.height; // An unbound tile reads as zero. Keep the layout stable once the image can share memory with an alias. binding_.not_zeroed = true; binding_.simultaneous_access = true; binding_.sampled_in_general = true; device_.context->add_sparse_resource(id(), binding_, std::move(sparse)); return S_OK; } // A placed buffer is a range of the heap's arena memory: it has no VkBuffer of its own and its console VA is // where it sits in the arena. The arena is host-visible, so an upload or readback place maps that same range. HRESULT create_placed_buffer(std::shared_ptr heap_range) { if (!device_.arena_ready()) return E_OUTOFMEMORY; // Inside its heap's arena range, which is one allocation: one mapping. std::uint8_t* const host = device_.arena_host(va_, desc_.Width); if (!host) return E_OUTOFMEMORY; heap_range_ = std::move(heap_range); if (cpu_visible()) mapped_ = host; std::memset(host, 0, std::size_t(desc_.Width)); // a fresh place reads as zeroed device_.arena_mark_dirty(va_, desc_.Width); leonida::ResourceBinding binding{}; binding.size = desc_.Width; binding.buffer = device_.arena.buffer; binding.indirect_arguments = device_.arena.indirect_arguments; binding.buffer_offset = va_; binding.va = va_; binding.host = cpu_writable() ? host : nullptr; binding.host_readable = (heap_.Type == D3D12_HEAP_TYPE_READBACK || (heap_.Type == D3D12_HEAP_TYPE_CUSTOM && heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK)); device_.context->add_resource(id(), binding); return S_OK; } static VkFormat unorm_srgb_twin(VkFormat format) { switch (format) { case VK_FORMAT_R8G8B8A8_UNORM: return VK_FORMAT_R8G8B8A8_SRGB; case VK_FORMAT_R8G8B8A8_SRGB: return VK_FORMAT_R8G8B8A8_UNORM; case VK_FORMAT_B8G8R8A8_UNORM: return VK_FORMAT_B8G8R8A8_SRGB; case VK_FORMAT_B8G8R8A8_SRGB: return VK_FORMAT_B8G8R8A8_UNORM; case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: return VK_FORMAT_BC1_RGBA_SRGB_BLOCK; case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: return VK_FORMAT_BC1_RGBA_UNORM_BLOCK; case VK_FORMAT_BC1_RGB_UNORM_BLOCK: return VK_FORMAT_BC1_RGB_SRGB_BLOCK; case VK_FORMAT_BC1_RGB_SRGB_BLOCK: return VK_FORMAT_BC1_RGB_UNORM_BLOCK; case VK_FORMAT_BC2_UNORM_BLOCK: return VK_FORMAT_BC2_SRGB_BLOCK; case VK_FORMAT_BC2_SRGB_BLOCK: return VK_FORMAT_BC2_UNORM_BLOCK; case VK_FORMAT_BC3_UNORM_BLOCK: return VK_FORMAT_BC3_SRGB_BLOCK; case VK_FORMAT_BC3_SRGB_BLOCK: return VK_FORMAT_BC3_UNORM_BLOCK; case VK_FORMAT_BC7_UNORM_BLOCK: return VK_FORMAT_BC7_SRGB_BLOCK; case VK_FORMAT_BC7_SRGB_BLOCK: return VK_FORMAT_BC7_UNORM_BLOCK; default: return VK_FORMAT_UNDEFINED; } } HRESULT create_texture(const Format& format, const std::vector& asked_castable = {}, TitleImageOrigin origin = TitleImageOrigin::ordinary, bool allow_staged_title = true) { auto& vk = device_.context->vk; // The console lets a typed RGBA8/BGRA8 render target or a title-placed texture (slot 133, including BC1/2/3/7 // and RGBA8/BGRA8) take a view in its UNORM/sRGB twin without a castable list: the title renders its movie // frames through an R8G8B8A8_UNORM view of an R8G8B8A8_UNORM_SRGB target and views placed BC7_UNORM/SRGB // composites across their UNORM/sRGB twin. Creating the VkImage with its twin in VkImageFormatListCreateInfo // makes those views legal under Vulkan (VUID-VkImageViewCreateInfo-image-01762, console_format_stand_ins). std::vector castable = asked_castable; if (castable.empty() && !format.uint_backed && !format.typeless && console_format_stand_ins() && ((desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || origin == TitleImageOrigin::placed)) { const VkFormat twin = origin == TitleImageOrigin::placed ? unorm_srgb_twin(format.format) : (format.format == VK_FORMAT_R8G8B8A8_UNORM ? VK_FORMAT_R8G8B8A8_SRGB : format.format == VK_FORMAT_R8G8B8A8_SRGB ? VK_FORMAT_R8G8B8A8_UNORM : format.format == VK_FORMAT_B8G8R8A8_UNORM ? VK_FORMAT_B8G8R8A8_SRGB : format.format == VK_FORMAT_B8G8R8A8_SRGB ? VK_FORMAT_B8G8R8A8_UNORM : VK_FORMAT_UNDEFINED); if (twin != VK_FORMAT_UNDEFINED && desc_.Format != DXGI_FORMAT_B8G8R8X8_UNORM && desc_.Format != DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) castable = {format.format, twin}; } const bool volume = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const UINT depth = volume ? desc_.DepthOrArraySize : 1; const bool one_d = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; const UINT16 mips = full_mips(desc_.Width, desc_.Height, depth); if (desc_.MipLevels == 0) desc_.MipLevels = mips; if ((volume || one_d) && (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { const UINT extent_limit = volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE1D_U_DIMENSION; const UINT slice_limit = volume ? extent_limit : D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION; if (!desc_.Width || desc_.Width > extent_limit || !desc_.Height || desc_.Height > extent_limit || !desc_.DepthOrArraySize || desc_.DepthOrArraySize > slice_limit || desc_.MipLevels > mips) return E_INVALIDARG; } TextureCreateInfo create(desc_, format, device_.color_attachment_usable(format.format), device_.sample_grid_1, device_.info.shader_image_int64_atomics); VkImageCreateInfo& info = create.info; if (!castable.empty()) { // D3D12 always allows a view in the resource's own format, whether or not the castable list names // it. Vulkan requires every view format to be in the image's format list, so add it when missing. view_formats_ = castable; if (std::find(view_formats_.begin(), view_formats_.end(), format.format) == view_formats_.end()) view_formats_.push_back(format.format); if (format.uint_backed) { // An unsigned-backed UAV texture needs both its formats whatever the list names (TextureCreateInfo). for (VkFormat pair : {format.format, format.uint_backed}) if (std::find(view_formats_.begin(), view_formats_.end(), pair) == view_formats_.end()) view_formats_.push_back(pair); } if (device_.info.shader_image_int64_atomics && desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && info.samples == VK_SAMPLE_COUNT_1_BIT && (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && (is_r32g32_format(format.format) || std::any_of(view_formats_.begin(), view_formats_.end(), is_r32g32_format))) { if (std::find(view_formats_.begin(), view_formats_.end(), VK_FORMAT_R64_UINT) == view_formats_.end()) view_formats_.push_back(VK_FORMAT_R64_UINT); info.flags |= VK_IMAGE_CREATE_EXTENDED_USAGE_BIT; } info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; create.format_list.viewFormatCount = std::uint32_t(view_formats_.size()); create.format_list.pViewFormats = view_formats_.data(); // A uint-backed format already chained format_list in TextureCreateInfo: chaining it to itself would // make the pNext chain cyclic (found in review). if (info.pNext != &create.format_list) { create.format_list.pNext = info.pNext; info.pNext = &create.format_list; } } const std::uint32_t samples = info.samples; // Textures the CPU reads and writes (WriteToSubresource/ReadFromSubresource) copy on the host when they can. // (A D24 texture stored as D32 goes through the staged copy: the host copy would not convert. Nor would it // repack a 96-bit texture's 12-byte texels.) const bool cpu_copyable = cpu_visible() && samples == 1 && !format.d24_as_float && !format.rgb96; host_transfer_ = cpu_copyable && device_.host_transfer_format(format.format); rgb96_ = format.rgb96; if (host_transfer_) info.usage |= VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; HRESULT support = device_.check_image_support(info); if (support == E_INVALIDARG && host_transfer_) { host_transfer_ = false; // staging copies do not require host-transfer usage info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; support = device_.check_image_support(info); } if (FAILED(support)) { std::fprintf(stderr, "[rt] d3d12: texture refused by the GPU's image support query (hr 0x%08x): vk format %d " "type %d %ux%ux%u mips %u layers %u samples %d usage 0x%x flags 0x%x (DXGI %d, D3D12 flags " "0x%x)\n", unsigned(support), int(info.format), int(info.imageType), info.extent.width, info.extent.height, info.extent.depth, info.mipLevels, info.arrayLayers, int(info.samples), unsigned(info.usage), unsigned(info.flags), int(desc_.Format), unsigned(desc_.Flags)); return support; } device_.share(info); // A host-copyable sampled image can exclude the GPU's unmapped device-local memory. // Compare identical creation parameters before dropping HOST_TRANSFER. Keep the fast // host path on UMA and on devices where host copies allow the same device-local type. static const bool stage_title = [] { const char* value = std::getenv("LEONIDA_TITLE_IMAGE_STAGING"); return !value || std::strcmp(value, "0"); }(); const bool can_stage_title = stage_title && allow_staged_title && cpu_copyable && origin != TitleImageOrigin::ordinary && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT; VkMemoryRequirements with_host{}; const bool have_host_requirements = can_stage_title && host_transfer_ && device_.memory_requirements(info, with_host); // A driver can accept HOST_TRANSFER for the image yet give it no bindable memory type. if (have_host_requirements && !with_host.memoryTypeBits) { info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; host_transfer_ = false; if (HRESULT hr = device_.check_image_support(info); FAILED(hr)) return hr; log_once("title image has no host-transfer memory type, using staging for Vulkan format", int(info.format)); } // Keep placed movie planes with a known linear CPU layout on the host-copy path, where there is one. // Map on a staged placement still returns the title's pages and participates in the refresh. std::uint32_t xg_layout = 0; const bool linear_placement = origin == TitleImageOrigin::placed && (desc_.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR || (leonida::title_xg_layouts::find({std::uint32_t(desc_.Dimension), std::uint32_t(desc_.Format), desc_.Height, desc_.DepthOrArraySize, desc_.MipLevels, desc_.Width}, xg_layout) && xg_layout == 1)); static const bool defer_placed = [] { const char* value = std::getenv("LEONIDA_PLACED_IMAGE_DEFER"); return !value || std::strcmp(value, "0"); }(); // A device without host copies has no other way to fill a title image: a refresh before a submission may not // use a staged copy through the queue (host_copy_now). Its linear movie planes are staged too. const bool no_host_copy = !device_.copy_memory_to_image && cpu_copyable; // Private BC copies start with the exact same zero blocks as the shared image. The host // transition and clear complete before a private view is published, including during command prepare. // Without host copies the staged upload fills the private image, and the first shader submission clears what // it has not filled. const bool can_fill = host_transfer_ || (no_host_copy && stage_title && allow_staged_title && device_.image_requirements); if (defer_placed && origin == TitleImageOrigin::placed && can_fill && device_.bindless && desc_.Flags == D3D12_RESOURCE_FLAG_NONE && desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc_.SampleDesc.Count == 1 && asked_castable.empty() && !format.typeless && leonida::block_format(format.format, format.aspects).block > 1) { if (have_host_requirements || device_.memory_requirements(info, with_host)) shared_zero_ = device_.zero_sampled_image(desc_, format, with_host.size); } std::uint32_t plain_bits = 0; const bool can_stage = can_stage_title && (!shared_zero_ || no_host_copy); // A refresh must queue an upload when this image cannot take host copies, including linear movie planes. const bool needs_staging = can_stage && !host_transfer_; if (needs_staging) { staged_title_ = true; plain_bits = UINT32_MAX; // the image already lacks HOST_TRANSFER; any compatible memory type will do } else if (can_stage && !linear_placement && device_.image_requirements) { for (std::uint32_t i = 0; i < device_.memory.memoryTypeCount; ++i) { const auto flags = device_.memory.memoryTypes[i].propertyFlags; if ((flags & (VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) plain_bits |= 1u << i; } VkMemoryRequirements without{}; auto staged = info; staged.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; if (plain_bits && have_host_requirements && !(with_host.memoryTypeBits & plain_bits) && device_.memory_requirements(staged, without) && (without.memoryTypeBits & plain_bits)) { staged_title_ = true; host_transfer_ = false; info.usage = staged.usage; } } const bool can_retry_host = staged_title_ && !needs_staging; auto retry_host = [&] { if (image_) vk.vkDestroyImage(device_.info.device, image_, nullptr); if (memory_) vk.vkFreeMemory(device_.info.device, memory_, nullptr); image_ = VK_NULL_HANDLE; memory_ = VK_NULL_HANDLE; staged_title_ = false; shared_zero_ = VK_NULL_HANDLE; log_once("no room for a staged title image; retrying host-copyable backing, format", int(info.format)); return create_texture(format, asked_castable, origin, false); }; const auto create_image = [&]() -> HRESULT { const VkResult created = vk.vkCreateImage(device_.info.device, &info, nullptr, &image_); if (created == VK_SUCCESS) return S_OK; image_ = VK_NULL_HANDLE; // undefined after a failed create; ~Resource destroys any non-null image_ std::fprintf(stderr, "[rt] d3d12: vkCreateImage failed (%d): vk format %d %ux%u usage 0x%x flags 0x%x\n", int(created), int(info.format), info.extent.width, info.extent.height, unsigned(info.usage), unsigned(info.flags)); if (created == VK_ERROR_OUT_OF_HOST_MEMORY || created == VK_ERROR_OUT_OF_DEVICE_MEMORY) return E_OUTOFMEMORY; if (!view_formats_.empty()) { log_once("castable format list refused by Vulkan; count", int(view_formats_.size())); return E_INVALIDARG; } return E_OUTOFMEMORY; }; if (HRESULT hr = create_image(); FAILED(hr)) return can_retry_host ? retry_host() : hr; VkMemoryRequirements requirements{}; std::uint32_t type = UINT32_MAX; const bool stream = origin == TitleImageOrigin::streamed || origin == TitleImageOrigin::pending_stream; const auto allowed = staged_title_ ? plain_bits : UINT32_MAX; const bool deferrable = desc_.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); // With pipelines and views prepared at bind time, a placed 2D texture that takes no host copies waits for // its memory too, until a command or a sampled view first uses it. const bool defer_sampled = device_.info.prepare_on_bind && origin == TitleImageOrigin::placed && desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && !(desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) && !host_transfer_; if (shared_zero_ || defer_sampled || (defer_placed && origin == TitleImageOrigin::placed && deferrable && !cpu_visible())) { vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); deferred_bytes_ = requirements.size; deferred_types_ = allowed; if (shared_zero_) { deferred_stream_ = true; std::lock_guard lock(device_.descriptor_mutex); device_.pending_image_keys[image_].zero = shared_zero_; } deferred_attachment_ = std::make_unique(this, [](void* owner) { return static_cast(owner)->bind_placed_memory(); }); } else if (origin == TitleImageOrigin::pending_stream && (host_transfer_ || staged_title_)) { vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); deferred_bytes_ = requirements.size; deferred_types_ = allowed; deferred_stream_ = true; std::lock_guard lock(device_.descriptor_mutex); device_.pending_image_keys.try_emplace(image_); } else if (origin != TitleImageOrigin::ordinary) { // A title image (placed or streamed) takes the title image pool or an allocation of its own, of the memory // types its placement allows; the shared texture blocks below are for the layer's ordinary textures. if (!bind_texture_memory(stream, allowed, requirements, type)) { if (can_retry_host) return retry_host(); std::fprintf(stderr, "[rt] d3d12: texture memory unavailable: %llu bytes, alignment %llu, type bits 0x%x (vk " "format %d %ux%u)\n", static_cast(requirements.size), static_cast(requirements.alignment), unsigned(requirements.memoryTypeBits), int(info.format), info.extent.width, info.extent.height); return E_OUTOFMEMORY; } } else { // Some drivers advertise VK_EXT_host_image_copy yet allow no memory type for a HOST_TRANSFER image // (NVIDIA Pascal / 582.78: memoryTypeBits == 0), or fail to allocate one. Staging copies do not need // that usage, so recreate the image without it and continue on that path, as for a refused format above. // Render targets and depth buffers keep their own allocations: there are few of them, and a driver may // give one a better place. constexpr D3D12_RESOURCE_FLAGS attachment = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; for (;;) { vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); // NVIDIA's Pascal driver (582.78 on a GTX 1050 Ti) reports HOST_IMAGE_TRANSFER for the format and // creates the image, but then allows it no memory type at all. The image has not been bound or used, // so it is made again without host-transfer usage and the CPU copies take the staging path. The test // forces this branch on any GPU with force_host_transfer_retry. bool retry = host_transfer_ && (requirements.memoryTypeBits == 0 || device_.info.force_host_transfer_retry); if (!(desc_.Flags & attachment) && !host_transfer_) image_range_ = device_.allocate_image(requirements, memory_flags_); if (image_range_) { if (vk.vkBindImageMemory(device_.info.device, image_, image_range_->memory(), image_range_->offset()) == VK_SUCCESS) break; return E_OUTOFMEMORY; } if (!retry) { memory_ = device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_); if (memory_ && vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) == VK_SUCCESS) break; if (memory_) { vk.vkFreeMemory(device_.info.device, memory_, nullptr); memory_ = VK_NULL_HANDLE; } retry = host_transfer_; // a failed allocation/bind retries on the staging path too } if (!retry) return E_OUTOFMEMORY; log_once(requirements.memoryTypeBits == 0 || device_.info.force_host_transfer_retry ? "host-transfer image has no memory type; using staging copies, format" : "host-transfer image could not be bound; using staging copies, format", int(info.format)); vk.vkDestroyImage(device_.info.device, image_, nullptr); image_ = VK_NULL_HANDLE; host_transfer_ = false; info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; if (HRESULT hr = device_.check_image_support(info); FAILED(hr)) return hr; if (HRESULT hr = create_image(); FAILED(hr)) { log_once("image refused after dropping host-transfer usage; format", int(info.format)); return hr; } vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); if (requirements.memoryTypeBits == 0) log_once("image has no memory type even without host-transfer usage; format", int(info.format)); } image_backing_bytes_ = requirements.size; } if (!deferred_stream_ && !deferred_attachment_ && origin != TitleImageOrigin::ordinary && leonida::mem_probe::interval_seconds()) { char key[160]; std::snprintf(key, sizeof(key), "image-class slot=%u format=%u dim=%u samples=%u flags=0x%x usage=0x%x bits=0x%x", stream ? 70u : 133u, unsigned(info.format), unsigned(info.imageType), unsigned(info.samples), unsigned(info.flags), unsigned(info.usage), requirements.memoryTypeBits); if (first_diagnostic(key, int(type))) { VkImageCreateInfo staged = info; staged.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; VkMemoryRequirements without = requirements; if (staged.usage != info.usage && !device_.memory_requirements(staged, without)) without.memoryTypeBits = 0; std::fprintf(stderr, "[rt] mem-probe: %s no-host-bits=0x%x type=%u\n", key, without.memoryTypeBits, type); } } leonida::ResourceBinding binding{}; if (deferred_attachment_) { binding.residency_owner = this; binding.ensure_residency = [](void* object) { auto* r=static_cast(object); const bool ready=r->ensure_texture_bound(); if (ready) r->gpu_referenced_.store(true,std::memory_order_release); return ready; }; } binding.image = image_; binding.typeless = format.typeless && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT; // views name their format binding.castable_view_formats = !view_formats_.empty(); // a castable list made the image mutable binding.uint_backed = format.uint_backed; binding.rgb96 = format.rgb96; binding.depth24_as_float = format.d24_as_float; binding.depth24 = format.d24; binding.xbox_depth16_stencil8=format.xbox_depth16_stencil8; binding.rgba4_render_fallback=format.rgba4_render_fallback; binding.format = format.format; binding.aspects = format.aspects; binding.width = std::uint32_t(desc_.Width); binding.height = one_d ? 1u : desc_.Height; binding.mip_levels = desc_.MipLevels; binding.array_layers = info.arrayLayers; binding.depth = depth; binding.volume = volume; binding.line = one_d; binding.samples = samples; binding.sample_locations_depth = (info.flags & VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT) != 0; binding.color_attachment = (info.usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) != 0; binding.sampled = (info.usage & VK_IMAGE_USAGE_SAMPLED_BIT) != 0; binding.simultaneous_access = (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) != 0; binding.not_zeroed = (heap_flags_ & D3D12_HEAP_FLAG_CREATE_NOT_ZEROED) != 0; // With the bindless set, a view's descriptor has one layout for as long as it lives (bind_image). binding.sampled_in_general = device_.bindless != nullptr; format_ = format.format; uint_backed_ = format.uint_backed; a8_as_alpha_ = format.a8_as_alpha; aspects_ = format.aspects; image_address_ = device_.next_image_address.fetch_add(256); device_.note_image_address(image_address_, this); DeviceState::trace_image(image_address_, id(), "registered"); binding.deferred_memory = deferred_attachment_.get(); if (origin == TitleImageOrigin::placed && leonida::mem_probe::interval_seconds()) binding.replay_seen = &replay_seen_; binding_ = binding; if (shared_zero_) { // All direct GPU commands resolve this binding in prepare(), before the descriptor table flush. device_.context->add_resource(id(), binding_, host_transfer_ ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_UNDEFINED); return S_OK; } return deferred_stream_ ? S_OK : register_bound_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_) { VkMemoryRequirements requirements{}; std::uint32_t type = UINT32_MAX; if (!bind_texture_memory(true, deferred_types_, requirements, type) && (deferred_types_ == UINT32_MAX || !(requirements.memoryTypeBits & ~deferred_types_) || !bind_texture_memory(true, ~deferred_types_, requirements, type))) return false; } if (FAILED(register_bound_texture())) return false; deferred_bytes_ = 0; return true; } // Backs a deferred slot-133 placement before uploading from `publish_from` on. bool back_placed_texture(unsigned publish_from = 0) { if (publish_from && deferred_attachment_ && !deferred_attachment_->bound()) placed_publish_from_.store(publish_from, std::memory_order_release); return image() != VK_NULL_HANDLE; } void clear_placed_publish_from() { placed_publish_from_.store(0, std::memory_order_release); } // For an already-backed non-GPU-written texture whose first upload fills only [from .. mips-1], clamp existing and // future views that request finer mips via VK_EXT_image_view_min_lod (and detach top-only views whose mip range // ends before `from` so they read the fallback until their mips arrive). void enable_partial_stream(unsigned from) { if (!from || deferred_stream_ || !image_ || !device_.info.image_view_min_lod) return; std::vector changed_keys; { std::lock_guard lock(device_.descriptor_mutex); deferred_stream_ = true; auto& p = device_.pending_image_keys[image_]; p.first_mip = from; std::vector> to_clamp; bool detached_top_only = false; const auto [first, last] = device_.image_keys.equal_range(image_address_); for (auto it = first; it != last;) { const auto entry = device_.image_entries.find(it->second); if (entry == device_.image_entries.end() || entry->second.storage || entry->second.view_key.vk_image != image_) { ++it; continue; } leonida::gfx10::Image decoded{}; if (!leonida::gfx10::decode(it->second, decoded)) { ++it; continue; } decoded.address = image_address_; // match bind_title_image_to normalization const std::uint32_t min_mip = leonida::effective_min_mip(decoded.first_mip, leonida::gfx10::image_min_lod(it->second)); if (min_mip < from) { const std::uint32_t last_mip = decoded.mip_count ? decoded.first_mip + decoded.mip_count - 1 : decoded.first_mip; DeviceState::PendingImageKey pk{decoded, entry->second.from_title_heap, entry->second.in_known_heap}; auto [pit, pinserted] = p.keys.try_emplace(it->second, pk); if (!pinserted) { if (!pk.evictable) pit->second.evictable = false; if (pk.in_known_heap) pit->second.in_known_heap = true; } if (from <= last_mip) { to_clamp.emplace_back(it->second, pit->second); ++it; } else { // Accessible mip range ends before `from`: detach pre-existing view so it reads fallback until // `filled_from <= last_mip` (never sampling unfilled mips 0..from-1). if (device_.tsharp_index_words && pit->second.in_known_heap) changed_keys.push_back(it->second); if (device_.bindless) device_.bindless->erase_key(it->second); const auto vk_key = entry->second.view_key; const std::size_t key_pos = entry->second.sv_key_pos; const bool from_title = entry->second.from_title_heap; if (from_title && device_.title_heap_image_keys > 0) --device_.title_heap_image_keys; device_.image_entries.erase(entry); device_.detach_view_key_locked(vk_key, key_pos, from_title, /*upgrading=*/false, 0); it = device_.image_keys.erase(it); detached_top_only = true; } } else { ++it; } } if (detached_top_only && device_.tsharp_index_words) device_.note_texture_change(leonida::SlotChange::texture_gone, image_address_); for (const auto& [words, pk] : to_clamp) { device_.bind_image_locked(words, pk.image, image_, format_, aspects_, false, has_view_format_list(), uint_backed_, nullptr, pk.evictable, pk.in_known_heap); if (device_.tsharp_index_words && pk.in_known_heap) changed_keys.push_back(words); } } if (device_.tsharp_index_words && !changed_keys.empty()) device_.write_tsharp_index_words(changed_keys); } // The mips from `from` on are filled: views whose effective minimum mip is at or above `from` leave // `pending_image_keys` and are finalized. When `VK_EXT_image_view_min_lod` is available and `from > 0`, views // wanting finer mips stay in `pending_image_keys` (so a later finer fill upgrades them) and are published now // clamped to `from` (provided `from` lies within the view's accessible mip range). void publish_streamed_texture(unsigned from = 0) { if (!deferred_stream_) return; std::vector published_keys; { std::lock_guard lock(device_.descriptor_mutex); VkImage had_zero = VK_NULL_HANDLE; std::map to_bind; if (const auto pending = device_.pending_image_keys.find(image_); pending != device_.pending_image_keys.end()) { // Never regress an already-published finer fill. if (from >= pending->second.first_mip && !pending->second.zero) { if (!from) deferred_stream_ = false; return; } had_zero = pending->second.zero; if (from == 0) { to_bind = std::move(pending->second.keys); device_.pending_image_keys.erase(pending); } else { pending->second.zero = VK_NULL_HANDLE; pending->second.first_mip = from; for (auto it = pending->second.keys.begin(); it != pending->second.keys.end();) { const std::uint32_t min_mip = leonida::effective_min_mip( it->second.image.first_mip, leonida::gfx10::image_min_lod(it->first)); if (min_mip >= from) { to_bind.emplace(it->first, it->second); it = pending->second.keys.erase(it); } else { if (device_.info.image_view_min_lod) to_bind.emplace(it->first, it->second); ++it; } } } } const auto owner = device_.images_by_address.find(image_address_); if (owner != device_.images_by_address.end() && owner->second == this) { if (had_zero) device_.forget_image_views_locked(image_address_); for (const auto& [words, pending_key] : to_bind) { device_.bind_image_locked(words, pending_key.image, image_, format_, aspects_, false, has_view_format_list(), uint_backed_, nullptr, pending_key.evictable, pending_key.in_known_heap); if (device_.tsharp_index_words && pending_key.in_known_heap) published_keys.push_back(words); } // Its image is there now (or finer mips arrived): title-written T#s refused or zero-indexed while // waiting (recorded as texture_waiting) wake via texture_added without forcing already-bound unchanged // slots through filter_slot_locked (which would transiently zero dword 6 in WC BAR VRAM). Upgraded or // replaced views already emit SlotChange::texture_gone in bind_image_views_locked / forget_image_views_locked. device_.note_texture_change(leonida::SlotChange::texture_added, image_address_); } if (!from) deferred_stream_ = false; } // Patch layer-owned (known_heap) descriptors outside descriptor_mutex (write_tsharp_index_words locks // visible_heap_mutex then descriptor_mutex). if (device_.tsharp_index_words && !published_keys.empty()) device_.write_tsharp_index_words(published_keys); } // 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_; } bool pooled_image() const { return pooled_image_ != nullptr; } private: bool bind_placed_memory() { // Always consume `placed_publish_from_` up front so a failed bind cannot leak a stale clamp to a later call. const unsigned publish_from = placed_publish_from_.exchange(0, std::memory_order_acq_rel); VkMemoryRequirements requirements{}; std::uint32_t type = UINT32_MAX; const bool pool = !(desc_.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); if (!image_backing_bytes_ && !bind_texture_memory(pool, deferred_types_, requirements, type)) { if (!(requirements.memoryTypeBits & ~deferred_types_) || !bind_texture_memory(pool, ~deferred_types_, requirements, type)) return false; } if (shared_zero_) { if (host_transfer_ && !host_initialize()) return false; if (!host_transfer_) device_.context->note_shader_image(id()); // zeros until something fills it publish_streamed_texture(publish_from); } return true; } bool bind_texture_memory(bool stream, std::uint32_t allowed_types, VkMemoryRequirements& requirements, std::uint32_t& type) { auto& vk = device_.context->vk; static const bool pool_images = [] { wchar_t value[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_TITLE_IMAGE_POOL", value, 2) == 1 && value[0] == L'0'); }(); VkMemoryDedicatedRequirements dedicated{VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS}; if (stream && pool_images && device_.bound_image_requirements) { VkImageMemoryRequirementsInfo2 query{VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2}; query.image = image_; VkMemoryRequirements2 result{VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; result.pNext = &dedicated; device_.bound_image_requirements(device_.info.device, &query, &result); requirements = result.memoryRequirements; if (!dedicated.requiresDedicatedAllocation) { auto pool_requirements = requirements; pool_requirements.memoryTypeBits &= allowed_types; pooled_image_ = device_.title_image_pool.bind(device_.info.device, image_, pool_requirements, vk.vkBindImageMemory, vk.vkDestroyImage, vk.vkFreeMemory, [&](VkDeviceSize size, std::uint32_t& type) { auto page = pool_requirements; page.size = size; leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::image_blocks); return device_.allocate(page, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, false, &type); }); if (pooled_image_) memory_flags_ = device_.memory.memoryTypes[pooled_image_->page->type].propertyFlags; } } else { vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); } type = pooled_image_ ? pooled_image_->page->type : UINT32_MAX; if (!pooled_image_) { auto selected = requirements; selected.memoryTypeBits &= allowed_types; memory_ = device_.allocate(selected, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_, false, &type, dedicated.requiresDedicatedAllocation ? image_ : VK_NULL_HANDLE); } if (!pooled_image_ && (!memory_ || vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) != VK_SUCCESS)) { if (memory_) vk.vkFreeMemory(device_.info.device, memory_, nullptr); memory_ = VK_NULL_HANDLE; return false; } image_backing_bytes_ = requirements.size; return true; } HRESULT register_bound_texture() { if (host_transfer_) { // Moved to GENERAL and zero-filled on the host now, so the CPU can copy into it before any command // list has touched it (a first GPU use would otherwise zero-fill over what the CPU wrote). if (!host_initialize()) return E_OUTOFMEMORY; device_.context->add_resource(id(), binding_, VK_IMAGE_LAYOUT_GENERAL); return S_OK; } // Never used yet: the first command that touches a part zero-fills it and moves it to the layout of the // state that command expects (vulkan_replay.h, initialize), so no submission is needed here. device_.context->add_resource(id(), binding_, VK_IMAGE_LAYOUT_UNDEFINED); // A shader may read it before any command names it: D3D12 gives zeros, and a reused range holds an older texture. if (image_range_ && image_range_->reused() && !binding_.not_zeroed) device_.context->note_shader_image(id()); return S_OK; } public: void mark_console_d16s8() { console_d16s8_ = true; } bool console_d16s8() const { return console_d16s8_; } // The Xbox proxy calls this before publishing an allocated depth texture. Each storage plane owns a // regular color image with its own GFX10 address, so a UAV cannot replace the original SRV in set 0. HRESULT enable_depth_stencil_uav(D3D12_HEAP_FLAGS storage_heap_flags) { const bool narrow_stencil = desc_.Format == xbox_d16s8 || console_d16s8_; const bool depth16 = desc_.Format == DXGI_FORMAT_R16_TYPELESS || narrow_stencil; if (!image_ || (!depth16 && desc_.Format != DXGI_FORMAT_R32G8X24_TYPELESS) || !(desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) || desc_.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc_.MipLevels != 1 || !desc_.DepthOrArraySize || desc_.SampleDesc.Count != 1) return E_INVALIDARG; if (storage_planes_[0]) return S_OK; try { decltype(storage_planes_) planes; D3D12_RESOURCE_DESC plane_desc = desc_; plane_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; // D16 copies through a buffer as raw UNORM bits. R16_TYPELESS lets an Xbox UAV view those bits as R16_UNORM or R16_UINT. const bool widened = narrow_stencil && format_ != VK_FORMAT_D16_UNORM_S8_UINT; std::unique_ptr conversion; if (widened) { const auto blit = VK_FORMAT_FEATURE_2_BLIT_SRC_BIT | VK_FORMAT_FEATURE_2_BLIT_DST_BIT; const bool d24_backing = format_ == VK_FORMAT_D24_UNORM_S8_UINT; if ((format_ != VK_FORMAT_D32_SFLOAT_S8_UINT && !d24_backing) || (d24_backing && !device_.context->has_depth24()) || (device_.optimal_features(VK_FORMAT_R16_UNORM) & blit) != blit || (device_.optimal_features(VK_FORMAT_R32_SFLOAT) & blit) != blit) return E_NOTIMPL; auto intermediate = plane_desc; intermediate.Format = DXGI_FORMAT_R32_FLOAT; intermediate.Flags = D3D12_RESOURCE_FLAG_NONE; conversion = std::make_unique(device_, intermediate, heap_, D3D12_HEAP_FLAG_NONE); const HRESULT hr = conversion->create_texture(device_.texture_format(intermediate)); if (FAILED(hr)) return hr; } const auto depth_format = depth16 ? DXGI_FORMAT_R16_TYPELESS : DXGI_FORMAT_R32_FLOAT; const DXGI_FORMAT formats[] = {depth_format, DXGI_FORMAT_R8_UINT}; const UINT plane_count = depth16 && !narrow_stencil ? 1 : 2; for (UINT plane = 0; plane < plane_count; ++plane) { plane_desc.Format = formats[plane]; planes[plane] = std::make_unique(device_, plane_desc, heap_, storage_heap_flags); const HRESULT hr = planes[plane]->create_texture(device_.texture_format(plane_desc)); if (FAILED(hr)) return hr; } // Replacing the binding preserves the tracked layout of the original depth/stencil image. auto binding = binding_; binding.depth_uav = planes[0]->id(); binding.depth_conversion = conversion ? conversion->id() : 0; binding.stencil_uav = planes[1] ? planes[1]->id() : 0; device_.context->add_resource(id(), binding); binding_ = binding; storage_planes_ = std::move(planes); depth_conversion_ = std::move(conversion); heap_flags_ |= storage_heap_flags; // GetHeapProperties describes the caller's entire logical texture. } catch (const std::bad_alloc&) { return E_OUTOFMEMORY; } return S_OK; } // D3D12 reports the placement alignment of a description that left it 0: 64 KiB, or 4 MiB for a multisampled // texture. One the description asked for is kept. Measured on the PC runtime and WARP (d3d12_resource_desc_test). D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override { D3D12_RESOURCE_DESC desc = desc_; if (storage_ || storage_planes_[0]) desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; if (!desc.Alignment) { desc.Alignment = (desc.SampleDesc.Count > 1 && !is_tiled_layout(desc.Layout)) ? D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; } return desc; } bool belongs_to(const DeviceState& device) const { return &device_ == &device; } // Both sparse resources and the committed fallback report the reserved layout and have no heap of their own. void make_reserved(D3D12_TEXTURE_LAYOUT layout) { reserved_ = true; desc_.Layout = layout; } bool reserved() const { return reserved_; } // A committed resource: neither placed in a heap nor reserved. It owns its memory, like a heap does. bool committed() const { return !placed_ && !reserved_; } // D3D12 answers only for committed and placed resources (E_INVALIDARG for reserved ones, measured on the PC // runtime). // Buffers report their console VA into the GPU address arena; an acceleration structure reports its real device // address (instance descriptors and builds hand it to the driver). A texture the title placed at its own address // through Xbox slot 133 reports that title address, as the console does (place_at_title_address; docs/d3d12_vulkan.md // 3.3). Any other texture answers 0, as on D3D12. D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress() override { if (image_ && title_address_) return reinterpret_cast(title_address_); return accel_ ? gpu_va_ : va_; } // A texture the title placed on its own memory (Xbox device slot 133, create_at_host_address). The console's // texture IS that memory: Map and GetGPUVirtualAddress answer with the address (the title memsets and fills // textures through the pointer Map gives it, and writes to address 0 when it gets none), and its T#s, the ones // the title writes itself into a console descriptor heap included, name it by that address. The image is still // ordinary GPU memory, filled from the title's bytes at the address by the title-texture registry // (TitleTexture) unless the GPU writes it. void place_at_title_address(void* address, bool separate_image_key = false) { title_address_ = address; const auto va = reinterpret_cast(address); if (!image_ || !image_address_ || (va & 0xff)) return; // a T# keeps the address without its low 8 bits if (separate_image_key) return; device_.forget_image(image_address_); device_.forget_image(va); // an earlier texture placed at this address, still alive: its views are stale image_address_ = va; device_.note_image_address(image_address_, this); DeviceState::trace_image(image_address_, id(), "registered"); } // The title's own address for a texture Xbox slot 133 placed. The image is still the committed fallback, so its // pixels do not alias the title's pages yet; the address is what GetGPUVirtualAddress answers (XCL PR #168's // behavior, measured on a retail title). void set_title_address(D3D12_GPU_VIRTUAL_ADDRESS address) { if (!image_ || !address || title_image_registered_) return; std::lock_guard lock(device_.title_image_mutex); va_ = address; device_.title_images.emplace(va_, this); title_image_registered_ = true; } // No descriptors have been built for a newly materialized raw surface. void set_raw_image_address(std::uint64_t address) { image_address_ = address; } void use_texture_lease(void* data, std::size_t size, UINT layout) { if (!image_ || !data) return; const auto addr = reinterpret_cast(data); if (va_ && va_ != addr) return; if ((layout == 1 || layout == 0x100) && desc_.Dimension==D3D12_RESOURCE_DIMENSION_TEXTURE2D) { // Placement callbacks get a title VA; pin_mapped_data checks its live XMem section on Map. title_linear_ = true; title_linear_limit_ = size ? size : SIZE_MAX; } if (!size || va_) return; std::uint64_t lo = 0, hi = 0; const bool tracked = leonida::title_va_aliases().title_memory(addr, lo, hi) && size <= hi - addr; MEMORY_BASIC_INFORMATION page{}; const bool writable = VirtualQuery(data, &page, sizeof(page)) && page.State == MEM_COMMIT && !(page.Protect & (PAGE_NOACCESS | PAGE_GUARD)) && ((page.Protect & 0xffu) == PAGE_READWRITE || (page.Protect & 0xffu) == PAGE_WRITECOPY); if (tracked && writable) { set_title_address(addr); } } // // The node masks read back as the one node of a single adapter (0 becomes 1), and the heap flags as the runtime // resolves them: the caller's, without the two creation-only bits (CREATE_NOT_RESIDENT, CREATE_NOT_ZEROED), plus // the DENY bits of the resource classes this resource is not (buffers 0xC0, textures without render-target or // depth use 0x44, the others 0x84). Measured on the PC runtime and WARP (d3d12_node_mask_test). HRESULT STDMETHODCALLTYPE GetHeapProperties(D3D12_HEAP_PROPERTIES* properties, D3D12_HEAP_FLAGS* flags) override { if (reserved_) return E_INVALIDARG; if (properties) { *properties = heap_; if (!properties->CreationNodeMask) properties->CreationNodeMask = 1; if (!properties->VisibleNodeMask) properties->VisibleNodeMask = 1; } if (flags) *flags = resolved_heap_flags(); return S_OK; } D3D12_HEAP_FLAGS resolved_heap_flags() const { const UINT deny_buffers = D3D12_HEAP_FLAG_DENY_BUFFERS, deny_rt_ds = D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES, deny_non_rt_ds = D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES; UINT deny = deny_buffers | deny_rt_ds; // a texture without render-target or depth use if (desc_.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) deny = deny_rt_ds | deny_non_rt_ds; else if (desc_.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) deny = deny_buffers | deny_non_rt_ds; const UINT creation_only = D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT | D3D12_HEAP_FLAG_CREATE_NOT_ZEROED; // A placed resource reports its heap's flags as they are (an ALLOW_ALL heap reads back 0): the DENY bits // are the runtime's choice only for the implicit heap of a committed resource (d3d12_heap_properties_test). if (placed_) return D3D12_HEAP_FLAGS(UINT(heap_flags_) & ~creation_only); return D3D12_HEAP_FLAGS((UINT(heap_flags_) & ~creation_only) | deny); } // Buffers on upload and readback heaps are mapped persistently; the ranges are hints, as on D3D12, except that // the host runtime refuses a non-empty read range that ends past the buffer. A texture in a CPU-visible heap has // no pointer to give (its layout is the driver's), so D3D12 only lets it be mapped with a null pointer, before // WriteToSubresource/ReadFromSubresource. HRESULT STDMETHODCALLTYPE Map(UINT subresource, const D3D12_RANGE* read, void** data) override { // LOCAL DIAGNOSTIC: LEONIDA_LOCK_TRACE=1 logs the first 256 texture Maps with a read range: the title's // texture lock passes the subresource's byte range there, computed from its XG computer's // layout, and adds the range's start to the pointer this answers. static const bool lock_trace = [] { char value[2]{}; return GetEnvironmentVariableA("LEONIDA_LOCK_TRACE", value, sizeof(value)) == 1 && value[0] == '1'; }(); if (lock_trace && read && image_) { static std::atomic logged{0}; if (logged.fetch_add(1, std::memory_order_relaxed) < 256) { const auto caller = reinterpret_cast(_ReturnAddress()); std::fprintf(stderr, "[rt] d3d12: LOCAL DIAGNOSTIC: Map sub %u range 0x%llx..0x%llx of texture %llux%ux%u " "fmt %d flags 0x%x at 0x%llx, caller 0x%llx\n", subresource, static_cast(read->Begin), static_cast(read->End), static_cast(desc_.Width), desc_.Height, unsigned(desc_.DepthOrArraySize), int(desc_.Format), unsigned(desc_.Flags), static_cast(reinterpret_cast(title_address_)), static_cast(caller)); } } // A texture whose lease says its title memory is linear (title_linear_) and that also has a placement // address (slot 133; the video planes among them) has two answers. The placement address, with the title // texture registry filling the image, is the one the retail boot ran through the intro movie and the story // load on, so it is asked first. LEONIDA_LINEAR_MAP_FIRST=1 gives such a texture the linear mapping instead // (pinned pages, with a GPU-written texture read back into them), and its refusal when the pages are gone. static const bool linear_first = [] { const char* v = std::getenv("LEONIDA_LINEAR_MAP_FIRST"); return v && *v == '1'; }(); if (linear_first && title_linear_ && data && image_) { *data = nullptr; return map_title_texture(subresource, read, data); } if (image_ && title_address_) { // place_at_title_address: the console answers with the texture's memory if (data) { *data = title_address_; rt::placed_image_map_note::note(title_address_, subresource, read, desc_.Width == 1 && desc_.Height == 1 && desc_.Format == DXGI_FORMAT_R32G32B32A32_FLOAT); read_back_on_map(subresource); } // From now on the CPU may write its texels whenever it likes (video planes are mapped once): the // registry checks this texture's bytes before submissions (Device::refresh_title_textures). if (title_texture_ && !title_mapped_.exchange(true, std::memory_order_relaxed)) device_.title_texture_mapped(this, reinterpret_cast(title_address_)); return S_OK; } if (title_linear_ && data && image_) { // a leased linear texture with no placement address *data = nullptr; return map_title_texture(subresource, read, data); } if (image_) { VkImageSubresourceRange range{}; return !data && cpu_visible() && subresource != leonida::all_subresources && leonida::image_range(binding_, subresource, range) ? S_OK : E_INVALIDARG; } if (!mapped_ || subresource != 0) return E_INVALIDARG; if (read && read->Begin < read->End && read->End > desc_.Width) return E_INVALIDARG; if (device_.arena.staged && !host_import_ && !shadow_ && heap_range_) { if (heap_.Type != D3D12_HEAP_TYPE_UPLOAD && (!read || read->End > read->Begin)) { const VkDeviceSize begin = read ? static_cast(read->Begin) : 0; const VkDeviceSize end = read ? static_cast(read->End) : desc_.Width; if (end > begin) device_.sync_arena_to_host(va_ + begin, end - begin); } if (cpu_writable()) { device_.arena.staging.track_mapped(va_, desc_.Width); arena_map_refs_.fetch_add(1, std::memory_order_relaxed); } } if (data) *data = mapped_; return S_OK; } // LEONIDA_MAP_READBACK=1: the GPU's texels of a small render target the title placed are written into the title's // pages when it maps the target. The title reads its exposure statistics that way every frame (a 1x1 and a 5x1 // RGBA32F target, Map at 0x5121690 from 0xb96aa0: team/exposure-readback.md); the GPU renders into our image, // never into those pages, so the CPU read zeros and the exposure went to ~0 (a frame crushed to black, peak // 0.008). Only a single-row, single-mip, single-layer 2D target of at most 4 KiB: the console's linear layout // puts that row at offset 0 (xg-rt-layout), so the row pitch does not matter. The copy waits for the GPU // (ReadFromSubresource's staging copy, behind the work already submitted), and lands through a guarded copy: a // page that is not writable now is left as it is. void read_back_on_map(UINT subresource) { static const bool on = [] { const char* v = std::getenv("LEONIDA_MAP_READBACK"); return v && std::strcmp(v, "1") == 0; }(); if (!on || subresource != 0) return; if (!(desc_.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) return; if (desc_.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc_.Height != 1 || desc_.DepthOrArraySize != 1 || desc_.MipLevels > 1 || binding_.samples > 1) return; const auto block = leonida::copy_block_format(binding_, VK_IMAGE_ASPECT_COLOR_BIT); if (!block.bytes || block.block != 1) return; const std::uint64_t row = desc_.Width * block.bytes; if (!row || row > 4096) return; std::uint8_t texels[4096]; const HRESULT hr = cpu_copy(false, 0, nullptr, texels, UINT(row), UINT(row)); static std::atomic done{0}, failed{0}; if (FAILED(hr) || !copy_guarded(static_cast(title_address_), texels, std::size_t(row), false)) { const std::uint64_t n = failed.fetch_add(1, std::memory_order_relaxed) + 1; if (n <= 4 || !(n & (n - 1))) std::fprintf(stderr, "[rt] d3d12: map read-back of a %llux1 target at %p failed (hr 0x%08lx; %llu so far)\n", static_cast(desc_.Width), title_address_, static_cast(hr), static_cast(n)); return; } const std::uint64_t n = done.fetch_add(1, std::memory_order_relaxed) + 1; if (n <= 8 || !(n & (n - 1))) { float f[4] = {}; std::memcpy(f, texels, (std::min)(sizeof(f), std::size_t(row))); std::fprintf(stderr, "[rt] d3d12: map read-back #%llu: %llux1 format %d target at %p, first texel %g %g %g " "%g\n", static_cast(n), static_cast(desc_.Width), int(desc_.Format), title_address_, f[0], f[1], f[2], f[3]); } } // A texture the title placed: Unmap ends its CPU writes (the title's lock passes the range it wrote), so its // image is filled again before the next submission (TitleTexture). void STDMETHODCALLTYPE Unmap(UINT sub, const D3D12_RANGE* written) override { if (device_.arena.staged && !image_ && !host_import_ && !shadow_ && heap_range_ && mapped_ && sub == 0 && cpu_writable()) { if (!written || written->End > written->Begin) { const VkDeviceSize begin = written ? std::min(written->Begin, desc_.Width) : 0; const VkDeviceSize end = written ? std::min(written->End, desc_.Width) : desc_.Width; if (end > begin) device_.arena_mark_dirty(va_ + begin, end - begin); } std::uint32_t refs = arena_map_refs_.load(std::memory_order_relaxed); while (refs > 0 && !arena_map_refs_.compare_exchange_weak(refs, refs - 1, std::memory_order_relaxed)) {} if (refs > 0) device_.arena.staging.untrack_mapped(va_, desc_.Width); } if (image_ && title_address_ && title_texture_ && (!written || written->End > written->Begin)) device_.title_texture_unmapped(this, reinterpret_cast(title_address_)); if (!title_linear_) return; std::lock_guard lock(title_map_mutex_); const auto it=title_maps_.find(sub); if(it==title_maps_.end()) return; if ((!written || written->End>written->Begin) && (!written || written->End<=it->second.bytes)) if(!upload_title_map(sub,it->second)) std::fprintf(stderr,"[rt] d3d12: texture upload on Unmap failed, format %u\n",unsigned(desc_.Format)); if (!--it->second.refs) title_maps_.erase(it); if (title_maps_.empty()) { std::lock_guard guard(device_.mapped_texture_mutex); if(device_.mapped_textures.erase(this)) --device_.map_count; } } bool publish_cpu_writes() { std::lock_guard lock(title_map_mutex_); for(auto& [sub,map]:title_maps_) if(!upload_title_map(sub,map)) return false; return true; } // CPU copies into and out of a texture subresource. D3D12 completes them before returning and leaves it to // the application to keep the GPU off the subresource meanwhile, so a blocking copy is the whole contract. HRESULT STDMETHODCALLTYPE WriteToSubresource(UINT subresource, const D3D12_BOX* box, const void* data, UINT row_pitch, UINT depth_pitch) override { return cpu_copy(true, subresource, box, const_cast(data), row_pitch, depth_pitch); } HRESULT STDMETHODCALLTYPE ReadFromSubresource(void* data, UINT row_pitch, UINT depth_pitch, UINT subresource, const D3D12_BOX* box) override { return cpu_copy(false, subresource, box, data, row_pitch, depth_pitch); } private: struct TitleMap { std::shared_ptr data; std::uintptr_t address{}; UINT row{},bytes{},refs{}; std::string fingerprint; bool shared_pages = false; }; static std::string fingerprint(const TitleMap& map) { std::string out; for(std::size_t at=0;at(1u<<20,map.bytes-at)}); return out; } bool upload_title_map(UINT sub, TitleMap& map) { if (map.shared_pages) { auto current=rt::d3d12_xs::pin_texture_pages(reinterpret_cast(map.address),map.bytes); if (!current || current.get()!=map.data.get()) return false; } auto hash=fingerprint(map); if(hash==map.fingerprint) return true; if(FAILED(cpu_copy(true,sub,nullptr,map.data.get(),map.row,map.bytes))) return false; map.fingerprint=std::move(hash); return true; } HRESULT map_title_texture(UINT sub, const D3D12_RANGE* read, void** out) { if (!va_ || desc_.SampleDesc.Count!=1 || aspects_!=VK_IMAGE_ASPECT_COLOR_BIT || binding_.rgba4_render_fallback || binding_.rgb96 || sub>=UINT(desc_.MipLevels)*desc_.DepthOrArraySize) return E_INVALIDARG; std::lock_guard lock(title_map_mutex_); if (auto it=title_maps_.find(sub);it!=title_maps_.end()) { if(read && read->End>read->Begin && read->End>it->second.bytes) return E_INVALIDARG; ++it->second.refs;*out=reinterpret_cast(it->second.address);return S_OK; } namespace ct=leonida::console_texture; ct::TextureDesc d{};d.format=unsigned(desc_.Format);d.width=UINT(desc_.Width);d.height=desc_.Height; d.depth_or_array=desc_.DepthOrArraySize;d.mips=desc_.MipLevels;d.swizzle=ct::kLinear; const auto shape=ct::Texture::make(d); if(!shape || shape->planes.size()!=1) return E_INVALIDARG; const auto& layout=shape->planes[0].layout; const UINT mip=sub%desc_.MipLevels,slice=sub/desc_.MipLevels; const auto& level=layout.mips[mip]; const std::uint64_t row=std::uint64_t(level.pitch)*layout.desc.element_bytes, size=row*level.height; std::uint64_t offset{}; if(layout.offset(mip,0,0,slice,offset)!=ct::Error::ok || !size || size>UINT_MAX || offset>title_linear_limit_ || size>title_linear_limit_-offset || offset>UINTPTR_MAX-va_ || size>UINTPTR_MAX-va_-offset || (read && read->End>read->Begin && read->End>size)) return E_INVALIDARG; const auto title_address=std::uintptr_t(va_+offset); auto pinned=rt::d3d12_xs::pin_texture_pages(reinterpret_cast(title_address),std::size_t(size)); const bool shared=bool(pinned); if (shared) previously_pinned_ = true; else if (previously_pinned_) return E_INVALIDARG; else { // A console GPU VA need not name CPU memory on the PC. Map the live Vulkan image by // staging it through our own allocation. The supplied VA is never dereferenced here. try { pinned = std::shared_ptr(new std::uint8_t[std::size_t(size)]{},std::default_delete()); } catch(const std::bad_alloc&) { return E_OUTOFMEMORY; } } const auto address=shared ? title_address : reinterpret_cast(pinned.get()); TitleMap map{std::move(pinned),address,UINT(row),UINT(size),1,{},shared}; if ((!read || read->End>read->Begin) && (!shared || gpu_referenced_.load(std::memory_order_acquire))) { const HRESULT hr=cpu_copy(false,sub,nullptr,map.data.get(),map.row,map.bytes); if(FAILED(hr)) return hr; map.fingerprint=fingerprint(map); } title_maps_.emplace(sub,std::move(map)); { std::lock_guard guard(device_.mapped_texture_mutex); if(device_.mapped_textures.insert(this).second) ++device_.map_count; } *out=reinterpret_cast(address); return S_OK; } bool title_linear_ = false; bool previously_pinned_ = false; std::uint64_t title_linear_limit_ = 0; std::atomic gpu_referenced_{false}; std::mutex title_map_mutex_; std::map title_maps_; // One subresource region in copy units: rows of texels, or of 4x4 blocks for block-compressed formats. struct Region { VkImageSubresourceLayers layers; D3D12_BOX box; leonida::BlockFormat block; std::uint32_t rows; std::uint64_t row_bytes; std::uint32_t slices; }; // The region a copy names, or false when D3D12 would reject it: an unknown subresource, a box whose right, // bottom or back edge lies past the mip's, or one that cuts a compressed block anywhere but at the mip edge. // An empty or inverted box that passes those checks is no copy at all: `rows` and `slices` are 0, and the host // runtime answers S_OK without touching a byte (d3d12_subresource_copy_test, RTX 3060 / 610.88). bool region(UINT subresource, const D3D12_BOX* box, Region& out) const { VkImageSubresourceRange range{}; if (subresource == leonida::all_subresources || !leonida::image_range(binding_, subresource, range)) return false; if (binding_.samples > 1) return false; // D3D12 has no CPU copies of multisampled textures; Vulkan neither const std::uint32_t mip = range.baseMipLevel; const std::uint32_t width = std::max(1u, binding_.width >> mip), height = std::max(1u, binding_.height >> mip); const std::uint32_t depth = binding_.volume ? std::max(1u, binding_.depth >> mip) : 1; out.box = box ? *box : D3D12_BOX{0, 0, 0, width, height, depth}; const D3D12_BOX& b = out.box; if (b.right > width || b.bottom > height || b.back > depth) return false; out.block = leonida::copy_block_format(binding_, range.aspectMask); if (!out.block.bytes) return false; const std::uint32_t k = out.block.block; if (b.left % k || b.top % k || (b.right % k && b.right != width) || (b.bottom % k && b.bottom != height)) return false; out.layers = {range.aspectMask, mip, range.baseArrayLayer, 1}; if (b.left >= b.right || b.top >= b.bottom || b.front >= b.back) { out.rows = 0; out.row_bytes = 0; out.slices = 0; return true; } out.rows = (b.bottom - b.top + k - 1) / k; out.row_bytes = std::uint64_t((b.right - b.left + k - 1) / k) * out.block.bytes; out.slices = b.back - b.front; return true; } HRESULT cpu_copy(bool write, UINT subresource, const D3D12_BOX* box, void* data, UINT row_pitch, UINT depth_pitch, bool allow_host = true) { if (!image_ || !data) return E_INVALIDARG; Region r{}; if (!region(subresource, box, r)) return E_INVALIDARG; if (!r.rows || !r.slices) return S_OK; // an empty box: nothing to copy if (deferred_attachment_ && !deferred_attachment_->ensure()) return E_OUTOFMEMORY; // The pitches are not checked, as on the host runtime: rows or slices that overlap (a pitch smaller than a // row, or 0) are copied in order, row by row and slice by slice, so on a read the last one wins. if (!cpu_visible()) log_once(write ? "WriteToSubresource on a texture outside a CPU-visible heap; heap type" : "ReadFromSubresource on a texture outside a CPU-visible heap; heap type", heap_.Type); auto* bytes = static_cast(data); // Between the application's pitches and `pitch`, the one a copy reads or writes. const auto pack = [&](std::byte* to, std::uint64_t pitch) { for (std::uint32_t z = 0; z < r.slices; ++z) for (std::uint32_t y = 0; y < r.rows; ++y) std::memcpy(to + (std::uint64_t(z) * r.rows + y) * pitch, bytes + std::uint64_t(z) * depth_pitch + std::uint64_t(y) * row_pitch, r.row_bytes); }; const auto unpack = [&](const std::byte* from, std::uint64_t pitch) { for (std::uint32_t z = 0; z < r.slices; ++z) for (std::uint32_t y = 0; y < r.rows; ++y) std::memcpy(bytes + std::uint64_t(z) * depth_pitch + std::uint64_t(y) * row_pitch, from + (std::uint64_t(z) * r.rows + y) * pitch, r.row_bytes); }; // On the host only while the subresource is in GENERAL: it is from creation, and stays there until a // barrier moves it (D3D12's COMMON is GENERAL). Any other layout goes through the staging copy, which // moves it as a CopyTextureRegion would. if (allow_host && host_transfer_ && device_.context->layout(id(), subresource) == VK_IMAGE_LAYOUT_GENERAL) { std::vector packed(r.row_bytes * r.rows * r.slices); if (write) pack(packed.data(), r.row_bytes); if (!host_copy(write, r, packed.data())) return E_FAIL; if (!write) unpack(packed.data(), r.row_bytes); return S_OK; } return staged_copy(write, subresource, r, pack, unpack); } // Tightly packed `memory` to or from the region, with VK_EXT_host_image_copy. bool host_copy(bool write, const Region& r, void* memory) { const VkOffset3D offset{std::int32_t(r.box.left), std::int32_t(r.box.top), std::int32_t(r.box.front)}; const VkExtent3D extent{r.box.right - r.box.left, r.box.bottom - r.box.top, r.slices}; const VkDevice dev = device_.info.device; if (write) { VkMemoryToImageCopyEXT copy{VK_STRUCTURE_TYPE_MEMORY_TO_IMAGE_COPY_EXT}; copy.pHostPointer = memory; copy.imageSubresource = r.layers; copy.imageOffset = offset; copy.imageExtent = extent; VkCopyMemoryToImageInfoEXT info{VK_STRUCTURE_TYPE_COPY_MEMORY_TO_IMAGE_INFO_EXT}; info.dstImage = image_; info.dstImageLayout = VK_IMAGE_LAYOUT_GENERAL; info.regionCount = 1; info.pRegions = © return device_.copy_memory_to_image(dev, &info) == VK_SUCCESS; } VkImageToMemoryCopyEXT copy{VK_STRUCTURE_TYPE_IMAGE_TO_MEMORY_COPY_EXT}; copy.pHostPointer = memory; copy.imageSubresource = r.layers; copy.imageOffset = offset; copy.imageExtent = extent; VkCopyImageToMemoryInfoEXT info{VK_STRUCTURE_TYPE_COPY_IMAGE_TO_MEMORY_INFO_EXT}; info.srcImage = image_; info.srcImageLayout = VK_IMAGE_LAYOUT_GENERAL; info.regionCount = 1; info.pRegions = © return device_.copy_image_to_memory(dev, &info) == VK_SUCCESS; } // Every subresource of a new host-transfer image to GENERAL, zero-filled unless the heap said not to. bool host_initialize() { const VkDevice dev = device_.info.device; VkHostImageLayoutTransitionInfoEXT transition{VK_STRUCTURE_TYPE_HOST_IMAGE_LAYOUT_TRANSITION_INFO_EXT}; transition.image = image_; transition.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; transition.newLayout = VK_IMAGE_LAYOUT_GENERAL; transition.subresourceRange = {binding_.aspects, 0, binding_.mip_levels, 0, binding_.volume ? VK_REMAINING_ARRAY_LAYERS : binding_.array_layers}; if (device_.transition_image_layout(dev, 1, &transition) != VK_SUCCESS) return false; if (binding_.not_zeroed) return true; const std::uint32_t planes = leonida::two_planes(binding_) ? 2 : 1; const std::uint32_t per_plane = binding_.mip_levels * binding_.array_layers; std::vector zero; for (UINT subresource = 0; subresource < planes * per_plane; ++subresource) { Region r{}; if (!region(subresource, nullptr, r)) return false; zero.assign(r.row_bytes * r.rows * r.slices, std::byte{0}); if (!host_copy(true, r, zero.data())) return false; } return true; } // A host-visible buffer at D3D12's footprint pitch, copied to or from the subresource by a CopyTextureRegion // replayed on the device's queue, then waited for. The replay handles the layout (and a first use's zero fill) // exactly as it does for the application's own copies. template HRESULT staged_copy(bool write, UINT subresource, const Region& r, const Pack& pack, const Unpack& unpack) { auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; const std::uint64_t pitch = (r.row_bytes + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1) / D3D12_TEXTURE_DATA_PITCH_ALIGNMENT * D3D12_TEXTURE_DATA_PITCH_ALIGNMENT; leonida::ResourceBinding staging{}; staging.size = pitch * r.rows * r.slices; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = staging.size; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; // storage: D24 depth conversion device_.share(info); if (vk.vkCreateBuffer(dev, &info, nullptr, &staging.buffer) != VK_SUCCESS) return E_OUTOFMEMORY; VkDeviceMemory memory = VK_NULL_HANDLE; void* mapped = nullptr; const auto release = [&](HRESULT hr) { if (memory) vk.vkFreeMemory(dev, memory, nullptr); // unmaps it vk.vkDestroyBuffer(dev, staging.buffer, nullptr); return hr; }; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(dev, staging.buffer, &requirements); { leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::staging); memory = device_.allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, write ? 0 : VK_MEMORY_PROPERTY_HOST_CACHED_BIT); } if (!memory || vk.vkBindBufferMemory(dev, staging.buffer, memory, 0) != VK_SUCCESS || vk.vkMapMemory(dev, memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) return release(E_OUTOFMEMORY); if (write) pack(static_cast(mapped), pitch); // The staging buffer is a resource only for the length of this call; its ID is its binding's address, // which no COM resource can share. const auto staging_id = reinterpret_cast(&staging); const std::uint32_t k = r.block.block; const leonida::CopyLocation texture{id(), false, subresource, 0, 0, 0, 0, 0}; const leonida::CopyLocation placed{staging_id, true, 0, 0, std::uint32_t(r.row_bytes / r.block.bytes) * k, r.rows * k, r.slices, std::uint32_t(pitch)}; leonida::CopyTexture copy{}; if (write) { copy = {texture, r.box.left, r.box.top, r.box.front, placed, false, {}}; } else { copy = {placed, 0, 0, 0, texture, true, {r.box.left, r.box.top, r.box.front, r.box.right, r.box.bottom, r.box.back}}; } leonida::CommandList list; if (!list.copy_texture(copy) || !list.close()) return release(E_INVALIDARG); device_.context->add_resource(staging_id, staging); leonida::ReplayResult result = leonida::ReplayResult::unsupported; { std::lock_guard lock(device_.staging_mutex); // Review D9: a VkQueue the game's direct queue is not on. CreateCommandQueue hands each family's VkQueues // out from the first, so the last one. A colour copy goes to the copy family, whose engine runs beside // queued graphics work (a second graphics VkQueue may be time-sliced behind it, as on NVIDIA); a depth // or stencil copy may convert D24, and an rgb96 one is repacked, by a compute shader, so they stay on // the graphics family. const bool copy_family = !device_.info.copy_queues.empty() && aspects_ == VK_IMAGE_ASPECT_COLOR_BIT && !rgb96_; auto& staging_queue = copy_family ? device_.staging_copy_queue : device_.staging_queue; if (!staging_queue) { if (copy_family) { staging_queue = std::make_unique( *device_.context, device_.info.copy_queues.back(), device_.info.copy_family, leonida::VulkanQueue::QueueKind::copy); } else { const auto& queues = device_.info.command_queues; const VkQueue own = queues.size() > 1 ? queues.back() : device_.info.queue; staging_queue = std::make_unique(*device_.context, own, device_.info.queue_family); } staging_queue->make_synchronous(); // submitted inline, then waited for (wait_submitted below) staging_queue->set_skip_before_execute(true); // internal staging copy only; never reads world heaps/mirror } if (staging_queue->ok()) { const leonida::CommandList* lists[] = {&list}; result = staging_queue->execute(lists); // Only this copy's own submission (review D9: was vkQueueWaitIdle under the submit lock). Other // queues need no wait: D3D12 asks the application to have seen the texture's GPU work complete before // a CPU copy, and that host wait, then this submission, orders it before the copy. if (result == leonida::ReplayResult::success && !staging_queue->wait_submitted()) result = leonida::ReplayResult::unsupported; } } device_.context->remove_resource(staging_id); if (result != leonida::ReplayResult::success) { log_once("WriteToSubresource/ReadFromSubresource staging copy failed; replay result", int(result)); return release(E_FAIL); } if (!write) unpack(static_cast(mapped), pitch); return release(S_OK); } bool cpu_visible() const { if (heap_.Type == D3D12_HEAP_TYPE_UPLOAD || heap_.Type == D3D12_HEAP_TYPE_READBACK) return true; return heap_.Type == D3D12_HEAP_TYPE_CUSTOM && heap_.CPUPageProperty != D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE && heap_.CPUPageProperty != D3D12_CPU_PAGE_PROPERTY_UNKNOWN; } // Only these heaps hold bytes the CPU writes. READBACK is CPU-visible but GPU-written, and DEFAULT arena memory // is also GPU-written; both can hold stale bytes at replay time, so host_at() must not read them as inputs. bool cpu_writable() const { if (heap_.Type == D3D12_HEAP_TYPE_UPLOAD) return true; return heap_.Type == D3D12_HEAP_TYPE_CUSTOM && (heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK || heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE); } DeviceState& device_; D3D12_RESOURCE_DESC desc_; Resource* storage_ = nullptr; bool title_image_registered_ = false; D3D12_HEAP_PROPERTIES heap_; D3D12_HEAP_FLAGS heap_flags_; VkImage image_ = VK_NULL_HANDLE; VkBuffer buffer_ = VK_NULL_HANDLE; VkDeviceMemory memory_ = VK_NULL_HANDLE; std::unique_ptr image_range_; // a texture's, instead of memory_ VkMemoryPropertyFlags memory_flags_ = 0; VkDeviceSize image_backing_bytes_ = 0; // Vulkan image memory requirement; excludes pool alignment/padding. std::unique_ptr pooled_image_; VkAccelerationStructureKHR accel_ = VK_NULL_HANDLE; void* mapped_ = nullptr; VkFormat format_ = VK_FORMAT_UNDEFINED; std::vector view_formats_; // creation-time castable list; empty means no restriction std::vector castable_formats_; // the same list as the application gave it VkFormat uint_backed_ = VK_FORMAT_UNDEFINED; bool a8_as_alpha_ = false; std::uint64_t image_address_ = 0; // what a T# names the texture by void* title_address_ = nullptr; // where the title placed this texture (place_at_title_address), or null bool title_texture_ = false; // mark_title_texture mutable std::atomic shader_views_{0}; // T#s written for it (write_image_descriptor), for the census mutable std::atomic min_shader_view_mip_{UINT32_MAX}; std::atomic title_mapped_{false}; // Map told the registry bool rgb96_ = false; VkImageAspectFlags aspects_ = 0; std::uint64_t buffer_va_ = 0; std::uint64_t gpu_va_ = 0; bool host_import_ = false; // memory_ is the caller's pages (create_host_buffer): freed at once, not deferred std::uint64_t host_pin_ = 0; // create_host_buffer: the pages' leonida::kernel_writes pin while memory_ lives std::uint8_t* shadow_ = nullptr; // create_shadow_buffer: memory_ mapped, in DeviceState::shadows bool aliased_ = false; // va_ is in leonida::title_va_aliases(), reached at title_alias_ std::uint64_t title_alias_ = 0; bool reserved_ = false; bool sparse_image_ = false; bool placed_ = false; leonida::ResourceBinding binding_{}; // a texture's, as registered with the context std::unique_ptr depth_conversion_; std::array, 2> storage_planes_; // Xbox depth/stencil UAV, by plane bool console_d16s8_ = false; // created from Xbox format 118 (even when pc_format made it D24S8) VkImage shared_zero_ = VK_NULL_HANDLE; // owned by the device std::unique_ptr deferred_attachment_; std::atomic replay_seen_{false}; bool staged_title_ = false; std::atomic deferred_stream_{false}; // keys stay unpublished until the mips they name are uploaded std::atomic placed_publish_from_{0}; VkDeviceSize deferred_bytes_ = 0; std::uint32_t deferred_types_ = 0; bool host_transfer_ = false; // created with VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT D3D12_GPU_VIRTUAL_ADDRESS va_ = 0; // a buffer's console VA, or a slot-133 texture's title address VkDeviceSize arena_offset_ = 0; bool in_arena_ = false; bool in_external_window_ = false; // A placed buffer's heap range, held as a D3D12 placed resource holds its heap: the app may release the heap // first, and the range must not go to another allocation while this buffer lives. std::shared_ptr heap_range_; std::atomic arena_map_refs_{0}; }; // One immutable, zeroed BC image per exact view shape (zeroed on the host, or by the first shader submission). It has // the right sampled format, extent, // mip count and zero-block decoding even before the title first supplies data or copies into the placement. VkImage DeviceState::zero_sampled_image(const D3D12_RESOURCE_DESC& d, const Format& format, VkDeviceSize bytes) { if (copy_memory_to_image && !host_transfer_format(format.format)) return VK_NULL_HANDLE; const ZeroShape key{d.Format, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels}; std::lock_guard lock(zero_image_mutex); if (auto it = zero_images.find(key); it != zero_images.end()) return it->second ? it->second->image() : VK_NULL_HANDLE; constexpr VkDeviceSize limit = 256ull << 20; const auto used = zero_image_bytes.load(std::memory_order_relaxed); if (used >= limit || bytes > limit - used) return VK_NULL_HANDLE; const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0, 1, 1}; auto* zero = new Resource(*this, d, heap, D3D12_HEAP_FLAG_NONE); std::vector zero_castable; if (!format.uint_backed && !format.typeless && console_format_stand_ins()) { const VkFormat twin = Resource::unorm_srgb_twin(format.format); if (twin != VK_FORMAT_UNDEFINED) zero_castable = {format.format, twin}; } if (FAILED(zero->create_texture(format, zero_castable)) || (copy_memory_to_image && !zero->host_initialized_image()) || zero->image_backing_bytes() > limit - used) { zero->Release(); zero_images.emplace(key, nullptr); return VK_NULL_HANDLE; } if (!zero->host_initialized_image()) context->note_shader_image(zero->id()); // cleared before a shader reads it zero_images.emplace(key, zero); zero_image_bytes.fetch_add(zero->image_backing_bytes(), std::memory_order_relaxed); return zero->image(); } // DXGI -> Vulkan for vertex attributes, with each element's size for D3D12_APPEND_ALIGNED_ELEMENT. bool vertex_format(DXGI_FORMAT format, VkFormat& out, UINT& bytes) { struct Row { DXGI_FORMAT dxgi; VkFormat vk; UINT bytes; }; static constexpr Row rows[] = { {DXGI_FORMAT_R32G32B32A32_FLOAT, VK_FORMAT_R32G32B32A32_SFLOAT, 16}, {DXGI_FORMAT_R32G32B32A32_UINT, VK_FORMAT_R32G32B32A32_UINT, 16}, {DXGI_FORMAT_R32G32B32A32_SINT, VK_FORMAT_R32G32B32A32_SINT, 16}, {DXGI_FORMAT_R32G32B32_FLOAT, VK_FORMAT_R32G32B32_SFLOAT, 12}, {DXGI_FORMAT_R32G32B32_UINT, VK_FORMAT_R32G32B32_UINT, 12}, {DXGI_FORMAT_R32G32B32_SINT, VK_FORMAT_R32G32B32_SINT, 12}, {DXGI_FORMAT_R32G32_FLOAT, VK_FORMAT_R32G32_SFLOAT, 8}, {DXGI_FORMAT_R32G32_UINT, VK_FORMAT_R32G32_UINT, 8}, {DXGI_FORMAT_R32G32_SINT, VK_FORMAT_R32G32_SINT, 8}, {DXGI_FORMAT_R32_FLOAT, VK_FORMAT_R32_SFLOAT, 4}, {DXGI_FORMAT_R32_UINT, VK_FORMAT_R32_UINT, 4}, {DXGI_FORMAT_R32_SINT, VK_FORMAT_R32_SINT, 4}, {DXGI_FORMAT_R16G16B16A16_FLOAT, VK_FORMAT_R16G16B16A16_SFLOAT, 8}, {DXGI_FORMAT_R16G16B16A16_UNORM, VK_FORMAT_R16G16B16A16_UNORM, 8}, {DXGI_FORMAT_R16G16B16A16_SNORM, VK_FORMAT_R16G16B16A16_SNORM, 8}, {DXGI_FORMAT_R16G16B16A16_UINT, VK_FORMAT_R16G16B16A16_UINT, 8}, {DXGI_FORMAT_R16G16B16A16_SINT, VK_FORMAT_R16G16B16A16_SINT, 8}, {DXGI_FORMAT_R16G16_FLOAT, VK_FORMAT_R16G16_SFLOAT, 4}, {DXGI_FORMAT_R16G16_UNORM, VK_FORMAT_R16G16_UNORM, 4}, {DXGI_FORMAT_R16G16_SNORM, VK_FORMAT_R16G16_SNORM, 4}, {DXGI_FORMAT_R16G16_UINT, VK_FORMAT_R16G16_UINT, 4}, {DXGI_FORMAT_R16G16_SINT, VK_FORMAT_R16G16_SINT, 4}, {DXGI_FORMAT_R16_FLOAT, VK_FORMAT_R16_SFLOAT, 2}, {DXGI_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, 2}, {DXGI_FORMAT_R16_SNORM, VK_FORMAT_R16_SNORM, 2}, {DXGI_FORMAT_R16_UINT, VK_FORMAT_R16_UINT, 2}, {DXGI_FORMAT_R16_SINT, VK_FORMAT_R16_SINT, 2}, {DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, 4}, {DXGI_FORMAT_R8G8B8A8_SNORM, VK_FORMAT_R8G8B8A8_SNORM, 4}, {DXGI_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_UINT, 4}, {DXGI_FORMAT_R8G8B8A8_SINT, VK_FORMAT_R8G8B8A8_SINT, 4}, {DXGI_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM, 4}, {DXGI_FORMAT_R8G8_UNORM, VK_FORMAT_R8G8_UNORM, 2}, {DXGI_FORMAT_R8G8_SNORM, VK_FORMAT_R8G8_SNORM, 2}, {DXGI_FORMAT_R8G8_UINT, VK_FORMAT_R8G8_UINT, 2}, {DXGI_FORMAT_R8G8_SINT, VK_FORMAT_R8G8_SINT, 2}, {DXGI_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, 1}, {DXGI_FORMAT_R8_SNORM, VK_FORMAT_R8_SNORM, 1}, {DXGI_FORMAT_R8_UINT, VK_FORMAT_R8_UINT, 1}, {DXGI_FORMAT_R8_SINT, VK_FORMAT_R8_SINT, 1}, {DXGI_FORMAT_R10G10B10A2_UNORM, VK_FORMAT_A2B10G10R10_UNORM_PACK32, 4}, {DXGI_FORMAT_R10G10B10A2_UINT, VK_FORMAT_A2B10G10R10_UINT_PACK32, 4}, {DXGI_FORMAT_R11G11B10_FLOAT, VK_FORMAT_B10G11R11_UFLOAT_PACK32, 4}, }; for (const Row& row : rows) if (row.dxgi == format) { out = row.vk; bytes = row.bytes; return true; } return false; } VkBlendFactor blend_factor(D3D12_BLEND blend) { switch (blend) { case D3D12_BLEND_ZERO: return VK_BLEND_FACTOR_ZERO; case D3D12_BLEND_ONE: return VK_BLEND_FACTOR_ONE; case D3D12_BLEND_SRC_COLOR: return VK_BLEND_FACTOR_SRC_COLOR; case D3D12_BLEND_INV_SRC_COLOR: return VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR; case D3D12_BLEND_SRC_ALPHA: return VK_BLEND_FACTOR_SRC_ALPHA; case D3D12_BLEND_INV_SRC_ALPHA: return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; case D3D12_BLEND_DEST_ALPHA: return VK_BLEND_FACTOR_DST_ALPHA; case D3D12_BLEND_INV_DEST_ALPHA: return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA; case D3D12_BLEND_DEST_COLOR: return VK_BLEND_FACTOR_DST_COLOR; case D3D12_BLEND_INV_DEST_COLOR: return VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR; case D3D12_BLEND_SRC_ALPHA_SAT: return VK_BLEND_FACTOR_SRC_ALPHA_SATURATE; case D3D12_BLEND_BLEND_FACTOR: return VK_BLEND_FACTOR_CONSTANT_COLOR; case D3D12_BLEND_INV_BLEND_FACTOR: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR; case D3D12_BLEND_SRC1_COLOR: return VK_BLEND_FACTOR_SRC1_COLOR; case D3D12_BLEND_INV_SRC1_COLOR: return VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR; case D3D12_BLEND_SRC1_ALPHA: return VK_BLEND_FACTOR_SRC1_ALPHA; case D3D12_BLEND_INV_SRC1_ALPHA: return VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA; case D3D12_BLEND_ALPHA_FACTOR: return VK_BLEND_FACTOR_CONSTANT_ALPHA; case D3D12_BLEND_INV_ALPHA_FACTOR: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA; default: return VK_BLEND_FACTOR_ONE; } } VkBlendOp blend_op(D3D12_BLEND_OP op) { switch (op) { case D3D12_BLEND_OP_SUBTRACT: return VK_BLEND_OP_SUBTRACT; case D3D12_BLEND_OP_REV_SUBTRACT: return VK_BLEND_OP_REVERSE_SUBTRACT; case D3D12_BLEND_OP_MIN: return VK_BLEND_OP_MIN; case D3D12_BLEND_OP_MAX: return VK_BLEND_OP_MAX; default: return VK_BLEND_OP_ADD; } } // D3D12 and Vulkan list the logic ops in different orders, so each is named. VkLogicOp logic_op(D3D12_LOGIC_OP op) { switch (op) { case D3D12_LOGIC_OP_CLEAR: return VK_LOGIC_OP_CLEAR; case D3D12_LOGIC_OP_SET: return VK_LOGIC_OP_SET; case D3D12_LOGIC_OP_COPY: return VK_LOGIC_OP_COPY; case D3D12_LOGIC_OP_COPY_INVERTED: return VK_LOGIC_OP_COPY_INVERTED; case D3D12_LOGIC_OP_NOOP: return VK_LOGIC_OP_NO_OP; case D3D12_LOGIC_OP_INVERT: return VK_LOGIC_OP_INVERT; case D3D12_LOGIC_OP_AND: return VK_LOGIC_OP_AND; case D3D12_LOGIC_OP_NAND: return VK_LOGIC_OP_NAND; case D3D12_LOGIC_OP_OR: return VK_LOGIC_OP_OR; case D3D12_LOGIC_OP_NOR: return VK_LOGIC_OP_NOR; case D3D12_LOGIC_OP_XOR: return VK_LOGIC_OP_XOR; case D3D12_LOGIC_OP_EQUIV: return VK_LOGIC_OP_EQUIVALENT; case D3D12_LOGIC_OP_AND_REVERSE: return VK_LOGIC_OP_AND_REVERSE; case D3D12_LOGIC_OP_AND_INVERTED: return VK_LOGIC_OP_AND_INVERTED; case D3D12_LOGIC_OP_OR_REVERSE: return VK_LOGIC_OP_OR_REVERSE; case D3D12_LOGIC_OP_OR_INVERTED: return VK_LOGIC_OP_OR_INVERTED; default: return VK_LOGIC_OP_COPY; } } // D3D12_COMPARISON_FUNC (NEVER = 1 .. ALWAYS = 8) and D3D12_STENCIL_OP (KEEP = 1 .. DECR = 8) list their values // in Vulkan's order, starting at 1 instead of 0. VkCompareOp compare_op(D3D12_COMPARISON_FUNC func) { const int value = int(func); return value >= 1 && value <= 8 ? VkCompareOp(value - 1) : VK_COMPARE_OP_ALWAYS; } VkStencilOp stencil_op(D3D12_STENCIL_OP op) { const int value = int(op); return value >= 1 && value <= 8 ? VkStencilOp(value - 1) : VK_STENCIL_OP_KEEP; } VkStencilOpState stencil_face(const D3D12_DEPTH_STENCILOP_DESC& face, UINT8 read_mask, UINT8 write_mask) { VkStencilOpState state{}; state.failOp = stencil_op(face.StencilFailOp); state.passOp = stencil_op(face.StencilPassOp); state.depthFailOp = stencil_op(face.StencilDepthFailOp); state.compareOp = compare_op(face.StencilFunc); state.compareMask = read_mask; state.writeMask = write_mask; return state; } bool equal_semantic(const std::string& a, const char* b) { if (!b || a.size() != std::strlen(b)) return false; for (std::size_t i = 0; i < a.size(); ++i) if (std::tolower(static_cast(a[i])) != std::tolower(static_cast(b[i]))) return false; return true; } // A heap (section 3.3): a range of the GPU address arena, as large as the game asked for, so a placed buffer can // name any 64 KiB-aligned offset in it. Textures placed in it still get their own VkDeviceMemory; the offset is only // their key, which keeps optimal-tiling images out of the arena's memory type. bool DeviceState::publish_mapped_textures() { if(!map_count.load(std::memory_order_acquire)) return true; std::vector pending; { std::lock_guard lock(mapped_texture_mutex); for(auto* r:mapped_textures) if(r->try_add_ref()) pending.push_back(r); } bool ok=true; for(auto* r:pending) { if(!r->publish_cpu_writes()) ok=false; r->Release(); } return ok; } bool DeviceState::materialize_sample(const leonida::DescriptorKey& key) { if (!pending_sample_count.load(std::memory_order_acquire)) return true; PendingSample sample{}; { std::lock_guard lock(pending_view_mutex); const auto it = pending_samples.find(key); if (it == pending_samples.end()) return true; sample = it->second; if (!sample.owner->try_add_ref()) return false; } const auto image = sample.owner->bound_image(); const bool ok = image && bind_image(key, sample.image, image, sample.view_format, sample.channels_format, sample.view_format, sample.owner->aspects(), true, false, {}, nullptr, true); if (ok) { context->note_shader_image(sample.owner->id()); std::lock_guard lock(pending_view_mutex); const auto it=pending_samples.find(key); if (it!=pending_samples.end() && it->second.owner==sample.owner) { pending_samples.erase(it); --pending_sample_count; } } sample.owner->Release(); return ok; } bool DeviceState::materialize_table(std::uint64_t address, std::uint32_t slots) { if (!pending_sample_count.load(std::memory_order_acquire)) return true; if (!slots && address) { std::vector keys; { std::lock_guard lock(pending_view_mutex); for (const auto& [key,view]:pending_samples) if (view.owner->id() == address) keys.push_back(key); } for (const auto& key:keys) if (!materialize_sample(key)) return false; write_tsharp_index_words(keys); return true; } std::uint64_t end = 0; if (slots) { std::lock_guard lock(visible_heap_mutex); auto it = visible_heaps.upper_bound(address); if (it != visible_heaps.begin()) { --it; const UINT step = descriptor_increment(it->second.type); if (address < it->second.end && (address - it->first) % step == 0) { if (it->second.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) return true; end = address + std::min(it->second.end - address, std::uint64_t(slots) * step); } } } if (!end) { // Directly indexed and unrecognized heaps have no trustworthy table extent. std::vector all; {std::lock_guard lock(pending_view_mutex);for(const auto& [key,v]:pending_samples) all.push_back(key);} for(const auto& key:all) if(!materialize_sample(key)) return false; write_tsharp_index_words(all); return true; } const auto refreshed = std::min(end-address, std::uint64_t(kViewScanLimit)*kDescriptorSize); std::uint8_t* const table = arena_host(address, end-address); // a live heap's table: one allocation if (!table) return false; if (end-address>refreshed) { leonida::title_va_aliases().pull_descriptors(table+refreshed,std::size_t(end-address-refreshed)); arena_mark_dirty(address + refreshed, end - address - refreshed); } for (auto at=address; at& keys) { if (!tsharp_index_words || keys.empty()) return; namespace g = leonida::gfx10; const std::set wanted(keys.begin(), keys.end()); // Hold visible_heap_mutex across the scan loop so concurrent ~DescriptorHeap() cannot free cpu_view_heaps // storage while we read/write it (lock order visible_heap_mutex -> descriptor_mutex is acyclic). std::lock_guard heap_lock(visible_heap_mutex); std::vector> ranges; for (const auto& [offset, heap] : visible_heaps) if (heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) if (std::uint8_t* host = arena_host(offset, heap.end - offset)) ranges.emplace_back(host, std::size_t(heap.end - offset)); for (const auto& [begin, end] : cpu_view_heaps) ranges.emplace_back(reinterpret_cast(begin), std::size_t(end - begin)); if (ranges.empty()) return; std::lock_guard desc_lock(descriptor_mutex); for (const auto& [base, bytes] : ranges) for (std::size_t at = 0; at + kDescriptorSize <= bytes; at += kDescriptorSize) { g::ImageWords words; std::memcpy(words.data(), base + at, sizeof(words)); if (!g::is_image(words)) continue; const g::ImageWords key = g::tsharp_key(words); if (!wanted.count(key)) continue; const std::uint32_t word = tsharp_index_word_locked(key); std::memcpy(base + at + 4 * g::kTsharpIndexDword, &word, sizeof(word)); arena_mark_dirty_ptr(base + at + 4 * g::kTsharpIndexDword, sizeof(word)); } } class Heap final : public Child { public: // {5d20c7a4-8e13-4b6d-9f27-3a1c94e0b7d8} static constexpr GUID kTag{0x5d20c7a4, 0x8e13, 0x4b6d, {0x9f, 0x27, 0x3a, 0x1c, 0x94, 0xe0, 0xb7, 0xd8}}; Heap(DeviceState& device, const D3D12_HEAP_DESC& desc) : device_(device), desc_(desc) { VkDeviceSize offset = 0; leonida::ArenaBacking::Location place; if (device_.arena_ready() && device_.arena_allocate(desc_.SizeInBytes, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, offset, DeviceState::arena_heap)) { // The heap is one arena allocation, so one backing unit: its tiles are that unit's memory, at the heap's // place in it. A reserved resource binds them (vulkan_backend.h bind_tiles), so `offset` is the memory // offset; the arena VA stays in arena_offset_. if (!device_.arena.backing.locate(offset, desc_.SizeInBytes, place)) { device_.note_unbacked_arena(offset, desc_.SizeInBytes); device_.arena_release(offset, desc_.SizeInBytes, DeviceState::arena_heap); return; } arena_offset_ = offset; allocation_ = std::shared_ptr( new leonida::TileHeapAllocation{place.memory, place.memory_offset, desc_.SizeInBytes, device_.arena.memory_type}, [&device, offset](const leonida::TileHeapAllocation* allocation) { device.arena_release(offset, allocation->size, DeviceState::arena_heap); delete allocation; }); } } // An existing heap (OpenExistingHeapFromAddress): `memory` is the caller's committed range imported with // VK_EXT_external_memory_host, and the heap owns that VkDeviceMemory, not the range. Not in the arena. Heap(DeviceState& device, const D3D12_HEAP_DESC& desc, VkDeviceMemory memory, std::uint32_t memory_type, const void* address) : device_(device), desc_(desc), host_address_(address) { allocation_ = std::shared_ptr( new leonida::TileHeapAllocation{memory, 0, desc_.SizeInBytes, memory_type}, [device = device_.info.device, free = device_.context->vk.vkFreeMemory] (const leonida::TileHeapAllocation* allocation) { free(device, allocation->memory, nullptr); delete allocation; }); } // As the host reports it (measured against the PC runtime, d3d12_vulkan_device_test compare_heap_descs): the // alignment the heap was placed with (64 KiB for an Alignment of 0) and the one node for a node mask of 0, as the // layer's resources, descriptor heaps and queues already answer. D3D12_HEAP_DESC STDMETHODCALLTYPE GetDesc() override { D3D12_HEAP_DESC desc = desc_; desc.Alignment = alignment(); desc.Properties.CreationNodeMask = 1; desc.Properties.VisibleNodeMask = 1; return desc; } bool reserved() const { return bool(allocation_); } // An existing heap: the caller's memory, not an arena range, so offset() is not a place in the arena. const void* host_address() const { return host_address_; } const std::shared_ptr& arena_range() const { return allocation_; } VkDeviceSize offset() const { return arena_offset_; } // the heap's arena VA (an arena heap only) UINT64 bytes() const { return desc_.SizeInBytes; } UINT64 alignment() const { return desc_.Alignment ? desc_.Alignment : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; } const D3D12_HEAP_PROPERTIES& properties() const { return desc_.Properties; } D3D12_HEAP_FLAGS flags() const { return desc_.Flags; } std::shared_ptr tiles(const leonida::VulkanContext& context, bool image, std::uint32_t memory_types) { const auto denied = image ? D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES : D3D12_HEAP_FLAG_DENY_BUFFERS; if (device_.context.get() != &context || desc_.Properties.Type != D3D12_HEAP_TYPE_DEFAULT || (desc_.Flags & denied) || host_address_) return {}; std::lock_guard lock(backing_mutex_); if (!image && device_.tiles_share_arena()) { if (tile_allocation_) return {}; arena_tiles_ = true; return allocation_; } // Vulkan only guarantees sparse aliasing between compatible images. A texture tile heap has its own // backing, so a heap already used for buffer tiles or placed buffers cannot also map texture tiles. if (arena_tiles_ || (tile_allocation_ && image_tiles_ != image)) return {}; if (placed_buffer_ || (image && placed_image_)) return {}; if (!tile_allocation_) { std::uint32_t memory_type = 0; if (!image) memory_types = device_.sparse_buffer_memory_types; const VkMemoryRequirements requirements{desc_.SizeInBytes, leonida::tile_size_in_bytes, memory_types}; // VRAM preferred, not required: with VRAM full a tile heap the title asked for has to come from system // memory rather than not at all. memory_types is the sparse resource's own memoryTypeBits. const auto memory = device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, !image, &memory_type); if (!memory) return {}; image_tiles_ = image; tile_allocation_ = std::shared_ptr( new leonida::TileHeapAllocation{memory, 0, desc_.SizeInBytes, memory_type}, [device = device_.info.device, free = device_.context->vk.vkFreeMemory] (const leonida::TileHeapAllocation* allocation) { free(device, allocation->memory, nullptr); delete allocation; }); } return tile_allocation_; } bool use_as_placed_resource(bool buffer) { std::lock_guard lock(backing_mutex_); // A placed resource cannot alias the separate sparse memory allocation. if (tile_allocation_ && (buffer || image_tiles_)) return false; (buffer ? placed_buffer_ : placed_image_) = true; return true; } private: DeviceState& device_; D3D12_HEAP_DESC desc_; const void* host_address_ = nullptr; std::shared_ptr allocation_; VkDeviceSize arena_offset_ = 0; std::mutex backing_mutex_; std::shared_ptr tile_allocation_; bool placed_buffer_ = false; bool placed_image_ = false; bool arena_tiles_ = false; bool image_tiles_ = false; }; // The S#s a shader builds from immediates (literal_samplers in its index entry) are named by no heap slot, so // nothing else gives them a sampler and a hash-table key: without this their lookup finds the fallback sampler // (index 0) and the shader samples with the wrong filter and address modes (docs/design.md, Literal samplers). // Registering is idempotent and also runs when the pipeline is created again. Returns one bindless sampler index per // entry in `entry.literal_samplers` (or 0xFFFFFFFFu when a sampler failed to bind so a specialized shader falls back // to the hash probe). std::vector register_literal_samplers(DeviceState& device, const leonida::ShaderEntry& entry) { std::vector indices; indices.reserve(entry.literal_samplers.size()); for (const leonida::gfx10::SamplerWords& words : entry.literal_samplers) { std::uint32_t idx = leonida::LiteralSamplerSpec::kFallbackIndex; if (!device.bind_sampler(words, &idx)) log_once("a shader's literal S# got no sampler (no bindless set, or its sampler array is full); " "literal S#s in that shader:", int(entry.literal_samplers.size())); indices.push_back(idx); } return indices; } // Among index entries for one program (containers with the same FSSM program; 789 groups in the 26,503-shader // corpus), the one to build: the first that `fits` and declares no set-0 bindings (the cheaper pipeline); else the // first that fits; else the first without bindings; else the first. Null when there is none. template const leonida::ShaderEntry* pick_entry(const std::vector& candidates, Fits&& fits) { const leonida::ShaderEntry* fitting = nullptr; const leonida::ShaderEntry* unbound = nullptr; for (const leonida::ShaderEntry* e : candidates) { const bool fit = fits(*e); if (fit && !e->binding_count) return e; if (fit && !fitting) fitting = e; if (!e->binding_count && !unbound) unbound = e; } if (fitting) return fitting; if (unbound) return unbound; return candidates.empty() ? nullptr : candidates.front(); } // Whether the input layout has an element for every ordinary (non-system-value) input of the vertex shader. bool layout_feeds(const leonida::ShaderEntry& vs, const D3D12_INPUT_LAYOUT_DESC& layout) { const UINT count = layout.pInputElementDescs ? layout.NumElements : 0; for (const auto& input : vs.input_signature) { if (input.system_value) continue; bool fed = false; for (UINT i = 0; i < count && !fed; ++i) fed = layout.pInputElementDescs[i].SemanticIndex == input.semantic_index && equal_semantic(input.semantic, layout.pInputElementDescs[i].SemanticName); if (!fed) return false; } return true; } // Known D3D12_PIPELINE_STATE_FLAGS bits: TOOL_DEBUG (0x1, kept for cached-PSO parity), bit 0x2, // DYNAMIC_DEPTH_BIAS (0x4), and DYNAMIC_INDEX_BUFFER_STRIP_CUT (0x8). Higher bits fail with E_INVALIDARG // on both Windows hardware D3D12 and WARP. constexpr UINT kKnownPipelineStateFlags = 0xFu; class RootSignature final : public Child { public: // {3e9b4a61-2d7c-4f18-b5a0-c71e8d92f036} static constexpr GUID kTag{0x3e9b4a61, 0x2d7c, 0x4f18, {0xb5, 0xa0, 0xc7, 0x1e, 0x8d, 0x92, 0xf0, 0x36}}; RootSignature(RootArgumentLayout layout, std::string content) : layout_(std::move(layout)), content_(std::move(content)) {} const RootArgumentLayout& layout() const { return layout_; } // SHA-256 of the serialized root signature: a cached PSO matches root signatures with the same content. const std::string& content() const { return content_; } private: RootArgumentLayout layout_; std::string content_; }; // The ID3DBlob GetCachedBlob returns. class CachedBlob final : public ID3DBlob { public: explicit CachedBlob(std::vector bytes) : bytes_(std::move(bytes)) {} HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { if (!out) return E_POINTER; if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D10Blob)) { AddRef(); *out = static_cast(this); return S_OK; } *out = nullptr; return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } ULONG STDMETHODCALLTYPE Release() override { const ULONG left = --refs_; if (!left) delete this; return left; } LPVOID STDMETHODCALLTYPE GetBufferPointer() override { return bytes_.data(); } SIZE_T STDMETHODCALLTYPE GetBufferSize() override { return bytes_.size(); } private: std::vector bytes_; std::atomic refs_{1}; }; // A shader as the key sees it, without reading the whole program on every PSO: a DXBC container already carries a // checksum of its contents (bytes 4..19), so that and the size stand for it. A container without one (all zero, as // hand-built test containers have) or other bytecode is hashed with FNV-1a. void key_shader(leonida::cached_pso::KeyBuilder& key, const char* stage, const D3D12_SHADER_BYTECODE& code) { const auto* bytes = static_cast(code.pShaderBytecode); const std::size_t size = bytes ? code.BytecodeLength : 0; key.tag(stage).u32(std::uint32_t(size)).u32(std::uint32_t(std::uint64_t(size) >> 32)); if (size >= 20 && std::memcmp(bytes, "DXBC", 4) == 0 && std::any_of(bytes + 4, bytes + 20, [](std::uint8_t b) { return b != 0; })) { key.bytes(bytes + 4, 16); return; } std::uint64_t h = 0xcbf29ce484222325ull; for (std::size_t i = 0; i < size; ++i) h = (h ^ bytes[i]) * 0x100000001b3ull; key.u32(std::uint32_t(h)).u32(std::uint32_t(h >> 32)); } void key_root_signature(leonida::cached_pso::KeyBuilder& key, ID3D12RootSignature* signature); // The parts of a compute description the PC runtime matches a cached PSO against (not Flags, measured). leonida::cached_pso::Key pipeline_key(const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc) { leonida::cached_pso::KeyBuilder key; key.tag("compute"); key_root_signature(key, desc.pRootSignature); key_shader(key, "cs", desc.CS); key.u32(desc.NodeMask); return leonida::sha256_hex(key.data()); } leonida::cached_pso::Key pipeline_key(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { leonida::cached_pso::KeyBuilder key; key.tag("graphics"); key_root_signature(key, desc.pRootSignature); key_shader(key, "vs", desc.VS); key_shader(key, "ps", desc.PS); key_shader(key, "ds", desc.DS); key_shader(key, "hs", desc.HS); key_shader(key, "gs", desc.GS); const D3D12_STREAM_OUTPUT_DESC& so = desc.StreamOutput; key.u32(so.pSODeclaration ? so.NumEntries : 0); for (UINT i = 0; so.pSODeclaration && i < so.NumEntries; ++i) { const D3D12_SO_DECLARATION_ENTRY& e = so.pSODeclaration[i]; key.u32(e.Stream).text(e.SemanticName).u32(e.SemanticIndex).u32(e.StartComponent).u32(e.ComponentCount); key.u32(e.OutputSlot); } key.u32(so.pBufferStrides ? so.NumStrides : 0); for (UINT i = 0; so.pBufferStrides && i < so.NumStrides; ++i) key.u32(so.pBufferStrides[i]); key.u32(so.RasterizedStream); const D3D12_BLEND_DESC& blend = desc.BlendState; key.u32(blend.AlphaToCoverageEnable).u32(blend.IndependentBlendEnable); for (const D3D12_RENDER_TARGET_BLEND_DESC& t : blend.RenderTarget) key.u32(t.BlendEnable).u32(t.LogicOpEnable).u32(t.SrcBlend).u32(t.DestBlend).u32(t.BlendOp).u32(t.SrcBlendAlpha) .u32(t.DestBlendAlpha).u32(t.BlendOpAlpha).u32(t.LogicOp).u32(t.RenderTargetWriteMask); key.u32(desc.SampleMask); const D3D12_RASTERIZER_DESC& r = desc.RasterizerState; std::uint32_t bias_clamp = 0, slope = 0; std::memcpy(&bias_clamp, &r.DepthBiasClamp, 4); std::memcpy(&slope, &r.SlopeScaledDepthBias, 4); key.u32(r.FillMode).u32(r.CullMode).u32(r.FrontCounterClockwise).u32(std::uint32_t(r.DepthBias)).u32(bias_clamp); key.u32(slope).u32(r.DepthClipEnable).u32(r.MultisampleEnable).u32(r.AntialiasedLineEnable); key.u32(r.ForcedSampleCount).u32(r.ConservativeRaster); const D3D12_DEPTH_STENCIL_DESC& d = desc.DepthStencilState; key.u32(d.DepthEnable).u32(d.DepthWriteMask).u32(d.DepthFunc).u32(d.StencilEnable).u32(d.StencilReadMask); key.u32(d.StencilWriteMask); for (const D3D12_DEPTH_STENCILOP_DESC& face : {d.FrontFace, d.BackFace}) key.u32(face.StencilFailOp).u32(face.StencilDepthFailOp).u32(face.StencilPassOp).u32(face.StencilFunc); const D3D12_INPUT_LAYOUT_DESC& input = desc.InputLayout; const UINT input_count = input.pInputElementDescs ? std::min(input.NumElements, D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT) : 0; key.u32(input_count); for (UINT i = 0; i < input_count; ++i) { const D3D12_INPUT_ELEMENT_DESC& e = input.pInputElementDescs[i]; key.text(e.SemanticName).u32(e.SemanticIndex).u32(e.Format).u32(e.InputSlot).u32(e.AlignedByteOffset); key.u32(e.InputSlotClass).u32(e.InstanceDataStepRate); } key.u32(desc.IBStripCutValue).u32(std::bit_cast(desc.PrimitiveTopologyType)) .u32(desc.NumRenderTargets); for (const DXGI_FORMAT format : desc.RTVFormats) key.u32(format); key.u32(desc.DSVFormat).u32(desc.SampleDesc.Count).u32(desc.SampleDesc.Quality).u32(desc.NodeMask); return leonida::sha256_hex(key.data()); } // CachedPSO as the PC runtime checks it before creating the PSO (src/cached_pso.h has the measured answers). HRESULT check_cached_pso(const leonida::cached_pso::Identity& identity, const leonida::cached_pso::Key& key, const D3D12_CACHED_PIPELINE_STATE& cached) { if (!cached.pCachedBlob) return S_OK; if (!cached.CachedBlobSizeInBytes) return E_INVALIDARG; using leonida::cached_pso::Check; switch (leonida::cached_pso::check(identity, key, {static_cast(cached.pCachedBlob), cached.CachedBlobSizeInBytes})) { case Check::accepted: return S_OK; case Check::other_adapter: return D3D12_ERROR_ADAPTER_NOT_FOUND; case Check::other_driver: return D3D12_ERROR_DRIVER_VERSION_MISMATCH; default: return E_INVALIDARG; } } // The console's ID3D12PipelineState goes past the public interface, which ends at slot 8 (GetCachedBlob). The // FidelityFX DLL calls slot 11 on every compute pipeline it creates (docs/d3d12_command_objects.md, "Pipeline slot 11 // sizes the compute scratch"). These three are declared here, ahead of Object's virtual destructor, so they are vtable // slots 9, 10 and 11 under MSVC and GCC alike; declared in PipelineState itself they would come after the destructor, // which takes one slot under MSVC and two under GCC. d3d12_fspx_compute_test calls slot 11 through the vtable. class XboxPipelineStateStubs : public ID3D12PipelineStateStubs { public: virtual HRESULT STDMETHODCALLTYPE xbox_slot9(UINT64, UINT64, UINT64) = 0; virtual HRESULT STDMETHODCALLTYPE xbox_slot10(UINT64, UINT64, UINT64) = 0; virtual HRESULT STDMETHODCALLTYPE xbox_slot11(UINT64, UINT64, void** out) = 0; }; // A D3D12_PIPELINE_STATE_STREAM_DESC (ID3D12Device2::CreatePipelineState) as the descriptions the PSO creators take. // The stream is a run of subobjects, each a D3D12_PIPELINE_STATE_SUBOBJECT_TYPE followed by its description at that // description's alignment, each subobject starting at pointer alignment (the d3dx12.h layout, `alignas(void*)`). A // subobject that is absent takes the runtime's default (the CD3DX12 defaults: depth test on with LESS, back-face // culling, no blending, sample mask 0xFFFFFFFF, one sample). A type given twice, a truncated stream or an unknown // type is E_INVALIDARG, as on the PC runtime; state this layer cannot honour yet is E_NOTIMPL with a log. // The back face's stencil masks of a DEPTH_STENCIL2 subobject. D3D12_DEPTH_STENCIL_DESC has one read and one write // mask for both faces, so the face masks travel beside the description. struct StencilFaceMasks { UINT8 read = D3D12_DEFAULT_STENCIL_READ_MASK; UINT8 write = D3D12_DEFAULT_STENCIL_WRITE_MASK; }; struct PipelineStream { D3D12_GRAPHICS_PIPELINE_STATE_DESC graphics{}; bool back_masks = false; // DEPTH_STENCIL2: back_stencil holds the back face's masks StencilFaceMasks back_stencil; D3D12_COMPUTE_PIPELINE_STATE_DESC compute{}; D3D12_SHADER_BYTECODE ms{}; D3D12_SHADER_BYTECODE as{}; bool has_cs = false; bool has_graphics_stage = false; // VS, PS, DS, HS, GS, AS or MS bool depth_bounds = false; // DEPTH_STENCIL1/2 DepthBoundsTestEnable (not in the plain graphics desc) }; // What pipeline_order.log names a stream's pipeline by: the cache key, with the mesh shader's hash folded in (the // graphics key does not cover the MS, so two mesh pipelines that differ only there would share it). leonida::cached_pso::Key order_key(const PipelineStream& stream) { if (stream.has_cs) return pipeline_key(stream.compute); auto key = pipeline_key(stream.graphics); if (stream.ms.BytecodeLength) { key += leonida::sha256_hex({static_cast(stream.ms.pShaderBytecode), stream.ms.BytecodeLength}); key = leonida::sha256_hex({reinterpret_cast(key.data()), key.size()}); } return key; } // Console stream retry adapted from Kokonotcu, ubiquitarianism/leonida #496 (GPL-3.0). bool console_stream_enum_enabled() { static const bool enabled = [] { char value[8] = {}; const DWORD n = GetEnvironmentVariableA("LEONIDA_XS_STREAM_ENUM", value, sizeof(value)); return !(n == 1 && value[0] == '0') && !(n == 2 && (value[0] == 'p' || value[0] == 'P') && (value[1] == 'c' || value[1] == 'C')); }(); return enabled; } // The first DWORD in a DXIL program header holds the shader kind in its high 16 bits. // Require a mesh program (kind 13) before changing the meaning of a stream that failed the PC parse. bool is_mesh_container(const D3D12_SHADER_BYTECODE& code) { if (!code.pShaderBytecode) return false; const auto dxil = leonida::dxbc_part({static_cast(code.pShaderBytecode), code.BytecodeLength}, "DXIL"); return dxil.size() >= 4 && dxil[2] == 13 && dxil[3] == 0; } HRESULT stream_unsupported(const char* reason, int type = 0) { d3d12_trace::stream_refusal = reason; log_once(reason, type); return E_NOTIMPL; } // The console numbering lacks the gap at 23 in the PC enumeration. HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, PipelineStream& out, bool console_enum = false) { if (!desc.pPipelineStateSubobjectStream || !desc.SizeInBytes) return E_INVALIDARG; D3D12_GRAPHICS_PIPELINE_STATE_DESC& g = out.graphics; for (auto& target : g.BlendState.RenderTarget) { target.SrcBlend = target.SrcBlendAlpha = D3D12_BLEND_ONE; target.DestBlend = target.DestBlendAlpha = D3D12_BLEND_ZERO; target.BlendOp = target.BlendOpAlpha = D3D12_BLEND_OP_ADD; target.LogicOp = D3D12_LOGIC_OP_NOOP; target.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; } g.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; g.RasterizerState.CullMode = D3D12_CULL_MODE_BACK; g.RasterizerState.DepthClipEnable = TRUE; g.DepthStencilState.DepthEnable = TRUE; g.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; g.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; g.DepthStencilState.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; g.DepthStencilState.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; g.DepthStencilState.FrontFace = g.DepthStencilState.BackFace = { D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS}; g.SampleMask = UINT_MAX; g.SampleDesc = {1, 0}; const auto* base = static_cast(desc.pPipelineStateSubobjectStream); const std::size_t size = desc.SizeInBytes; const auto round_up = [](std::size_t v, std::size_t a) { return (v + a - 1) / a * a; }; std::uint64_t seen = 0; std::size_t at = 0; while (at < size) { D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type; if (size - at < sizeof(type)) return E_INVALIDARG; std::memcpy(&type, base + at, sizeof(type)); type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(d3d12_xs::pc_stream_type(unsigned(type), console_enum)); // The versioned depth-stencil and rasterizer subobjects describe the same state as their base type, so the // stream contract counts any two of one family as duplicates; the payload below still follows `type`. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE family = type; if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1 || type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2) family = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL; else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1 || type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2) family = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER; if (unsigned(type) >= 64 || (seen >> unsigned(family) & 1)) return E_INVALIDARG; seen |= std::uint64_t(1) << unsigned(family); bool ok = true; const auto take = [&](auto& value) { using T = std::remove_reference_t; const std::size_t payload = round_up(at + sizeof(type), alignof(T)); if (payload > size || size - payload < sizeof(T)) { ok = false; return; } std::memcpy(&value, base + payload, sizeof(T)); at = round_up(payload + sizeof(T), sizeof(void*)); }; const auto stage = [&](D3D12_SHADER_BYTECODE& code) { take(code); out.has_graphics_stage = true; }; switch (type) { case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE: take(g.pRootSignature); out.compute.pRootSignature = g.pRootSignature; break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS: stage(g.VS); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS: stage(g.PS); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS: stage(g.DS); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS: stage(g.HS); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS: stage(g.GS); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS: stage(out.as); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS: stage(out.ms); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS: take(out.compute.CS); out.has_cs = true; break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT: take(g.StreamOutput); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND: take(g.BlendState); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK: take(g.SampleMask); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER: take(g.RasterizerState); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL: take(g.DepthStencilState); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT: take(g.InputLayout); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE: take(g.IBStripCutValue); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY: take(g.PrimitiveTopologyType); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS: { D3D12_RT_FORMAT_ARRAY formats{}; take(formats); if (formats.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return E_INVALIDARG; g.NumRenderTargets = formats.NumRenderTargets; std::copy(std::begin(formats.RTFormats), std::end(formats.RTFormats), std::begin(g.RTVFormats)); break; } case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT: take(g.DSVFormat); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC: take(g.SampleDesc); break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK: take(g.NodeMask); out.compute.NodeMask = g.NodeMask; break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO: take(g.CachedPSO); out.compute.CachedPSO = g.CachedPSO; break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS: take(g.Flags); out.compute.Flags = g.Flags; break; case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: { D3D12_DEPTH_STENCIL_DESC1 d{}; take(d); if (ok) out.depth_bounds = d.DepthBoundsTestEnable != FALSE; g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, d.StencilReadMask, d.StencilWriteMask, d.FrontFace, d.BackFace}; break; } case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2: { D3D12_DEPTH_STENCIL_DESC2 d{}; take(d); if (!ok) break; out.depth_bounds = d.DepthBoundsTestEnable != FALSE; // Each face has its own read and write mask (OPTIONS14.IndependentFrontAndBackStencilRefMaskSupported): // the description takes the front face's, back_stencil the back face's. out.back_masks = true; out.back_stencil = {UINT8(d.BackFace.StencilReadMask), UINT8(d.BackFace.StencilWriteMask)}; const auto face = [](const D3D12_DEPTH_STENCILOP_DESC1& f) { return D3D12_DEPTH_STENCILOP_DESC{f.StencilFailOp, f.StencilDepthFailOp, f.StencilPassOp, f.StencilFunc}; }; g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, UINT8(d.FrontFace.StencilReadMask), UINT8(d.FrontFace.StencilWriteMask), face(d.FrontFace), face(d.BackFace)}; break; } case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1: case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2: { // Their DepthBias is a float; the PSO path takes D3D12_RASTERIZER_DESC's integer one. FLOAT bias = 0; D3D12_RASTERIZER_DESC& r = g.RasterizerState; if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1) { D3D12_RASTERIZER_DESC1 d{}; take(d); r = {d.FillMode, d.CullMode, d.FrontCounterClockwise, 0, d.DepthBiasClamp, d.SlopeScaledDepthBias, d.DepthClipEnable, d.MultisampleEnable, d.AntialiasedLineEnable, d.ForcedSampleCount, d.ConservativeRaster}; bias = d.DepthBias; } else { D3D12_RASTERIZER_DESC2 d{}; take(d); r = {d.FillMode, d.CullMode, d.FrontCounterClockwise, 0, d.DepthBiasClamp, d.SlopeScaledDepthBias, d.DepthClipEnable, FALSE, FALSE, d.ForcedSampleCount, d.ConservativeRaster}; bias = d.DepthBias; } r.DepthBias = INT(bias); if (ok && FLOAT(r.DepthBias) != bias) log_once("a fractional depth bias is truncated; bias x1000", int(bias * 1000)); break; } case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING: { D3D12_VIEW_INSTANCING_DESC d{}; take(d); if (ok && d.ViewInstanceCount) { return stream_unsupported("view instancing is not supported yet; stream subobject", int(type)); } break; } default: log_once("unknown pipeline state stream subobject type:", int(type)); return E_INVALIDARG; } if (!ok) return E_INVALIDARG; } if (out.has_cs && out.has_graphics_stage) return E_INVALIDARG; // a compute stage with graphics stages if (!out.has_cs && !out.has_graphics_stage) return E_INVALIDARG; return S_OK; } // A pipeline state, compute (create_compute) or graphics (create_graphics): each shader is found by the SHA-256 of // its FSSM program in the translator's index, and the FSSM blob is copied into the arena as the shader's code base. std::atomic live_pipeline_state_count{0}; // live_pipeline_states() // What the bindless set layout was made from, for a compute pipeline's journal name: a pipeline built against another // layout is another pipeline. Field by field, so padding never reaches the hash. void hash_bindless_layout(leonida::pipeline_journal::Hasher& hash, const leonida::BindlessFeatures& features) { for (const std::uint32_t count : features.counts) hash.value(count); hash.value(std::uint8_t(features.update_after_bind)); hash.value(std::uint8_t(features.partially_bound)); hash.value(std::uint8_t(features.null_descriptor)); hash.value(std::uint8_t(features.shader_image_int64_atomics)); for (const VkSampleCountFlagBits samples : features.ms_samples) hash.value(std::uint32_t(samples)); } // Opt in on this branch. Async workers normally compile while other queues submit. std::unique_lock compute_driver_turn(DeviceState& device) { static const bool enabled = [] { wchar_t value[2]{}; return GetEnvironmentVariableW(L"LEONIDA_COMPILE_GATE", value, 2) == 1 && value[0] == L'1'; }(); std::unique_lock turn(device.context->submit_mutex(), std::defer_lock); if (enabled) turn.lock(); return turn; } // LOCAL FIX (pipeline journal, pipeline_cache_journal.h): one compute pipeline's own VkPipelineCache for the length // of its build. load() reads the journal file, before any driver call. In the build's one compile-gate turn, // create() makes the cache from the file's contents (seeded) or empty, and finish() takes the cache's data when the // pipeline had to be compiled and destroys the cache. publish(), after the turn, writes the file, or refreshes its // last use after a hit: no file I/O in the turn. Nothing else uses the cache, so it needs no synchronization beyond // the build's own. class JournalCache { public: VkPipelineCache cache = VK_NULL_HANDLE; bool seeded = false; // made from the file's contents JournalCache(DeviceState& device, leonida::SubmitMutex& submits, const char* trigger, const char* name) : device_(device), submits_(&submits), trigger_(trigger), name_(name) {} // A build outside the submit lock's owners (the async compile workers' own turn helper): compute_driver_turn. JournalCache(DeviceState& device, const char* name) : device_(device), name_(name) {} JournalCache(const JournalCache&) = delete; JournalCache& operator=(const JournalCache&) = delete; ~JournalCache() { if (!cache) return; // finish() always destroys it; this is only for a build that left early if (submits_) { const DriverTurn turn(*submits_, trigger_, "vkDestroyPipelineCache", true, name_); device_.context->vk.vkDestroyPipelineCache(device_.info.device, cache, nullptr); } else { const auto turn = compute_driver_turn(device_); device_.context->vk.vkDestroyPipelineCache(device_.info.device, cache, nullptr); } } bool enabled() const { return enabled_; } bool has_file_data() const { return !file_.data.empty(); } bool found() const { return enabled_ && built_ && !write_; } // the pipeline came out of the journal file bool written() const { return written_; } // publish() wrote the file void load(std::filesystem::path path) { const auto& vk = device_.context->vk; if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkGetPipelineCacheData) return; enabled_ = true; path_ = std::move(path); namespace journal = leonida::pipeline_journal; const auto role = compile_helper::build_host.load() ? journal::ReadRole::materialize_local : journal::ReadRole::runtime; file_ = journal::read_with_seed(path_, pipeline_journal_roots().seed, device_.pso_identity, role); } // In the build's driver turn. void create() { if (!enabled_) return; const auto& vk = device_.context->vk; VkPipelineCacheCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, file_.data.size(), file_.data.empty() ? nullptr : file_.data.data()}; if (!file_.data.empty() && vk.vkCreatePipelineCache(device_.info.device, &info, nullptr, &cache) == VK_SUCCESS) { seeded = true; } else { cache = VK_NULL_HANDLE; // no file, or one the driver declined: start empty, and the build rewrites it info.initialDataSize = 0; info.pInitialData = nullptr; if (vk.vkCreatePipelineCache(device_.info.device, &info, nullptr, &cache) != VK_SUCCESS) cache = VK_NULL_HANDLE; } std::vector().swap(file_.data); // the driver has its own copy } // In the build's driver turn, after the create against `cache`. `built`: that create made the pipeline; `hit`: // its creation feedback; `driver_ms`: the vkCreateComputePipelines call alone. void finish(bool built, int hit, std::uint64_t driver_ms) { if (!cache) return; const auto& vk = device_.context->vk; built_ = built; write_ = built && leonida::pipeline_journal::should_write(seeded, hit, driver_ms); if (write_) { std::size_t size = 0; result_ = vk.vkGetPipelineCacheData(device_.info.device, cache, &size, nullptr); if (result_ == VK_SUCCESS && size > leonida::pipeline_cache_store::header_bytes && size <= leonida::pipeline_journal::entry_read_limit) { blob_.resize(size); result_ = vk.vkGetPipelineCacheData(device_.info.device, cache, &size, blob_.data()); blob_.resize(result_ == VK_SUCCESS ? size : 0); } data_size_ = size; } vk.vkDestroyPipelineCache(device_.info.device, cache, nullptr); cache = VK_NULL_HANDLE; } // The shared cache had the pipeline (FAIL_ON_PIPELINE_COMPILE_REQUIRED gave it, as a hit or quickly). void found_in_shared() { report(device_.journal_shared_hits.fetch_add(1) + 1, "found in the shared cache"); } // After the driver turn. void publish() { namespace journal = leonida::pipeline_journal; if (!enabled_ || !built_) return; if (!write_) { report(device_.journal_hits.fetch_add(1) + 1, "found in their journal file"); journal::touch_local_hit(path_, file_, std::filesystem::file_time_type::clock::now()); return; } if (blob_.size() <= leonida::pipeline_cache_store::header_bytes) { std::fprintf(stderr, "[rt] d3d12: pipeline journal: no cache data for %s (VkResult %d, %zu bytes)\n", name_, int(result_), data_size_); return; } // A rewrite replaces the file's old size. Two builds of one name at once may both count: the next boot's // tidy counts again. if (journal::replace_bytes(device_.journal_bytes.load(), file_.bytes, blob_.size()) > device_.journal_budget) { static std::atomic said{false}; if (!said.exchange(true)) std::fprintf(stderr, "[rt] d3d12: pipeline journal: %llu bytes on disk, the %llu-byte budget " "(LEONIDA_PIPELINE_JOURNAL_BYTES) is spent; nothing more is written this boot\n", static_cast(device_.journal_bytes.load()), static_cast(device_.journal_budget)); return; } if (const std::error_code error = journal::write_entry(path_, blob_.data(), blob_.size())) { static std::atomic said{false}; if (!said.exchange(true)) std::fprintf(stderr, "[rt] d3d12: pipeline journal: could not write %ls: %s\n", path_.c_str(), error.message().c_str()); return; } auto total = device_.journal_bytes.load(); while (!device_.journal_bytes.compare_exchange_weak(total, journal::replace_bytes(total, file_.bytes, blob_.size()))) { } written_ = true; report(device_.journal_writes.fetch_add(1) + 1, "compiled and written to their journal file"); } private: // The first of each kind, then every 100th, with all three counts. void report(unsigned count, const char* what) const { if (count != 1 && count % 100) return; std::fprintf(stderr, "[rt] d3d12: pipeline journal: %u compute pipeline(s) %s (so far: %u from journal files, " "%u written, %u from the shared cache)\n", count, what, device_.journal_hits.load(), device_.journal_writes.load(), device_.journal_shared_hits.load()); } DeviceState& device_; leonida::SubmitMutex* submits_ = nullptr; // null: compute_driver_turn, for a build outside the submit lock const char* trigger_ = ""; const char* name_; bool enabled_ = false; bool built_ = false; bool write_ = false; bool written_ = false; std::filesystem::path path_; leonida::pipeline_journal::EntryFile file_; std::vector blob_; std::size_t data_size_ = 0; VkResult result_ = VK_SUCCESS; }; // What one compute pipeline build did (build_compute_pipeline). struct ComputeBuild { VkPipeline pipeline = VK_NULL_HANDLE; // the caller's from here on VkResult result = VK_ERROR_UNKNOWN; std::size_t bytes = 0; // SPIR-V ULONGLONG ms = 0; // the whole build std::filesystem::path journal_path; // its journal file's name (empty with the journal off) bool skipped = false; // ComputeBuildOptions::skip_journaled and the journal file was there: nothing built bool busy = false; // ComputeBuildOptions::mark_building and another process is building it: nothing built bool deferred = false; // asked of the compile helper without waiting: nothing built yet bool journal_hit = false; // found in its journal file bool journaled = false; // compiled and written to its journal file bool from_shared = false; // found in the shared cache }; struct ComputeBuildOptions { const char* trigger = "dispatch"; // what asked: dispatch, warmup, dispatch-worker, precompile... const std::string* cache_key = nullptr; // the title's PSO description key, for the compile trace bool serialize_big = true; // LEONIDA_SERIAL_BIG_COMPILES=1: modules over 128 KiB one at a time bool skip_journaled = false; // precompile: leave a pipeline whose journal file exists alone bool use_helper = true; // LEONIDA_COMPILE_HELPER: a missing journal file comes from the helper bool helper_wait = true; // wait for the helper's file (false: ask, and answer deferred) std::uint64_t helper_priority = 0; // the request's urgency: 0 a dispatch, else the warm-up's module size bool mark_building = false; // precompile, helper: claim the entry, skip it when another process has it bool key_only = false; // only name the journal file (journal_path), build nothing }; // A compute pipeline from a library entry: what a PSO's first dispatch, the warm-up worker and gta6rt // --precompile-pipelines all build, so their journal names and the driver's keys are the same. `layout` is the push // range of leonida::ShaderUserData, with the device's bindless set 0 when the entry declares bindings; `subgroup` is // leonida::decide_subgroup_size's answer for the entry. ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEntry& compute_entry, VkPipelineLayout layout, const leonida::SubgroupRequest& subgroup, const ComputeBuildOptions& options) { ComputeBuild out; CompileActivity activity(device.active_compiles); const char* const trigger = options.trigger; std::filesystem::path marked; // mark_building: released on the way out struct Unmark { std::filesystem::path& path; ~Unmark() { if (!path.empty()) compile_helper::unmark_building(path); } } unmark{marked}; static const std::string no_key; auto& vk = device.context->vk; const VkDevice dev = device.info.device; const leonida::ShaderLibrary* library = device.library(); const leonida::ShaderEntry* entry = &compute_entry; if (!library) return out; // The driver's compiler needs hundreds of MiB per very large module; several at once exhausted host memory. By // default large modules share a memory budget (big_compile_gate, taken by the caller before any PSO lock: see // PipelineState::enter_build); LEONIDA_SERIAL_BIG_COMPILES=1 compiles them one at a time here instead. static std::mutex big_compile; std::unique_lock big_lock(big_compile, std::defer_lock); // taken below, only for a compile here auto words = library->spirv(*entry); if (words.empty()) { std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); return out; } const std::size_t bytes = words.size() * sizeof(std::uint32_t); out.bytes = bytes; leonida::LiteralSamplerSpec literal_spec; if (entry->binding_count && entry->literal_sampler_spec_base && !entry->literal_samplers.empty()) { const auto indices = register_literal_samplers(device, *entry); literal_spec.build(*entry->literal_sampler_spec_base, indices); } VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; pipeline_info.stage.pName = "main"; pipeline_info.stage.pSpecializationInfo = literal_spec.ptr(); VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; leonida::apply_subgroup_request(subgroup, required_size, pipeline_info.stage); pipeline_info.layout = layout; pipeline_info.flags |= fast_pipeline_flags(true); // before the journal key, which hashes the flags const VkPipelineCache shared = device.pipeline_cache(); auto& submits = device.context->submit_mutex(); // LOCAL FIX (pipeline journal, pipeline_cache_journal.h): the pipeline is created against its own cache, made // from its journal file or empty and written back after a compile, so a boot killed or crashed later keeps it. // The file is named by what the pipeline is made of and read here, before the driver turn. Without a file // the shared cache (seeded from the offline corpus or the last session) is asked first, without a compile. JournalCache journal(device, submits, trigger, entry->name.c_str()); if (const std::filesystem::path& journal_dir = pipeline_journal_dir(); !journal_dir.empty()) { leonida::pipeline_journal::Hasher key; key.text("cs"); key.value(std::uint64_t(words.size())); key.bytes(words.data(), bytes); key.text(pipeline_info.stage.pName); key.value(std::uint32_t(pipeline_info.flags)); key.value(std::uint32_t(pipeline_info.stage.flags)); key.value(std::uint32_t(pipeline_info.stage.pNext == &required_size ? required_size.requiredSubgroupSize : 0)); key.value(std::uint32_t(sizeof(leonida::ShaderUserData))); key.value(std::uint32_t(entry->binding_count != 0)); if (literal_spec.active()) { key.text("literal-samplers"); key.value(*entry->literal_sampler_spec_base); key.value(std::uint32_t(literal_spec.values.size())); key.bytes(literal_spec.values.data(), literal_spec.values.size() * sizeof(std::uint32_t)); } // NVIDIA's diagnostics config (LEONIDA_DEVICE_FAULT=1, Aftermath) compiles with shader debug info: other // pipelines, kept apart so switching it on and off does not rewrite every file. Absent when off, so the // names of ordinary boots stay as they were. if (device.info.device_diagnostics_config) { key.text("nv-diagnostics-config"); key.value(std::uint32_t(leonida::aftermath::extra_config_flags())); } if (entry->binding_count) hash_bindless_layout(key, device.bindless->features()); const auto path = leonida::pipeline_journal::entry_path(journal_dir, "cs", key.digest()); out.journal_path = path; if (options.key_only) return out; // Precompile: a usable file is there already, so the pipeline is not built (only its header is read). if (options.skip_journaled && leonida::pipeline_journal::entry_usable(path, device.pso_identity)) { out.skipped = true; return out; } journal.load(path); // LOCAL FIX (compile helper, d3d12_compile_helper.h): no file, so this would be a compile in this process, // where the driver's lock it holds stops the title's submissions. The helper process compiles it into the file // instead, and the create below is a hit. Asked without waiting, the build answers deferred and is asked // again at the pipeline's next use; waited for, nothing of ours is in the driver meanwhile. // Skip the out-of-process helper when literal-sampler specialization constants are bound, because bindless // sampler indices are process-local and would not match the helper's journal key. if (!journal.has_file_data() && options.use_helper && !literal_spec.active() && compile_helper::wanted(bytes)) { auto& helper = compile_helper::Client::instance(); std::string why; if (!options.helper_wait) { if (helper.request(path, entry->name, options.helper_priority, device.pso_identity, &why)) { out.deferred = true; return out; } std::fprintf(stderr, "[rt] d3d12: compile helper: %s for %s; built here\n", why.c_str(), entry->name.c_str()); } else { const ULONGLONG asked = GetTickCount64(); if (helper.build(path, entry->name, device.pso_identity, &why)) { journal.load(path); std::fprintf(stderr, "[rt] d3d12: compile helper built %s in %.1f s (%zu B SPIR-V, %s)\n", entry->name.c_str(), double(GetTickCount64() - asked) / 1000.0, bytes, trigger); } else { std::fprintf(stderr, "[rt] d3d12: compile helper: %s for %s after %.1f s; built here\n", why.c_str(), entry->name.c_str(), double(GetTickCount64() - asked) / 1000.0); } } } // Precompile and helper: another process compiling this entry is left to it. if (options.mark_building && !journal.has_file_data()) { if (!compile_helper::mark_building(path)) { out.busy = true; return out; } marked = path; } } // Only a compile here is serialized: a pipeline from its journal file takes milliseconds. if (!journal.has_file_data() && options.serialize_big && big_compiles() == BigCompiles::serial && big_compute(bytes)) big_lock.lock(); const bool ask_shared = journal.enabled() && !journal.has_file_data() && shared && device.pipeline_cache_seeded && device.info.pipeline_cache_control && device.journal_ask_shared.load(); VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; module_info.codeSize = bytes; module_info.pCode = words.data(); VkShaderModule module = VK_NULL_HANDLE; const ULONGLONG started = GetTickCount64(); VkPipeline built = VK_NULL_HANDLE; CompileTrace trace; trace.begin(pipeline_info, device.info.pipeline_creation_feedback, trigger, entry->name.c_str(), 0, bytes, options.cache_key ? *options.cache_key : no_key); // Was it in the cache? Core feedback on a Vulkan 1.3 device; pipeline_cache_control implies one. if (journal.enabled() && device.info.pipeline_cache_control) trace.request_feedback(pipeline_info); const leonida::dev_status::Build dev_build(entry->name.c_str()); const leonida::pipeline_profile::DriverCall profile("cs", trigger, entry->name.c_str()); // LOCAL DIAGNOSTIC (early device loss): a vkQueueSubmit was measured blocking 10 s and losing the device // while another thread sat in this call. Name what is building (once past the gate: in the driver), and log // the start of big ones. auto& compiling = leonida::driver_compile; VkResult created = VK_ERROR_UNKNOWN; bool from_shared = false, probe_compiled = false; int hit_reported = -1; // what the journal sees as its hit, printed below to explain a missing write ULONGLONG probe_ms = 0, driver_ms = 0; { // Every driver call of the build (shader module, journal cache, pipeline) in one turn through the compile // gate: from the journal a build takes milliseconds and the warm-up worker makes them back to back, and // three warm boots lost the device in a vkQueueSubmit (no GPU fault, no TDR) while only the create was // gated. No file I/O in here. const DriverTurn turn(submits, trigger, "vkCreateComputePipelines", true, entry->name.c_str(), leonida::SubmitMutex::CreateKind::compute, bytes); { const leonida::aftermath::ShaderName named(entry->name); if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return out; } pipeline_info.stage.module = module; journal.create(); const VkPipelineCache cache = journal.cache ? journal.cache : shared; compiling.bytes.store(bytes, std::memory_order_relaxed); compiling.trigger.store(trigger, std::memory_order_relaxed); compiling.since_ms.store(leonida::diagnostic_ms(), std::memory_order_relaxed); compiling.name.store(entry->name.c_str(), std::memory_order_release); if (bytes >= 128 * 1024) std::fprintf(stderr, "[rt] d3d12: compute pipeline %s (%zu B SPIR-V, %s) build starts at t=%.3f s\n", entry->name.c_str(), bytes, trigger, double(leonida::diagnostic_ms()) / 1000.0); if (ask_shared) { // VK_PIPELINE_COMPILE_REQUIRED (a success code, no pipeline) when the shared cache does not have it. pipeline_info.flags |= VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT; const ULONGLONG asked = GetTickCount64(); created = vk.vkCreateComputePipelines(dev, shared, 1, &pipeline_info, nullptr, &built); probe_ms = GetTickCount64() - asked; pipeline_info.flags &= ~VkPipelineCreateFlags(VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT); from_shared = created == VK_SUCCESS && built; if (from_shared && leonida::pipeline_journal::probe_compiled(trace.hit(), probe_ms)) { // NVIDIA 630.20 compiled it instead of answering VK_PIPELINE_COMPILE_REQUIRED, into the shared // cache. Built once more against the journal cache below, so it is journaled; asking stops. vk.vkDestroyPipeline(dev, built, nullptr); from_shared = false; probe_compiled = true; } if (!from_shared) built = VK_NULL_HANDLE; } if (!from_shared) { const ULONGLONG at = GetTickCount64(); created = vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &built); driver_ms = GetTickCount64() - at; } compiling.name.store(nullptr, std::memory_order_release); vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists hit_reported = trace.hit(); // what finish() sees; decides whether the file is written journal.finish(!from_shared && created == VK_SUCCESS && built, hit_reported, driver_ms); } std::vector().swap(words); profile.finish(int(created)); trace.end(trigger, entry->name.c_str(), 0, bytes, created); if (big_lock.owns_lock()) big_lock.unlock(); if (probe_compiled && device.journal_ask_shared.exchange(false)) std::fprintf(stderr, "[rt] d3d12: pipeline journal: the driver compiled %s for " "FAIL_ON_PIPELINE_COMPILE_REQUIRED (%llu ms, no cache hit); built again for its journal " "file, and the shared cache is no longer asked first\n", entry->name.c_str(), static_cast(probe_ms)); if (from_shared) journal.found_in_shared(); journal.publish(); out.pipeline = built; out.result = created; out.from_shared = from_shared; out.journal_hit = journal.found(); out.journaled = journal.written(); out.ms = GetTickCount64() - started; if (created == VK_SUCCESS && built && out.ms >= 2000) // The timer starts before the journal file is read and before the shared cache is asked, so this // line reports the whole call. Name where the pipeline came from: a compile, the shared cache or // its own journal file, which is what a compile cost has to be read from. std::fprintf(stderr, "[rt] d3d12: compute pipeline %s took %.1f s to obtain from %s (%zu B SPIR-V; hit %d," " seeded %d, written %d)\n", entry->name.c_str(), double(out.ms) / 1000.0, out.journal_hit ? "its journal file" : out.from_shared ? "the shared cache" : "a compile", bytes, hit_reported, int(journal.seeded), int(out.journaled)); return out; } class PipelineState final : public Child { public: // {8d2f6c14-b0e7-4a93-9c58-1f4a7e3b6d20} static constexpr GUID kTag{0x8d2f6c14, 0xb0e7, 0x4a93, {0x9c, 0x58, 0x1f, 0x4a, 0x7e, 0x3b, 0x6d, 0x20}}; explicit PipelineState(DeviceState& device) : device_(device) { ++live_pipeline_state_count; } // Object::Release at zero references. Background builds hold no reference to the PSO: its queued ones are dropped // here. One already running (a vkCreate*Pipelines in the driver, minutes for some modules) is not waited for: the // PSO is deleted on the worker when that build returns, so the title's Release returns now. The device reference // goes now, so a device released with its last PSO is torn down here, and ~Device waits for the build and the // deletion (PipelineCompiler::cancel). Released on the worker inside its own build, both wait for its return. void last_release() { // The registry's build callback reaches this PSO by a raw pointer: unregistered first, so nothing queues a // build for it after the queued ones are dropped. unregister(); IUnknown* const device = detach_device(); auto& compiler = PipelineCompiler::instance(); const bool own_build = compiler.running_here(compile_owner()); IUnknown* const release_after = own_build ? device : nullptr; if (compiler.after_running(compile_owner(), [this, release_after] { delete this; if (release_after) release_after->Release(); })) { if (device && !own_build) device->Release(); return; } delete this; if (device) device->Release(); } ~PipelineState() override { unregister(); PipelineCompiler::instance().cancel(compile_owner()); // nothing left in practice (last_release) auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; if (pipeline_.pipeline) vk.vkDestroyPipeline(dev, pipeline_.pipeline, nullptr); if (pipeline_.layout && owns_compute_layout_) vk.vkDestroyPipelineLayout(dev, pipeline_.layout, nullptr); if (module_) vk.vkDestroyShaderModule(dev, module_, nullptr); if (graphics_.pipeline) vk.vkDestroyPipeline(dev, graphics_.pipeline, nullptr); for (const auto& [unbound, built] : variants_) vk.vkDestroyPipeline(dev, built, nullptr); if (graphics_.masked_layout && owns_graphics_layouts_) vk.vkDestroyPipelineLayout(dev, graphics_.masked_layout, nullptr); if (graphics_.layout && owns_graphics_layouts_) vk.vkDestroyPipelineLayout(dev, graphics_.layout, nullptr); modules_.clear(); if (code_bytes_) device_.arena_release(code_base_, code_bytes_, DeviceState::arena_shader); --live_pipeline_state_count; } // Pipeline layouts declare the whole 144-byte block as one push-constant range. A device whose // maxPushConstantsSize is smaller (128 bytes is the Vulkan minimum, which some Intel and mobile drivers // report) needs the uniform-buffer tail #224 flags with push_constants_need_fallback, which is not built yet, // so pipelines are refused there with the limit named instead of breaking VUID-VkPushConstantRange-size-00298. bool push_constants_fit() const { const std::uint32_t limit = device_.info.max_push_constants_size; if (limit == 0 || limit >= sizeof(leonida::ShaderUserData)) return true; // 0: not queried log_once("pipelines need 144 bytes of push constants (uniform-buffer fallback not built yet); " "maxPushConstantsSize", int(limit)); return false; } // Asks for the subgroup size the shader was translated for, where the device allows (src/subgroup_size.h): the // stage gets VkPipelineShaderStageRequiredSubgroupSizeCreateInfo in `storage` (which must outlive pipeline // creation) and, for compute, REQUIRE_FULL_SUBGROUPS. A size the device cannot give is reported, not hidden. // decide_subgroup_size's answer for a compute entry, reported and recorded as subgroup_size_for does; the build // applies it (build_compute_pipeline). leonida::SubgroupRequest subgroup_request_for(const leonida::ShaderEntry& entry) { const leonida::SubgroupRequest request = leonida::decide_subgroup_size(entry, device_.info.subgroup); if (request.outcome == leonida::SubgroupOutcome::unavailable) report_subgroup_unavailable(entry, request, device_.info.subgroup); subgroup_requests_.push_back(request); return request; } void subgroup_size_for(const leonida::ShaderEntry& entry, VkPipelineShaderStageRequiredSubgroupSizeCreateInfo& storage, VkPipelineShaderStageCreateInfo& stage) { const leonida::SubgroupRequest request = leonida::decide_subgroup_size(entry, device_.info.subgroup); if (request.outcome == leonida::SubgroupOutcome::unavailable) report_subgroup_unavailable(entry, request, device_.info.subgroup); leonida::apply_subgroup_request(request, storage, stage); subgroup_requests_.push_back(request); } std::uintptr_t id() const { return native_owner_ ? native_owner_->id() : reinterpret_cast(static_cast(this)); } void share_native_graphics(std::shared_ptr owner) { native_owner_ = std::move(owner); } bool ensure_native_source(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc, D3D12_SHADER_BYTECODE mesh, std::span containers) { std::call_once(native_source_once_,[&]{ if(rt::d3d12_xs::find_pso_record(this)){native_source_ready_=true;return;} rt::d3d12_xs::native_pipeline_detail::Stream source; rt::d3d12_xs::native_pipeline_detail::build_stream(pc,mesh,source); auto record=rt::d3d12_xs::PsoStreamRecord::capture(source.desc(),containers); native_source_ready_=record && rt::d3d12_xs::attach_pso_record(this,std::move(record)); }); return native_source_ready_; } // What its PipelineCompiler jobs are filed under: the interface pointer the title holds. const void* compile_owner() const { return static_cast(this); } // Out of the context's pipeline registry (and its build callback), once. void unregister() { if (!registered_ || unregistered_) return; device_.context->remove_pipeline(id()); unregistered_ = true; } void set_cache_key(leonida::cached_pso::Key key) { cache_key_ = std::move(key); } // The key pipeline_order.log names this pipeline by, where the cache key does not tell two descriptions apart (a // mesh pipeline's MS is not in it). Set before create_*, only while the log is on. void set_order_key(leonida::cached_pso::Key key) { order_key_ = std::move(key); } // pipeline_order.h: the first dispatch or draw that names a pipeline and variant. Runs while a submission is // prepared, so it never blocks and allocates nothing: the first-time test is one compare-and-swap (the readiness callbacks only try_lock, without waiting, on the first request of a pipeline and variant). static void order_requested(void* self, std::uint32_t variant) { static_cast(self)->order_request(variant); } void order_request(std::uint32_t variant) { auto* const log = device_.order_log.get(); if (!log) return; const auto& key = order_key_.empty() ? cache_key_ : order_key_; log->request(order_hash_, key, variant, order_kind_, order_created_ms_, [&] { return order_ready(variant); }, [&] { return variant == 0 ? order_build_ms_.load() : leonida::pipeline_order::unknown_ms; }, order_name_hash_); } // Its handle existed, and nobody was building it, when it was first asked for. bool order_ready(std::uint32_t variant) { if (is_graphics_) { if (variant == 0 && graphics_.pipeline) return true; return graphics_.built && graphics_.built(variant) != VK_NULL_HANDLE; } return pipeline_.built ? pipeline_.built(this) != VK_NULL_HANDLE : pipeline_.pipeline != VK_NULL_HANDLE; } // Called at the end of create_compute / create_graphics, before the pipeline is registered with the replay. // A compute pipeline passes the name of its library entry: the log then adds an E line for it. void order_install(void (*&requested)(void*, std::uint32_t), void*& context, char kind, std::string_view entry_name = {}) { if (!device_.order_log) return; const auto& key = order_key_.empty() ? cache_key_ : order_key_; if (key.empty()) return; order_hash_ = leonida::pipeline_order::key_hash(key); order_kind_ = kind; if (!entry_name.empty()) order_name_hash_ = leonida::pipeline_order::entry_name_hash(entry_name); requested = &order_requested; context = this; } void order_note_build(std::uint32_t variant, ULONGLONG took_ms) { if (!device_.order_log || !order_hash_) return; const std::uint32_t ms = std::uint32_t(std::min(took_ms, 0xfffffffeull)); if (variant == 0) order_build_ms_.store(ms); device_.order_log->note_build(order_hash_, variant, ms); } // A null pointer is accepted with S_OK, as by the PC runtime (measured on an RTX 3060 and WARP). HRESULT STDMETHODCALLTYPE GetCachedBlob(ID3DBlob** blob) override { if (native_owner_) return native_owner_->GetCachedBlob(blob); if (!blob) return S_OK; *blob = new CachedBlob(leonida::cached_pso::encode(device_.pso_identity, cache_key_)); return S_OK; } // Slots 9 and 10: console methods no caller is known to use; refused, and named once in the log. HRESULT STDMETHODCALLTYPE xbox_slot9(UINT64, UINT64, UINT64) override { log_once("console pipeline slot called (not implemented); slot", 9); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE xbox_slot10(UINT64, UINT64, UINT64) override { log_once("console pipeline slot called (not implemented); slot", 10); return E_NOTIMPL; } // Slot 11, called by the FidelityFX DLL as (0, 0, &obj) after it creates a pipeline. It reads one dword through // obj's slot 3 (the shape of ID3DBlob::GetBufferPointer), multiplies it by 1024, releases obj through slot 2, and // creates and binds a compute scratch buffer before a dispatch only when that value is non-zero (measured in the // DLL's code, docs/d3d12_command_objects.md). The answer is a blob holding 0: none of the 1.0.2.1 DLL's 29 programs // enables scratch (COMPUTE_PGM_RSRC2.SCRATCH_EN clear in all 29) or has a scratch instruction (measured), and a // translated module keeps its private data in SPIR-V, not in a console scratch buffer. With 0 the DLL creates no // scratch buffer and skips list slot 141. The arguments are logged once when they are not the measured zeros. HRESULT STDMETHODCALLTYPE xbox_slot11(UINT64 a, UINT64 b, void** out) override { if (a || b) log_once("console pipeline slot 11 with unexpected arguments; first", int(a ? a : b)); if (!out) return E_POINTER; *out = static_cast(new CachedBlob(std::vector(4, 0))); return S_OK; } void set_pending_stream(bool compute) { pending_stream_kind_=compute?2:1; } bool resolve_type(bool graphics) { if(native_owner_)return native_owner_->resolve_type(graphics); if(pending_stream_kind_) { if(pending_stream_kind_!=(graphics?1u:2u))return false; std::call_once(resolve_stream_once_,[&]{ const auto* record=rt::d3d12_xs::find_pso_record(this); PipelineStream stream{}; HRESULT hr=record?parse_pipeline_stream(record->desc(),stream):E_INVALIDARG; if(SUCCEEDED(hr))hr=stream.has_cs?create_compute(stream.compute):create_graphics(stream.graphics,&stream.ms,&stream.as); }); } return registered_ && (is_graphics_==graphics); } StubPipelineKind stub_kind() const { return native_owner_ ? native_owner_->stub_kind() : stub_kind_; } bool compute() const { return pending_stream_kind_==2 || (registered_ && !is_graphics_); } bool graphics() const { return native_owner_ ? native_owner_->graphics() : pending_stream_kind_==1 || (registered_ && is_graphics_); } const std::vector& subgroup_requests() const { return native_owner_ ? native_owner_->subgroup_requests() : subgroup_requests_; } // A VS (+ GS) (+ PS) pipeline for dynamic rendering. Vertex input comes from the input layout matched to the // VS's input signature by semantic name and index: location = the element's register, the translator's rule // (docs/design.md, "Vertex fetch"). Refused with a log: hull and domain stages, stream output, the centre // multisample pattern, two stages that both read their code base, and state that needs a Vulkan feature the // device lacks (including the geometryShader feature a GS needs). A GS takes triangles; the sample count may // be above one. Viewport, scissor, topology, vertex strides, stencil reference and blend factor are dynamic, // set from the list's state at each draw. // With `ms` (a pipeline state stream's MS subobject) it is an MS (+ PS) pipeline on VK_EXT_mesh_shader instead: // no VS, no vertex input or input assembly (the input layout, topology type and strip cut are ignored, as D3D12 // does for mesh PSOs), drawn by DispatchMesh. A nonempty PC AS still needs a task-stage translation. // `back_masks`, from a DEPTH_STENCIL2 subobject, are the back face's stencil masks; without it both faces take // the description's. // LEONIDA_STUB_PIPELINES=1 (diagnostic): a pipeline whose translated shader is missing does not fail. No game // shader runs; the boot gets past a title that refuses to go on when pipeline creation fails. // - A graphics pipeline with a vertex stage (MVP-GPU-04) is a real Vulkan pipeline built from the stages in // src/stub_pipeline.h, registered like any other, so its draws run through replay and the validation layer. // Its vertex stage puts every vertex outside the clip volume: the draw rasterizes nothing. With // LEONIDA_STUB_PIPELINES=color it covers the viewport instead and writes leonida::stub_colour to every render // target, so the passes that are stubbed show on screen; the title's cull, depth, stencil, blend and logic-op // state are off for it (the write mask stays). // - A compute or mesh pipeline is created without a Vulkan pipeline and never registered, so SetPipelineState // leaves no PSO bound and its dispatches and draws are recorded as no-ops (D3D-482). static bool stub_pipelines() { wchar_t v[8] = {}; const DWORD n = GetEnvironmentVariableW(L"LEONIDA_STUB_PIPELINES", v, 8); return n > 0 && n < 8 && v[0] != L'0'; } static bool stub_pipelines_cover() { wchar_t v[8] = {}; const DWORD n = GetEnvironmentVariableW(L"LEONIDA_STUB_PIPELINES", v, 8); return n > 0 && n < 8 && _wcsicmp(v, L"color") == 0; } // The pixel-stage output a stub writes for a render-target format: integer for the UINT and SINT formats. static leonida::StubOutput stub_output(DXGI_FORMAT format) { switch (vulkan_format(format, false).format) { case VK_FORMAT_UNDEFINED: return leonida::StubOutput::none; case VK_FORMAT_R8_UINT: case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_R16_UINT: case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16G16B16A16_UINT: case VK_FORMAT_R32_UINT: case VK_FORMAT_R32G32_UINT: case VK_FORMAT_R32G32B32A32_UINT: case VK_FORMAT_A2B10G10R10_UINT_PACK32: return leonida::StubOutput::uint_; case VK_FORMAT_R8_SINT: case VK_FORMAT_R8G8_SINT: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_R16_SINT: case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R32_SINT: case VK_FORMAT_R32G32_SINT: case VK_FORMAT_R32G32B32A32_SINT: return leonida::StubOutput::sint_; default: return leonida::StubOutput::float_; } } // The stage table's stand-in entry for a stub stage: no bindings, no inputs, no code base, no subgroup request. static const leonida::ShaderEntry& stub_entry() { static const leonida::ShaderEntry entry = [] { leonida::ShaderEntry e; e.name = "LEONIDA_STUB_PIPELINES"; return e; }(); return entry; } // `kind` is what the stub is to the command list (stub_pipeline_kind): its dispatches or mesh draws record nothing. HRESULT stub_or(HRESULT hr, const char* what, StubPipelineKind kind) { if (!stub_pipelines()) return hr; stub_kind_ = kind; static std::atomic stubbed{0}; const unsigned n = ++stubbed; if (n == 1 || (n & (n - 1)) == 0) std::fprintf(stderr, "[rt] d3d12: LEONIDA_STUB_PIPELINES: %s pipeline without a translated shader is a " "no-op stub (%u so far)\n", what, n); return S_OK; } // LOCAL DIAGNOSTIC: one line per distinct graphics pipeline that uses a program translated from // game_scarlett_master.exe (/exe), so the passes those inline containers serve can be read off a // boot. LEONIDA_LOG_EXE_PIPELINES=1. static void log_exe_pipeline(const leonida::ShaderEntry* vs, const leonida::ShaderEntry* ps, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { const auto from_exe = [](const leonida::ShaderEntry* e) { return e && e->name.rfind("exe/", 0) == 0; }; if (!from_exe(vs) && !from_exe(ps)) return; char line[512]; std::snprintf(line, sizeof line, "[rt] d3d12: exe pipeline vs=%s ps=%s rts=%u rt0=%d rt1=%d dsv=%d topo=%d samples=%u", vs ? vs->fssm_sha256.c_str() : "-", ps ? ps->fssm_sha256.c_str() : "-", unsigned(desc.NumRenderTargets), int(desc.RTVFormats[0]), int(desc.RTVFormats[1]), int(desc.DSVFormat), int(desc.PrimitiveTopologyType), unsigned(desc.SampleDesc.Count)); static std::mutex mutex; static std::set seen; std::lock_guard lock(mutex); if (seen.insert(line).second) std::fprintf(stderr, "%s\n", line); } HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, const D3D12_SHADER_BYTECODE* ms = nullptr, const D3D12_SHADER_BYTECODE* as = nullptr, const StencilFaceMasks* back_masks = nullptr, bool depth_bounds = false) { auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; const bool mesh = ms && ms->pShaderBytecode && ms->BytecodeLength; if (as && as->pShaderBytecode && as->BytecodeLength) { return stream_unsupported("amplification shaders are not supported; stream subobject", D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS); } if (mesh && (desc.VS.BytecodeLength || desc.HS.BytecodeLength || desc.DS.BytecodeLength || desc.GS.BytecodeLength || desc.StreamOutput.NumEntries)) return E_INVALIDARG; // D3D12: a mesh PSO has no vertex, tessellation or geometry stage if (!mesh && (!desc.VS.pShaderBytecode || !desc.VS.BytecodeLength)) return E_INVALIDARG; if (mesh && (!device_.info.mesh_shader || !vk.vkCmdDrawMeshTasksEXT)) { return stream_unsupported("mesh-shader PSOs need VK_EXT_mesh_shader, which the device has not enabled; stage", 1); } if (desc.NodeMask & ~1u) return E_INVALIDARG; if (static_cast(desc.Flags) & ~kKnownPipelineStateFlags) return E_INVALIDARG; if (!device_.arena_ready()) { return stream_unsupported("pipelines need the GPU address arena (bufferDeviceAddress); stage", 1); } if (!push_constants_fit()) return stream_unsupported("graphics push-constant limit"); if (!vk.graphics_complete()) { return stream_unsupported("graphics pipelines need Vulkan 1.3 dynamic rendering and extended dynamic state; stage", 1); } if (desc.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return E_INVALIDARG; for (UINT i = desc.NumRenderTargets; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i) if (desc.RTVFormats[i] != DXGI_FORMAT_UNKNOWN) return E_INVALIDARG; if (desc.DSVFormat != DXGI_FORMAT_UNKNOWN) { const Format dsv_fmt = vulkan_format(desc.DSVFormat, true); if (dsv_fmt.format == VK_FORMAT_UNDEFINED || dsv_fmt.typeless || !(dsv_fmt.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) { log_once("depth-stencil format not supported:", desc.DSVFormat); return E_INVALIDARG; } } if (desc.InputLayout.NumElements > D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT) return E_INVALIDARG; if (desc.InputLayout.NumElements > 0 && !desc.InputLayout.pInputElementDescs) return E_INVALIDARG; for (UINT i = 0; i < desc.InputLayout.NumElements; ++i) { const D3D12_INPUT_ELEMENT_DESC& element = desc.InputLayout.pInputElementDescs[i]; if (!element.SemanticName) return E_INVALIDARG; if (element.InputSlot >= D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT) return E_INVALIDARG; if (element.InputSlotClass != D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA && element.InputSlotClass != D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA) return E_INVALIDARG; if (element.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA && element.InstanceDataStepRate != 0) return E_INVALIDARG; } if (desc.BlendState.IndependentBlendEnable) { for (const D3D12_RENDER_TARGET_BLEND_DESC& rt : desc.BlendState.RenderTarget) if (rt.LogicOpEnable) return E_INVALIDARG; } else { const D3D12_RENDER_TARGET_BLEND_DESC& rt0 = desc.BlendState.RenderTarget[0]; if (rt0.BlendEnable && rt0.LogicOpEnable) return E_INVALIDARG; if (rt0.LogicOpEnable && unsigned(rt0.LogicOp) > D3D12_LOGIC_OP_OR_INVERTED) return E_INVALIDARG; } if (desc.HS.BytecodeLength || desc.DS.BytecodeLength || desc.StreamOutput.NumEntries) { return stream_unsupported("graphics pipeline stage not supported yet (hull/domain/stream output):", 0); } // A geometry shader is the translator's Vulkan geometry stage (docs/design.md, "Geometry shaders"): it takes // triangles and emits a triangle strip. It needs the geometryShader feature, and the PSO's topology type must // be its input primitive, as D3D12 requires. const bool geometry = desc.GS.pShaderBytecode && desc.GS.BytecodeLength; if (geometry && !device_.info.features.geometryShader) { return stream_unsupported("geometry shaders need the Vulkan geometryShader feature; stage", 0); } // The console's rectangle topology type (19) draws as triangles through a generated geometry stage that adds // each rectangle's fourth corner (src/rect_list_geometry.h); it needs the same device feature, and no GS of // the application's own. // Decode the ABI field as bits. The console's value is outside the PC enum's range. const auto topology_type = std::bit_cast(desc.PrimitiveTopologyType); const bool rect_list = !mesh && topology_type == leonida::topology_type_rect_list; if (rect_list && (geometry || !device_.info.features.geometryShader)) { log_once("a rectangle-list pipeline needs the geometryShader feature and no geometry shader; stage", 0); return geometry ? E_INVALIDARG : E_NOTIMPL; } if (geometry && topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { log_once("a translated geometry shader takes triangles; topology type", topology_type); return E_INVALIDARG; } const UINT samples = desc.SampleDesc.Count; if (!samples || samples > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT || (samples & (samples - 1))) { log_once("invalid graphics pipeline sample count:", int(samples)); return E_INVALIDARG; } // D3D12 takes quality 0 and the two pattern values (measured natively on an RX 7800 XT, a Radeon iGPU and // WARP: 0, D3D12_STANDARD_MULTISAMPLE_PATTERN and D3D12_CENTER_MULTISAMPLE_PATTERN succeed, 1 is // E_INVALIDARG, as NumQualityLevels is 1). The standard pattern is Vulkan's standard sample positions, so it // is quality 0 here. The centre pattern puts every sample at the pixel centre, which needs custom sample // locations: refused with a log until those are set. if (desc.SampleDesc.Quality == DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN) { return stream_unsupported("D3D12_CENTER_MULTISAMPLE_PATTERN needs custom sample locations (not set yet); samples", int(samples)); } if (desc.SampleDesc.Quality != 0 && desc.SampleDesc.Quality != DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN) { log_once("invalid graphics pipeline sample quality:", int(desc.SampleDesc.Quality)); return E_INVALIDARG; } const leonida::ShaderLibrary* library = device_.library(); // LEONIDA_STUB_PIPELINES: a vertex pipeline with a missing translation takes the built-in stages below. const bool can_stub = !mesh && stub_pipelines(); bool stubbed = false; if (!library) { // Without the built-in stages (a mesh pipeline), stub_or makes it a mesh stub, or refuses with the switch off. if (!can_stub) return stub_or(E_FAIL, "mesh", StubPipelineKind::mesh); stubbed = true; } struct Stage { const char* name; VkShaderStageFlagBits bit; const D3D12_SHADER_BYTECODE& code; const leonida::ShaderEntry* entry = nullptr; std::vector fssm; std::vector words; std::vector literal_sampler_indices; }; Stage stages[3] = {mesh ? Stage{"ms", VK_SHADER_STAGE_MESH_BIT_EXT, *ms} : Stage{"vs", VK_SHADER_STAGE_VERTEX_BIT, desc.VS}, {"gs", VK_SHADER_STAGE_GEOMETRY_BIT, desc.GS}, {"ps", VK_SHADER_STAGE_FRAGMENT_BIT, desc.PS}}; // stage_infos.size() indexes the recipe's per-stage required-size structs: one for every table entry. static_assert(std::size(stages) <= std::size(decltype(recipe_.required_sizes){}), "Recipe::required_sizes needs an entry per graphics stage"); static_assert(std::size(stages) <= std::extent_v, "Recipe::literal_sampler_specs needs an entry per graphics stage"); unsigned packed_color_mask=0; // A LEONIDA_STUB_PIPELINES=color stub turns blending and logic ops off (below), so the packed fallback's refusal // of them waits until it is known whether this pipeline is such a stub. bool packed_blend_refused=false; for(unsigned i=0;i stage_infos; // Chained from stage_infos, which the recipe keeps for variants built at draw time: so they live in the recipe. auto& required_sizes = recipe_.required_sizes; const Stage* code_stage = nullptr; // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (no D24 on the GPU): the pixel stage writes the depth D24 // would hold, biased in D24 units and quantised (src/depth24_fragment.h, D3D-309), and the rasterizer's own // bias is turned off. Multisampled targets keep the old path: a FragDepth write is per pixel. const VkFormat dsv_vk = desc.DSVFormat != DXGI_FORMAT_UNKNOWN ? vulkan_format(desc.DSVFormat, true).format : VK_FORMAT_UNDEFINED; const bool d24_as_float = dsv_vk == VK_FORMAT_D24_UNORM_S8_UINT && !device_.depth_usable(VK_FORMAT_D24_UNORM_S8_UINT); const bool packed16_fallback = dsv_vk == VK_FORMAT_D16_UNORM_S8_UINT && device_.depth_backing(VK_FORMAT_D16_UNORM_S8_UINT) != VK_FORMAT_D16_UNORM_S8_UINT; if(packed16_fallback && samples>1 && desc.DepthStencilState.DepthEnable) return E_NOTIMPL; bool depth24_fragment = (d24_as_float || packed16_fallback) && desc.DepthStencilState.DepthEnable; if (depth24_fragment && samples > 1) { log_once("D24 depth stored as D32 keeps float depth bias and precision on multisampled targets; samples", int(samples)); depth24_fragment = false; } const leonida::Depth24Bias depth24_bias{desc.RasterizerState.DepthBias, desc.RasterizerState.SlopeScaledDepthBias, desc.RasterizerState.DepthBiasClamp,packed16_fallback?65535.0f:16777215.0f}; for (Stage& stage : stages) { if (stubbed) break; if (!stage.code.pShaderBytecode || !stage.code.BytecodeLength) continue; // no PS: depth only const std::span raw_bytes{ static_cast(stage.code.pShaderBytecode), stage.code.BytecodeLength}; stage.fssm = leonida::fssm_program(raw_bytes); const bool vertex = stage.bit == VK_SHADER_STAGE_VERTEX_BIT; if (!stage.fssm.empty()) { const std::string hash = leonida::sha256_hex(stage.fssm); // Containers with the same program can differ in their input signature or bindings: a VS must have its // inputs fed by this input layout (else the layout check below reports it). stage.entry = pick_entry(library->candidates(stage.name, hash), [&](const leonida::ShaderEntry& e) { return !vertex || layout_feeds(e, desc.InputLayout); }); if (!stage.entry) { std::fprintf(stderr, "[rt] d3d12: no translated %s for FSSM sha256 %s\n", stage.name, hash.c_str()); if (d3d12_trace::enabled()) std::fprintf(stderr, "[rt] d3d12: missing %s in graphics PSO %s (RTs %u, RT0 %d, DSV %d)\n", stage.name, pipeline_key(desc).c_str(), desc.NumRenderTargets, int(desc.RTVFormats[0]), int(desc.DSVFormat)); if (can_stub) { stubbed = true; break; } return stub_or(E_INVALIDARG, "mesh", StubPipelineKind::mesh); } } else if (leonida::fspx_bare_program(raw_bytes)) { // Slot 57 (DeserializeGraphicsPipelineStateX): bare RDNA2 program indexed by fspx_code_sha256 in // /fspx_gfx/index.json. const std::string hash = leonida::sha256_hex(raw_bytes); stage.entry = pick_entry(library->fspx_candidates(stage.name, hash), [&](const leonida::ShaderEntry& e) { return !vertex || layout_feeds(e, desc.InputLayout); }); if (!stage.entry) stage.entry = pick_entry(library->fspx_candidates(stage.name, hash), [](const leonida::ShaderEntry&) { return true; }); if (!stage.entry) { std::fprintf(stderr, "[rt] d3d12: no translated %s for FSPX code sha256 %s (%zu B)\n", stage.name, hash.c_str(), raw_bytes.size()); if (can_stub) { stubbed = true; break; } return stub_or(E_INVALIDARG, "mesh", StubPipelineKind::mesh); } } else { log_once("shader bytecode holds no FSSM or FSPX program; bytes", int(stage.code.BytecodeLength)); return E_INVALIDARG; } if (stage.entry->needs_maintenance8 && !device_.info.maintenance8) { // A texel offset outside a gather is invalid SPIR-V for Vulkan without VK_KHR_maintenance8; refuse // it here, with the reason, instead of handing the driver a module it may reject or miscompile. std::fprintf(stderr, "[rt] d3d12: %s samples with a texel offset; the device has no VK_KHR_maintenance8\n", stage.entry->name.c_str()); return E_NOTIMPL; } if (stage.entry->binding_count) { if (!device_.bindless) { std::fprintf(stderr, "[rt] d3d12: %s uses set-0 bindings; the device has no bindless set 0\n", stage.entry->name.c_str()); return stream_unsupported("graphics shader requires a bindless descriptor set"); } uses_bindless = true; stage.literal_sampler_indices = register_literal_samplers(device_, *stage.entry); } if (stage.entry->uses_image_int64_atomics && !device_.info.shader_image_int64_atomics) { std::fprintf(stderr, "[rt] d3d12: %s requires VK_EXT_shader_image_atomic_int64 (shaderImageInt64Atomics); " "the device lacks it\n", stage.entry->name.c_str()); return stream_unsupported("graphics shader requires shaderImageInt64Atomics"); } if (stage.bit == VK_SHADER_STAGE_MESH_BIT_EXT) { // The SPIR-V's output arrays are sized from PSV0 (the index's max_vertices / max_primitives); Vulkan // has no per-pipeline limit to set, so a mesh shader beyond the device's is refused here // (docs/d3d12_vulkan.md, "Pipelines"). if (const std::string refusal = leonida::mesh_limit_refusal(*stage.entry, device_.mesh_limits()); !refusal.empty()) { std::fprintf(stderr, "[rt] d3d12: %s\n", refusal.c_str()); return stream_unsupported("mesh shader exceeds a device mesh limit"); } // The graphics bind point lays root arguments out from push dword 8, which a mesh shader reads from // its s16 only when translated with the graphics root window (index "root_window", D3D-448). if (!stage.entry->graphics_root_window) { std::fprintf(stderr, "[rt] d3d12: mesh shader %s was translated before the graphics root window; translate " "the shaders again (make_game.py --stages shaders)\n", stage.entry->name.c_str()); return E_INVALIDARG; } } if (stage.entry->uses_code_base) { if (code_stage) { return stream_unsupported("two stages read their code base; one push-constant slot holds one (question 14)", 0); } code_stage = &stage; } stage.words = library->spirv(*stage.entry); if (stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT) { std::string why; if (!rewrite_fragment(stage.words, why)) { if (why.rfind("has no second colour output", 0) == 0) return stream_unsupported("a SRC1 blend factor needs the pixel shader's second colour output; " "this module's outputs do not fit Location 0 Index 1; stage", 0); return E_INVALIDARG; } } if (stage.words.empty()) return E_FAIL; const auto inner = leonida::conservative_raster::inner_coverage_requirements(stage.words); if (!inner.valid) return E_INVALIDARG; if (inner.fully_covered && (stage.bit != VK_SHADER_STAGE_FRAGMENT_BIT || device_.conservative_raster_tier != D3D12_CONSERVATIVE_RASTERIZATION_TIER_3 || (inner.post_depth && !device_.conservative_post_depth_coverage))) { return stream_unsupported("FullyCoveredEXT needs an enabled Tier 3 shader ABI and device properties; stage", int(stage.bit)); } if (stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT && inner.post_depth) fragment_post_depth = true; } const bool stub_cover = stubbed && stub_pipelines_cover(); // also overrides the fixed-function state below if (packed_blend_refused && !stub_cover) return E_NOTIMPL; // translated after all: the refusal stands if (stubbed) { // The built-in vertex and pixel stages replace the whole stage table: no geometry stage, no set 0, no code // base, nothing read from the input layout. The rasterizer keeps the description's depth bias (no D24 // fragment patch), and the colour needs no 4-bit quantisation (exact in every UNORM format). const bool cover = stub_cover; static std::atomic stubbed_count{0}; const unsigned n = ++stubbed_count; if (n == 1 || (n & (n - 1)) == 0) std::fprintf(stderr, "[rt] d3d12: LEONIDA_STUB_PIPELINES: graphics pipeline without a translated shader " "uses the built-in %s stages (%u so far)\n", cover ? "colour" : "empty", n); std::vector outputs(desc.NumRenderTargets, leonida::StubOutput::none); for (UINT i = 0; i < desc.NumRenderTargets; ++i) outputs[i] = stub_output(desc.RTVFormats[i]); for (Stage& stage : stages) { stage.entry = nullptr; stage.fssm.clear(); stage.words.clear(); } stages[0].entry = &stub_entry(); stages[0].words = leonida::stub_vertex_stage(cover, topology_type == D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT); stages[2].entry = &stub_entry(); stages[2].words = leonida::stub_pixel_stage(outputs); uses_bindless = false; code_stage = nullptr; depth24_fragment = false; } if (std::getenv("LEONIDA_LOG_EXE_PIPELINES")) log_exe_pipeline(stages[0].entry, stages[2].entry, desc); // --f16-interp-fallback (SHADER-378): align/synthesize VS decoded f16 halves for this (VS, PS) pair before // creating the shader modules so colliding PS and high-param producers link within MoltenVK's 30 locations. // stages[] is {vs, gs, ps} since geometry shaders joined graphics PSOs (#2109): the PS is stages[2], and with a // GS the PS reads the GS's outputs, not the VS's, so the VS/PS halves link only applies without one. Stage& vs_stage = stages[0]; Stage& gs_stage = stages[1]; Stage& ps_stage = stages[2]; leonida::ShaderEntry ps_f16_entry; const leonida::ShaderEntry* ps_f16_ptr = ps_stage.entry; if (vs_stage.entry && ps_stage.entry && !gs_stage.entry && !vs_stage.fssm.empty() && !ps_stage.fssm.empty()) { const std::span prod_raw{ static_cast(vs_stage.code.pShaderBytecode), vs_stage.code.BytecodeLength}; const std::span ps_raw{ static_cast(ps_stage.code.pShaderBytecode), ps_stage.code.BytecodeLength}; auto sl = leonida::link_stage_varyings(mesh ? leonida::ProducerStage::mesh : leonida::ProducerStage::vertex, prod_raw, vs_stage.fssm, vs_stage.words, ps_raw, ps_stage.fssm, ps_stage.words, device_.f16_half_top_location); if (!sl.ok && !sl.message.empty()) log_once(sl.message.c_str(), 0); if (sl.ok) { if (sl.remapped) { static std::atomic remapped_psos{0}; const auto n = remapped_psos.fetch_add(1, std::memory_order_relaxed) + 1; if (n <= 8 || (n & (n - 1)) == 0) std::fprintf(stderr, "[rt] d3d12: stage-link remapped PS varyings (%u graphics PSO(s) so far; %zu loc(s))\n", n, sl.location_remap.size()); } ps_location_remap_ = std::move(sl.location_remap); ps_attr_to_param_ = std::move(sl.attr_to_param); if (!ps_stage.entry->f16_halves.empty() && (!ps_attr_to_param_.empty() || !ps_location_remap_.empty())) { ps_f16_entry = leonida::remap_ps_f16_halves_entry(*ps_stage.entry, ps_attr_to_param_, ps_location_remap_); ps_f16_ptr = &ps_f16_entry; } } } if (vs_stage.entry && ps_stage.entry && !ps_stage.entry->f16_halves.empty() && gs_stage.entry) { log_once("--f16-interp-fallback halves are linked VS->PS only; this PSO has a geometry shader", 0); } if (vs_stage.entry && ps_stage.entry && !gs_stage.entry && (!ps_stage.entry->f16_halves.empty() || !vs_stage.entry->f16_halves.empty())) { std::string link_error; if (!link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_f16_ptr, &link_error)) { std::fprintf(stderr, "[rt] d3d12: %s\n", link_error.c_str()); return E_FAIL; } f16_linked_ = true; } // A lazy pipeline keeps where each stage's words come from, not the words or a module: build() makes them // again, the same way, and drops them once the pipeline exists. lazy_ = !stubbed && lazy_graphics_pipelines(); // a lazy build reads its stages from the library again depth24_bias_ = depth24_bias; rgba4_mask_ = packed_color_mask; // A stage that declares a storage image or buffer it may write needs a device feature outside compute // (src/spirv_stores.h). Without it the pipeline would be created all the same and break // VUID-RuntimeSpirv-NonWritable-06340 / -06341, so the PSO is refused here with the stage named. for (const Stage& stage : stages) { if (!stage.entry) continue; const bool pixel = stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT; const VkBool32 allowed = pixel ? device_.info.features.fragmentStoresAndAtomics : device_.info.features.vertexPipelineStoresAndAtomics; if (allowed || !leonida::spirv_declares_writable_storage(stage.words)) continue; std::fprintf(stderr, "[rt] d3d12: %s (%s) writes a storage image or buffer, which needs the Vulkan feature %s; " "the device does not have it enabled, so the pipeline is refused\n", stage.entry->name.c_str(), stage.name, pixel ? "fragmentStoresAndAtomics" : "vertexPipelineStoresAndAtomics"); return stream_unsupported("graphics shader requires an unavailable storesAndAtomics feature"); } const auto topology_bits = std::bit_cast(desc.PrimitiveTopologyType); if (!mesh && topology_bits != leonida::topology_type_rect_list) graphics_.rectangle_variant_topology = leonida::topology_rect_list; std::uint64_t spirv_bytes = 0; bool graphics_writes_buffer = false; bool graphics_reads_glc_buffer = false; for (Stage& stage : stages) { if (!stage.entry) continue; if (stage.entry->writes_buffer) graphics_writes_buffer = true; if (stage.entry->reads_glc_buffer) graphics_reads_glc_buffer = true; // After the f16 link above, which can also edit the pixel shader's words. if (depth24_fragment && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT) { std::string why; std::vector patched = leonida::depth24_patch_fragment(stage.words, depth24_bias, why); if (patched.empty()) { std::fprintf(stderr, "[rt] d3d12: %s keeps float depth on a D24 target stored as D32: %s\n", stage.entry->name.c_str(), why.c_str()); depth24_fragment = false; } else { stage.words = std::move(patched); } } spirv_bytes += stage.words.size() * sizeof(std::uint32_t); if (trace_pipeline_compile()) { if (!profile_shaders_.empty()) profile_shaders_ += ','; profile_shaders_ += stage.entry->name; stage_bytes_ += stage.words.size() * sizeof(std::uint32_t); } VkShaderModule module = VK_NULL_HANDLE; if (lazy_) { const bool patched = depth24_fragment && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT; sources_.push_back({StageSource::library, std::uint8_t(&stage - stages), patched, stage.entry}); } else { module = shader_module(stage.words); if (!module) return E_FAIL; } if (stage.bit == VK_SHADER_STAGE_VERTEX_BIT && !geometry && device_.info.features.geometryShader && topology_type == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { rectangle_capable_ = true; if (!lazy_) rectangle_vertex_ = modules_.back(); } if (stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT) { has_fragment_ = true; if (!lazy_) fragment_module_ref_ = modules_.back(); } VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = stage.bit; info.module = module; info.pName = "main"; if (stage.entry->binding_count && stage.entry->literal_sampler_spec_base && !stage.literal_sampler_indices.empty()) { auto& spec = recipe_.literal_sampler_specs[stage_infos.size()]; spec.build(*stage.entry->literal_sampler_spec_base, stage.literal_sampler_indices); info.pSpecializationInfo = spec.ptr(); } subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } if (rect_list) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs std::string why; const std::vector words = leonida::rect_list_geometry(vs_stage.words, why); if (words.empty()) { std::fprintf(stderr, "[rt] d3d12: %s cannot be drawn as a rectangle list: %s\n", vs_stage.entry->name.c_str(), why.c_str()); return stream_unsupported("rectangle-list geometry shader generation failed"); } if (trace_pipeline_compile()) stage_bytes_ += words.size() * sizeof(std::uint32_t); VkShaderModule module = VK_NULL_HANDLE; if (lazy_) { sources_.push_back({StageSource::rect_list}); } else { module = shader_module(words); if (!module) return E_FAIL; } VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = VK_SHADER_STAGE_GEOMETRY_BIT; info.module = module; info.pName = "main"; stage_infos.push_back(info); } if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); if (words.empty()) return E_FAIL; if (trace_pipeline_compile()) stage_bytes_ += words.size() * sizeof(std::uint32_t); VkShaderModule module = VK_NULL_HANDLE; if (lazy_) { sources_.push_back({StageSource::depth_only}); } else { module = shader_module(words); if (!module) return E_FAIL; } VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = VK_SHADER_STAGE_FRAGMENT_BIT; info.module = module; info.pName = "main"; stage_infos.push_back(info); } // Input layout -> vertex input, by semantic. A mesh pipeline has none. std::vector attributes; std::vector bindings; std::vector divisors; std::uint32_t divisor_slots = 0; UINT slot_end[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT] = {}; for (UINT i = 0; !mesh && i < desc.InputLayout.NumElements; ++i) { const D3D12_INPUT_ELEMENT_DESC& element = desc.InputLayout.pInputElementDescs[i]; if (element.InputSlot >= D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT) return E_INVALIDARG; VkFormat format; UINT bytes; if (!vertex_format(element.Format, format, bytes)) { log_once("vertex attribute format not supported yet:", element.Format); return E_INVALIDARG; } const UINT alignment = std::min(bytes, 4u); const UINT offset = element.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT ? (slot_end[element.InputSlot] + alignment - 1) / alignment * alignment : element.AlignedByteOffset; slot_end[element.InputSlot] = offset + bytes; const leonida::SignatureElement* input = nullptr; for (const auto& e : stages[0].entry->input_signature) if (e.system_value == 0 && e.semantic_index == element.SemanticIndex && equal_semantic(e.semantic, element.SemanticName)) input = &e; if (!input) continue; // the shader does not read this element attributes.push_back({input->register_index, element.InputSlot, format, offset}); const bool instance = element.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA; // Step rate 0: every instance reads element 0, which a stride of 0 gives (set at each draw). if (instance && element.InstanceDataStepRate == 0) graphics_.zero_step_slots |= 1u << element.InputSlot; if (instance && element.InstanceDataStepRate > 1) { if (!device_.info.vertex_attribute_divisor) { return stream_unsupported("instance step rates above 1 need vertexAttributeInstanceRateDivisor; rate", int(element.InstanceDataStepRate)); } if (!(divisor_slots & (1u << element.InputSlot))) { divisor_slots |= 1u << element.InputSlot; divisors.push_back({element.InputSlot, element.InstanceDataStepRate}); graphics_.nonunit_vertex_divisor = true; } } if (!(graphics_.vertex_slots & (1u << element.InputSlot))) { graphics_.vertex_slots |= 1u << element.InputSlot; bindings.push_back({element.InputSlot, 0, // stride: dynamic, from IASetVertexBuffers instance ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX}); } } for (const auto& e : stages[0].entry->input_signature) { if (e.system_value) continue; const bool fed = std::any_of(attributes.begin(), attributes.end(), [&](const auto& a) { return a.location == e.register_index; }); if (!fed) { // D3D12 rejects an input layout that leaves a shader input unfed std::fprintf(stderr, "[rt] d3d12: the input layout does not feed %s%u (register %u)\n", e.semantic.c_str(), e.semantic_index, e.register_index); return E_INVALIDARG; } } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; // Type 19 is the console's rectangles, drawn as triangle lists through the geometry stage added above. switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : topology_type) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; default: log_once("primitive topology type not supported:", topology_type); return E_INVALIDARG; } if (!mesh) { // a mesh PSO has no index buffer: its strip cut is ignored if (desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED && desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF && desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF) { log_once("index-buffer strip cut value not supported:", desc.IBStripCutValue); return E_INVALIDARG; } graphics_.strip_cut = desc.IBStripCutValue; } const D3D12_RASTERIZER_DESC& r = desc.RasterizerState; if (r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF && r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON) return E_INVALIDARG; if (r.ConservativeRaster == D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON) { if (device_.conservative_raster_tier == D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) { log_once("conservative rasterization needs enabled VK_EXT_conservative_rasterization and Tier 1 precision", 1); return E_INVALIDARG; } // A mesh pipeline has no input assembler, so its stream need not set the topology type: what is rasterized // is the module's output, and it has to be triangles as well. if (r.FillMode != D3D12_FILL_MODE_SOLID) return E_INVALIDARG; if (mesh ? !leonida::conservative_raster::mesh_outputs_triangles(stages[0].words) : topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; // Target-independent rasterization is a separate pipeline path; do not silently ignore its count. if (r.ForcedSampleCount) return stream_unsupported("target-independent rasterization; forced sample count", int(r.ForcedSampleCount)); } VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; raster.polygonMode = r.FillMode == D3D12_FILL_MODE_WIREFRAME ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL; raster.cullMode = r.CullMode == D3D12_CULL_MODE_FRONT ? VK_CULL_MODE_FRONT_BIT : r.CullMode == D3D12_CULL_MODE_BACK ? VK_CULL_MODE_BACK_BIT : VK_CULL_MODE_NONE; // With the negative-height viewport, framebuffer winding matches D3D12's screen-space winding. raster.frontFace = r.FrontCounterClockwise ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE; // The D24-as-D32 pixel stage applies the bias itself, in D24 units (depth24_fragment above): the // rasterizer's bias stays off and zero, so its clamp needs no depthBiasClamp feature either. raster.depthBiasEnable = !depth24_fragment && (r.DepthBias || r.SlopeScaledDepthBias != 0.0f); if (raster.depthBiasEnable) { raster.depthBiasConstantFactor = float(r.DepthBias); raster.depthBiasClamp = r.DepthBiasClamp; raster.depthBiasSlopeFactor = r.SlopeScaledDepthBias; } raster.lineWidth = 1.0f; // No depth clipping: fragments outside the viewport's depth range are kept and their depth clamped to it, as // D3D12 clamps output depth to MinDepth..MaxDepth anyway (needs depthClamp, checked below). raster.depthClampEnable = r.DepthClipEnable ? VK_FALSE : VK_TRUE; VkPipelineMultisampleStateCreateInfo multisample{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; multisample.rasterizationSamples = VkSampleCountFlagBits(samples); VkSampleMask sample_mask = desc.SampleMask; // all samples for a =color stub (below) multisample.pSampleMask = &sample_mask; multisample.alphaToCoverageEnable = desc.BlendState.AlphaToCoverageEnable; const D3D12_DEPTH_STENCIL_DESC& ds = desc.DepthStencilState; VkPipelineDepthStencilStateCreateInfo depth{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; depth.depthTestEnable = ds.DepthEnable; depth.depthWriteEnable = ds.DepthEnable && ds.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ALL; depth.depthCompareOp = compare_op(ds.DepthFunc); depth.stencilTestEnable = ds.StencilEnable; depth.front = stencil_face(ds.FrontFace, ds.StencilReadMask, ds.StencilWriteMask); depth.back = back_masks ? stencil_face(ds.BackFace, back_masks->read, back_masks->write) : stencil_face(ds.BackFace, ds.StencilReadMask, ds.StencilWriteMask); // The depth-bounds test (DEPTH_STENCIL1/2): the bounds are dynamic, set from OMSetDepthBounds at each draw. depth.depthBoundsTestEnable = depth_bounds ? VK_TRUE : VK_FALSE; depth.minDepthBounds = 0.0f; depth.maxDepthBounds = 1.0f; std::vector blends(desc.NumRenderTargets); for (UINT i = 0; i < desc.NumRenderTargets; ++i) { const D3D12_RENDER_TARGET_BLEND_DESC& b = desc.BlendState.RenderTarget[desc.BlendState.IndependentBlendEnable ? i : 0]; blends[i].blendEnable = b.BlendEnable; blends[i].srcColorBlendFactor = blend_factor(b.SrcBlend); blends[i].dstColorBlendFactor = blend_factor(b.DestBlend); blends[i].colorBlendOp = blend_op(b.BlendOp); blends[i].srcAlphaBlendFactor = blend_factor(b.SrcBlendAlpha); blends[i].dstAlphaBlendFactor = blend_factor(b.DestBlendAlpha); blends[i].alphaBlendOp = blend_op(b.BlendOpAlpha); blends[i].colorWriteMask = b.RenderTargetWriteMask & 0xf; // R, G, B, A in both APIs // B8G8R8X8 has no alpha, so blending reads destination alpha as 1 there (WARP and AMD's D3D12 driver), // where its BGRA8 Vulkan image would read the X byte. For colour SRC_ALPHA_SAT is min(As, 1 - Ad), so 0; // for alpha it is 1 in both APIs already. if (alpha_unused(desc.RTVFormats[i])) { const auto dest_alpha_one = [](VkBlendFactor& factor, bool colour) { if (factor == VK_BLEND_FACTOR_DST_ALPHA) factor = VK_BLEND_FACTOR_ONE; else if (factor == VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA) factor = VK_BLEND_FACTOR_ZERO; else if (colour && factor == VK_BLEND_FACTOR_SRC_ALPHA_SATURATE) factor = VK_BLEND_FACTOR_ZERO; }; dest_alpha_one(blends[i].srcColorBlendFactor, true); dest_alpha_one(blends[i].dstColorBlendFactor, true); dest_alpha_one(blends[i].srcAlphaBlendFactor, false); dest_alpha_one(blends[i].dstAlphaBlendFactor, false); } } VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; blend.attachmentCount = std::uint32_t(blends.size()); blend.pAttachments = blends.data(); // A logic op replaces blending for every target in Vulkan (one per pipeline), and D3D12 takes it from // RenderTarget[0]. Vulkan applies it to integer and normalized formats and skips float ones. const D3D12_RENDER_TARGET_BLEND_DESC& first = desc.BlendState.RenderTarget[0]; if (desc.NumRenderTargets && first.LogicOpEnable) { if (unsigned(first.LogicOp) > D3D12_LOGIC_OP_OR_INVERTED) return E_INVALIDARG; blend.logicOpEnable = VK_TRUE; blend.logicOp = logic_op(first.LogicOp); } // LEONIDA_STUB_PIPELINES=color: the cover triangle has one fixed winding at z = 0 and the pixel stage writes // one colour, so the title's state would often hide it: the D3D12 default back-face cull, wireframe fill, a // zero sample mask, a reverse-Z GREATER test against a clear of 0, a failing stencil test, SRC1 blend factors // (the stub writes no second output), a logic op. All of that is off for the stub; the write mask stays, so a // target the title does not write keeps its contents. if (stub_cover) { raster.polygonMode = VK_POLYGON_MODE_FILL; raster.cullMode = VK_CULL_MODE_NONE; sample_mask = ~VkSampleMask{0}; multisample.alphaToCoverageEnable = VK_FALSE; depth.depthTestEnable = VK_FALSE; depth.depthWriteEnable = VK_FALSE; depth.stencilTestEnable = VK_FALSE; for (auto& b : blends) b.blendEnable = VK_FALSE; blend.logicOpEnable = VK_FALSE; } // State that needs a Vulkan feature the device did not enable (VulkanDeviceInfo::features) is refused, rather // than handed to the driver against the spec. const VkPhysicalDeviceFeatures& features = device_.info.features; if (depth_bounds && !features.depthBounds) return stream_unsupported("depth-bounds tests need depthBounds, which the device lacks; stream subobject", 21); if (depth_bounds) { // how many PSOs use the test (they were all refused before) static std::atomic made{0}; const unsigned n = ++made; if ((n & (n - 1)) == 0) std::fprintf(stderr, "[rt] d3d12: depth-bounds PSO #%u\n", n); } if (raster.polygonMode != VK_POLYGON_MODE_FILL && !features.fillModeNonSolid) return stream_unsupported("wireframe fill needs fillModeNonSolid, which the device lacks; fill mode", r.FillMode); if (raster.depthBiasEnable && raster.depthBiasClamp != 0.0f && !features.depthBiasClamp) return stream_unsupported("a depth-bias clamp needs depthBiasClamp, which the device lacks; clamp x1000", int(raster.depthBiasClamp * 1000)); for (std::size_t i = 1; i < blends.size(); ++i) if (std::memcmp(&blends[i], &blends[0], sizeof(blends[0])) != 0 && !features.independentBlend) return stream_unsupported("per-render-target blend state needs independentBlend, which the device lacks; target", int(i)); const auto src1 = [](VkBlendFactor f) { return f == VK_BLEND_FACTOR_SRC1_COLOR || f == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR || f == VK_BLEND_FACTOR_SRC1_ALPHA || f == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA; }; for (const auto& b : blends) if (b.blendEnable && !features.dualSrcBlend && (src1(b.srcColorBlendFactor) || src1(b.dstColorBlendFactor) || src1(b.srcAlphaBlendFactor) || src1(b.dstAlphaBlendFactor))) return stream_unsupported("SRC1 blend factors need dualSrcBlend, which the device lacks; factor", int(b.srcColorBlendFactor)); if (blend.logicOpEnable && !features.logicOp) return stream_unsupported("logic ops need logicOp, which the device lacks; op", int(first.LogicOp)); if (raster.depthClampEnable && !features.depthClamp) return stream_unsupported("DepthClipEnable = FALSE needs depthClamp, which the device lacks; flag", 0); graphics_.viewport_with_count = features.multiViewport && vk.vkCmdSetViewportWithCount && vk.vkCmdSetScissorWithCount; graphics_.color_formats.assign(desc.NumRenderTargets, VK_FORMAT_UNDEFINED); for (UINT i = 0; i < desc.NumRenderTargets; ++i) { if (desc.RTVFormats[i] == DXGI_FORMAT_UNKNOWN) continue; graphics_.color_formats[i] = desc.RTVFormats[i] == DXGI_FORMAT_A8_UNORM && device_.info.a8_render_target ? kA8UnormFormat : desc.RTVFormats[i] == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && device_.r9g9b9e5_target_stand_in ? VK_FORMAT_B10G11R11_UFLOAT_PACK32 // what such a target is made of : vulkan_format(desc.RTVFormats[i], false).format; // B4G4R4A4 targets are RGBA8 images where no 4444 format renders (DeviceState's texture format choice). if (graphics_.color_formats[i] == VK_FORMAT_A4R4G4B4_UNORM_PACK16 && !device_.color_attachment_usable(VK_FORMAT_A4R4G4B4_UNORM_PACK16)) graphics_.color_formats[i] = VK_FORMAT_R8G8B8A8_UNORM; if (graphics_.color_formats[i] == VK_FORMAT_UNDEFINED) { log_once("render-target format not supported yet:", desc.RTVFormats[i]); return E_INVALIDARG; } } if (desc.DSVFormat != DXGI_FORMAT_UNKNOWN) { Format f = vulkan_format(desc.DSVFormat, true); if (f.format == VK_FORMAT_D24_UNORM_S8_UINT && !device_.depth_usable(f.format)) f.format = VK_FORMAT_D32_SFLOAT_S8_UINT; // as CreateCommittedResource does graphics_.depth_format = device_.depth_backing(f.format); graphics_.depth_aspects = f.aspects; } if (samples > 1) { const auto& dinfo = device_.info; const bool has_color = std::any_of(graphics_.color_formats.begin(), graphics_.color_formats.end(), [](VkFormat f) { return f != VK_FORMAT_UNDEFINED; }); const bool has_depth = graphics_.depth_format != VK_FORMAT_UNDEFINED; if (const auto get_props = reinterpret_cast( dinfo.get_instance_proc ? dinfo.get_instance_proc(dinfo.instance, "vkGetPhysicalDeviceProperties") : nullptr)) { VkPhysicalDeviceProperties props{}; get_props(dinfo.physical, &props); VkSampleCountFlags supported = ~VkSampleCountFlags(0); if (has_color) supported &= props.limits.framebufferColorSampleCounts; if (has_depth && (graphics_.depth_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) supported &= props.limits.framebufferDepthSampleCounts; if (has_depth && (graphics_.depth_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) supported &= props.limits.framebufferStencilSampleCounts; if (!has_color && !has_depth) supported &= props.limits.framebufferNoAttachmentsSampleCounts; if (!(supported & samples)) { log_once("multisample count not supported by framebuffer limits; samples", int(samples)); return E_INVALIDARG; } } if ((has_color || has_depth) && !device_.image_format_properties) { log_once("cannot query per-format multisample support; samples", int(samples)); return E_INVALIDARG; } for (const VkFormat fmt : graphics_.color_formats) { if (fmt == VK_FORMAT_UNDEFINED) continue; VkImageFormatProperties img_props{}; if (device_.image_format_properties(dinfo.physical, fmt, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, 0, &img_props) != VK_SUCCESS || !(img_props.sampleCounts & samples)) { log_once("multisample count not supported by color attachment format; samples", int(samples)); return E_INVALIDARG; } } if (has_depth) { VkImageFormatProperties img_props{}; if (device_.image_format_properties(dinfo.physical, graphics_.depth_format, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, 0, &img_props) != VK_SUCCESS || !(img_props.sampleCounts & samples)) { log_once("multisample count not supported by depth/stencil attachment format; samples", int(samples)); return E_INVALIDARG; } } } // Every stage this path accepts reads the user SGPRs, so the range covers the whole stage table, not only the // stages present. A stage added to the table (geometry, mesh) is covered without touching this. // (The geometry bit only where the device has the stage: a range may not name a stage it cannot run.) for (const Stage& stage : stages) if (stage.bit != VK_SHADER_STAGE_GEOMETRY_BIT || device_.info.features.geometryShader) graphics_.push_stages |= stage.bit; if (uses_bindless) graphics_.bindless_set = device_.bindless->set(); graphics_.layout = device_.shared_pipeline_layout(graphics_.push_stages, sizeof(leonida::ShaderUserData), uses_bindless); if (!graphics_.layout) return E_FAIL; owns_graphics_layouts_ = false; // Separate 148-byte push-constant layout for on-demand OMSetSampleMaskX masked twin variants. // Depth-only PSOs (!has_fragment_), PostDepthCoverage shaders, and devices with maxPushConstantsSize < 148 // keep masked_layout null. const std::uint32_t push_limit = device_.info.max_push_constants_size; if (has_fragment_ && !fragment_post_depth && (push_limit == 0 || push_limit >= leonida::kPixelMaskPushBytes)) { graphics_.masked_layout = device_.shared_pipeline_layout(graphics_.push_stages, leonida::kPixelMaskPushBytes, uses_bindless); if (!graphics_.masked_layout) return E_FAIL; } // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. graphics_.mesh = mesh; graphics_.depth_bounds = depth_bounds; graphics_.reads_glc_buffer = graphics_reads_glc_buffer; graphics_.writes_buffer = graphics_writes_buffer; const auto stencil_face_writes = [](const VkStencilOpState& f) { return f.writeMask != 0 && (f.failOp != VK_STENCIL_OP_KEEP || f.passOp != VK_STENCIL_OP_KEEP || f.depthFailOp != VK_STENCIL_OP_KEEP); }; graphics_.depth_writes = depth.depthWriteEnable != VK_FALSE; graphics_.stencil_writes = depth.stencilTestEnable != VK_FALSE && (stencil_face_writes(depth.front) || stencil_face_writes(depth.back)); recipe_.mesh = mesh; recipe_.stages = std::move(stage_infos); recipe_.attributes = std::move(attributes); recipe_.bindings = std::move(bindings); recipe_.divisors = std::move(divisors); recipe_.assembly = assembly; recipe_.raster = raster; recipe_.conservative = r.ConservativeRaster == D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON; recipe_.multisample = multisample; graphics_.samples = samples; graphics_.sample_grid_1 = device_.sample_grid_1; graphics_.sample_grid_4 = device_.sample_grid_4; recipe_.sample_mask = sample_mask; recipe_.depth = depth; recipe_.blends = std::move(blends); recipe_.blend = blend; if (!lazy_) { VkResult compile_status = VK_SUCCESS; const bool cache_only = device_.info.cold_graphics_compile; const ULONGLONG build_started = device_.order_log ? GetTickCount64() : 0; graphics_.pipeline = build(0, "graphics-create", cache_only ? VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT : 0, &compile_status); if (graphics_.pipeline && device_.order_log) order_build_ms_.store(std::uint32_t(std::min(GetTickCount64() - build_started, 0xfffffffeull))); // A cache-only create that the driver would have to compile stays null: the first draw builds it. if (!graphics_.pipeline && !(cache_only && compile_status == VK_PIPELINE_COMPILE_REQUIRED)) return E_FAIL; } // lazy: graphics_.pipeline stays null and the first draw builds it as variant 0 // LEONIDA_ASYNC_MIN_BYTES_GRAPHICS (unset: LEONIDA_ASYNC_MIN_BYTES): a pipeline smaller than that (all its // stages) is built where a draw needs it. graphics_.async_build = async_replay_compile(true, spirv_bytes); graphics_.variant = [this](std::uint32_t unbound) { return replay_pipeline("draw", [&] { return graphics_.async_build ? queue_build(false, unbound) : variant(unbound, "draw"); }); }; graphics_.built = [this](std::uint32_t unbound) { std::unique_lock lock(variants_mutex_, std::try_to_lock); // held: another thread is compiling one if (!lock.owns_lock()) return VkPipeline(VK_NULL_HANDLE); const auto it = variants_.find(unbound); return it == variants_.end() ? VkPipeline(VK_NULL_HANDLE) : it->second; }; graphics_large_module_ = spirv_bytes >= leonida::PipelineCompiles::large_spirv_bytes; graphics_.large = graphics_large_module_ && big_compiles() != BigCompiles::unlimited; graphics_.estimate = leonida::large_module_estimate(spirv_bytes); if (code_stage) { VkDeviceSize offset = 0; if (!device_.arena_allocate(code_stage->fssm.size(), 256, offset, DeviceState::arena_shader)) return E_OUTOFMEMORY; std::memcpy(device_.arena_host(offset, code_stage->fssm.size()), code_stage->fssm.data(), code_stage->fssm.size()); device_.arena_mark_dirty(offset, code_stage->fssm.size()); code_bytes_ = code_stage->fssm.size(); code_base_ = offset; graphics_.code_base = offset; } if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC: what this pipeline is, for the fsdraw probe's draw lines const auto& rt0 = desc.BlendState.RenderTarget[0]; char text[640]; std::snprintf(text, sizeof text, "vs %s (fssm %.16s) ps %s (fssm %.16s) rootsig %p rts %u fmt0 %d fmt1 %d dsv %d depth %d " "blend0 en %d src %d dst %d op %d srcA %d dstA %d opA %d logic %d wm 0x%x alpha2cov %d " "independent %d sample_mask 0x%x cull %d fill %d topo %d samples %u", stages[0].entry ? stages[0].entry->name.c_str() : "-", stages[0].entry ? stages[0].entry->fssm_sha256.c_str() : "-", stages[2].entry ? stages[2].entry->name.c_str() : "-", stages[2].entry ? stages[2].entry->fssm_sha256.c_str() : "-", static_cast(desc.pRootSignature), desc.NumRenderTargets, int(desc.RTVFormats[0]), int(desc.RTVFormats[1]), int(desc.DSVFormat), int(desc.DepthStencilState.DepthEnable), int(rt0.BlendEnable), int(rt0.SrcBlend), int(rt0.DestBlend), int(rt0.BlendOp), int(rt0.SrcBlendAlpha), int(rt0.DestBlendAlpha), int(rt0.BlendOpAlpha), int(rt0.LogicOpEnable), unsigned(rt0.RenderTargetWriteMask), int(desc.BlendState.AlphaToCoverageEnable), int(desc.BlendState.IndependentBlendEnable), unsigned(desc.SampleMask), int(desc.RasterizerState.CullMode), int(desc.RasterizerState.FillMode), int(desc.PrimitiveTopologyType), desc.SampleDesc.Count); leonida::fsdraw::note_pipeline(id(), text); } order_install(graphics_.requested, graphics_.request_context, graphics_.mesh ? 'm' : 'g'); if (device_.info.device_checkpoints || leonida::gpu_profile::enabled()) { // names for both reports leonida::CheckpointShaders shaders{}; for (std::size_t i = 0; i < std::size(stages); ++i) if (stages[i].entry) shaders[i] = stages[i].entry->name.c_str(); device_.context->add_graphics_pipeline(id(), graphics_, &shaders); } else { device_.context->add_graphics_pipeline(id(), graphics_); } registered_ = true; is_graphics_ = true; prewarm_queue(std::size_t((std::max)(spirv_bytes, std::uint64_t{1}))); return S_OK; } HRESULT create_compute(const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc) { auto& vk = device_.context->vk; const VkDevice dev = device_.info.device; if (!desc.CS.pShaderBytecode || !desc.CS.BytecodeLength) return E_INVALIDARG; if (desc.NodeMask & ~1u) return E_INVALIDARG; if (static_cast(desc.Flags) & ~kKnownPipelineStateFlags) return E_INVALIDARG; if (!device_.arena_ready()) { return stream_unsupported("pipelines need the GPU address arena (bufferDeviceAddress); stage", 0); } if (!push_constants_fit()) return stream_unsupported("compute push-constant limit"); // The game's FSSM program, or the FidelityFX DLL's FSPX kind-6 program: in a DXBC container's ACCC part at // slot 62, bare from a slot-67 description (docs/fspx.md, "Run-time lookup"). const leonida::ComputeProgram program = leonida::compute_program( {static_cast(desc.CS.pShaderBytecode), desc.CS.BytecodeLength}); if (program.kind == leonida::ComputeProgram::Kind::none) { log_once("compute shader bytecode holds no FSSM or FSPX program; bytes", int(desc.CS.BytecodeLength)); return E_INVALIDARG; } const leonida::ShaderLibrary* library = device_.library(); if (!library) return stub_or(E_FAIL, "compute", StubPipelineKind::compute); // A binding-free entry wins over one with bindings for the same program (pick_entry). // An FSPX program from a container is matched on its kind-0 state too; a bare kind-6 program whose // translations differ is ambiguous without that state and is refused (program_candidates). bool ambiguous = false; const leonida::ShaderEntry* entry = pick_entry(library->program_candidates("cs", program, &ambiguous), [](const leonida::ShaderEntry&) { return true; }); if (!entry) { const bool fspx = program.kind == leonida::ComputeProgram::Kind::fspx; if (ambiguous) { // Ambiguous is not missing: translations exist, so it is refused even with LEONIDA_STUB_PIPELINES. std::fprintf(stderr, "[rt] d3d12: FSPX kind-6 program sha256 %s is ambiguous without its kind-0 " "state: its translations differ\n", leonida::sha256_hex(program.bytes).c_str()); return E_INVALIDARG; } std::fprintf(stderr, "[rt] d3d12: no translated compute shader for %s sha256 %s\n", fspx ? (program.state.empty() ? "FSPX kind-6" : "FSPX kind-6 and kind-0") : "FSSM", leonida::sha256_hex(program.bytes).c_str()); return stub_or(E_INVALIDARG, "compute", StubPipelineKind::compute); } // Set 0 (bindless images, samplers, the descriptor hash table): the device keeps it, and a pipeline whose // shader declares bindings has it in its layout and has it bound at every dispatch. if (entry->binding_count && !device_.bindless) { std::fprintf(stderr, "[rt] d3d12: %s uses set-0 bindings; the device has no bindless set 0\n", entry->name.c_str()); return stream_unsupported("compute shader requires a bindless descriptor set"); } if (entry->uses_image_int64_atomics && !device_.info.shader_image_int64_atomics) { std::fprintf(stderr, "[rt] d3d12: %s requires VK_EXT_shader_image_atomic_int64 (shaderImageInt64Atomics); " "the device lacks it\n", entry->name.c_str()); return stream_unsupported("compute shader requires shaderImageInt64Atomics"); } if (entry->binding_count) register_literal_samplers(device_, *entry); if (entry->needs_maintenance8 && !device_.info.maintenance8) { std::fprintf(stderr, "[rt] d3d12: %s samples with a texel offset; the device has no VK_KHR_maintenance8\n", entry->name.c_str()); return E_NOTIMPL; } // SHADER-309: a module over the device's maxComputeSharedMemorySize is invalid usage that spirv-val accepts // and RADV dies on (#1721); some drivers report 32768. Refuse it here instead of creating the pipeline. if (entry->lds_bytes) { std::uint32_t max_shared = device_.max_compute_shared_memory_size; if (!max_shared) { const auto& dinfo = device_.info; if (const auto get_props = reinterpret_cast( dinfo.get_instance_proc ? dinfo.get_instance_proc(dinfo.instance, "vkGetPhysicalDeviceProperties") : nullptr)) { VkPhysicalDeviceProperties props{}; get_props(dinfo.physical, &props); max_shared = props.limits.maxComputeSharedMemorySize; } } if (max_shared && entry->lds_bytes > max_shared) { std::fprintf(stderr, "[rt] d3d12: %s declares %u bytes of workgroup memory, over the device's " "maxComputeSharedMemorySize %u\n", entry->name.c_str(), unsigned(entry->lds_bytes), unsigned(max_shared)); return stream_unsupported("compute shader exceeds shared memory limit"); } } const std::size_t spirv_bytes = library->spirv_bytes(*entry); if (!spirv_bytes) { std::fprintf(stderr, "[rt] d3d12: %s.spv is missing\n", entry->name.c_str()); return E_FAIL; } const bool with_bindless = entry->binding_count != 0; if (with_bindless) pipeline_.bindless_set = device_.bindless->set(); pipeline_.layout = device_.shared_pipeline_layout(VK_SHADER_STAGE_COMPUTE_BIT, sizeof(leonida::ShaderUserData), with_bindless); if (!pipeline_.layout) return E_FAIL; owns_compute_layout_ = false; compute_entry_ = entry; stage_bytes_ = spirv_bytes; pipeline_.estimate = leonida::large_module_estimate(spirv_bytes); pipeline_.reads_glc_buffer = entry->reads_glc_buffer; pipeline_.writes_buffer = entry->writes_buffer; // The title creates hundreds of compute pipelines from job threads during startup and one of its init tasks // waits for all of them; some modules (wave64-emulated ray-tracing resolves, 4 MiB of SPIR-V) take the driver // minutes each. So the Vulkan pipeline is built on first use (build_compute): at the first dispatch that names // it, or earlier by the warm-up thread. CreateComputePipelineState answers at once, as it does on the console // where these are precompiled. LEONIDA_LAZY_COMPUTE=0: built here, as before. static const bool lazy_compute = [] { wchar_t v[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_LAZY_COMPUTE", v, 2) == 1 && v[0] == L'0'); }(); if (skip_compute(entry->name)) { // Never built. Replay drops each dispatch (ComputePipeline::skipped); the first one is logged, so a // boot's log lists the skipped programs the title actually ran. pipeline_.skipped = true; pipeline_.build = [](void* self) -> VkPipeline { auto* pso = static_cast(self); if (!pso->skip_logged_.exchange(true)) std::fprintf(stderr, "[rt] d3d12: compute program %s is skipped (LEONIDA_SKIP_COMPUTE): its " "dispatches are dropped\n", pso->compute_entry_->name.c_str()); return VK_NULL_HANDLE; }; pipeline_.build_context = this; } else if (lazy_compute) { // LEONIDA_ASYNC_MIN_BYTES: a module smaller than that is built where a dispatch needs it. pipeline_.async_build = async_replay_compile(false, spirv_bytes); pipeline_.build = [](void* self) { auto* pso = static_cast(self); return replay_pipeline("dispatch", [&] { return pso->pipeline_.async_build ? pso->queue_build(true, 0) : pso->build_compute("dispatch"); }); }; pipeline_.build_context = this; pipeline_.built = [](void* self) { auto* pso = static_cast(self); std::unique_lock lock(pso->variants_mutex_, std::try_to_lock); // held: another thread is compiling it return lock.owns_lock() ? pso->pipeline_.pipeline : VkPipeline(VK_NULL_HANDLE); }; pipeline_.large = big_compute(spirv_bytes) && big_compiles() != BigCompiles::unlimited; } else if (!build_compute("compute-create")) { return E_FAIL; } // The code base: shaders read constant tables embedded in their own program through s_getpc_b64. The // translator's code offsets are into the bytes the key hashes (the FSSM blob, or the kind-6 program). if (entry->uses_code_base || !entry->code_base_known) { const auto& code = program.bytes; if (!device_.arena_allocate(code.size(), 256, code_base_, DeviceState::arena_shader)) return E_OUTOFMEMORY; std::memcpy(device_.arena_host(code_base_, code.size()), code.data(), code.size()); device_.arena_mark_dirty(code_base_, code.size()); code_bytes_ = code.size(); pipeline_.code_base = code_base_; } if (!pipeline_.skipped) order_install(pipeline_.requested, pipeline_.request_context, 'c', entry->name); device_.context->add_pipeline(id(), pipeline_, device_.info.device_fault_diagnostics || leonida::gpu_profile::enabled() ? entry->name.c_str() : nullptr); registered_ = true; if (pipeline_.build && !pipeline_.skipped) warmup_enqueue(this, spirv_bytes); return S_OK; } private: using Work = leonida::LargeModuleGate::Work; // Locks the PSO (`lock`, on variants_mutex_) for a build and, with an `estimate`, takes the build's place at the gate. A // thread that waits for its place holds no PSO's lock, and one that has its place waits for none: another thread may be // building that PSO, with a place of its own. Returns without a place when the PSO is `built` already. template leonida::LargeModuleGate::Ticket enter_build(std::unique_lock& lock, std::uint64_t estimate, Work work, Built&& built) { for (;;) { lock.lock(); if (!estimate || built()) return {}; lock.unlock(); leonida::LargeModuleGate::Ticket place(big_compile_gate(), estimate, work); if (lock.try_lock()) return place; } } // The compute pipeline, built once: by create_compute (LEONIDA_LAZY_COMPUTE=0), by the first dispatch that names // it (the replay layer calls ComputePipeline::build) or by the warm-up thread. Null when it cannot be built; the // failure is logged and not retried. VkPipeline build_compute(const char* trigger, Work work = Work::demand) { // A large module's place at the compile gate is taken before the PSO's lock (enter_build): a thread that waits // for memory holds no PSO lock. std::unique_lock lock(variants_mutex_, std::defer_lock); const bool budgeted = big_compute(stage_bytes_) && big_compiles() == BigCompiles::budget; auto place = enter_build(lock, budgeted ? pipeline_.estimate : 0, work, [this] { return pipeline_.pipeline || compute_failed_; }); if (pipeline_.pipeline || compute_failed_) return pipeline_.pipeline; const leonida::ShaderEntry* entry = compute_entry_; if (!device_.library() || !entry) { compute_failed_ = true; return VK_NULL_HANDLE; } // LOCAL FIX (compile helper, d3d12_compile_helper.h): asynchronous builds and warm-ups only ask the helper and // are deferred (queue_build publishes nothing for them, so their next use asks again). While the helper is // still making the file this answers at once, without reading the module; a use asks with replay's priority. // Only replay's own and the warm-up's triggers may answer deferred: compute-create (LEONIDA_LAZY_COMPUTE=0) is // a create whose caller needs a pipeline now, so it waits for the file as a dispatch does in a strict replay // (LOCAL FIX, review: with LEONIDA_ASYNC_PIPELINES=1 it was deferred and returned E_FAIL). const bool warmup = !std::strcmp(trigger, "warmup"); const bool replay_trigger = !std::strcmp(trigger, "dispatch") || !std::strcmp(trigger, "dispatch-worker"); // An asynchronous pipeline only (one under LEONIDA_ASYNC_MIN_BYTES waits for the file, as without them). const bool helper_nowait = warmup || (replay_trigger && pipeline_.async_build); if (!helper_file_.empty()) { auto& helper = compile_helper::Client::instance(); std::string why; const auto state = helper.state(helper_file_, device_.pso_identity, &why); if (state == compile_helper::Client::State::pending) { if (!warmup) helper.request(helper_file_, entry->name, 0, device_.pso_identity, nullptr); if (helper_nowait) { helper_deferred_ = true; return VK_NULL_HANDLE; } } else if (state != compile_helper::Client::State::ready) { std::fprintf(stderr, "[rt] d3d12: compile helper: %s for %s; built here\n", why.c_str(), entry->name.c_str()); helper_refused_ = true; } helper_file_.clear(); } compute_failed_ = true; // until the pipeline exists ComputeBuildOptions options; options.trigger = trigger; options.cache_key = &cache_key_; options.use_helper = !helper_refused_; options.helper_wait = !helper_nowait; options.helper_priority = warmup ? stage_bytes_ : 0; const ComputeBuild build = build_compute_pipeline(device_, *entry, pipeline_.layout, subgroup_request_for(*entry), options); if (build.deferred) { compute_failed_ = false; helper_file_ = build.journal_path; helper_deferred_ = true; return VK_NULL_HANDLE; } if (build.result != VK_SUCCESS || !build.pipeline) { std::fprintf(stderr, "[rt] d3d12: compute pipeline %s could not be built (VkResult %d); its dispatches are " "dropped\n", entry->name.c_str(), int(build.result)); return VK_NULL_HANDLE; } maybe_checkpoint(device_.pipeline_cache()); pipeline_.pipeline = build.pipeline; compute_failed_ = false; order_note_build(0, build.ms); return build.pipeline; } // Lazy compute pipelines are also built in the background, smallest module first, so most exist before their // first dispatch. One low-priority thread; modules over LEONIDA_COMPUTE_WARMUP_MAX_BYTES of SPIR-V (default // 1 MiB) are left to their first dispatch, since some take the driver minutes each. LEONIDA_COMPUTE_WARMUP=0 // turns the thread off. A queued build holds no reference: a PSO released first drops it (last_release). // The startup cache checkpoint is the device's job, not this PSO's: ~Device cancels it before the cache goes. void maybe_checkpoint(VkPipelineCache cache) { if (!cache || !startup_cache_checkpoints_enabled()) return; auto now = GetTickCount64(); auto next = device_.next_checkpoint.load(); if (now < next || !device_.next_checkpoint.compare_exchange_strong(next, ULLONG_MAX)) return; DeviceState* const state = &device_; bool queued = false; try { queued = PipelineCompiler::instance().submit(state, state, SIZE_MAX, [state, cache] { try { if (!state->active_compiles.load() && !PipelineCompiler::instance().has_compile_waiter()) save_session_pipeline_cache(state->context->vk, state->info.device, cache, true); } catch (const std::exception& e) { std::fprintf(stderr, "[rt] pipeline cache checkpoint failed: %s\n", e.what()); } state->next_checkpoint.store(GetTickCount64() + 120000); }); } catch (...) { } if (!queued) device_.next_checkpoint.store(now + 120000); // refused after an exit stop, or out of memory } // Asynchronous builds (LEONIDA_ASYNC_PIPELINES=1): replay asks here at prepare, with the resource lock held. The // handle once built; otherwise a compile-worker job is queued (once) and null answered, so the draw or dispatch is // skipped and a later submission uses the pipeline. `warm_bytes`: a warm-up, queued by module size. `count_skip`: // false for a request made at record time (request_early), which skips nothing. // `priority`: where a warm-up goes among the others (PipelineCompiler); 0: by `warm_bytes`, the module size. VkPipeline queue_build(bool compute, std::uint32_t unbound, std::size_t warm_bytes = 0, bool count_skip = true, std::size_t priority = 0) { static std::mutex publication; // ready handles only; no compiler call holds this lock const bool warm = warm_bytes != 0; // After an exit stop (stop_pipeline_compiles) nothing is queued: a warm-up or an early request is skipped, // and a draw or dispatch builds in place, as without LEONIDA_ASYNC_PIPELINES, rather than waiting for a build // that never comes. if (PipelineCompiler::instance().closed()) { if (warm || !count_skip) return VK_NULL_HANDLE; return compute ? build_compute("dispatch") : variant(unbound, "draw"); } std::lock_guard lock(publication); if (!warm) { if (!requested_) requested_ = std::make_unique(); auto [it, inserted] = requested_->try_emplace(unbound); if (!it->second.handle && count_skip) ++it->second.skips; if (!inserted) return it->second.handle; } bool queued = false; try { queued = PipelineCompiler::instance().submit(compile_owner(), &device_, warm && priority ? priority : warm_bytes, [this, compute, warm, unbound, warm_bytes] { // A big warm-up while the title submits is left to the pipeline's first use (warmup_waits_for_quiet). if (warm && warmup_waits_for_quiet(warm_bytes)) return; VkPipeline built{}; try { built = compute ? build_compute(warm ? "warmup" : "dispatch-worker", warm ? Work::speculative : Work::demand) : variant(unbound, "draw-worker"); // The compile helper is still making the journal file (build_compute): not built, so nothing is // published and the next use asks again. const bool deferred = compute && helper_deferred_.exchange(false); if (compute ? pipeline_.async_build : graphics_.async_build) { unsigned long long skipped = 0; { std::lock_guard publish(publication); if (!requested_) requested_ = std::make_unique(); if (deferred) { if (!warm) requested_->erase(unbound); } else { auto& entry = (*requested_)[unbound]; if (!entry.handle) skipped = entry.skips; entry.handle = built; } } if (skipped && trace_pipeline_compile()) std::fprintf(stderr, "[rt] pipeline-deferred type=%s skipped=%llu ready=%d\n", compute ? "compute" : "graphics", skipped, int(built != VK_NULL_HANDLE)); } } catch (const std::exception& e) { std::fprintf(stderr, "[rt] pipeline compile worker failed: %s\n", e.what()); } }, !compute, // a graphics build may also take the graphics worker compute ? big_compute(stage_bytes_) : graphics_large_module_); // the pool's heavy count } catch (...) { } // Not queued (refused by a stop that came after the check above, or out of memory): no request stays // recorded, so the next use asks again instead of waiting for a build that never comes. if (!queued && !warm) requested_->erase(unbound); return VK_NULL_HANDLE; } // LEONIDA_PIPELINE_PREWARM_ORDER: the variants an earlier run asked this graphics pipeline for, queued as warm-ups at // their recorded rank (pipeline_prewarm.h): after every demanded build, one warm-up at a time and none while a // demanded build runs (PipelineCompiler). A queued one holds no reference: a release first drops it (last_release). void prewarm_queue(std::size_t bytes) { const auto* plan = device_.prewarm_plan.get(); if (!plan) return; const auto& key = order_key_.empty() ? cache_key_ : order_key_; const auto* entries = key.empty() ? nullptr : plan->find(key); if (!entries) return; for (const auto& entry : *entries) { if (entry.variant == 0 && graphics_.pipeline) continue; // built at create queue_build(false, entry.variant, bytes, true, leonida::pipeline_prewarm::priority(entry.rank)); } } public: // A console stream kept for its first bind (LEONIDA_PIPELINE_COMPILE=on-demand, set_pending_stream) is parsed only // when it is first resolved, and create_graphics queues the prewarm from there: no lead at all. When the plan has // the stream's pipeline, the parse is queued here as its first prewarm job instead, at the rank of its first // recorded variant, on a compile worker rather than the title's thread; create_graphics then queues the variants // with their ranks as for any other PSO. A bind meanwhile waits for that parse (resolve_type's call_once), which it // would otherwise have done itself. Like any queued build it holds no reference (last_release drops it). void prewarm_pending_stream() { const auto* plan = device_.prewarm_plan.get(); if (!plan || pending_stream_kind_ != 1) return; const auto& key = order_key_.empty() ? cache_key_ : order_key_; const auto* entries = key.empty() ? nullptr : plan->find(key); if (!entries || entries->empty()) return; try { PipelineCompiler::instance().submit(compile_owner(), &device_, leonida::pipeline_prewarm::priority(entries->front().rank), [this] { resolve_type(true); }, true); } catch (...) { } } // Record time (SetPipelineState for compute, a draw for graphics, with the render-target slots it binds and // whether it binds a depth buffer): asynchronous builds start on the compile worker before the list is submitted. // Never waits; nothing to do when the variant is the last one asked for here. void request_early(std::uint32_t bound_targets, bool depth_bound, bool sample_masked = false) { if (!async_replay_compile() || !registered_) return; // A pipeline under LEONIDA_ASYNC_MIN_BYTES is built where it is needed, as without asynchronous builds. if (!(is_graphics_ ? graphics_.async_build : pipeline_.async_build)) return; std::uint32_t unbound = 0; if (is_graphics_) { for (std::size_t slot = 0; slot < graphics_.color_formats.size() && slot < 8; ++slot) if (graphics_.color_formats[slot] != VK_FORMAT_UNDEFINED && !(bound_targets & (1u << slot))) unbound |= 1u << slot; if (graphics_.depth_format != VK_FORMAT_UNDEFINED && !depth_bound) unbound |= leonida::GraphicsPipeline::unbound_depth; if (sample_masked && graphics_.masked_layout != VK_NULL_HANDLE) unbound |= leonida::GraphicsPipeline::sample_masked; if (!unbound && graphics_.pipeline) return; } else if (!pipeline_.build || pipeline_.skipped) { return; // an eager pipeline has no build } if (early_.exchange(unbound + 1, std::memory_order_relaxed) == unbound + 1) return; queue_build(!is_graphics_, unbound, 0, false); } private: // LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES= (opt-in; unset or 0: no limit, the warm-up builds every module as on // main): a warm-up of a module over n bytes of SPIR-V is not started while the title submits (a submission in the // last second); it is left to the pipeline's first use. A create holds the compile gate (SubmitMutex::CompileTurn) // for its whole length and every submission waits behind it; on NVIDIA 630.20 the modules over 640 KiB take 4-25 s // each. Measured in a native boot past the story load (with 131072): 694 warm-ups of modules over 128 KiB against // 25 such builds a dispatch asked for, and one run's submissions waited 140 s in all at the gate behind warm-ups. static bool warmup_waits_for_quiet(std::size_t bytes) { static const std::size_t limit = [] { char text[32]{}; const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES", text, sizeof(text)); return (n > 0 && n < sizeof(text)) ? static_cast(std::strtoull(text, nullptr, 10)) : std::size_t{0}; }(); if (!limit || bytes <= limit || !leonida::pipeline_wait::title_submitting()) return false; if (compile_helper::wanted(bytes)) return false; // the helper compiles it, in its own process if (leonida::pipeline_wait::warmups_left().fetch_add(1, std::memory_order_relaxed) == 0) { static std::atomic logged{false}; if (!logged.exchange(true)) std::fprintf(stderr, "[rt] d3d12: compute warm-ups over %zu KiB are left to their first use while the " "title submits (LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES), from t=%.3f s\n", limit >> 10, double(leonida::diagnostic_ms()) / 1000.0); } return true; } static void warmup_enqueue(PipelineState* pso, std::size_t bytes) { static const std::size_t max_bytes = [] { char text[32]{}; const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPUTE_WARMUP_MAX_BYTES", text, sizeof(text)); const unsigned long long v = (n > 0 && n < sizeof(text)) ? std::strtoull(text, nullptr, 10) : 0; return v ? static_cast(v) : std::size_t{1} << 20; }(); static const bool on = [] { wchar_t v[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_COMPUTE_WARMUP", v, 2) == 1 && v[0] == L'0'); }(); if (on && bytes && bytes <= max_bytes) pso->queue_build(true, 0, bytes); } // What a graphics pipeline is made from, so variants can be built at draw time. struct Recipe { bool mesh = false; // no vertex input or input assembly state, and no dynamic topology or strides std::vector stages; // One per entry of create_graphics's stage table (VS, GS, PS), static_assert there; what `stages` chain. VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_sizes[3]{}; leonida::LiteralSamplerSpec literal_sampler_specs[3]{}; std::vector attributes; std::vector bindings; std::vector divisors; VkPipelineInputAssemblyStateCreateInfo assembly{}; VkPipelineRasterizationStateCreateInfo raster{}; bool conservative = false; VkPipelineMultisampleStateCreateInfo multisample{}; VkSampleMask sample_mask = ~0u; VkPipelineDepthStencilStateCreateInfo depth{}; std::vector blends; VkPipelineColorBlendStateCreateInfo blend{}; }; // The graphics pipeline with the formats of the `unbound` slots (leonida::GraphicsPipeline::variant) undefined. VkPipeline build(std::uint32_t unbound, const char* trigger, VkPipelineCreateFlags flags = 0, VkResult* status = nullptr) { CompileActivity activity(device_.active_compiles); const Recipe& r = recipe_; std::vector colors = graphics_.color_formats; for (std::size_t slot = 0; slot < colors.size(); ++slot) if (unbound & (1u << slot)) colors[slot] = VK_FORMAT_UNDEFINED; const bool depth_bound = !(unbound & leonida::GraphicsPipeline::unbound_depth); VkPipelineRenderingCreateInfo rendering{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO}; rendering.colorAttachmentCount = std::uint32_t(colors.size()); rendering.pColorAttachmentFormats = colors.data(); if (depth_bound && (graphics_.depth_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) rendering.depthAttachmentFormat = graphics_.depth_format; if (depth_bound && (graphics_.depth_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) rendering.stencilAttachmentFormat = graphics_.depth_format; VkPipelineVertexInputStateCreateInfo vertex_input{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; VkPipelineVertexInputDivisorStateCreateInfoEXT divisor_state{ VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO_EXT}; if (!r.divisors.empty()) { divisor_state.vertexBindingDivisorCount = std::uint32_t(r.divisors.size()); divisor_state.pVertexBindingDivisors = r.divisors.data(); vertex_input.pNext = &divisor_state; } vertex_input.vertexBindingDescriptionCount = std::uint32_t(r.bindings.size()); vertex_input.pVertexBindingDescriptions = r.bindings.data(); vertex_input.vertexAttributeDescriptionCount = std::uint32_t(r.attributes.size()); vertex_input.pVertexAttributeDescriptions = r.attributes.data(); VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; if (!graphics_.viewport_with_count) { viewport.viewportCount = 1; viewport.scissorCount = 1; } VkPipelineMultisampleStateCreateInfo multisample = r.multisample; VkPipelineRasterizationStateCreateInfo raster = r.raster; VkPipelineRasterizationConservativeStateCreateInfoEXT conservative{ VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_CONSERVATIVE_STATE_CREATE_INFO_EXT}; if (r.conservative) { conservative.conservativeRasterizationMode = VK_CONSERVATIVE_RASTERIZATION_MODE_OVERESTIMATE_EXT; conservative.extraPrimitiveOverestimationSize = 0.0f; conservative.pNext = raster.pNext; raster.pNext = &conservative; } multisample.pSampleMask = &r.sample_mask; VkPipelineColorBlendStateCreateInfo blend = r.blend; blend.attachmentCount = std::uint32_t(r.blends.size()); blend.pAttachments = r.blends.data(); // A mesh pipeline takes neither the topology nor the strides as dynamic state // (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065 and -07066). // With multiViewport enabled, VIEWPORT_WITH_COUNT / SCISSOR_WITH_COUNT allow 1..16 dynamic viewports/scissors. VkDynamicState dyn_list[9]{}; std::uint32_t dyn_count = 0; dyn_list[dyn_count++] = graphics_.viewport_with_count ? VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT : VK_DYNAMIC_STATE_VIEWPORT; dyn_list[dyn_count++] = graphics_.viewport_with_count ? VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT : VK_DYNAMIC_STATE_SCISSOR; if (!r.mesh) { dyn_list[dyn_count++] = VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY; dyn_list[dyn_count++] = VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE; } dyn_list[dyn_count++] = VK_DYNAMIC_STATE_STENCIL_REFERENCE; dyn_list[dyn_count++] = VK_DYNAMIC_STATE_BLEND_CONSTANTS; if (!r.mesh && !r.bindings.empty()) dyn_list[dyn_count++] = VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE; if (r.depth.depthBoundsTestEnable) dyn_list[dyn_count++] = VK_DYNAMIC_STATE_DEPTH_BOUNDS; VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; dynamic.dynamicStateCount = dyn_count; dynamic.pDynamicStates = dyn_list; VkPipelineSampleLocationsStateCreateInfoEXT custom{VK_STRUCTURE_TYPE_PIPELINE_SAMPLE_LOCATIONS_STATE_CREATE_INFO_EXT}; if (unbound & leonida::GraphicsPipeline::custom_samples) { dyn_list[dyn_count++] = VK_DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT; dynamic.dynamicStateCount = dyn_count; custom.sampleLocationsEnable = VK_TRUE; custom.sampleLocationsInfo.sType = VK_STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT; custom.pNext = multisample.pNext; multisample.pNext = &custom; } // A lazy pipeline's stages get their modules here, for this one call (Vulkan lets a module go once the // pipeline exists), so the driver holds no SPIR-V for pipelines that are not drawn. const bool want_sample_mask = (unbound & leonida::GraphicsPipeline::sample_masked) != 0; if (want_sample_mask && (!has_fragment_ || !graphics_.masked_layout || sample_mask_failed_)) return VK_NULL_HANDLE; auto bytes = stage_bytes_; std::vector stages; std::vector made; const auto drop_modules = [&] { for (VkShaderModule module : made) device_.context->vk.vkDestroyShaderModule(device_.info.device, module, nullptr); }; std::vector> words; if (lazy_) { std::string why; if (!stage_words(words, why) || words.size() != r.stages.size()) { std::fprintf(stderr, "[rt] d3d12: a pipeline built at its first draw lost its SPIR-V: %s\n", why.empty() ? "stage count" : why.c_str()); return VK_NULL_HANDLE; } if (want_sample_mask) { std::size_t ps_idx = SIZE_MAX; for (std::size_t i = 0; i < r.stages.size(); ++i) if (r.stages[i].stage == VK_SHADER_STAGE_FRAGMENT_BIT && sources_[i].kind == StageSource::library) ps_idx = i; if (ps_idx == SIZE_MAX) return VK_NULL_HANDLE; std::vector patched = leonida::sample_mask_patch_fragment(words[ps_idx], why); if (patched.empty()) { if (!sample_mask_failed_) { sample_mask_failed_ = true; std::fprintf(stderr, "[rt] d3d12: sample-mask patch failed for %s: %s (falling back to plain)\n", sources_[ps_idx].entry ? sources_[ps_idx].entry->name.c_str() : "(fragment)", why.c_str()); } return VK_NULL_HANDLE; } words[ps_idx] = std::move(patched); } bytes = 0; stages = r.stages; for (std::size_t i = 0; i < stages.size(); ++i) { VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; module_info.codeSize = words[i].size() * 4; bytes += module_info.codeSize; module_info.pCode = words[i].data(); VkShaderModule module = VK_NULL_HANDLE; const leonida::aftermath::ShaderName named( sources_[i].entry ? sources_[i].entry->name.c_str() : sources_[i].kind == StageSource::rect_list ? "(rect-list geometry)" : "(depth24 depth-only fragment)"); if (device_.context->vk.vkCreateShaderModule(device_.info.device, &module_info, nullptr, &module) != VK_SUCCESS) { drop_modules(); return VK_NULL_HANDLE; } made.push_back(module); stages[i].module = module; } } else if (want_sample_mask) { if (!fragment_module_ref_) return VK_NULL_HANDLE; if (!masked_fragment_module_) { std::string why; const std::vector patched = leonida::sample_mask_patch_fragment(fragment_module_ref_->words, why); if (patched.empty()) { if (!sample_mask_failed_) { sample_mask_failed_ = true; std::fprintf(stderr, "[rt] d3d12: sample-mask patch failed: %s (falling back to plain)\n", why.c_str()); } return VK_NULL_HANDLE; } masked_fragment_module_ = shader_module(patched); if (!masked_fragment_module_) return VK_NULL_HANDLE; } stages = r.stages; bool replaced = false; for (auto& s : stages) { if (s.stage == VK_SHADER_STAGE_FRAGMENT_BIT) { s.module = masked_fragment_module_; replaced = true; break; } } if (!replaced) return VK_NULL_HANDLE; } VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; // A triangle-family pipeline drawn as a rectangle list: the same stages plus the generated geometry stage. std::vector rectangle_stages; if (unbound & leonida::GraphicsPipeline::rectangle_stage) { VkShaderModule rectangle = VK_NULL_HANDLE; if (!rectangle_capable_) { drop_modules(); return VK_NULL_HANDLE; } if (lazy_) { std::size_t vs = SIZE_MAX; for (std::size_t i = 0; i < sources_.size(); ++i) if (sources_[i].kind == StageSource::library && sources_[i].slot == 0) vs = i; std::string why; const std::vector geometry_words = vs == SIZE_MAX ? std::vector{} : leonida::rect_list_geometry(words[vs], why); VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; module_info.codeSize = geometry_words.size() * 4; module_info.pCode = geometry_words.data(); if (geometry_words.empty() || device_.context->vk.vkCreateShaderModule(device_.info.device, &module_info, nullptr, &rectangle) != VK_SUCCESS) { std::fprintf(stderr, "[rt] d3d12: cannot draw rectangle list: %s\n", why.c_str()); drop_modules(); return VK_NULL_HANDLE; } made.push_back(rectangle); bytes += module_info.codeSize; rectangle_stages = stages; } else { if (!rectangle_vertex_) return VK_NULL_HANDLE; if (!rectangle_module_) { std::string why; const auto geometry_words = leonida::rect_list_geometry(rectangle_vertex_->words, why); if (geometry_words.empty()) { std::fprintf(stderr, "[rt] d3d12: cannot draw rectangle list: %s\n", why.c_str()); return VK_NULL_HANDLE; } rectangle_module_ = shader_module(geometry_words); if (!rectangle_module_) return VK_NULL_HANDLE; } rectangle = rectangle_module_; rectangle_stages = !stages.empty() ? stages : r.stages; } VkPipelineShaderStageCreateInfo geometry{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; geometry.stage = VK_SHADER_STAGE_GEOMETRY_BIT; geometry.module = rectangle; geometry.pName = "main"; rectangle_stages.push_back(geometry); } const auto& pipeline_stages = !rectangle_stages.empty() ? rectangle_stages : !stages.empty() ? stages : r.stages; info.stageCount = std::uint32_t(pipeline_stages.size()); info.pStages = pipeline_stages.data(); info.pVertexInputState = r.mesh ? nullptr : &vertex_input; // ignored with a mesh stage; null for clarity info.pInputAssemblyState = r.mesh ? nullptr : &r.assembly; info.pViewportState = &viewport; info.pRasterizationState = &raster; info.pMultisampleState = &multisample; info.pDepthStencilState = &r.depth; info.pColorBlendState = &blend; info.pDynamicState = &dynamic; info.flags=flags; info.layout = want_sample_mask ? graphics_.masked_layout : graphics_.layout; info.flags |= fast_pipeline_flags(false); VkPipeline pipeline = VK_NULL_HANDLE; const auto cache = device_.pipeline_cache(); const char* program = "-", *fragment = "-"; if (leonida::pipeline_profile::enabled()) { for (const auto& source : sources_) { if (!source.entry) continue; if (source.slot == 0) program = source.entry->name.c_str(); if (source.slot == 2) fragment = source.entry->name.c_str(); } } CompileTrace trace; trace.begin(info, device_.info.pipeline_creation_feedback, trigger, profile_shaders_.c_str(), unbound, bytes, cache_key_); const leonida::dev_status::Build dev_build(r.mesh ? "mesh pipeline" : "graphics pipeline"); const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager", program, fragment, unbound); // Through the compile gate as a graphics create (a mesh pipeline is one): on NVIDIA 621.40 a vkQueueSubmit // sat in the driver for as long as a mesh create was in it (54 s) and lost the device. Not with the classic // gate (the default), which keeps graphics creates out of it as before. const char* gate_name = nullptr; for (const auto& source : sources_) if (source.entry && source.slot == 0) gate_name = source.entry->name.c_str(); VkResult result = VK_ERROR_UNKNOWN; { std::optional turn; if (leonida::SubmitMutex::compile_gate_graphics()) turn.emplace(device_.context->submit_mutex(), trigger, r.mesh ? "vkCreateGraphicsPipelines (mesh)" : "vkCreateGraphicsPipelines", true, gate_name, leonida::SubmitMutex::CreateKind::graphics, bytes); result = device_.create_pipeline(flags, [&](VkPipelineCache with, VkPipelineCreateFlags f) { info.flags = f; pipeline = VK_NULL_HANDLE; return device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, with, 1, &info, nullptr, &pipeline); }); } if (status) *status = result; profile.finish(int(result)); trace.end(trigger, profile_shaders_.c_str(), unbound, bytes, result); if (result != VK_SUCCESS) { if (pipeline) device_.context->vk.vkDestroyPipeline(device_.info.device, pipeline, nullptr); pipeline = VK_NULL_HANDLE; } drop_modules(); if (pipeline) maybe_checkpoint(cache); return pipeline; } // A lazy pipeline's SPIR-V, one module's words per recipe stage, made as create_graphics made them: the library // stages (VS or MS, GS, PS) read again, the f16 halves linked, the D24 fragment patch, then the generated stages // (the rectangle-list geometry stage from the vertex stage, the depth-only fragment stage). False with `why` when // a file went missing since. // The rewrites a pixel shader's words get for this pipeline, the same at creation and in a lazy build(): // quantising B4G4R4A4 targets stored as RGBA8, then moving SV_Target1 to Location 0, Index 1 for a SRC1 blend // factor (RT-DUAL-SOURCE-BLEND). bool rewrite_fragment(std::vector& words, std::string& why) const { if (rgba4_mask_ && !leonida::rgba4::quantize(words, rgba4_mask_)) { why = "could not be quantised for a B4G4R4A4 target stored as RGBA8"; return false; } if (dual_source_ && !leonida::dual_source::remap(words)) { why = "has no second colour output at Location 1 for a SRC1 blend factor"; return false; } return true; } bool link_f16_halves(std::vector& vs_words, const leonida::ShaderEntry& vs_entry, std::vector& ps_words, const leonida::ShaderEntry& ps_entry, std::string* error) const { return leonida::link_f16_halves(vs_words, vs_entry, ps_words, ps_entry, error, device_.f16_half_top_location); } public: bool stage_words(std::vector>& words, std::string& why) const { const leonida::ShaderLibrary* library = device_.library(); if (!library) { why = "no shader library"; return false; } if (sources_.empty()) { why = "not a lazy pipeline"; return false; } words.assign(sources_.size(), {}); std::size_t vs = SIZE_MAX, ps = SIZE_MAX; for (std::size_t i = 0; i < sources_.size(); ++i) { const StageSource& source = sources_[i]; if (source.kind != StageSource::library) continue; words[i] = library->spirv(*source.entry); if (words[i].empty()) { why = source.entry->name + ".spv is missing or not SPIR-V"; return false; } if (source.slot == 2 && !rewrite_fragment(words[i], why)) { why = source.entry->name + ": " + why; return false; } if (source.slot == 0) vs = i; if (source.slot == 2) ps = i; } if (!ps_location_remap_.empty()) { if (ps == SIZE_MAX || !leonida::apply_ps_location_remap(words[ps], ps_location_remap_, &why)) return false; } if (f16_linked_) { if (vs == SIZE_MAX || ps == SIZE_MAX) return false; leonida::ShaderEntry ps_f16_entry; const leonida::ShaderEntry* ps_f16_ptr = sources_[ps].entry; if (!sources_[ps].entry->f16_halves.empty() && (!ps_attr_to_param_.empty() || !ps_location_remap_.empty())) { ps_f16_entry = leonida::remap_ps_f16_halves_entry(*sources_[ps].entry, ps_attr_to_param_, ps_location_remap_); ps_f16_ptr = &ps_f16_entry; } if (!link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *ps_f16_ptr, &why)) return false; } for (std::size_t i = 0; i < sources_.size(); ++i) { if (!sources_[i].depth24) continue; std::vector patched = leonida::depth24_patch_fragment(words[i], depth24_bias_, why); if (patched.empty()) return false; words[i] = std::move(patched); } for (std::size_t i = 0; i < sources_.size(); ++i) { if (sources_[i].kind == StageSource::rect_list) { if (vs == SIZE_MAX) return false; words[i] = leonida::rect_list_geometry(words[vs], why); } else if (sources_[i].kind == StageSource::depth_only) { words[i] = leonida::depth24_depth_only_fragment(depth24_bias_); } else { continue; } if (words[i].empty()) return false; } return true; } private: // Built on first use and kept until the PSO is released (replay may call this from any queue). VkPipeline variant(std::uint32_t unbound, const char* trigger) { std::unique_lock lock(variants_mutex_, std::defer_lock); const bool budgeted = graphics_.large && big_compiles() == BigCompiles::budget; const auto place = enter_build(lock, budgeted ? graphics_.estimate : 0, Work::demand, [&] { return variants_.contains(unbound) || ((unbound & leonida::GraphicsPipeline::sample_masked) && sample_mask_failed_); }); if (const auto it = variants_.find(unbound); it != variants_.end()) return it->second; if ((unbound & leonida::GraphicsPipeline::sample_masked) && sample_mask_failed_) return VK_NULL_HANDLE; const ULONGLONG build_started = device_.order_log ? GetTickCount64() : 0; const VkPipeline pipeline = build(unbound, trigger); if (pipeline && device_.order_log) order_note_build(unbound, GetTickCount64() - build_started); if (!pipeline) { if (unbound & leonida::GraphicsPipeline::sample_masked) sample_mask_failed_ = true; if (leonida::pipeline_profile::enabled()) std::fprintf(stderr, "[rt] pso-variant failed stage=%s mask=%u\n", recipe_.mesh ? "ms" : "vs", unbound); if (!(unbound & leonida::GraphicsPipeline::sample_masked)) log_once("a pipeline variant for unbound attachment slots could not be built; slots", int(unbound)); return VK_NULL_HANDLE; } variants_.emplace(unbound, pipeline); return pipeline; } // Where a lazy graphics pipeline's stage modules come from, in recipe_.stages order (stage_words). struct StageSource { enum Kind : std::uint8_t { library, rect_list, depth_only } kind = library; std::uint8_t slot = 0; // library: the create_graphics stage table entry (0 VS or MS, 1 GS, 2 PS) bool depth24 = false; // library: the D24 fragment patch applies const leonida::ShaderEntry* entry = nullptr; // library: the translated shader }; DeviceState& device_; leonida::ComputePipeline pipeline_; leonida::GraphicsPipeline graphics_; bool owns_compute_layout_ = true; bool owns_graphics_layouts_ = true; Recipe recipe_; const leonida::ShaderEntry* compute_entry_ = nullptr; // compute: the translated shader build_compute reads bool compute_failed_ = false; // compute: could not be built; not retried std::atomic skip_logged_{false}; // compute: the skipped program's first dispatch was logged bool lazy_ = false; // graphics: built at the first draw (lazy_graphics_pipelines) bool f16_linked_ = false; // graphics: the VS and PS words had their f16 halves linked std::vector> ps_location_remap_; std::vector> ps_attr_to_param_; leonida::Depth24Bias depth24_bias_{}; unsigned rgba4_mask_ = 0; // graphics: the B4G4R4A4 targets stored as RGBA8 that the pixel shader is quantised for bool dual_source_ = false; // graphics: a SRC1 blend factor; the pixel shader's SV_Target1 is Location 0, Index 1 std::vector sources_; struct Request { VkPipeline handle{}; unsigned long long skips = 0; }; using Requests = std::map; std::unique_ptr requested_; // Compile helper (build_compute, under variants_mutex_): the journal file asked for and not there yet; whether // the helper gave up on this pipeline (it is then built here); a build just deferred (read by queue_build). std::filesystem::path helper_file_; bool helper_refused_ = false; std::atomic helper_deferred_{false}; std::atomic early_{0}; // request_early: the last mask asked for, plus one std::string profile_shaders_; // populated only with compile tracing enabled std::size_t stage_bytes_ = 0; // A graphics pipeline of PipelineCompiles::large_spirv_bytes or more, whatever LEONIDA_SERIAL_BIG_COMPILES says: // the compile pool's heavy count (CompilePool) caps these and large compute builds alike. bool graphics_large_module_ = false; std::mutex variants_mutex_; std::map variants_; VkShaderModule module_ = VK_NULL_HANDLE; std::vector modules_; leonida::GraphicsShaderModules::Reference rectangle_vertex_; VkShaderModule rectangle_module_ = VK_NULL_HANDLE; bool rectangle_capable_ = false; // graphics: a vertex stage the rectangle-list geometry stage can follow leonida::GraphicsShaderModules::Reference fragment_module_ref_; VkShaderModule masked_fragment_module_ = VK_NULL_HANDLE; bool has_fragment_ = false; // graphics: has a real pixel shader (depth-only PSOs are not sample-masked) bool sample_mask_failed_ = false; // guarded by variants_mutex_: patch/build failed once; skip future retries VkShaderModule shader_module(std::span words) { auto& vk=device_.context->vk; auto object = device_.graphics_modules.acquire(device_.info.device, vk.vkCreateShaderModule, vk.vkDestroyShaderModule, words); if(!object)return VK_NULL_HANDLE; const auto h=object->handle;modules_.push_back(std::move(object)); return h; } VkDeviceSize code_base_ = 0; VkDeviceSize code_bytes_ = 0; bool registered_ = false; bool unregistered_ = false; // taken out of the context's registry (unregister) bool is_graphics_ = false; StubPipelineKind stub_kind_ = StubPipelineKind::none; // set by stub_or: a compute or mesh stub (never registered) std::vector subgroup_requests_; // one per stage, in creation order unsigned pending_stream_kind_=0; std::once_flag resolve_stream_once_; std::once_flag native_source_once_; bool native_source_ready_ = false; std::shared_ptr native_owner_; leonida::cached_pso::Key cache_key_; leonida::cached_pso::Key order_key_; // see set_order_key; empty: cache_key_ std::uint64_t order_hash_ = 0; // 0: this pipeline is not in the order log char order_kind_ = 'c'; std::uint64_t order_name_hash_ = 0; // compute: the hash of its library entry's name (E line); 0: none std::uint32_t order_created_ms_ = device_.order_log ? DeviceState::order_now_ms() : 0; std::atomic order_build_ms_{leonida::pipeline_order::unknown_ms}; // variant 0, once built }; void key_root_signature(leonida::cached_pso::KeyBuilder& key, ID3D12RootSignature* signature) { if (!signature) { key.tag("no root signature"); } else if (const RootSignature* own = RootSignature::from(signature)) { key.tag("root signature").text(own->content().c_str()); } else { const auto address = reinterpret_cast(signature); key.tag("foreign root signature").bytes(&address, sizeof(address)); } } // A view of a texture as Create*View describes it, before the resource's own shape is applied. struct TextureView { DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; // UNKNOWN: the resource's leonida::gfx10::ImageType type = leonida::gfx10::ImageType::image_2d; UINT first_mip = 0; UINT mip_count = ~0u; // ~0: to the last UINT first_layer = 0; UINT layer_count = ~0u; UINT mapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; UINT plane = 0; float min_lod = 0.0f; }; // The existing mutable Vulkan formats come from these DXGI typeless families. A typed resource cannot be // reinterpreted by the 1D/3D UAV path; equal texel sizes alone don't make a cast legal. bool uav_format_compatible(DXGI_FORMAT resource, DXGI_FORMAT view) { if (view == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || view == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB) return false; if (resource == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) return view == DXGI_FORMAT_R8G8B8A8_UNORM; if (resource == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB) return view == DXGI_FORMAT_B8G8R8A8_UNORM; if (resource == view) return true; switch (resource) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: return view >= DXGI_FORMAT_R32G32B32A32_FLOAT && view <= DXGI_FORMAT_R32G32B32A32_SINT; case DXGI_FORMAT_R16G16B16A16_TYPELESS: return view >= DXGI_FORMAT_R16G16B16A16_FLOAT && view <= DXGI_FORMAT_R16G16B16A16_SINT; case DXGI_FORMAT_R32G32_TYPELESS: return view >= DXGI_FORMAT_R32G32_FLOAT && view <= DXGI_FORMAT_R32G32_SINT; case DXGI_FORMAT_R10G10B10A2_TYPELESS: return view == DXGI_FORMAT_R10G10B10A2_UNORM || view == DXGI_FORMAT_R10G10B10A2_UINT; case DXGI_FORMAT_R8G8B8A8_TYPELESS: return view >= DXGI_FORMAT_R8G8B8A8_UNORM && view <= DXGI_FORMAT_R8G8B8A8_SINT; case DXGI_FORMAT_R16G16_TYPELESS: return view >= DXGI_FORMAT_R16G16_FLOAT && view <= DXGI_FORMAT_R16G16_SINT; case DXGI_FORMAT_R8G8_TYPELESS: return view >= DXGI_FORMAT_R8G8_UNORM && view <= DXGI_FORMAT_R8G8_SINT; case DXGI_FORMAT_R32_TYPELESS: return view >= DXGI_FORMAT_R32_FLOAT && view <= DXGI_FORMAT_R32_SINT; case DXGI_FORMAT_R16_TYPELESS: return view >= DXGI_FORMAT_R16_FLOAT && view <= DXGI_FORMAT_R16_SINT; case DXGI_FORMAT_B8G8R8A8_TYPELESS: return view == DXGI_FORMAT_B8G8R8A8_UNORM; default: return false; } } // In-memory pipeline library (docs/d3d12_vulkan.md sections 3.6 and 4). D3D12 cached blobs are driver-specific // and ignored across runs; Serialize writes a versioned header so CreatePipelineLibrary recognizes our own blobs. // As on the host runtime (d3d12_pipeline_library_host_test), a foreign, truncated or corrupt blob is E_INVALIDARG; // one of ours from another version is D3D12_ERROR_DRIVER_VERSION_MISMATCH. A pipeline library is a device child, // not a pageable object: the host answers E_NOINTERFACE for ID3D12Pageable. class PipelineLibrary final : public Child { public: // {6e2a9d41-7b5f-4c83-8e14-2a9d6f3c5b10} static constexpr GUID kTag{0x6e2a9d41, 0x7b5f, 0x4c83, {0x8e, 0x14, 0x2a, 0x9d, 0x6f, 0x3c, 0x5b, 0x10}}; struct Header { std::uint32_t magic; std::uint32_t version; std::uint32_t count; std::uint32_t reserved; }; static constexpr std::uint32_t kMagic = 0x314C504Cu; // "LPL1" static constexpr std::uint32_t kVersion = 1; ~PipelineLibrary() override { std::lock_guard lock(mutex_); for (auto& [name, pso] : entries_) if (pso) pso->Release(); entries_.clear(); } // S_OK for a blob of ours, D3D12_ERROR_DRIVER_VERSION_MISMATCH for one of ours from another version, // E_INVALIDARG for anything else (foreign, truncated or corrupt). static HRESULT check_blob(const void* data, SIZE_T size) { if (!data || size < sizeof(Header)) return E_INVALIDARG; Header h{}; std::memcpy(&h, data, sizeof(h)); if (h.magic != kMagic || h.reserved != 0) return E_INVALIDARG; return h.version == kVersion ? S_OK : D3D12_ERROR_DRIVER_VERSION_MISMATCH; } HRESULT STDMETHODCALLTYPE StorePipeline(LPCWSTR name, ID3D12PipelineState* pipeline) override { if (!name || !*name || !pipeline) return E_INVALIDARG; if (!PipelineState::from(pipeline)) return E_INVALIDARG; std::lock_guard lock(mutex_); auto [it, inserted] = entries_.emplace(name, pipeline); if (!inserted) return E_INVALIDARG; pipeline->AddRef(); return S_OK; } HRESULT STDMETHODCALLTYPE LoadGraphicsPipeline(LPCWSTR name, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, REFIID riid, void** out) override { if (!out) return E_INVALIDARG; // the host runtime's answer (not E_POINTER) *out = nullptr; if (!name || !*name || !desc) return E_INVALIDARG; return load_entry(name, false, true, riid, out); } HRESULT STDMETHODCALLTYPE LoadComputePipeline(LPCWSTR name, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, void** out) override { if (!out) return E_INVALIDARG; // the host runtime's answer (not E_POINTER) *out = nullptr; if (!name || !*name || !desc) return E_INVALIDARG; return load_entry(name, true, false, riid, out); } HRESULT STDMETHODCALLTYPE LoadPipeline(LPCWSTR name, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** out) override { if (!out) return E_INVALIDARG; // the host runtime's answer (not E_POINTER) *out = nullptr; if (!name || !*name || !desc || !desc->SizeInBytes || !desc->pPipelineStateSubobjectStream) return E_INVALIDARG; return load_entry(name, false, false, riid, out); } SIZE_T STDMETHODCALLTYPE GetSerializedSize() override { return sizeof(Header); } HRESULT STDMETHODCALLTYPE Serialize(void* data, SIZE_T size) override { if (!data || size < sizeof(Header)) return E_INVALIDARG; std::lock_guard lock(mutex_); const Header h{kMagic, kVersion, static_cast(entries_.size()), 0}; std::memcpy(data, &h, sizeof(h)); return S_OK; } private: HRESULT load_entry(LPCWSTR name, bool require_compute, bool require_graphics, REFIID riid, void** out) { std::lock_guard lock(mutex_); const auto it = entries_.find(name); if (it == entries_.end()) return E_INVALIDARG; PipelineState* ps = PipelineState::from(it->second); if (!ps) return E_INVALIDARG; if (require_compute && !ps->compute()) return E_INVALIDARG; if (require_graphics && !ps->graphics()) return E_INVALIDARG; return it->second->QueryInterface(riid, out); } std::mutex mutex_; std::unordered_map entries_; }; // Process-wide backing for ID3D12Device9::CreateShaderCacheSession and ID3D12ShaderCacheSession (D3D-34). // Sessions in the same process sharing (Identifier, Mode, disk_path) share their entries; a live session with a // different Version returns DXGI_ERROR_ALREADY_EXISTS, while reopening after all sessions close clears and recreates // the cache. MODE_MEMORY discards its entries when the final session is released; MODE_DISK persists entries to a // versioned binary file via unique per-writer temp files and atomic replacement. struct ShaderCacheKey { GUID identifier{}; D3D12_SHADER_CACHE_MODE mode = D3D12_SHADER_CACHE_MODE_MEMORY; std::wstring disk_path; // empty for MODE_MEMORY bool operator<(const ShaderCacheKey& other) const { const int cmp = std::memcmp(&identifier, &other.identifier, sizeof(GUID)); if (cmp != 0) return cmp < 0; if (mode != other.mode) return mode < other.mode; return disk_path < other.disk_path; } }; struct ShaderCacheStore { static constexpr std::uint32_t kDiskMagic = 0x3143534Cu; // "LSC1" static constexpr std::uint32_t kDiskFormatVersion = 2; static constexpr UINT kDefaultMaxMemoryBytes = 1024u; static constexpr UINT kDefaultMaxMemoryEntries = 128u; static constexpr UINT kDefaultMaxValueFileBytes = 128u * 1024u * 1024u; struct DiskHeader { std::uint32_t magic; std::uint32_t format_version; std::uint32_t entry_count; std::uint32_t reserved; std::uint64_t cache_version; }; std::mutex mutex; std::map> entries; std::size_t total_bytes = 0; std::uint32_t live_sessions = 0; UINT64 version = 0; bool delete_on_destroy = false; std::filesystem::path disk_path; void load_from_disk_locked(UINT64 expected_version, UINT max_file_bytes) { if (disk_path.empty()) return; std::error_code ec; const std::uintmax_t file_size = std::filesystem::file_size(disk_path, ec); if (ec || file_size < sizeof(DiskHeader)) return; std::ifstream in(disk_path, std::ios::binary); if (!in) return; DiskHeader header{}; if (!in.read(reinterpret_cast(&header), sizeof(header))) return; if (header.magic != kDiskMagic || header.format_version != kDiskFormatVersion || header.reserved != 0) return; if (header.cache_version != expected_version) { in.close(); std::filesystem::remove(disk_path, ec); return; } std::uint64_t remaining = static_cast(file_size) - sizeof(DiskHeader); if (header.entry_count > remaining / 8u) return; std::map> loaded; std::size_t bytes = 0; for (std::uint32_t i = 0; i < header.entry_count; ++i) { if (remaining < 8u) return; std::uint32_t lens[2]{}; if (!in.read(reinterpret_cast(lens), sizeof(lens))) return; remaining -= 8u; const std::uint64_t key_len = lens[0]; const std::uint64_t val_len = lens[1]; if (!key_len || !val_len || key_len > remaining || val_len > remaining - key_len) return; if (val_len > max_file_bytes || bytes > max_file_bytes - val_len) return; std::string k(static_cast(key_len), '\0'); std::vector v(static_cast(val_len)); if (!in.read(k.data(), static_cast(key_len)) || !in.read(reinterpret_cast(v.data()), static_cast(val_len))) return; remaining -= key_len + val_len; loaded.emplace(std::move(k), std::move(v)); bytes += static_cast(val_len); } entries = std::move(loaded); total_bytes = bytes; } bool save_to_disk_locked() const { if (disk_path.empty()) return true; std::error_code ec; std::filesystem::create_directories(disk_path.parent_path(), ec); static std::atomic write_seq{0}; const std::uint64_t seq = write_seq.fetch_add(1, std::memory_order_relaxed); wchar_t suffix[64]{}; std::swprintf(suffix, std::size(suffix), L".%lu.%lu.%llu.tmp", static_cast(GetCurrentProcessId()), static_cast(GetCurrentThreadId()), static_cast(seq)); std::filesystem::path tmp = disk_path; tmp += suffix; { std::ofstream out(tmp, std::ios::binary | std::ios::trunc); if (!out) return false; const DiskHeader header{kDiskMagic, kDiskFormatVersion, static_cast(entries.size()), 0, version}; out.write(reinterpret_cast(&header), sizeof(header)); for (const auto& [k, v] : entries) { const std::uint32_t lens[2] = {static_cast(k.size()), static_cast(v.size())}; out.write(reinterpret_cast(lens), sizeof(lens)); out.write(k.data(), static_cast(k.size())); out.write(reinterpret_cast(v.data()), static_cast(v.size())); } if (!out.good()) return false; } if (!MoveFileExW(tmp.c_str(), disk_path.c_str(), MOVEFILE_REPLACE_EXISTING)) { std::filesystem::remove(tmp, ec); return false; } return true; } void clear() { std::lock_guard lock(mutex); entries.clear(); total_bytes = 0; if (!disk_path.empty()) { std::error_code ec; std::filesystem::remove(disk_path, ec); } } }; std::filesystem::path default_shader_cache_dir() { std::error_code ec; const auto tmp = std::filesystem::temp_directory_path(ec); if (ec || tmp.empty()) return {}; return tmp / L"leonida_shader_cache"; } struct ShaderCacheRegistry { std::mutex mutex; std::map> stores; std::atomic disabled{false}; HRESULT acquire(const ShaderCacheKey& key, UINT64 version, UINT max_file_bytes, std::shared_ptr& out) { if (disabled.load(std::memory_order_relaxed)) return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; std::lock_guard lock(mutex); if (disabled.load(std::memory_order_relaxed)) return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; auto it = stores.find(key); if (it != stores.end()) { if (it->second->version != version) return DXGI_ERROR_ALREADY_EXISTS; ++it->second->live_sessions; out = it->second; return S_OK; } auto store = std::make_shared(); store->version = version; if (key.mode == D3D12_SHADER_CACHE_MODE_DISK && !key.disk_path.empty()) { store->disk_path = key.disk_path; std::lock_guard store_lock(store->mutex); store->load_from_disk_locked(version, max_file_bytes); } store->live_sessions = 1; stores.emplace(key, store); out = std::move(store); return S_OK; } void mark_delete_on_destroy(const std::shared_ptr& store) { std::lock_guard lock(mutex); if (store) store->delete_on_destroy = true; } void release(const ShaderCacheKey& key, const std::shared_ptr& store) { std::lock_guard lock(mutex); if (!store) return; if (store->live_sessions > 0) --store->live_sessions; if (store->live_sessions == 0) { if (store->delete_on_destroy && !store->disk_path.empty()) { std::error_code ec; std::filesystem::remove(store->disk_path, ec); } // Discard both idle MEMORY stores (per D3D12 spec) and idle DISK stores (so reopening reloads from disk). const auto it = stores.find(key); if (it != stores.end() && it->second == store) stores.erase(it); } } void clear_all() { std::vector> snapshot; { std::lock_guard lock(mutex); snapshot.reserve(stores.size()); for (const auto& [k, v] : stores) snapshot.push_back(v); } for (const auto& store : snapshot) store->clear(); // Also remove inactive and prior-run disk caches stored in the default cache directory (non-USE_WORKING_DIR). const auto default_dir = default_shader_cache_dir(); if (!default_dir.empty()) { std::error_code ec; if (std::filesystem::exists(default_dir, ec)) { for (const auto& entry : std::filesystem::directory_iterator(default_dir, ec)) { if (ec) break; if (!entry.is_regular_file(ec)) continue; const auto fname = entry.path().filename().wstring(); if (fname.rfind(L"leonida_sc_", 0) == 0) std::filesystem::remove(entry.path(), ec); } } } } }; ShaderCacheRegistry& process_shader_cache_registry() { static auto* registry = new ShaderCacheRegistry(); return *registry; } std::filesystem::path shader_cache_disk_path(const D3D12_SHADER_CACHE_SESSION_DESC& desc, const VkPhysicalDeviceProperties& gpu_props) { std::error_code ec; std::filesystem::path dir = (desc.Flags & D3D12_SHADER_CACHE_FLAG_USE_WORKING_DIR) ? std::filesystem::current_path(ec) : default_shader_cache_dir(); if (ec || dir.empty()) return {}; wchar_t name[160]{}; const auto& g = desc.Identifier; if (desc.Flags & D3D12_SHADER_CACHE_FLAG_DRIVER_VERSIONED) { std::swprintf(name, std::size(name), L"leonida_sc_%08lx%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x_d%04x_%04x_%08x.bin", static_cast(g.Data1), g.Data2, g.Data3, g.Data4[0], g.Data4[1], g.Data4[2], g.Data4[3], g.Data4[4], g.Data4[5], g.Data4[6], g.Data4[7], gpu_props.vendorID, gpu_props.deviceID, gpu_props.driverVersion); } else { std::swprintf(name, std::size(name), L"leonida_sc_%08lx%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x.bin", static_cast(g.Data1), g.Data2, g.Data3, g.Data4[0], g.Data4[1], g.Data4[2], g.Data4[3], g.Data4[4], g.Data4[5], g.Data4[6], g.Data4[7]); } return dir / name; } class ShaderCacheSession final : public Child { public: // {9a4f1b2c-8d6e-43a7-b152-7e3c9f0d4a81} static constexpr GUID kTag{0x9a4f1b2c, 0x8d6e, 0x43a7, {0xb1, 0x52, 0x7e, 0x3c, 0x9f, 0x0d, 0x4a, 0x81}}; ShaderCacheSession(const D3D12_SHADER_CACHE_SESSION_DESC& desc, const ShaderCacheKey& key, ShaderCacheRegistry& registry, std::shared_ptr store) : desc_(desc), key_(key), registry_(®istry), store_(std::move(store)) {} ~ShaderCacheSession() override { if (registry_) registry_->release(key_, store_); } HRESULT STDMETHODCALLTYPE FindValue(const void* key, UINT key_size, void* value, UINT* value_size) override { if (!key || !key_size || !value_size) return E_INVALIDARG; if (registry_ && registry_->disabled.load(std::memory_order_relaxed)) return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; std::lock_guard lock(store_->mutex); const std::string k(static_cast(key), key_size); const auto it = store_->entries.find(k); if (it == store_->entries.end()) return DXGI_ERROR_NOT_FOUND; const UINT stored_size = static_cast(it->second.size()); if (!value) { *value_size = stored_size; return S_OK; } if (*value_size < stored_size) { *value_size = stored_size; return DXGI_ERROR_MORE_DATA; } std::memcpy(value, it->second.data(), stored_size); *value_size = stored_size; return S_OK; } HRESULT STDMETHODCALLTYPE StoreValue(const void* key, UINT key_size, const void* value, UINT value_size) override { if (!key || !key_size || !value || !value_size) return E_INVALIDARG; if (registry_ && registry_->disabled.load(std::memory_order_relaxed)) return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; std::lock_guard lock(store_->mutex); const std::string k(static_cast(key), key_size); if (store_->entries.find(k) != store_->entries.end()) return DXGI_ERROR_ALREADY_EXISTS; if (desc_.Mode == D3D12_SHADER_CACHE_MODE_MEMORY) { const UINT max_entries = desc_.MaximumInMemoryCacheEntries ? desc_.MaximumInMemoryCacheEntries : ShaderCacheStore::kDefaultMaxMemoryEntries; const UINT max_bytes = desc_.MaximumInMemoryCacheSizeBytes ? desc_.MaximumInMemoryCacheSizeBytes : ShaderCacheStore::kDefaultMaxMemoryBytes; if (store_->entries.size() >= max_entries || value_size > max_bytes || store_->total_bytes > max_bytes - value_size) return DXGI_ERROR_CACHE_FULL; } else { const UINT max_file_bytes = desc_.MaximumValueFileSizeBytes ? desc_.MaximumValueFileSizeBytes : ShaderCacheStore::kDefaultMaxValueFileBytes; if (value_size > max_file_bytes || store_->total_bytes > max_file_bytes - value_size) return DXGI_ERROR_CACHE_FULL; } const auto* bytes = static_cast(value); auto [it, inserted] = store_->entries.emplace(k, std::vector(bytes, bytes + value_size)); store_->total_bytes += value_size; if (desc_.Mode == D3D12_SHADER_CACHE_MODE_DISK && !store_->save_to_disk_locked()) { store_->total_bytes -= value_size; store_->entries.erase(it); return E_FAIL; } return S_OK; } void STDMETHODCALLTYPE SetDeleteOnDestroy() override { if (registry_) registry_->mark_delete_on_destroy(store_); } #if defined(_MSC_VER) || !defined(_WIN32) D3D12_SHADER_CACHE_SESSION_DESC STDMETHODCALLTYPE GetDesc() override { return desc_; } #else D3D12_SHADER_CACHE_SESSION_DESC* STDMETHODCALLTYPE GetDesc(D3D12_SHADER_CACHE_SESSION_DESC* out) override { *out = desc_; return out; } #endif private: D3D12_SHADER_CACHE_SESSION_DESC desc_{}; ShaderCacheKey key_{}; ShaderCacheRegistry* registry_ = nullptr; std::shared_ptr store_; }; // A texture the title keeps in its own memory (gfxres notes, section 5): asset and UI textures it reads from its // archives straight into that memory in the console's tiled layout and names only through device slot 70 views // (resource words with the explicit XG Layout, view words, the address), and slot-133 textures it fills itself, // through XG copies into the memory or the pointer Map gives it. The PC GPU cannot sample the console layout, so each // has an image filled from the memory by detiling it with the layout of the slot-70 resource words (XG, // xg_xs_layout.h), and filled again when the bytes change (Device::refresh_title_textures). Textures the GPU writes // (render targets, depth, unordered access) are never filled from memory. The approach is five-star-recomp's // (docs/gpu-resources.md "Textures", GpuTextures.cs / GpuTextureUploader.cs, GPL-3.0-or-later): a registry by // address, refreshed at every slot-70 view and once a frame for textures the title maps. struct TitleTexture { std::uint64_t address = 0; // the GPU address the title names it by std::uint64_t cpu = 0; // where the CPU reads its bytes (title_gpu_views::to_cpu) std::array desc{}; // the console resource words the layout was built from rt::xg_xs::Texture layout{}; // valid when layout_known bool layout_known = false; bool layout_guessed = false; // a slot-133 texture's own description (Layout 0), no slot-70 view yet bool layout_from_xg = false; // the title's XG computer of its shape (title_xg_layout) Resource* resource = nullptr; // Snapshot at registration. A diagnostic census then need not fault in each Resource to count its image memory. VkDeviceSize backing_bytes = 0, unbound_bytes = 0; bool device_local = false; void set_resource(Resource* r) { resource = r; backing_bytes = r->image_backing_bytes(); unbound_bytes = r->unbound_bytes(); device_local = (r->memory_flags() & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; invalidate_gpu_upload_cache(); } bool owned = false; // made here for slot-70 views (a reference is held); else slot 133's bool attachment_4k = false; // slot 133: 3840x2160 color or depth attachment bool gpu_written = false; // render target, depth or unordered access: never filled bool mapped = false; // a slot-133 texture the title mapped: checked before submissions bool stale = false; // changed bytes not uploaded yet (budget, or no host copy then) leonida::TextureReadability memory; // protected by title_texture_mutex std::vector formats; // owned: the image's format and castable view formats std::uint64_t hash = 0; // combined TilePieces hash of the bytes the image was last filled from leonida::TilePieces pieces; // and of its part in each 64 KiB tile (the refresh's reads) bool hashed = false; bool write_combined = false; // cached PAGE_WRITECOMBINE from VirtualQuery; invalidated on remap bool write_combined_known = false; bool gpu_uploaded = false; // last upload came directly from TitleMirror (GPU detile/copy) std::uint64_t mirror_hash = 0; // TitleMirror::range_sum() as of the last upload (GPU or 256B-aligned CPU) std::uint64_t mirror_hash_span = 0; // byte span covered by mirror_hash bool mirror_hash_valid = false; std::uint64_t gpu_upload_cached_offset = UINT64_MAX; // cached can_gpu_upload() key (mirror_offset) VkDeviceSize gpu_upload_cached_chunk = 0; bool gpu_upload_cached_ok = false; rt::d3d12::TitleImageUpload::UploadKind gpu_upload_cached_kind = rt::d3d12::TitleImageUpload::UploadKind::cpu_slot; void invalidate_gpu_upload_cache() { gpu_upload_cached_offset = UINT64_MAX; gpu_upload_cached_chunk = 0; gpu_upload_cached_ok = false; } std::uint64_t fills = 0; unsigned view_mip = 0; // minimum effective_min_mip seen across views bool view_mip_set = false; bool partial_budget_counted = false; // backing_bytes currently accounted in state_.title_partial_bytes // 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 bool is_write_combined() { if (!write_combined_known) { const auto va = static_cast(cpu); if (va && leonida::title_frames::may_hold(va, va + 1) && leonida::title_frames::backed(va)) { write_combined = false; } else { MEMORY_BASIC_INFORMATION region{}; write_combined = VirtualQuery(reinterpret_cast(va), ®ion, sizeof(region)) && (region.Protect & PAGE_WRITECOMBINE) != 0; } write_combined_known = true; } return write_combined; } }; // LEONIDA_TITLE_PARTIAL_MIPS (default ON; set 0 to opt out). A 2D single-slice texture whose larger mips are not // readable is filled from the first mip that is, honoring both MostDetailedMip and ResourceMinLODClamp. inline bool title_partial_mips_enabled() { static const bool enabled = [] { const char* v = std::getenv("LEONIDA_TITLE_PARTIAL_MIPS"); return !v || std::strcmp(v, "0") != 0; }(); return enabled; } // First mip of a 2D single-slice non-GPU-written texture with known non-guessed layout whose views all start below // mip 0 (e.g., packed SW_4KB_S mip-tail sub-allocations). Zero for all other textures or when partial mips are off. inline unsigned title_texture_active_from(const TitleTexture& t) { if (!title_partial_mips_enabled() || t.gpu_written || !t.layout_known || t.layout_guessed) return 0; if (t.layout.layout.dimension != rt::xg_xs::kTexture2D || t.layout.array != 1 || t.layout.layout.mips <= 1) return 0; if (!t.view_mip_set || t.view_mip == 0) return 0; unsigned from = (std::min)(t.view_mip, t.layout.layout.mips - 1); if (t.fills) from = (std::min)(from, t.filled_from); return from; } // Byte prefix actually owned by `t` from its base address: mip_chain_bytes(layout, active_from) when bounded by // view_mip > 0, else full layout.size. Prevents packed SW_4KB_S mip-tail textures from falsely colliding with // adjacent gpu_owned textures or reading/watching neighboring textures' bytes. inline std::uint64_t title_texture_active_span(const TitleTexture& t) { const unsigned from = title_texture_active_from(t); if (!from) return t.layout.layout.size; return (std::min)(rt::xg_xs::mip_chain_bytes(t.layout, from), t.layout.layout.size); } // The layout of a slot-133 texture as the title's own XG computer for its shape says (title_xg_layouts): how the title // lays out what it writes through Map. False when the title made none, or its layout does not fit the image. bool title_xg_layout(const Resource& r, rt::xg_xs::Texture& out, std::array& words) { const D3D12_RESOURCE_DESC& d = r.desc(); std::uint32_t layout = 0; if (!leonida::title_xg_layouts::find({std::uint32_t(d.Dimension), std::uint32_t(d.Format), d.Height, d.DepthOrArraySize, d.MipLevels, d.Width}, layout)) return false; rt::xg_xs::ResourceDesc x{}; x.dimension = std::uint32_t(d.Dimension); x.width = d.Width; x.height = d.Height; x.depth_or_array = d.DepthOrArraySize; x.mips = d.MipLevels; x.format = std::uint32_t(d.Format); x.samples = 1; x.layout = layout; rt::xg_xs::Texture t; if (!rt::xg_xs::build_texture(x, t) || t.layout.mips != d.MipLevels) return false; const leonida::BlockFormat element = r.copy_element(); if (element.bytes != t.format.bytes || element.block != t.format.side) return false; out = t; std::memcpy(words.data(), &x, sizeof(x)); return true; } // Whether the refresh fills the texture from memory, and so watches its pages: not a texture the GPU writes, not one // without a layout, and not a slot-133 texture whose layout is only guessed until the title maps it. // The watched textures over the new range stop being filled from memory. void DeviceState::add_gpu_owned(const void* owner, std::uint64_t address, std::uintptr_t cpu, std::uint64_t span) { gpu_owned[owner] = {address, cpu, cpu + span}; std::vector over; texture_watch.for_each_over(cpu, cpu + span, [&](std::uint64_t k) { over.push_back(k); }); for (const std::uint64_t k : over) { const auto it = title_textures.find(k); if (it != title_textures.end() && over_gpu_owned(it->second->cpu, it->second->cpu + title_texture_active_span(*it->second))) texture_watch.untrack(k); } } void DeviceState::drop_gpu_owned(const void* owner) { const auto it = gpu_owned.find(owner); if (it == gpu_owned.end()) return; const std::uintptr_t old_begin = it->second.begin; const std::uintptr_t old_end = it->second.end; gpu_owned.erase(it); // Re-index every title texture whose active span overlapped [old_begin, old_end), not just an exact address match. for (const auto& [addr, entry] : title_textures) { if (!entry || !entry->resource || entry->resource == owner || entry->gpu_written || !entry->layout_known) continue; const std::uint64_t span = title_texture_active_span(*entry); if (!span) continue; const std::uintptr_t t_begin = static_cast(entry->cpu); const std::uintptr_t t_end = span > (std::numeric_limits::max)() - t_begin ? (std::numeric_limits::max)() : t_begin + static_cast(span); if (t_begin < old_end && old_begin < t_end) index_texture(*entry); } } // Not one nothing names yet either: a texture no descriptor names is not read, uploaded or watched (the title may // fill it over many passes before its first view); its first descriptor (title_texture_named) brings it in, and it is // read whole and uploaded before the submission that made that descriptor. An image made for slot-70 views is named // by the view it is made for. void DeviceState::index_texture(const TitleTexture& t) { const bool filled = !t.gpu_written && t.layout_known && t.resource && (t.owned || t.resource->shader_views()) && !((t.layout_guessed || t.layout_from_xg) && !t.mapped && !t.stale); const std::uint64_t span = title_texture_active_span(t); if (filled && over_gpu_owned(t.cpu, t.cpu + span)) { ++gpu_owned_refusals; static std::atomic refusal_logged{0}; if (refusal_logged.fetch_add(1, std::memory_order_relaxed) < 16) { const std::uintptr_t t_end = t.cpu + static_cast(span); const void* hit_owner = nullptr; GpuOwned hit_range{}; for (const auto& [owner, range] : gpu_owned) { if (range.begin < t_end && t.cpu < range.end) { hit_owner = owner; hit_range = range; break; } } const D3D12_RESOURCE_DESC td = t.resource->desc(); if (hit_owner) { const D3D12_RESOURCE_DESC od = static_cast(hit_owner)->desc(); std::fprintf(stderr, "[rt] d3d12: gpu_owned refusal #%llu: tex 0x%llx cpu 0x%llx+0x%llx (%llux%u mips %u fmt %d " "owned=%d) overlaps gpu_owned 0x%llx cpu 0x%llx..0x%llx (%llux%u mips %u fmt %d flags 0x%x)\n", static_cast(gpu_owned_refusals), static_cast(t.address), static_cast(t.cpu), static_cast(span), static_cast(td.Width), td.Height, unsigned(td.MipLevels), int(td.Format), int(t.owned), static_cast(hit_range.address), static_cast(hit_range.begin), static_cast(hit_range.end), static_cast(od.Width), od.Height, unsigned(od.MipLevels), int(od.Format), unsigned(od.Flags)); } } texture_watch.untrack(t.address); return; } if (filled) { texture_watch.track(t.address, t.cpu, span); if (!t.hashed || t.stale) texture_watch.touch(t.address); // never filled, or known changed: read it } else { texture_watch.untrack(t.address); } } // Set on the current thread by refresh_title_textures(true) right after refresh_page_mirror() + flush_page_mirror() // ran in the same BeforeExecuteCoalescer leader pass so page_mirror_check_batch() can skip re-dirtying hot pages // that were just uploaded (while NEVER skipping cold pages that faulted after refresh_page_mirror()). static thread_local bool t_page_mirror_just_synced = false; // trivially destructible (no TLS callback) // Single-lock batched TitleMirror check & sync for all examined textures of a refresh_title_textures() pass: // - Acquires page_mirror.mutex ONCE per pass (eliminating per-texture lock contention with refresh_page_mirror and // write_back_batch). // - Snapshots pending xmem remaps from page_mirror.feed under shared feed_lock (lock order: title_texture_mutex -> // page_mirror.mutex -> feed_lock) and rejects ONLY textures whose own pages overlap an unapplied remap, instead of // aborting the whole pass on unrelated buffer remaps. // - Marks all dirty/hot mirror pages across all eligible textures (deduplicated automatically per physical frame by // TitleMirror::dirty()), runs ONE batched parallel TitleMirror::upload(), and evaluates range_sum() + chunk_at() // (or partial-tile range_sum() comparison) for every texture in the same lock hold. void DeviceState::page_mirror_check_batch( std::vector& items, std::vector& feed_pages, std::uint64_t mirror_synced_serial, const std::function)>& parallel_run) { if (!page_mirror.mirror || items.empty()) return; constexpr std::uint64_t kPage = leonida::TitleMirror::kPage; constexpr std::uint64_t kPiece = leonida::shadow_keep::kPiece; const bool mirror_just_synced = t_page_mirror_just_synced; std::lock_guard lock(page_mirror.mutex); feed_pages.clear(); if (page_mirror.feed_pending.load(std::memory_order_acquire)) { AcquireSRWLockShared(&page_mirror.feed_lock); feed_pages.reserve(page_mirror.feed.size()); for (const auto& c : page_mirror.feed) feed_pages.push_back(static_cast(c.page) & ~(kPage - 1)); ReleaseSRWLockShared(&page_mirror.feed_lock); if (feed_pages.size() > 1) { std::sort(feed_pages.begin(), feed_pages.end()); feed_pages.erase(std::unique(feed_pages.begin(), feed_pages.end()), feed_pages.end()); } } const auto page_in_feed = [&](std::uint64_t p) -> bool { return !feed_pages.empty() && std::binary_search(feed_pages.begin(), feed_pages.end(), p); }; bool need_upload = false; auto& mirror = *page_mirror.mirror; auto* const tracking = page_mirror.tracking.get(); const bool any_pending = mirror.has_pending_binds(); const auto mark_dirty_page = [&](std::uint64_t p) { if (mirror.dirty(p)) need_upload = true; }; const auto record_reject = [](TitleMirrorCheckItem& item, std::uint8_t reason) { // Priority: in_feed (3) / pending_bind (4) > unmirrored_plain (1) > unmirrored_other (2). if (item.reject_reason == 0 || item.reject_reason == 2 || (item.reject_reason == 1 && reason >= 3)) item.reject_reason = reason; }; const auto try_full_view = [&](TitleMirrorCheckItem& item, std::uint64_t va, bool is_cpu_view) -> bool { if (!va || !item.bytes || va + item.bytes < va) return false; const std::uint64_t end = va + item.bytes; for (std::uint64_t p = va & ~(kPage - 1); p < end; p += kPage) { if (page_in_feed(p)) { record_reject(item, 3); return false; } if (!mirror.mirrored(p)) { auto pit = page_mirror.plain.upper_bound(p); const bool in_plain = (pit != page_mirror.plain.begin() && std::prev(pit)->second > p); record_reject(item, in_plain ? 1 : 2); return false; } if (any_pending && mirror.has_pending(p)) { record_reject(item, 4); return false; } if (p > UINT64_MAX - kPage) break; } const bool serial_clean = mirror_just_synced && mirror_synced_serial != 0 && item.ex_armed && item.max_version <= mirror_synced_serial; if (!serial_clean) { const bool filter_written = is_cpu_view && item.written_tiles && !item.written_tiles->empty(); for (std::uint64_t p = va & ~(kPage - 1); p < end; p += kPage) { if (filter_written && !std::binary_search(item.written_tiles->begin(), item.written_tiles->end(), static_cast(p))) { if (p > UINT64_MAX - kPage) break; continue; } const bool clean_cpu = is_cpu_view && tracking && (tracking->unwritten(p) || (mirror_just_synced && tracking->hot(p))); if (!clean_cpu) mark_dirty_page(p); if (p > UINT64_MAX - kPage) break; } } item.mode = TitleMirrorCheckItem::Mode::full; item.mirror_va = va; return true; }; // Pass 1: classify each active item (full mirror vs partial-tile mirror vs CPU fallback) and mark dirty pages. std::uint64_t pass3_bytes = 0; std::vector pass3_indices; pass3_indices.reserve(items.size()); for (std::size_t i = 0; i < items.size(); ++i) { TitleMirrorCheckItem& item = items[i]; item.full_ok = false; item.single_chunk = false; item.tile_cmp = 0; item.reject_reason = 0; item.mode = TitleMirrorCheckItem::Mode::none; item.mirror_va = 0; if (!item.active || !item.bytes) continue; if (try_full_view(item, item.cpu, true)) { pass3_bytes += item.bytes; pass3_indices.push_back(i); continue; } if (item.gpu && item.gpu != item.cpu && try_full_view(item, item.gpu, false)) { pass3_bytes += item.bytes; pass3_indices.push_back(i); continue; } if (item.tile_cmp_written && !item.tile_cmp_written->empty() && item.pieces && (item.cpu & (kPiece - 1)) == 0 && (item.bytes & (kPiece - 1)) == 0) { const std::uintptr_t base_tile = static_cast(item.cpu) & ~(leonida::TilePieces::kTile - 1); bool all_ok = true; for (const std::uintptr_t tile : *item.tile_cmp_written) { if (tile < base_tile) { all_ok = false; break; } const std::size_t idx = (tile - base_tile) / leonida::TilePieces::kTile; if (idx >= item.pieces->hashes.size()) { all_ok = false; break; } const std::uint64_t p = static_cast(tile) & ~(kPage - 1); if (page_in_feed(p) || !mirror.mirrored(p) || (any_pending && mirror.has_pending(p))) { all_ok = false; break; } } if (all_ok) { item.mode = TitleMirrorCheckItem::Mode::partial_tiles; const bool serial_clean = mirror_just_synced && mirror_synced_serial != 0 && item.ex_armed && item.max_version <= mirror_synced_serial; if (!serial_clean) { for (const std::uintptr_t tile : *item.tile_cmp_written) { const std::uint64_t p = static_cast(tile) & ~(kPage - 1); const bool clean_cpu = tracking && (tracking->unwritten(p) || (mirror_just_synced && tracking->hot(p))); if (!clean_cpu) mark_dirty_page(p); } } pass3_bytes += std::uint64_t(item.tile_cmp_written->size()) * kPage; pass3_indices.push_back(i); } } } // Pass 2: ONE batched parallel upload across all dirty mirror pages of the pass. if (need_upload) { const std::uint64_t failures_before = mirror.counters().upload_failures; if (page_mirror.readback_in_flight) { page_mirror.uploads += mirror.upload([this](std::uint8_t* frame, const std::array& changed) { note_readback_pieces_uploaded_locked(frame, changed); }); } else { page_mirror.uploads += mirror.upload(); } // Do not upload zeroed fallback pieces or poison mirror_hash when hooks_.copy failed mid-sync. if (mirror.counters().upload_failures != failures_before) return; } // Pass 3: read-only mirror range_sum / chunk_at / partial-tile comparison into disjoint per-item outputs. // Safe to fan out across title_read_pool() while holding page_mirror.mutex: only reads immutable mirror maps/sums. const VkSemaphore mirror_timeline = page_mirror.timeline; const std::uint64_t mirror_value = page_mirror.value; const auto eval_item = [&](std::size_t slot_idx) { TitleMirrorCheckItem& item = items[pass3_indices[slot_idx]]; if (item.mode == TitleMirrorCheckItem::Mode::full) { std::uint64_t m_hash = 0; if (!mirror.range_sum(item.mirror_va, item.bytes, m_hash)) return; VkBuffer buf = VK_NULL_HANDLE; VkDeviceSize off = 0; const bool has_chunk = mirror.chunk_at(item.mirror_va, buf, off); const bool in_one_chunk = has_chunk && item.bytes <= leonida::TitleMirror::kChunk - off; item.full_ok = true; item.single_chunk = in_one_chunk; if (in_one_chunk) { item.buffer = buf; item.offset = off; item.chunk_size = leonida::TitleMirror::kChunk; item.timeline = mirror_timeline; item.value = mirror_value; } item.mirror_hash = m_hash; } else if (item.mode == TitleMirrorCheckItem::Mode::partial_tiles) { const std::uintptr_t base_tile = static_cast(item.cpu) & ~(leonida::TilePieces::kTile - 1); int cmp = 1; for (const std::uintptr_t tile : *item.tile_cmp_written) { const std::size_t idx = (tile - base_tile) / leonida::TilePieces::kTile; const auto [offset, length] = leonida::TilePieces::part(static_cast(item.cpu), item.bytes, tile); if (!length) continue; std::uint64_t h = 0; if (!mirror.range_sum(item.cpu + offset, length, h)) { cmp = 0; break; } if (h != item.pieces->hashes[idx]) { cmp = -1; break; } } item.tile_cmp = cmp; } }; constexpr std::uint64_t kParallelRangeSumBytes = 8ull << 20; if (parallel_run && pass3_indices.size() > 1 && pass3_bytes >= kParallelRangeSumBytes) { parallel_run(pass3_indices.size(), eval_item); } else { for (std::size_t k = 0; k < pass3_indices.size(); ++k) eval_item(k); } } void DeviceState::title_texture_mapped(const void* resource, std::uint64_t address) { std::lock_guard lock(title_texture_mutex); const auto it = title_textures.find(address); if (it == title_textures.end() || it->second->resource != resource) return; TitleTexture& t = *it->second; t.mapped = true; t.write_combined_known = false; t.memory.retry(); index_texture(t); // watched from now on, and looked at by the next refresh // The title computes the layout of what it writes right before it maps: take it when no view gave one. if (!t.gpu_written && (t.layout_guessed || !t.layout_known) && title_xg_layout(*static_cast(resource), t.layout, t.desc)) { t.layout_known = true; t.layout_guessed = false; t.layout_from_xg = true; t.mirror_hash_valid = false; t.invalidate_gpu_upload_cache(); index_texture(t); t.hashed = false; } static std::atomic logged{0}; if (logged.fetch_add(1, std::memory_order_relaxed) < 48) { const auto& r = *static_cast(resource); const D3D12_RESOURCE_DESC& d = r.desc(); std::fprintf(stderr, "[rt] d3d12: the title maps slot-133 texture 0x%llx (CPU 0x%llx): dimension %d %llux%ux%u mips %u " "format %d flags 0x%x; layout %s, %s\n", static_cast(address), static_cast(t.cpu), int(d.Dimension), static_cast(d.Width), d.Height, unsigned(d.DepthOrArraySize), unsigned(d.MipLevels), int(d.Format), unsigned(d.Flags), t.gpu_written ? "none (GPU-written)" : !t.layout_known ? "unknown" : t.layout_guessed ? "guessed (no slot-70 view, no XG computer of its shape)" : t.layout_from_xg ? (t.layout.mode == rt::xg_xs::kLinear ? "the title's XG computer's (linear)" : "the title's XG computer's (swizzled)") : "from a slot-70 view", t.fills ? "filled before" : "not filled yet"); } } void DeviceState::title_texture_unmapped(const void* resource, std::uint64_t address) { std::lock_guard lock(title_texture_mutex); const auto it = title_textures.find(address); if (it != title_textures.end() && it->second->resource == resource) { it->second->stale = true; it->second->write_combined_known = false; it->second->memory.retry(); index_texture(*it->second); texture_watch.touch(address); } } void DeviceState::clear_partial_budget(TitleTexture& t) { if (!t.partial_budget_counted) return; title_partial_bytes = title_partial_bytes >= t.backing_bytes ? title_partial_bytes - t.backing_bytes : 0; t.partial_budget_counted = false; } void DeviceState::title_texture_gone(const void* resource, std::uint64_t address) { if (t_in_title_textures) { // this thread holds title_texture_mutex { // Never held here: ~Resource takes descriptor_mutex itself (image_owner, forget_image). The submit path // reads gpu_placements under descriptor_mutex alone, so the placement must not outlive the resource. std::lock_guard descriptors(descriptor_mutex); gpu_placements.remove(address, resource); note_texture_change(leonida::SlotChange::texture_gone, address); } const auto it = title_textures.find(address); if (it != title_textures.end() && it->second->resource == resource) { clear_partial_budget(*it->second); it->second->resource = nullptr; texture_watch.untrack(address); } drop_gpu_owned(resource); titles_gone.push_back({resource, address}); titles_gone_pending.store(true, std::memory_order_release); return; } std::lock_guard lock(title_texture_mutex); { std::lock_guard descriptors(descriptor_mutex); gpu_placements.remove(address, resource); note_texture_change(leonida::SlotChange::texture_gone, address); } const auto it = title_textures.find(address); if (it != title_textures.end() && it->second->resource == resource) { clear_partial_budget(*it->second); texture_watch.untrack(address); it->second->resource = nullptr; title_textures.erase(it); } drop_gpu_owned(resource); } void DeviceState::drain_titles_gone() { if (!titles_gone_pending.load(std::memory_order_acquire)) return; std::lock_guard lock(title_texture_mutex); for (const auto& [resource, address] : titles_gone) { const auto it = title_textures.find(address); if (it != title_textures.end() && !it->second->resource) title_textures.erase(it); } titles_gone.clear(); titles_gone_pending.store(false, std::memory_order_release); } // The T# of a view: what the shader gets to know about it, in the structure the console's shaders read. // False (with a log) for a view set 0 cannot show yet. // A T# the title wrote into a console descriptor heap itself (DeviceState::fix_console_slots). Translated shaders // find an image by the T#'s exact eight dwords, so one that no Create*View wrote is decoded here, its texture looked // up by the base address it names (Resource::image_address, the only texture addresses the title can know: it // learns them from descriptors the layer wrote), and the image is given a view and a hash-table entry for exactly // these words, as write_image_descriptor does. Every field the layer does not encode (tiling, compression, // performance hints) only makes the key differ, so a title-built T# still finds its texture. Checked against the // texture first: a view of mips, layers or a dimension it lacks would be an invalid Vulkan view. // LEONIDA_UNKNOWN_TSHARP=1 (diagnostic): one line for each distinct base address a title-written T# names with no // texture there (its shape, the tiling bits SW_MODE = dword 3 bits 20..24 by the GFX10 layout, unverified, and whether // the address is title memory), up to 300 addresses, and every 8192 such lookups a summary by format, type and tiling. // What a texture made from the T# on its first read would have to create. void note_unknown_tsharp(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image) { static const bool on = [] { const char* v = std::getenv("LEONIDA_UNKNOWN_TSHARP"); return v && *v == '1'; }(); if (!on) return; struct Shape { std::uint32_t format, type, sw, width, height, depth, mips, layers; }; static std::mutex mutex; static std::unordered_map seen; static std::map by_shape; static std::uint64_t lookups = 0, in_title = 0; const Shape s{image.format, std::uint32_t(image.type), (words[3] >> 20) & 0x1f, image.width, image.height, image.depth, image.resource_mips, image.layer_count}; std::uint64_t lo = 0, hi = 0; const bool title = leonida::title_va_aliases().title_memory(image.address, lo, hi); std::lock_guard lock(mutex); ++lookups; if (seen.emplace(image.address, s).second) { in_title += title; char key[64]; std::snprintf(key, sizeof(key), "fmt %u type %u sw %u", s.format, s.type, s.sw); ++by_shape[key]; if (seen.size() <= 300) std::fprintf(stderr, "[rt] unknown-tsharp: #%zu base 0x%llx fmt %u type %u sw %u %ux%ux%u mips %u layers %u%s\n", seen.size(), static_cast(image.address), s.format, s.type, s.sw, s.width, s.height, s.depth, s.mips, s.layers, title ? " (title memory)" : " (not title memory)"); if (seen.size() <= 24) std::fprintf(stderr, "[rt] unknown-tsharp: #%zu words %08x %08x %08x %08x %08x %08x %08x %08x\n", seen.size(), words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7]); } if (!(lookups % 8192)) { std::vector> top; for (const auto& [k, n] : by_shape) top.emplace_back(n, k); std::sort(top.rbegin(), top.rend()); std::string text; for (std::size_t i = 0; i < top.size() && i < 10; ++i) text += (i ? "; " : "") + top[i].second + " x" + std::to_string(top[i].first); std::fprintf(stderr, "[rt] unknown-tsharp: %llu lookups, %zu distinct addresses (%llu in title memory); by shape: %s\n", static_cast(lookups), seen.size(), static_cast(in_title), text.c_str()); } } const char* DeviceState::no_texture_reason_locked(const leonida::gfx10::Image& image) { std::uint64_t lo = 0, hi = 0; if (leonida::title_va_aliases().title_memory(image.address, lo, hi)) return kTsharpNoTextureTitleMemory; // The layer's own texture addresses: 1 << 32 and up, 256 apart (Resource::image_address). constexpr std::uint64_t ours = std::uint64_t(1) << 32; const std::uint64_t next = next_image_address.load(std::memory_order_relaxed); if (image.address >= ours && image.address < next) return kTsharpNoTextureGone; const std::uint64_t low = ours | (image.address & 0xffffffffull); if (low >= next) return kTsharpNoTextureNothing; const auto found = images_by_address.find(low); if (found == images_by_address.end()) return kTsharpNoTextureLow32Gone; const auto& owner = *static_cast(found->second); return TitleGpuPlacements::matches(image, owner.desc()) ? kTsharpNoTextureLow32Same : kTsharpNoTextureLow32Other; } // bind_title_image's binding of the T# to `r`'s image; false with the reason. descriptor_mutex held. bool bind_title_image_to(DeviceState& device, const leonida::gfx10::ImageWords& words, leonida::gfx10::Image image, const Resource& r, const char*& reason, leonida::ResourceId& sparse) { namespace g = leonida::gfx10; image.address = r.image_address(); // release this key with its actual owner const D3D12_RESOURCE_DESC& d = r.desc(); const bool volume = d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const bool line = d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; const bool msaa = d.SampleDesc.Count > 1; const UINT layers = volume ? 1 : d.DepthOrArraySize; const bool type_fits = image.type == g::ImageType::image_3d ? volume : image.type == g::ImageType::image_1d ? line && image.layer_count == 1 : image.type == g::ImageType::image_1d_array ? line : g::multisampled(image.type) ? msaa && !volume && !line && image.samples == d.SampleDesc.Count : !volume && !line && !msaa; if (!r.descriptor_image()) return reason = "the texture has no image", false; if (!type_fits) return reason = "T# type or samples do not fit the texture", false; const bool extent_fits = image.width == d.Width && image.height == d.Height && (!volume || image.depth == d.DepthOrArraySize); if (!extent_fits) return reason = "T# extent does not match the texture", false; if (!msaa && image.first_mip + image.mip_count > d.MipLevels) return reason = "T# names mips the texture lacks", false; if (image.type == g::ImageType::cube && !(r.format() && layers >= 6)) return reason = "cube T# on fewer than six layers", false; if (!volume && image.first_layer + image.layer_count > layers) return reason = "T# names layers the texture lacks", false; const bool storage = (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !msaa && r.aspects() == VK_IMAGE_ASPECT_COLOR_BIT; if (volume && storage && g::has_hardware_volume_uav_slice_offset(words, image)) return reason = "a title-written 3D UAV with a slice offset is not supported", false; reason = "no view for the T#'s format or range"; // unless set 0 has no room (bind_image) if (!device.bind_image_locked(words, image, r.descriptor_image(), r.format(), r.aspects(), storage, r.has_view_format_list(), r.uint_backed(), &reason)) return false; // Include descriptors written directly into title heaps and propagate lowered MIN_LOD / BASE_LEVEL to active_span. r.note_shader_view(leonida::effective_min_mip(image.first_mip, g::image_min_lod(words))); if (r.sparse_image()) sparse = r.id(); return true; } TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why, std::uint32_t* out_index_word, std::uint64_t* out_texture_address) { namespace g = leonida::gfx10; if (out_index_word) *out_index_word = 0; if (out_texture_address) *out_texture_address = 0; const auto refuse = [why](const char* reason) { if (why) *why = reason; return TitleImage::refused; }; g::Image image{}; if (!g::decode(words, image)) { if (why) *why = "not a valid T# (swizzle, levels or layers)"; return TitleImage::not_tsharp; } // GFX10.3 SQ_IMG_RSRC_WORD4[30:29] and [15:14] are reserved (must be 0; bit [31] is Leonida's synthetic // volume_uav_flag and is intentionally excluded). GFX10_FORMAT_INVALID (0) is also never a valid T#. // Rejecting both here filters CBV/data overwrites in the shared console heap before owner lookup. constexpr std::uint32_t kWord4ReservedMask = 0x6000C000u; if ((words[4] & kWord4ReservedMask) != 0 || image.format == 0) { if (why) *why = "not a valid T# (reserved WORD4 bits or invalid format)"; return TitleImage::not_tsharp; } // Leonida's gfx10::encode() leaves RESOURCE_LEVEL (WORD2[31]) == 0 and SW_MODE (WORD3[24:20]) == 0 // (real GFX10.3 hardware T#s set RESOURCE_LEVEL == 1), sets WORD5[31:8] == 0, and leaves WORD7 == 0 // unless volume_uav_flag (WORD4[31]) is set. Non-zero WORD5[31:8] or unexpected WORD7 on such a slot // identifies a half-overwritten dead T# tail in the shared transient ring. const bool leonida_encoded = (words[2] >> 31) == 0 && g::detail::get(words[3], 20, 5) == 0; if (leonida_encoded && (((words[5] & 0xFFFFFF00u) != 0) || (words[7] != 0 && (words[4] & g::volume_uav_flag) == 0))) { if (why) *why = "not a valid T# (overwritten tail on encoded T#)"; return TitleImage::not_tsharp; } leonida::ResourceId sparse = 0; { std::lock_guard lock(device.descriptor_mutex); if (!device.bindless) return refuse("no bindless set"); if (const auto it = device.image_entries.find(words); it != device.image_entries.end()) { const std::uint64_t gen = ++device.tsharp_use_gen; it->second.last_seen_gen = gen; if (const auto sv_it = device.shared_views.find(it->second.view_key); sv_it != device.shared_views.end()) { sv_it->second.last_seen_gen = gen; sv_it->second.last_touch_ticket = device.context ? device.context->submitted_retire_ticket() + 1 : 0; } if (out_index_word) *out_index_word = g::tsharp_index_word( it->second.index, device.bindless->image_kind_at(it->second.dimension, it->second.index)); if (out_texture_address && (image.address >> 32) == 0x1000ull && it->second.address == ((std::uint64_t(1) << 32) | (image.address & 0xffffffffull))) *out_texture_address = it->second.address; return TitleImage::known; } auto found = device.images_by_address.find(image.address); // Null/zero-offset CPU-window T# (0x100000000000, title_mirror_space::kLow + 0): never alias via other_view // to the GPU-only stream pool base (0x100400000000), where an unrelated streamed texture lives. const bool zero_cpu_window = words[0] == 0 && (words[1] & 0xFFu) == 0x10u; // Memory of the texture stream pool has two addresses, the CPU view's and the GPU-only alias the title hands // to the GPU (title_gpu_views): a T# naming either finds a texture registered under the other. if (found == device.images_by_address.end() && !zero_cpu_window) if (const std::uint64_t other = leonida::title_gpu_views::other_view(image.address)) found = device.images_by_address.find(other); const auto matches = [&](const Resource& r) { return TitleGpuPlacements::matches(image, r.desc()); }; // A GPU-written texture placed at the address (a render target, depth or UAV texture) answers before any // other texture there: its image holds what the GPU rendered, and the title's pages under it do not, so a // texture filled from them shows nothing the GPU drew. Compatible: the T#'s extent and samples, and mips and // layers within the target's (TitleGpuPlacements::matches); the format is any the target's image takes a view // in (bind_image_locked: its own, a castable one, or one of the same block size its view list allows). With // none, the other texture answers as before (counted by reason in the title texture refresh's line). const auto alias = zero_cpu_window ? std::uint64_t(0) : leonida::title_gpu_views::other_view(image.address); Resource* gpu = device.gpu_placements.find(image.address, alias, matches); if (zero_cpu_window && found == device.images_by_address.end() && !gpu) { if (why) *why = "not a valid T# (zero-offset CPU-window address)"; return TitleImage::not_tsharp; } // A T# the title rebuilt from the low 32 bits of the layer's texture address (tsharp_texture_key): taken only // with the texture's shape, as those bits alone are a weaker sign than the whole address. Also allow the // high == 0x10, mid == 0 fallback (title_mirror_space::kLow upper byte) ONLY when no title texture owns // image.address or its other_view (neither images_by_address nor gpu_placements). bool by_low_bits = false; if (found == device.images_by_address.end() && !gpu) { if (const std::uint64_t key = device.tsharp_texture_key(image.address); key != image.address) { found = device.images_by_address.find(key); by_low_bits = true; } else if (const std::uint64_t key10 = device.tsharp_high10_low32_key(image.address); key10 != image.address) { found = device.images_by_address.find(key10); by_low_bits = true; } } const Resource* owner = found == device.images_by_address.end() ? nullptr : static_cast(found->second); if (owner && by_low_bits && !matches(*owner)) owner = nullptr; const Resource* plain = owner && owner != gpu ? owner : nullptr; if (gpu) { owner = gpu; } else if (plain && !by_low_bits) { if (const Resource* any = device.gpu_placements.find(image.address, alias, [](const Resource&) { return true; })) { const D3D12_RESOURCE_DESC& d = any->desc(); const bool extent = d.Width != image.width || d.Height != image.height || (d.SampleDesc.Count > 1) != g::multisampled(image.type); ++device.over_gpu_target[extent ? DeviceState::kOverTargetExtent : DeviceState::kOverTargetRange]; } } if (!owner) { if (why) *why = device.no_texture_reason_locked(image); note_unknown_tsharp(words, image); return TitleImage::unknown; } struct TitleHeapBindGuard { bool& flag; bool prev; explicit TitleHeapBindGuard(bool& f) : flag(f), prev(f) { flag = true; } ~TitleHeapBindGuard() { flag = prev; } } title_guard(device.binding_from_title_heap); const auto log_refusal_locked = [&](const char* why_str, const Resource& target) { const D3D12_RESOURCE_DESC& od = target.desc(); const std::string_view reason_key = why_str ? std::string_view(why_str) : std::string_view{}; auto& reason_count = device.logged_tsharp_refusals_by_reason[reason_key]; if (reason_count >= 8) return; const std::uint32_t sw_mode = g::detail::get(words[3], 20, 5); const DeviceState::TsharpRefusalKey key{ reason_key, std::uint32_t(image.type), sw_mode, image.first_layer, image.layer_count, std::uint32_t(od.Dimension), std::uint32_t(od.DepthOrArraySize), std::uint32_t(od.MipLevels), std::uint32_t(od.Format)}; if (device.logged_tsharp_refusals.insert(key).second) { ++reason_count; const unsigned w4_rsvd = (words[4] & kWord4ReservedMask) != 0 ? 1u : 0u; std::fprintf(stderr, "[rt] tsharp-refuse: reason=\"%s\" type=%u sw_mode=%u fmt=%u layers=%u+%u mips=%u+%u " "owner_dim=%u owner_layers=%u owner_mips=%u owner_fmt=%u " "tsharp_size=%ux%u owner_size=%llux%u w4_rsvd=%u\n", why_str ? why_str : "", unsigned(image.type), unsigned(sw_mode), unsigned(image.format), unsigned(image.first_layer), unsigned(image.layer_count), unsigned(image.first_mip), unsigned(image.mip_count), unsigned(od.Dimension), unsigned(od.DepthOrArraySize), unsigned(od.MipLevels), unsigned(od.Format), unsigned(image.width), unsigned(image.height), static_cast(od.Width), unsigned(od.Height), w4_rsvd); } }; const char* reason = nullptr; if (bind_title_image_to(device, words, image, *owner, reason, sparse)) { if (owner == gpu && plain) ++device.over_gpu_target[DeviceState::kOverTargetResolved]; } else if (owner == gpu && plain) { ++device.over_gpu_target[DeviceState::kOverTargetFormat]; if (!bind_title_image_to(device, words, image, *plain, reason, sparse)) { log_refusal_locked(reason, *plain); return refuse(reason); } } else { log_refusal_locked(reason, *owner); return refuse(reason); } if (out_index_word) *out_index_word = device.tsharp_index_word_locked(words); if (out_texture_address && by_low_bits && (image.address >> 32) == 0x1000ull) *out_texture_address = owner->image_address(); } if (sparse) device.context->note_shader_image(sparse); return TitleImage::bound; } TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why) { return bind_title_image(device, words, why, nullptr, nullptr); } bool valid_shader_4_component_mapping(UINT mapping) { if ((mapping >> 12) != 1) return false; for (UINT i = 0; i < 4; ++i) { if (D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(i, mapping) > D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1) return false; } return true; } bool image_descriptor(const Resource& resource, const TextureView& asked, bool storage, leonida::gfx10::Image& out, VkFormat& view_format, DeviceState::VolumeSlices& slices) { TextureView view = asked; view.format = pc_format(view.format); // the console's D16S8 plane views as D24S8's namespace g = leonida::gfx10; const D3D12_RESOURCE_DESC& desc = resource.desc(); if (storage && (resource.aspects() & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) { log_once("storage view not supported for depth-stencil texture:", int(desc.Format)); return false; } // A shader-resource view's own fields (an unordered-access view has neither). if (!storage && !valid_shader_4_component_mapping(view.mapping)) { log_once("invalid shader view component mapping:", int(view.mapping)); return false; } if (!storage && (std::isnan(view.min_lod) || view.min_lod < 0.0f)) { log_once("invalid shader view ResourceMinLODClamp; first mip", int(view.first_mip)); return false; } // Plane 1 of a depth-stencil texture is its stencil, viewed as X24_TYPELESS_G8_UINT (D24S8) or // X32_TYPELESS_G8X24_UINT (D32S8): eight unsigned bits in G, as D3D12 returns them. The T# is 8_UINT, the // format of the console's separate stencil surface, and bind_image views the stencil aspect for it. const bool stencil = view.plane == 1; if (view.plane > 1 || (stencil && !(resource.aspects() & VK_IMAGE_ASPECT_STENCIL_BIT))) { log_once("no such plane in this texture; plane", int(view.plane)); return false; } // Each stencil view format belongs to its own DXGI family only, as in D3D12: the family is the texture's DXGI // format, not the Vulkan format behind it (a D24 texture may be D32_SFLOAT_S8_UINT underneath). const bool stencil_format_fits = (view.format==xbox_s8_plane && desc.Format==xbox_d16s8) || (view.format == DXGI_FORMAT_X24_TYPELESS_G8_UINT && (desc.Format == DXGI_FORMAT_R24G8_TYPELESS || desc.Format == DXGI_FORMAT_D24_UNORM_S8_UINT)) || (view.format == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT && (desc.Format == DXGI_FORMAT_R32G8X24_TYPELESS || desc.Format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT)); if (stencil && !stencil_format_fits) { log_once("a stencil-plane view needs its texture family's stencil view format; format", int(view.format)); return false; } const bool volume = view.type == g::ImageType::image_3d; const bool line = view.type == g::ImageType::image_1d; const bool line_array = view.type == g::ImageType::image_1d_array; const bool one_d = line || line_array; const bool msaa = g::multisampled(view.type); const auto dimension = volume ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : one_d ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; if (desc.Dimension != dimension || (msaa ? desc.SampleDesc.Count <= 1 : desc.SampleDesc.Count != 1) || (storage ? msaa : line_array) || (line && view.layer_count != 1)) { log_once("view type incompatible with texture dimension or sample count; view type", int(view.type)); return false; } if (msaa) { // The MS bindings expose typed colour SRVs. An MS view has one mip and can name an array slice range. const Format format = texture_storage_format(desc.Format, false); if (resource.aspects() != VK_IMAGE_ASPECT_COLOR_BIT || format.typeless || (view.format != DXGI_FORMAT_UNKNOWN && view.format != desc.Format)) { log_once("multisample shader view requires a matching typed colour format:", int(desc.Format)); return false; } } const VkFormat resource_format = resource.uint_backed() ? resource.uint_backed() : resource.format(); VkFormat named = resource_format; // A B4G4R4A4 render target stored as an RGBA8 image (no 4444 colour attachment on the device): its T# names // 4_4_4_4 as on the console, and bind_image views the RGBA8 image with the 4444 view's channels. const bool rgba8_4444 = desc.Format == DXGI_FORMAT_B4G4R4A4_UNORM && resource.format() == VK_FORMAT_R8G8B8A8_UNORM; if (rgba8_4444) named = VK_FORMAT_A4R4G4B4_UNORM_PACK16; if (volume && !storage) { const bool compatible = vulkan_format(desc.Format, false).typeless ? desc.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS && (view.format == DXGI_FORMAT_R8G8B8A8_UNORM || view.format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) : view.format == DXGI_FORMAT_UNKNOWN || view.format == desc.Format || (view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && resource.lists_castable_format(view.format)); if (!compatible) { log_once("unsupported volume SRV format for this resource:", int(view.format)); return false; } } // Depth and depth-stencil textures can only be viewed through their own family's depth-plane SRV format (or // UNKNOWN on typed depth textures): in Vulkan a depth image's view format must equal the image's own depth // format (VUID-VkImageViewCreateInfo-image-01762 / 09594), so colour view formats such as R16_FLOAT on D16 or // R32_UINT on D32 must be rejected. Each view format belongs to its own DXGI family only, whatever format // backs the texture (a D24 texture may be D32_SFLOAT_S8_UINT underneath). const bool depth_plane = (resource.aspects() & VK_IMAGE_ASPECT_DEPTH_BIT) && !stencil; if (depth_plane) { const bool depth_format_fits = (desc.Format == xbox_d16s8 && (view.format == DXGI_FORMAT_UNKNOWN || view.format == xbox_d16_plane)) || (desc.Format == DXGI_FORMAT_D16_UNORM && (view.format == DXGI_FORMAT_UNKNOWN || view.format == DXGI_FORMAT_R16_UNORM)) || (desc.Format == DXGI_FORMAT_R16_TYPELESS && view.format == DXGI_FORMAT_R16_UNORM) || (desc.Format == DXGI_FORMAT_D32_FLOAT && (view.format == DXGI_FORMAT_UNKNOWN || view.format == DXGI_FORMAT_R32_FLOAT)) || (desc.Format == DXGI_FORMAT_R32_TYPELESS && view.format == DXGI_FORMAT_R32_FLOAT) || (desc.Format == DXGI_FORMAT_D24_UNORM_S8_UINT && (view.format == DXGI_FORMAT_UNKNOWN || view.format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS)) || (desc.Format == DXGI_FORMAT_R24G8_TYPELESS && view.format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS) || (desc.Format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT && (view.format == DXGI_FORMAT_UNKNOWN || view.format == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS)) || (desc.Format == DXGI_FORMAT_R32G8X24_TYPELESS && view.format == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS); if (!depth_format_fits) { log_once("incompatible depth shader-resource view format:", int(view.format)); return false; } } // Both view kinds: a typeless texture needs a concrete view format, and a view format cannot be typeless. if (!stencil && !depth_plane) { if (view.format == DXGI_FORMAT_UNKNOWN && vulkan_format(desc.Format, false).typeless) { log_once("typeless texture view requires a concrete view format:", int(desc.Format)); return false; } if (view.format != DXGI_FORMAT_UNKNOWN && vulkan_format(view.format, false).typeless) { log_once("view format cannot be typeless:", int(view.format)); return false; } } const bool new_uav = storage && (volume || one_d); if (new_uav) { const DXGI_FORMAT dxgi = view.format == DXGI_FORMAT_UNKNOWN ? desc.Format : view.format; const Format format = texture_storage_format(dxgi, false); if (format.typeless || format.aspects != VK_IMAGE_ASPECT_COLOR_BIT || !uav_format_compatible(desc.Format, dxgi)) { log_once("unordered-access view format is not compatible with the resource:", dxgi); return false; } named = format.format; } else if (view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane) { if ((view.format == DXGI_FORMAT_A8_UNORM) != (desc.Format == DXGI_FORMAT_A8_UNORM)) { log_once("incompatible typed A8 view format:", int(view.format)); return false; } // Only a castable-format list that names the view's format lets a view cross the two families, as WARP and // AMD's D3D12 driver accept (relaxed casting). if (alpha_unused(view.format) != alpha_unused(desc.Format) && !resource.lists_castable_format(view.format)) { log_once("view format from another typeless family (B8G8R8X8 and B8G8R8A8):", int(view.format)); return false; } // A 32-bit texture that lists R9G9B9E5 as castable (a slot-133 R32 unordered-access target the title packs // E5 values into, create_at_host_address) is viewed as E5B9G9R9. if ((view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) != (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) && !(view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && resource.lists_castable_format(view.format))) { log_once("incompatible R9G9B9E5 view format:", int(view.format)); return false; } // An A8 render target is viewed in its own A8 format (Format::a8_as_alpha), other A8 textures through R8. named = resource.a8_as_alpha() ? resource_format : texture_storage_format(view.format, false).format; if (g::is_depth_stencil_format(named)) { log_once("depth-stencil view format on a colour texture:", int(view.format)); return false; } } // A 96-bit texture takes views of its own family only (and a four-channel texture none of it), and only the // TYPELESS one is cast between FLOAT, UINT and SINT. Its T# names the three-channel format (alpha reads as // one), but the format list and Vulkan view use the RGBA32 format that backs it. const bool rgb96 = resource.rgb96(); if (!stencil && !depth_plane) { const bool view_rgb96 = view.format != DXGI_FORMAT_UNKNOWN ? vulkan_format(view.format, false).rgb96 : rgb96; if (view_rgb96 != rgb96 || (rgb96 && desc.Format != DXGI_FORMAT_R32G32B32_TYPELESS && named != resource.format())) { log_once("view format outside the texture's 96-bit family:", int(view.format)); return false; } } if (named == VK_FORMAT_UNDEFINED || (rgba8_4444 ? named != VK_FORMAT_A4R4G4B4_UNORM_PACK16 : !resource.allows_view_format(named))) { log_once("view format not in the resource's castable list:", int(view.format)); return false; } const std::uint32_t code = stencil ? g::stencil_format : g::format_from_vulkan(rgb96 ? rgb96_named_format(named) : named); view_format = VK_FORMAT_UNDEFINED; if (stencil) { view_format = resource.format(); } else if (code && (new_uav || rgb96)) { view_format = rgb96 ? rgb96_view_format(resource.format(), code) : named; } else if (code && rgba8_4444) { view_format = resource.format(); } else if (code) { view_format = g::vulkan_view_format(resource_format, code, resource.has_view_format_list()); } if (!storage && resource.rgba4_render_backing() && (view.format == DXGI_FORMAT_B4G4R4A4_UNORM || view.format == DXGI_FORMAT_UNKNOWN)) view_format = resource.format(); if (view_format == VK_FORMAT_UNDEFINED || !resource.allows_view_format(view_format)) { log_once("view format not supported for this texture:", int(view.format)); return false; } if (view.first_mip >= desc.MipLevels) { log_once("view starts past the texture's mips; first mip", int(view.first_mip)); return false; } // SRVs address an entire volume; only a UAV descriptor can specify a W range within its mip. const UINT layers = volume ? (storage ? std::max(1u, UINT(desc.DepthOrArraySize) >> view.first_mip) : 1u) : desc.DepthOrArraySize; if (view.first_layer >= layers) { log_once("view starts past the texture's mips or layers; first mip", int(view.first_mip)); return false; } const UINT remaining = layers - view.first_layer; const UINT layer_count = view.layer_count == ~0u ? remaining : view.layer_count; if (new_uav && (!layer_count || layer_count > remaining)) { log_once("unordered-access view slice count is outside the selected mip:", int(view.layer_count)); return false; } if (msaa && layer_count > remaining) { log_once("multisample shader view ends past the texture array; layers", int(view.layer_count)); return false; } if (!storage && view.mip_count != UINT_MAX && view.mip_count > UINT(desc.MipLevels) - view.first_mip) { log_once("shader view ends past the texture mips; mips", int(view.mip_count)); return false; } if (!storage && view.layer_count != UINT_MAX && view.layer_count > remaining) { log_once("shader view ends past the texture array; layers", int(view.layer_count)); return false; } out = {}; out.address = resource.image_address(); out.format = code; out.type = view.type; out.width = std::uint32_t(desc.Width); out.height = desc.Height; out.depth = volume ? desc.DepthOrArraySize : 1; out.samples = desc.SampleDesc.Count; out.first_mip = view.first_mip; out.mip_count = std::min(view.mip_count, desc.MipLevels - view.first_mip); if (volume) { if (storage && (view.first_layer != 0 || layer_count != layers)) slices = {view.first_layer, layer_count}; } else { out.first_layer = view.first_layer; out.layer_count = std::min(layer_count, remaining); } if (view.type == g::ImageType::cube) out.layer_count -= out.layer_count % 6; // whole cubes out.resource_mips = desc.MipLevels; out.min_lod = view.min_lod; if (!out.mip_count || !out.layer_count) { log_once("view of no mips or no layers; type", int(view.type)); return false; } // D3D12's component mapping picks, for each of R, G, B, A, a channel of the format or a constant; the T# // says the same about the hardware's channels, which the format places. // A stencil view's format has its eight bits in G and no R, B or A of its own (0, 0, 1 when read). // B8G8R8X8 has no alpha: a view in its family reads 1, and a B8G8R8A8 view of a B8G8R8X8 texture (through a // castable-format list) the stored byte. The view's format decides, as on WARP and AMD's D3D12 driver. // The T#'s format code is the same for both channel orders of a colour format (R8G8B8A8 and B8G8R8A8 are one // 8_8_8_8 code), and the image view keeps the image's format; a castable-format list may still ask for the other // order, so then the view's own format places the channels. Depth images keep their own format's channels. const bool other_order = view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane && !rgb96 && named != view_format && !g::is_depth_stencil_format(view_format); const VkFormat channels_format = rgb96 ? rgb96_named_format(view_format) : other_order ? named : view_format; g::Swizzle channels = g::format_swizzle(channels_format); if (stencil) channels = {g::select_zero, g::select_x, g::select_zero, g::select_one}; else if (desc.Format == DXGI_FORMAT_A8_UNORM) channels = {g::select_zero, g::select_zero, g::select_zero, g::select_x}; else if (alpha_unused(view.format != DXGI_FORMAT_UNKNOWN ? view.format : desc.Format)) channels[3] = g::select_one; for (UINT i = 0; i < 4; ++i) { const UINT from = D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(i, view.mapping); out.swizzle[i] = from < 4 ? channels[from] : from == D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0 ? g::select_zero : g::select_one; } return true; } // The S# of a D3D12 sampler. leonida::gfx10::Sampler sampler_descriptor(const D3D12_SAMPLER_DESC& desc, DeviceState* state = nullptr) { namespace g = leonida::gfx10; const auto address = [](D3D12_TEXTURE_ADDRESS_MODE mode) { switch (mode) { case D3D12_TEXTURE_ADDRESS_MODE_MIRROR: return g::AddressMode::mirror; case D3D12_TEXTURE_ADDRESS_MODE_CLAMP: return g::AddressMode::clamp_last_texel; case D3D12_TEXTURE_ADDRESS_MODE_BORDER: return g::AddressMode::clamp_border; case D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE: return g::AddressMode::mirror_once_last_texel; default: return g::AddressMode::wrap; } }; const bool anisotropic = D3D12_DECODE_IS_ANISOTROPIC_FILTER(desc.Filter); const auto filter = [&](D3D12_FILTER_TYPE type) { if (anisotropic) return type == D3D12_FILTER_TYPE_LINEAR ? g::Filter::aniso_bilinear : g::Filter::aniso_point; return type == D3D12_FILTER_TYPE_LINEAR ? g::Filter::bilinear : g::Filter::point; }; g::Sampler out{}; out.address_u = address(desc.AddressU); out.address_v = address(desc.AddressV); out.address_w = address(desc.AddressW); out.mag_filter = filter(D3D12_DECODE_MAG_FILTER(desc.Filter)); out.min_filter = filter(D3D12_DECODE_MIN_FILTER(desc.Filter)); out.mip_filter = D3D12_DECODE_MIP_FILTER(desc.Filter) == D3D12_FILTER_TYPE_LINEAR ? g::MipFilter::linear : g::MipFilter::point; out.max_anisotropy = anisotropic ? std::clamp(desc.MaxAnisotropy, 1, 16) : 1; const D3D12_FILTER_REDUCTION_TYPE reduction = D3D12_DECODE_FILTER_REDUCTION(desc.Filter); // D3D12's comparison functions are 1 (NEVER) to 8 (ALWAYS); the S#'s are 0 to 7 in the same order. if (reduction == D3D12_FILTER_REDUCTION_TYPE_COMPARISON && desc.ComparisonFunc >= D3D12_COMPARISON_FUNC_NEVER) out.compare = g::CompareFunction(desc.ComparisonFunc - D3D12_COMPARISON_FUNC_NEVER); out.compare_never = reduction == D3D12_FILTER_REDUCTION_TYPE_COMPARISON && desc.ComparisonFunc == D3D12_COMPARISON_FUNC_NEVER; if (reduction == D3D12_FILTER_REDUCTION_TYPE_MINIMUM) out.filter_mode = g::FilterMode::minimum; if (reduction == D3D12_FILTER_REDUCTION_TYPE_MAXIMUM) out.filter_mode = g::FilterMode::maximum; out.min_lod = desc.MinLOD; out.max_lod = desc.MaxLOD; out.lod_bias = desc.MipLODBias; const FLOAT* border = desc.BorderColor; const bool black = border[0] == 0 && border[1] == 0 && border[2] == 0; if (black && border[3] == 0) { out.border_color = g::BorderColor::transparent_black; } else if (black && border[3] == 1) { out.border_color = g::BorderColor::opaque_black; } else if (border[0] == 1 && border[1] == 1 && border[2] == 1 && border[3] == 1) { out.border_color = g::BorderColor::opaque_white; } else { out.border_color = g::BorderColor::table; if (state) out.border_color_index = state->register_border_color(false, border); } return out; } // A query heap: one VkQueryPool, registered with the context so that lists can resolve it by ID // (docs/d3d12_vulkan.md section 4.6). Occlusion heaps hold both OCCLUSION and BINARY_OCCLUSION queries; timestamp // and copy-queue timestamp heaps are timestamp pools; pipeline-statistics heaps count all eleven Vulkan // statistics, whose result order is the field order of D3D12_QUERY_DATA_PIPELINE_STATISTICS. Stream-output // statistics heaps have no pool: without stream output every such query is zero. class QueryHeap final : public Child { public: // {6e2b9a41-d83c-4f17-b5e9-0a7c3d1f8b62} static constexpr GUID kTag{0x6e2b9a41, 0xd83c, 0x4f17, {0xb5, 0xe9, 0x0a, 0x7c, 0x3d, 0x1f, 0x8b, 0x62}}; explicit QueryHeap(DeviceState& device) : device_(device) {} ~QueryHeap() override { if (!registered_) return; device_.context->remove_query_pool(id()); if (pool_) device_.context->vk.vkDestroyQueryPool(device_.info.device, pool_, nullptr); } leonida::QueryHeapId id() const { return query_heap_id(this); } HRESULT create(const D3D12_QUERY_HEAP_DESC& desc) { namespace h = leonida::d3d12_query_heap; auto& vk = device_.context->vk; if (!vk.vkCreateQueryPool || !vk.vkDestroyQueryPool) return E_NOTIMPL; VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; info.queryCount = desc.Count; switch (desc.Type) { case h::occlusion: info.queryType = VK_QUERY_TYPE_OCCLUSION; break; case h::timestamp: case h::copy_queue_timestamp: { const bool supported = desc.Type == D3D12_QUERY_HEAP_TYPE_COPY_QUEUE_TIMESTAMP ? device_.copy_timestamps_supported() : device_.context->timestamp_period() > 0; if (!supported) { log_once("timestamp query heap: the queue writes no timestamps; type", desc.Type); return E_NOTIMPL; } info.queryType = VK_QUERY_TYPE_TIMESTAMP; break; } case h::so_statistics: // D3D-302: with VK_EXT_transform_feedback enabled, an SO_STATISTICS heap is a real transform-feedback // pool whose queries begin/end on a stream (vkCmdBeginQueryIndexedEXT); a resolve copies 16 bytes per // query (NumPrimitivesWritten, PrimitivesStorageNeeded), in the same order. StreamOutput PSOs are still // refused and SOSetTargets is still not implemented, so no primitive reaches a stream yet and every // query counts 0. The pool needs the transformFeedbackQueries property and at least one stream; without // them (or without the feature) the heap is made without a pool and every query resolves to zero. if (!device_.info.transform_feedback || !device_.info.transform_feedback_queries || !device_.info.max_transform_feedback_streams) return register_pool(desc); info.queryType = VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT; break; case h::pipeline_statistics: if (!device_.info.pipeline_statistics_query) { log_once("pipeline-statistics query heap: pipelineStatisticsQuery not enabled; type", desc.Type); return E_NOTIMPL; } info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; info.pipelineStatistics = kPipelineStatistics; break; default: // Video decode and mesh-shader statistics (PIPELINE_STATISTICS1) have no path yet. log_once("query heap type not supported:", desc.Type); return E_NOTIMPL; } if (vk.vkCreateQueryPool(device_.info.device, &info, nullptr, &pool_) != VK_SUCCESS) { pool_ = VK_NULL_HANDLE; return E_OUTOFMEMORY; } return register_pool(desc); } private: HRESULT register_pool(const D3D12_QUERY_HEAP_DESC& desc) { leonida::QueryPool pool{}; pool.pool = pool_; pool.heap_type = desc.Type; pool.count = desc.Count; pool.precise = device_.info.occlusion_query_precise; pool.ended.assign(desc.Count, false); // D3D-302: a real transform-feedback pool queries streams below maxTransformFeedbackStreams; D3D12 has four. if (pool_ && desc.Type == leonida::d3d12_query_heap::so_statistics) pool.streams = std::min(4, device_.info.max_transform_feedback_streams); device_.context->add_query_pool(id(), pool); registered_ = true; return S_OK; } // VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT through COMPUTE_SHADER_INVOCATIONS_BIT (0x1-0x400): // IAVertices, IAPrimitives, VSInvocations, GSInvocations, GSPrimitives, CInvocations, CPrimitives, // PSInvocations, HSInvocations (patches), DSInvocations, CSInvocations. static constexpr VkQueryPipelineStatisticFlags kPipelineStatistics = 0x7ff; static_assert(sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS) == 11 * sizeof(UINT64)); DeviceState& device_; VkQueryPool pool_ = VK_NULL_HANDLE; // null for a stream-output heap (no Vulkan query behind it) bool registered_ = false; // added to the context, so removed from it on destruction }; // The live devices whose session pipeline cache an ending process writes (save_pipeline_caches_at_exit). A title // never releases its device, so ~Device, the only other writer, does not run in a real boot: without this, a run that // ends (normally, at a console close or in a crash) keeps none of what it compiled. Timed, so a crash handler that // finds it held gives up instead of hanging the process. std::timed_mutex exit_cache_mutex; std::vector exit_cache_devices; std::atomic exit_cache_saved{false}; // VK_EXT_memory_budget read from a device's info: the reader a device publishes for the title HUD and the dev overlay // (src/memory_figures.h), and vulkan_vram_budget. Not available without the extension. leonida::VramBudget read_vram_budget(const VulkanDeviceInfo& info) { if (!info.memory_budget || !info.get_instance_proc || !info.instance) return {}; const auto get = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceMemoryProperties2")); return leonida::query_vram_budget(get, info.physical); } // The Vulkan objects create_vulkan_device_standalone made, destroyed with the device. struct OwnedRuntime { PFN_vkDestroyDevice destroy_device = nullptr; PFN_vkDestroyInstance destroy_instance = nullptr; VkDevice device = VK_NULL_HANDLE; VkInstance instance = VK_NULL_HANDLE; }; class Device final : public Object { public: // {c58e1d27-3a96-4b4f-9e72-6d0a8b5f3c61} static constexpr GUID kTag{0xc58e1d27, 0x3a96, 0x4b4f, {0x9e, 0x72, 0x6d, 0x0a, 0x8b, 0x5f, 0x3c, 0x61}}; explicit Device(const VulkanDeviceInfo& info) { // Every Vulkan device serves Xbox device slot 133, whichever entry made it: create_vulkan_device and the // standalone device gta6rt --run uses both come through here (found in review: registering only in // create_vulkan_device left the retail path without it). rt::d3d12_xs::set_placed_at_va_handler(&create_buffer_at_host_address); rt::d3d12_xs::set_console_descriptor_heap_handler(&rt::d3d12::create_console_descriptor_heap); // A queued pipeline build holds its PipelineState, which holds the device: a reference count read while the // worker still has a warm-up to run is one too high. The proxy's count waits for the pool. rt::d3d12_xs::set_reference_settler([] { PipelineCompiler::instance().wait_idle(); }); state_.info = info; { std::lock_guard lock(exit_cache_mutex); exit_cache_devices.push_back(&state_); } // The GPU memory figure of the title HUD and the dev overlay: the newest device with VK_EXT_memory_budget. if (info.memory_budget) leonida::memory_figures::publish_vram_reader( [](const void* context) { return read_vram_budget(static_cast(context)->info); }, &state_); queue_users_.resize(info.command_queues.size(), 0); compute_users_.resize(info.compute_queues.size(), 0); copy_users_.resize(info.copy_queues.size(), 0); for (std::uint32_t f : {info.queue_family, info.compute_family, info.copy_family}) if (f != UINT32_MAX && std::find(state_.families.begin(), state_.families.end(), f) == state_.families.end()) state_.families.push_back(f); // LEONIDA_AFTERMATH: every function table loaded through it (the context's, the helpers' own) creates its // shader modules through the wrapper that maps Aftermath shader hashes to names (src/vulkan_aftermath.h). const auto get_device = leonida::aftermath::wrap_get_device_proc_addr(reinterpret_cast( info.get_instance_proc(info.instance, "vkGetDeviceProcAddr"))); state_.format_properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties")); state_.format_properties2 = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties2")); state_.image_format_properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties")); state_.image_format_properties2 = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties2")); if (!state_.image_format_properties2) { state_.image_format_properties2 = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties2KHR")); } const auto memory_properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceMemoryProperties")); const auto device_properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties")); const auto queue_families = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceQueueFamilyProperties")); if (!get_device || !state_.format_properties || !state_.image_format_properties || !memory_properties || !device_properties || !queue_families) return; state_.r9g9b9e5_uav_emulated = state_.probe_uint_backed_uav(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, VK_FORMAT_R32_UINT); state_.b5g5r5a1_uav_emulated = state_.probe_uint_backed_uav(VK_FORMAT_A1R5G5B5_UNORM_PACK16, VK_FORMAT_R16_UINT); state_.rgba8_srgb_uav_emulated = state_.probe_uint_backed_uav(VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_R8G8B8A8_UNORM); state_.bgra8_srgb_uav_emulated = state_.probe_uint_backed_uav(VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_B8G8R8A8_UNORM); { // The console's D16S8 family (pc_format): as D24S8 where the GPU has that format, as itself where not. const char* asked = std::getenv("LEONIDA_CONSOLE_D16S8"); const bool d24 = state_.depth_usable(VK_FORMAT_D24_UNORM_S8_UINT); const bool native = asked && std::strcmp(asked, "native") == 0 ? true : asked && std::strcmp(asked, "d24") == 0 ? false : !d24; g_console_d16s8_native.store(native, std::memory_order_relaxed); static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) std::fprintf(stderr, "[rt] d3d12: console D16S8 textures are %s (D24_UNORM_S8_UINT attachments: %s, " "D16_UNORM_S8_UINT: %s%s)\n", native ? "kept as D16+S8" : "made as D24S8", d24 ? "yes" : "no", state_.depth_usable(VK_FORMAT_D16_UNORM_S8_UINT) ? "yes" : "no", asked ? ", LEONIDA_CONSOLE_D16S8 set" : ""); } if (console_format_stand_ins()) { state_.r9g9b9e5_target_stand_in = !state_.color_attachment_usable(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32) && state_.color_attachment_usable(VK_FORMAT_B10G11R11_UFLOAT_PACK32) && state_.storage_usable(VK_FORMAT_B10G11R11_UFLOAT_PACK32) && state_.sampled_usable(VK_FORMAT_B10G11R11_UFLOAT_PACK32); std::fprintf(stderr, "[rt] d3d12: console format stand-ins: R9G9B9E5 target as R11G11B10F %d, sRGB UAV as UNORM " "rgba %d bgra %d\n", int(state_.r9g9b9e5_target_stand_in), int(state_.rgba8_srgb_uav_emulated), int(state_.bgra8_srgb_uav_emulated)); } memory_properties(info.physical, &state_.memory); { char text[4] = {}; size_t length = 0; const bool sysmem = getenv_s(&length, text, "LEONIDA_UPLOAD_SYSMEM") == 0 && length > 1 && text[0] != '0'; state_.upload_in_vram = leonida::resizable_bar(state_.memory) && !sysmem; std::fprintf(stderr, "[rt] d3d12: upload heaps in %s\n", state_.upload_in_vram ? "VRAM (DEVICE_LOCAL | HOST_VISIBLE, Resizable BAR)" : sysmem ? "system memory (LEONIDA_UPLOAD_SYSMEM)" : "system memory (no Resizable BAR)"); } if (get_device) state_.bound_image_requirements = reinterpret_cast( get_device(info.device, "vkGetImageMemoryRequirements2")); for (const char* name : {"vkGetDeviceImageMemoryRequirements", "vkGetDeviceImageMemoryRequirementsKHR"}) if (!state_.image_requirements) state_.image_requirements = reinterpret_cast(get_device(info.device, name)); if (info.physical && info.get_instance_proc) { const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties")); if (get_props) { VkPhysicalDeviceProperties props{}; get_props(info.physical, &props); state_.pso_identity.vendor = props.vendorID; state_.pso_identity.device = props.deviceID; state_.pso_identity.driver = props.driverVersion; std::memcpy(state_.pso_identity.cache_uuid, props.pipelineCacheUUID, VK_UUID_SIZE); state_.load_prewarm_plan(); // first: the order log may append this run to the same file state_.start_order_log(); if (state_.info.max_push_constants_size == 0) { state_.info.max_push_constants_size = props.limits.maxPushConstantsSize; state_.info.push_constants_need_fallback = (state_.info.max_push_constants_size < 144); } state_.max_compute_shared_memory_size = props.limits.maxComputeSharedMemorySize; // The counts D3D12 offers with no outputs are the target-independent-rasterization ones: 1, 4, 8 // and 16 (ForcedSampleCount is 0, 1, 4, 8 or 16; DirectX-Specs VulkanOn12.md "Sample-frequency MSAA // with no render targets bound": a driver reports at least 0b11101). 2x is not one of them, though // framebufferNoAttachmentsSampleCounts has it on every GPU here; reporting it would offer a count the // PC runtime refuses (its hosts report 0x1d). constexpr VkSampleCountFlags kD3D12SampleCounts = VK_SAMPLE_COUNT_1_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_16_BIT; state_.no_output_sample_counts = static_cast(props.limits.framebufferNoAttachmentsSampleCounts & kD3D12SampleCounts); state_.f16_half_top_location = info.f16_half_top_location != 0 ? info.f16_half_top_location : leonida::f16_half_top_location( props.limits.maxVertexOutputComponents, props.limits.maxFragmentInputComponents); } if (const auto get_props2 = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2"))) { VkPhysicalDeviceDepthStencilResolveProperties resolve{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES}; VkPhysicalDeviceConservativeRasterizationPropertiesEXT conservative{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT}; if (info.conservative_rasterization) resolve.pNext = &conservative; VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &resolve}; get_props2(info.physical, &props); if (info.sample_locations) { VkPhysicalDeviceSampleLocationsPropertiesEXT locations{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT}; VkPhysicalDeviceProperties2 sample_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &locations}; get_props2(info.physical, &sample_props); const auto get_grid = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceMultisamplePropertiesEXT")); if (get_grid && props.properties.limits.standardSampleLocations && locations.variableSampleLocations && locations.sampleLocationSubPixelBits >= 4 && locations.sampleLocationCoordinateRange[0] <= 0 && locations.sampleLocationCoordinateRange[1] >= 15.f / 16) { for (unsigned samples = 1; samples <= 16; samples *= 2) { if (!leonida::SamplePositions::programmable_count(samples)) continue; if (!(locations.sampleLocationSampleCounts & samples)) continue; VkMultisamplePropertiesEXT grid{VK_STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT}; get_grid(info.physical, VkSampleCountFlagBits(samples), &grid); const auto extent = grid.maxSampleLocationGridSize; if (extent.width && extent.height) state_.sample_grid_1 |= samples; if (samples <= 4 && extent.width >= 2 && extent.height >= 2 && extent.width % 2 == 0 && extent.height % 2 == 0) state_.sample_grid_4 |= samples; } const auto counts = (props.properties.limits.framebufferColorSampleCounts | props.properties.limits.framebufferDepthSampleCounts | props.properties.limits.framebufferStencilSampleCounts | props.properties.limits.framebufferNoAttachmentsSampleCounts) & 31u; // Four repeating pixels can name at most sixteen sample locations altogether. // Only multisampled counts take programmable positions (1x is kept out of the grids above). const auto multisample_counts = counts & ~VkSampleCountFlags(VK_SAMPLE_COUNT_1_BIT); const auto grid_counts = multisample_counts & (VK_SAMPLE_COUNT_2_BIT | VK_SAMPLE_COUNT_4_BIT); const auto tier1_counts = counts & (VK_SAMPLE_COUNT_2_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_8_BIT); if (multisample_counts && (state_.sample_grid_1 & multisample_counts) == multisample_counts && (state_.sample_grid_4 & grid_counts) == grid_counts) state_.sample_positions_tier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_2; else if (tier1_counts && (state_.sample_grid_1 & tier1_counts) == tier1_counts) state_.sample_positions_tier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_1; } } state_.conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER(leonida::conservative_raster::tier( info.conservative_rasterization, props.properties.limits.subPixelPrecisionBits, conservative.primitiveOverestimationSize, conservative.degenerateTrianglesRasterized == VK_TRUE, conservative.fullyCoveredFragmentShaderInputVariable == VK_TRUE, info.inner_coverage_abi)); state_.conservative_post_depth_coverage = conservative.conservativeRasterizationPostDepthCoverage == VK_TRUE; state_.depth_resolve_modes = resolve.supportedDepthResolveModes; state_.stencil_resolve_modes = resolve.supportedStencilResolveModes; const leonida::ArenaLimits limits = leonida::query_arena_limits(get_props2, info.physical); if (!state_.info.max_buffer_size) state_.info.max_buffer_size = limits.max_buffer_size; if (!state_.info.max_memory_allocation_size) state_.info.max_memory_allocation_size = limits.max_allocation_size; } } const leonida::GraphicsIndirectCapabilities indirect{ .first_instance = info.draw_indirect_first_instance, .multiple = info.multi_draw_indirect, .count_buffer = info.draw_indirect_count_enabled, .max_count = info.max_draw_indirect_count, .robust_index_view = info.robust_index_view, .require_clamp = leonida::indirect_clamp_enabled()}; // Before the context: its SubmitMutex takes the gate's mode and limits when it is made. decide_auto_compile_gate(info, get_device, state_.pso_identity); state_.context = std::make_unique(get_device, info.device, info.separate_depth_stencil_layouts, info.conditional_rendering, info.ray_tracing, info.xdxr_acceleration_structures && info.buffer_device_address, indirect); if (info.device_fault_diagnostics) { state_.context->configure_device_fault(get_device, {info.device_fault_info, info.device_checkpoints, info.device_diagnostics_config, info.device_markers}, &state_.memory); state_.context->add_diagnostic_queue(info.queue); for (auto queue : info.command_queues) state_.context->add_diagnostic_queue(queue); for (auto queue : info.compute_queues) state_.context->add_diagnostic_queue(queue); for (auto queue : info.copy_queues) state_.context->add_diagnostic_queue(queue); } leonida::mem_probe::install(state_.context->vk); // LOCAL DIAGNOSTIC: before anything allocates if (info.device_fault_diagnostics && rt::compute_probe::enabled()) { state_.context->set_input_probe([this](auto lists, auto sequence, auto queue) { rt::compute_probe::inspect(state_, lists, sequence, queue); }); if (auto* fault = state_.context->device_fault()) fault->set_lost_hook([this] { rt::compute_probe::recheck(state_); }); } state_.setup_console_heap_gpu(get_device); // LEONIDA_CONSOLE_HEAP_GPU: the context's prelude state_.context->set_on_enqueue_execute([this] { return state_.geometry.execute_enqueue(); }); state_.context->set_on_finish_execute([this](std::uint64_t serial) { if (serial) { state_.geometry.execute_end(serial, [this] { return state_.context->submitted_retire_ticket(); }); state_.stamp_retired_windows(); } }); state_.context->set_on_buffer_write_submitted([this](std::uint64_t ticket) { state_.promote_passive_title_writes(ticket); }); state_.context->set_after_execute([this] { state_.end_execute_write_back(); }); // Cross-queue single-flight visibility coalescer for before_execute_(): // Only one queue worker at a time runs the global refresh sequence (eliminating page_mirror.mutex <-> // console_heap_mutex <-> title_texture_mutex lock convoys across Direct + 4 Compute queues), and any // concurrent or back-to-back submission whose required visibility epoch `req_seq` (captured at enqueue time // and updated on any queue/CPU fence Signal) was already covered by a refresh pass that STARTED at // `pass_seq >= req_seq` skips the redundant global refresh completely while keeping begin/end_execute_write_back // paired for every submission. Disable with LEONIDA_BEFORE_EXECUTE_COALESCE=0. struct BeforeExecuteCoalescer { std::mutex mutex; std::condition_variable cv; bool in_flight = false; std::uint64_t completed_seq = 0; std::uint64_t ran = 0; std::uint64_t coalesced = 0; std::uint64_t wait_count = 0; std::uint64_t wait_ns = 0; std::uint64_t wb_ns = 0; std::uint64_t mirror_ns = 0; std::uint64_t shadows_ns = 0; std::uint64_t flush_ns = 0; std::uint64_t tex_ns = 0; std::atomic feed_drains{0}; std::atomic feed_drain_ns{0}; std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now(); }; auto before_coalescer = std::make_shared(); state_.context->set_before_execute([this, coalescer = std::move(before_coalescer)] { state_.begin_execute_write_back(); static thread_local bool t_in_before_execute = false; // trivially destructible (no TLS callback) if (t_in_before_execute) return; struct ReentryGuard { bool& flag; explicit ReentryGuard(bool& f) noexcept : flag(f) { flag = true; } ~ReentryGuard() { flag = false; } } reentry_guard{t_in_before_execute}; namespace phases = leonida::submit_phases; // LEONIDA_REFRESH_PER_FRAME (for runs that only need the title to go on): 1 = the slot-133 shadows, title // windows and geometry copies are brought up to date only by the first submission after each present, // not by every one of the ~24 submissions of a title frame (speed-18: ~30 ms of them a submission, one // title frame a second); 2 = the console heaps too. A GPU read of them is then up to a frame behind the // title's writes: wrong pixels, nothing the title waits for (the copies are one way). 0 (default): all // at every submission, as before. static const int per_frame = [] { const char* v = std::getenv("LEONIDA_REFRESH_PER_FRAME"); return v && *v ? std::atoi(v) : 0; }(); static const bool coalesce_enabled = [] { const char* v = std::getenv("LEONIDA_BEFORE_EXECUTE_COALESCE"); return !(v && v[0] == '0' && v[1] == '\0'); }(); const std::uint64_t req_seq = leonida::VulkanContext::current_before_execute_seq(); const bool use_coalesce = coalesce_enabled && !per_frame && req_seq != 0; std::uint64_t pass_seq = 0; struct LeaderGuard { BeforeExecuteCoalescer* c = nullptr; std::uint64_t pass_seq = 0; std::uint64_t wb_ns = 0; std::uint64_t mirror_ns = 0; std::uint64_t shadows_ns = 0; std::uint64_t flush_ns = 0; std::uint64_t tex_ns = 0; bool completed = false; ~LeaderGuard() { if (!c) return; bool log = false; std::uint64_t ran = 0, coalesced = 0, waits = 0, wait_ns = 0; std::uint64_t s_wb = 0, s_mirror = 0, s_shadows = 0, s_flush = 0, s_tex = 0; std::uint64_t fd_cnt = 0, fd_ns = 0; double secs = 0.0; { std::lock_guard lock(c->mutex); if (completed && pass_seq > c->completed_seq) c->completed_seq = pass_seq; ++c->ran; c->wb_ns += wb_ns; c->mirror_ns += mirror_ns; c->shadows_ns += shadows_ns; c->flush_ns += flush_ns; c->tex_ns += tex_ns; c->in_flight = false; const auto now = std::chrono::steady_clock::now(); secs = std::chrono::duration(now - c->since).count(); if (secs >= 10.0 && c->ran > 0) { ran = c->ran; coalesced = c->coalesced; waits = c->wait_count; wait_ns = c->wait_ns; s_wb = c->wb_ns; s_mirror = c->mirror_ns; s_shadows = c->shadows_ns; s_flush = c->flush_ns; s_tex = c->tex_ns; fd_cnt = c->feed_drains.exchange(0, std::memory_order_relaxed); fd_ns = c->feed_drain_ns.exchange(0, std::memory_order_relaxed); c->ran = c->coalesced = c->wait_count = c->wait_ns = 0; c->wb_ns = c->mirror_ns = c->shadows_ns = c->flush_ns = c->tex_ns = 0; c->since = now; log = true; } } c->cv.notify_all(); if (log) { const std::uint64_t total = ran + coalesced; const double inv_ran = ran ? 1e-6 / double(ran) : 0.0; const double sum_ms = double(s_wb + s_mirror + s_shadows + s_flush + s_tex) * inv_ran; std::fprintf(stderr, "[rt] before-execute: %llu ran, %llu coalesced (%.0f%% skipped) in %.1f s; " "%llu single-flight waits (%.2f ms avg); %llu feed-only drains (%.2f ms avg); " "leader avg %.2f ms (wb %.2f, mirror %.2f, shadows %.2f, flush %.2f, tex %.2f)\n", static_cast(ran), static_cast(coalesced), total ? 100.0 * double(coalesced) / double(total) : 0.0, secs, static_cast(waits), waits ? double(wait_ns) * 1e-6 / double(waits) : 0.0, static_cast(fd_cnt), fd_cnt ? double(fd_ns) * 1e-6 / double(fd_cnt) : 0.0, sum_ms, double(s_wb) * inv_ran, double(s_mirror) * inv_ran, double(s_shadows) * inv_ran, double(s_flush) * inv_ran, double(s_tex) * inv_ran); } } } leader_guard{}; if (use_coalesce) { std::unique_lock lock(coalescer->mutex); while (coalescer->in_flight && coalescer->completed_seq < req_seq) { const std::int64_t wait_start = phases::now_ns(); coalescer->cv.wait(lock, [&] { return !coalescer->in_flight || coalescer->completed_seq >= req_seq; }); const std::uint64_t waited = std::uint64_t(phases::now_ns() - wait_start); phases::add_part(phases::part_lock_wait, waited); ++coalescer->wait_count; coalescer->wait_ns += waited; } if (coalescer->completed_seq >= req_seq) { ++coalescer->coalesced; lock.unlock(); const std::int64_t fd0 = phases::now_ns(); if (state_.drain_page_mirror_feed_only()) { const std::uint64_t fd_ns = std::uint64_t((std::max)(std::int64_t(0), phases::now_ns() - fd0)); coalescer->feed_drains.fetch_add(1, std::memory_order_relaxed); coalescer->feed_drain_ns.fetch_add(fd_ns, std::memory_order_relaxed); } return; } coalescer->in_flight = true; leader_guard.c = coalescer.get(); leader_guard.pass_seq = req_seq; } const std::int64_t t0 = phases::now_ns(); std::int64_t t1 = t0, t2 = t0; std::uint64_t mirror_serial = 0; { const phases::Scope timed(phases::shadows); // First, while pending_ sparse binds are empty and before any map()/upload() mutates homes or agreed // sums: copy retired GPU writes back to their physical frames. state_.write_back_titles(); t1 = phases::now_ns(); if (use_coalesce) { // Acquire current visibility epoch AFTER write_back_titles() and immediately BEFORE // refresh_page_mirror() so batches enqueued during write_back_titles() coalesce into this single // pass. pass_seq = (std::max)(req_seq, state_.context->current_visibility_seq()); leader_guard.pass_seq = pass_seq; } mirror_serial = leonida::geometry_writes::state().serial.load(std::memory_order_acquire); state_.refresh_page_mirror(); // what this submission's title-written addresses read t2 = phases::now_ns(); } // Flush sparse binds and run title texture refresh immediately after refresh_page_mirror() so concurrent // xmem remaps during refresh_shadows()/geometry.refresh() do not force in_feed CPU fallbacks, and so // newly-published streamed textures bind on the same submission in refresh_shadows() below. { const phases::Scope timed(phases::shadows); state_.flush_page_mirror(); } const std::int64_t t_flush1 = phases::now_ns(); { const phases::Scope timed(phases::textures); refresh_title_textures(/*mirror_just_synced=*/true, mirror_serial); } const std::int64_t t_tex1 = phases::now_ns(); bool full = true; if (per_frame) { const std::uint64_t serial = phases::totals().present_serial.load(std::memory_order_relaxed); full = refreshed_present_.exchange(serial, std::memory_order_relaxed) != serial; } state_.drain_geometry_releases(); state_.reclaim_retired_windows(); state_.reclaim_arena(); state_.refresh_shadows(full || per_frame < 2, full); state_.retire_orphan_windows(); // LEONIDA_GEOMETRY_ASYNC=1 (for runs that only need the title to go on): the geometry copies are brought // up to date on a worker of ours, started here and not waited for, instead of on the title's GPU submit // thread (speed-27: 230-330 ms a refresh after the load, a VirtualQuery and VirtualProtect per written // tile under Wine). A draw may then read a copy the worker is still writing: wrong vertices for a frame. static const bool geometry_async = [] { const char* v = std::getenv("LEONIDA_GEOMETRY_ASYNC"); return v && std::strcmp(v, "1") == 0; }(); if (full && geometry_async) { kick_geometry_refresh(); } else if (full) { const phases::Scope timed(phases::geometry); state_.geometry.refresh(DeviceState::copy_geometry); } // Last, once the heap refresh, the windows and the geometry copies have made what this submission reads. state_.update_address_guard(); const std::int64_t t_shadows = phases::now_ns(); // Mandatory 2nd O(1) flush for any plain-page sparse binds added by finish_in_place() -> fix_vsharp(). { const phases::Scope timed(phases::shadows); state_.flush_page_mirror(); } const std::int64_t t_flush2 = phases::now_ns(); std::uint64_t tex2_ns = 0; // Mandatory trailing texture refresh only if refresh_shadows() newly named a first-time slot-133 texture. if (state_.titles_named_pending.load(std::memory_order_acquire)) { const std::int64_t t_tex2_start = phases::now_ns(); { const phases::Scope timed(phases::textures); refresh_title_textures(/*mirror_just_synced=*/true, mirror_serial); } tex2_ns = std::uint64_t(phases::now_ns() - t_tex2_start); } leader_guard.wb_ns = std::uint64_t(t1 - t0); leader_guard.mirror_ns = std::uint64_t(t2 - t1); leader_guard.shadows_ns = std::uint64_t(t_shadows - t_tex1); leader_guard.flush_ns = std::uint64_t(t_flush1 - t2) + std::uint64_t(t_flush2 - t_shadows); leader_guard.tex_ns = std::uint64_t(t_tex1 - t_flush1) + tex2_ns; leader_guard.completed = true; }); { char text[16] = {}; size_t length = 0; if (getenv_s(&length, text, "LEONIDA_TITLE_WINDOWS_MB") == 0 && length > 1) state_.title_window_cap = std::strtoull(text, nullptr, 10) << 20; } leonida::title_va_aliases().set_buffer_maker(this, [](void* device, std::uint64_t va, std::uint64_t bytes) { static_cast*>(device)->make_title_buffer(va, bytes); }); { char text[32] = {}; size_t length = 0; const bool present = getenv_s(&length, text, "LEONIDA_PIPELINE_THREADS") == 0 && length > 1; const auto threads = leonida::pipeline_threads(present ? text : "", std::thread::hardware_concurrency()); if (!threads.valid) std::fprintf(stderr, "[rt] d3d12: LEONIDA_PIPELINE_THREADS=%s is not a number; using %u\n", text, threads.count); if (present) { if (threads.count) state_.context->set_pipeline_workers(std::make_unique(threads.count)); } else { // Default (LEONIDA_PIPELINE_THREADS unset): fan out batch-parallel synchronous pipeline compiles // concurrently onto PipelineCompiler::instance() worker threads (with work-stealing on the calling // thread and deadlock-free RAII fallback if PipelineCompiler::closed() or cancel()/stop_for_exit() // races), avoiding an extra idle thread pool while giving full multi-core cold-compile scaling. state_.context->set_batch_compile_runner( [device_key = static_cast(&state_)](std::size_t count, const std::function& job) { if (!count) return; auto& compiler = PipelineCompiler::instance(); if (count == 1 || compiler.closed() || compiler.has_job_probe()) { for (std::size_t i = 0; i < count; ++i) job(i); return; } struct BatchState { std::atomic next{0}; std::size_t count = 0; const std::function* job = nullptr; std::vector owner_tags; std::mutex mutex; std::condition_variable cv; std::size_t pending_helpers = 0; std::exception_ptr error{}; std::size_t error_index = SIZE_MAX; }; auto run_work = [](BatchState& s) { for (;;) { const std::size_t i = s.next.fetch_add(1, std::memory_order_relaxed); if (i >= s.count) break; try { (*s.job)(i); } catch (...) { std::lock_guard lock(s.mutex); if (!s.error || i < s.error_index) { s.error = std::current_exception(); s.error_index = i; } } } }; struct HelperDone { std::shared_ptr state; explicit HelperDone(std::shared_ptr s) : state(std::move(s)) { std::lock_guard lock(state->mutex); ++state->pending_helpers; } ~HelperDone() { if (!state) return; std::lock_guard lock(state->mutex); if (--state->pending_helpers == 0) state->cv.notify_all(); } }; auto state = std::make_shared(); state->count = count; state->job = &job; const std::size_t helpers = (std::min)(count - 1, std::size_t(leonida::PipelineWorkers::kMaxThreads)); state->owner_tags.resize(helpers, 0); { struct WaitHelpers { PipelineCompiler& compiler; std::shared_ptr state; std::size_t submitted_helpers = 0; ~WaitHelpers() { // Drop any unstarted helper lambdas immediately so we never stall behind unrelated // long compiles in PipelineCompiler::jobs_; only wait on helpers already running // a job from this batch. for (std::size_t k = 0; k < submitted_helpers; ++k) compiler.cancel(&state->owner_tags[k]); std::unique_lock lock(state->mutex); state->cv.wait(lock, [&] { return state->pending_helpers == 0; }); } } wait_guard{compiler, state, 0}; for (std::size_t k = 0; k < helpers; ++k) { auto done = std::make_shared(state); const bool queued = compiler.submit( &state->owner_tags[k], device_key, 0, [done = std::move(done), run_work] { run_work(*done->state); }, /*graphics=*/true, /*large=*/false); if (!queued) break; ++wait_guard.submitted_helpers; } run_work(*state); } if (state->error) std::rethrow_exception(state->error); }); } if (big_compiles() == BigCompiles::budget) state_.context->set_large_compiles( [] { return big_compile_gate().budget(); }, [] { return std::make_shared(big_compile_gate()); }); } leonida::title_va_aliases().set_hooks( &state_, [](void* device, std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { return static_cast(device)->resolve_title_memory(va, bytes, out); }, [](void* device, std::uint64_t table, std::uint32_t descriptors) { static_cast(device)->scan_title_table(table, descriptors); }); leonida::title_va_aliases().set_noter([](void* device, std::uint64_t va, std::uint64_t bytes) { static_cast(device)->note_title_write(va, bytes); }); // Every device, hooks or not: its console heaps' slot records follow the alias table's changes. leonida::title_va_aliases().add_listener(&state_, &DeviceState::alias_changed); state_.image_memory = std::make_unique( [device = info.device, make = state_.context->vk.vkAllocateMemory](std::uint32_t type, std::uint64_t bytes) { VkMemoryAllocateInfo block{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; block.allocationSize = bytes; block.memoryTypeIndex = type; VkDeviceMemory out = VK_NULL_HANDLE; leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::image_blocks); return make(device, &block, nullptr, &out) == VK_SUCCESS ? out : VkDeviceMemory(VK_NULL_HANDLE); }, [device = info.device, free = state_.context->vk.vkFreeMemory](VkDeviceMemory block) { free(device, block, nullptr); }); state_.context->mesh_queries = info.mesh_shader_queries; state_.context->set_cpu_texture_publisher([this]{return state_.publish_mapped_textures();}); state_.context->set_sample_table_resolver([this](std::uint64_t address, std::uint32_t slots) { return state_.materialize_table(address, slots); }); state_.context->set_table_scanner([this](std::uint64_t table, std::uint32_t descriptors) { state_.scan_title_table(table, descriptors); }); state_.context->set_graphics_family(info.queue_family); #ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME if (info.maintenance10 && info.physical) { const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties2")); if (get_props) { const auto aspects = [&](VkFormat format) { VkFormatProperties3 props{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; VkFormatProperties2 query{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &props}; get_props(info.physical, format, &query); VkImageAspectFlags mask = 0; if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_2_DEPTH_COPY_ON_COMPUTE_QUEUE_BIT_KHR) mask |= VK_IMAGE_ASPECT_DEPTH_BIT; if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_2_STENCIL_COPY_ON_COMPUTE_QUEUE_BIT_KHR) mask |= VK_IMAGE_ASPECT_STENCIL_BIT; return mask; }; state_.context->set_compute_copy_aspects( [d16 = aspects(VK_FORMAT_D16_UNORM), ds = aspects(VK_FORMAT_D32_SFLOAT_S8_UINT)](VkFormat format) { if (format == VK_FORMAT_D16_UNORM) return d16; if (format == VK_FORMAT_D32_SFLOAT_S8_UINT) return ds; return VkImageAspectFlags{}; }); } } #endif state_.context->set_depth_range_unrestricted(info.depth_range_unrestricted); state_.context->set_store_op_none(info.store_op_none); // The console's value writes (list slots 71 and 72) at an arena offset land in the arena // (src/value_write_sink.h): the list values' pump and the GPU-label path ask this device before any host store. leonida::value_sink::set_arena( [](void* device, std::uint64_t address, const void* bytes, unsigned size) { return static_cast(device)->write_arena_value(address, bytes, size); }, &state_); if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { VkFormatProperties properties{}; get_props(physical, format, &properties); return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0; }); } { VkDriverId driver_id = VkDriverId(0); if (info.physical && info.get_instance_proc) { const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties")); const auto get_props2 = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2")); VkPhysicalDeviceProperties base_props{}; if (get_props) get_props(info.physical, &base_props); if (base_props.apiVersion >= VK_API_VERSION_1_2 && get_props2) { VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES}; VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver}; get_props2(info.physical, &props); driver_id = driver.driverID; } } state_.sparse_unbind_zero_page = leonida::sparse_unbind_needs_zero_page(driver_id, std::getenv("LEONIDA_SPARSE_UNBIND_ZERO_PAGE")); } if (info.buffer_device_address && state_.context->loaded() && !create_arena()) std::fprintf(stderr, "[rt] d3d12: the GPU address arena could not be created\n"); { // LOCAL DIAGNOSTIC: mem probe (LEONIDA_MEM_PROBE=) leonida::mem_probe::DeviceFacts facts; facts.memory = state_.memory; facts.title_ranges = [] { return leonida::title_va_aliases().title_memory_ranges(); }; facts.describe = [this] { state_.geometry.report(); DeviceState& d = state_; // The driver serializes the whole cache to answer the size: only on request (LEONIDA_MEM_PROBE_CACHE=1). std::size_t cache = 0; static const bool ask_cache = [] { wchar_t value[2]{}; return GetEnvironmentVariableW(L"LEONIDA_MEM_PROBE_CACHE", value, 2) == 1 && value[0] == L'1'; }(); const VkPipelineCache handle = d.pipeline_cache_handle; if (ask_cache && handle && d.context->vk.vkGetPipelineCacheData) d.context->vk.vkGetPipelineCacheData(d.info.device, handle, &cache, nullptr); std::uint64_t title = 0, title_ranges = 0; for (const auto& [begin, end] : leonida::title_va_aliases().title_memory_ranges()) { title += end - begin; ++title_ranges; } std::uint64_t shadows = 0; { std::lock_guard lock(d.shadow_mutex); shadows = d.shadows.size(); } VkDeviceSize in_use = 0, peak = 0, use[DeviceState::arena_use_count] = {}; { std::lock_guard lock(d.arena.mutex); in_use = d.arena.in_use; peak = d.arena.peak_end; for (int i = 0; i < DeviceState::arena_use_count; ++i) use[i] = d.arena.use_in_use[i]; } char text[512]; std::snprintf(text, sizeof text, "pipeline cache %.0f MiB; arena %.0f MiB (type %u), in use %.0f MiB (buffer %.0f, " "descriptor heap %.0f, shader %.0f, heap %.0f, windows/shadows %.0f), peak end %.0f MiB; " "title memory %llu ranges %.0f MiB reserved/committed VA; shadows %llu; fsdraw pipeline " "notes %zu", leonida::mem_probe::mib(cache), leonida::mem_probe::mib(d.arena.size), d.arena.memory_type, leonida::mem_probe::mib(in_use), leonida::mem_probe::mib(use[0]), leonida::mem_probe::mib(use[1]), leonida::mem_probe::mib(use[2]), leonida::mem_probe::mib(use[3]), leonida::mem_probe::mib(use[DeviceState::arena_window]), leonida::mem_probe::mib(peak), (unsigned long long)title_ranges, leonida::mem_probe::mib(title), (unsigned long long)shadows, leonida::fsdraw::pipeline_count()); return std::string(text); }; facts.share = [this] { leonida::memory_breakdown::DeviceShare share; DeviceState& d = state_; if (d.arena.buffer) { share.arena = true; std::lock_guard lock(d.arena.mutex); share.arena_reserved = d.arena.size; share.arena_bound = d.arena.backing.stats().bound; share.arena_in_use = d.arena.in_use; for (std::size_t i = 0; i < share.arena_use.size(); ++i) share.arena_use[i] = d.arena.use_in_use[i]; share.arena_windows = d.arena.use_in_use[DeviceState::arena_window]; } if (d.page_mirror.mirror) { std::lock_guard held(d.page_mirror.mutex); const auto c = d.page_mirror.mirror->counters(); share.mirror = true; share.mirror_homes = c.homes; share.mirror_pages = c.pages; share.mirror_chunks = c.chunks; share.mirror_units_local = d.page_mirror.units_local; share.mirror_units_host = d.page_mirror.units_host; } std::lock_guard lock(d.descriptor_mutex); // the bindless set's lock (ExecuteCommandLists' flush) if (const auto* bindless = d.bindless.get()) share.bindless_table_bytes = bindless->table_buffer_bytes(); return share; }; leonida::mem_probe::start(std::move(facts)); } if (info.conditional_rendering) { const auto properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties")); const auto families = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceQueueFamilyProperties")); if (properties && families) { VkPhysicalDeviceProperties limits{}; properties(info.physical, &limits); std::uint32_t count = 0; families(info.physical, &count, nullptr); std::vector queues(count); families(info.physical, &count, queues.data()); if (info.copy_family < count && !(queues[info.copy_family].queueFlags & VK_QUEUE_COMPUTE_BIT)) state_.context->set_transfer_only_family(info.copy_family); if (info.queue_family < count && (queues[info.queue_family].queueFlags & VK_QUEUE_COMPUTE_BIT)) { state_.context->configure_predication(get_device, state_.memory, limits.limits.maxStorageBufferRange, info.queue_family); if (info.storage_buffer_8bit) state_.context->configure_predicated_copy(get_device, limits.limits); } } } if (info.host_image_copy) load_host_image_copy(get_device); if (info.host_pointer_alignment) state_.get_host_pointer_properties = reinterpret_cast( get_device(info.device, "vkGetMemoryHostPointerPropertiesEXT")); // Depth <-> colour copies are staged through scratch buffers (vulkan_scratch.h), on every GPU. With buffer // device addresses the same scratch holds the triangle indices of indexed quad lists (quad_index_expand.h): // a compute pass writes them through the chunk's address and the draw binds the chunk as its index buffer. const bool index_scratch = info.buffer_device_address; const VkBufferUsageFlags scratch_extra = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (index_scratch ? VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0); state_.context->enable_copy_scratch( get_device, [this, index_scratch](const VkMemoryRequirements& requirements) { leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::staging); return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, index_scratch); }, scratch_extra, state_.families); if (info.buffer_device_address && info.physical && info.get_instance_proc) { if (const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { VkPhysicalDeviceProperties props{}; get_props(info.physical, &props); state_.context->configure_counted_dispatch(get_device, state_.memory, props.limits); state_.context->configure_quad_indices(get_device, props.limits); // ExecuteIndirect arguments are clamped on the GPU before every indirect command (vulkan_indirect_clamp.h). // Its record scratch is device-local memory with a device address, like the arena's. state_.context->enable_indirect_clamp(get_device, state_.memory, props.limits, [this](const VkMemoryRequirements& requirements) { return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, /*device_address=*/true); }, state_.families); } } // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h), and so do the copies of // a 96-bit texture, which every GPU stores as RGBA32 (D3D-62): the converter is there whether or not the // GPU has a native D24_UNORM_S8_UINT. It costs nothing until a copy needs it (its pipeline is made on the // first job, and a queue takes the tracker lock for it only when a list has such a copy). { std::uint64_t max_storage_range = 1u << 27; // the least Vulkan allows, if the limit cannot be read if (info.physical && info.get_instance_proc) { if (const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { VkPhysicalDeviceProperties props{}; get_props(info.physical, &props); max_storage_range = props.limits.maxStorageBufferRange; } } state_.context->enable_depth24(get_device, [this](const VkMemoryRequirements& requirements) { return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); }, max_storage_range); } if (info.bindless && state_.context->loaded() && !create_bindless(get_device)) std::fprintf(stderr, "[rt] d3d12: the bindless set 0 could not be created\n"); query_luid_and_clock(get_device); // Timestamps: the device's timestampPeriod, enabled when the graphics family (info.queue_family) has // timestampValidBits. VkPhysicalDeviceProperties properties{}; device_properties(info.physical, &properties); state_.max_sampler_lod_bias = properties.limits.maxSamplerLodBias; std::uint32_t family_count = 0; queue_families(info.physical, &family_count, nullptr); std::vector families(family_count); queue_families(info.physical, &family_count, families.data()); state_.timestamp_bits.reserve(family_count); for (std::uint32_t i = 0; i < family_count; ++i) { // Timestamp writes alone can work on a transfer-only family. Resetting the query and resolving it // with vkCmdCopyQueryPoolResults require a graphics- or compute-capable family as well. const auto& family = families[i]; const bool can_resolve = (family.queueFlags & (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT)) != 0; state_.timestamp_bits.push_back(can_resolve ? family.timestampValidBits : 0); } state_.context->set_timestamp_bits(state_.timestamp_bits); // the queues LEONIDA_GPU_PROFILE can time if (info.queue_family < family_count) { const auto& family = families[info.queue_family]; if (family.timestampValidBits) state_.context->set_timestamp_period(properties.limits.timestampPeriod); // MoltenVK (1.4.2 and 1.4.3 measured) resolves a timestamp before the write that precedes it lands, unless // something orders the two (docs/d3d12_vulkan.md section 4.6). const auto get_props2 = reinterpret_cast( info.get_instance_proc ? info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2") : nullptr); if (family.timestampValidBits && get_props2) { VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES}; VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver}; get_props2(info.physical, &props); if (driver.driverID == VK_DRIVER_ID_MOLTENVK) { state_.context->set_order_timestamp_copies(true); log_once("timestamp resolves wait for the timestamps before them (MoltenVK); driver", int(driver.driverID)); } } if (family.queueFlags & VK_QUEUE_COMPUTE_BIT) state_.context->set_occlusion_resolve_memory(state_.memory); } if (info.debug_utils) { leonida::DebugLabelFunctions labels; const auto load = [&](auto& f, const char* name) { f = reinterpret_cast>(info.get_instance_proc(info.instance, name)); }; load(labels.cmd_insert, "vkCmdInsertDebugUtilsLabelEXT"); load(labels.cmd_begin, "vkCmdBeginDebugUtilsLabelEXT"); load(labels.cmd_end, "vkCmdEndDebugUtilsLabelEXT"); load(labels.queue_insert, "vkQueueInsertDebugUtilsLabelEXT"); load(labels.queue_begin, "vkQueueBeginDebugUtilsLabelEXT"); load(labels.queue_end, "vkQueueEndDebugUtilsLabelEXT"); state_.context->enable_debug_labels(labels); if (!state_.context->debug_labels()) std::fprintf(stderr, "[rt] d3d12: VK_EXT_debug_utils entry points missing; debug markers are off\n"); } const bool sparse_aliasing = state_.context->vk.vkQueueBindSparse && leonida::supports_sparse_tile_aliasing(info.features, properties.sparseProperties) && info.queue_family < family_count && (families[info.queue_family].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT); state_.sparse_image_tiles = sparse_aliasing && info.features.sparseResidencyImage2D && state_.context->vk.vkGetImageSparseMemoryRequirements; if (sparse_aliasing && state_.arena_ready() && info.features.sparseResidencyBuffer) { auto& vk = state_.context->vk; const auto sparse_info = state_.sparse_buffer_info(leonida::tile_size_in_bytes); VkBuffer sample = VK_NULL_HANDLE; if (vk.vkCreateBuffer(info.device, &sparse_info, nullptr, &sample) == VK_SUCCESS) { VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(info.device, sample, &requirements); vk.vkDestroyBuffer(info.device, sample, nullptr); if (!(leonida::tile_size_in_bytes % requirements.alignment)) state_.sparse_buffer_memory_types = requirements.memoryTypeBits; } } state_.create_page_mirror(sparse_aliasing && info.features.sparseResidencyBuffer); // Eagerly seed the shared Vulkan pipeline cache while device setup is still single-threaded so the // 800+ MiB vkCreatePipelineCache load never races with concurrent slot 57/67 pipeline creation under Wine. if (state_.context && state_.context->loaded() && !compile_helper::build_host) state_.pipeline_cache(); } // Set 0 of every translated shader that declares bindings: images, samplers and the descriptor hash table // (docs section 3.4). Each ExecuteCommandLists brings it up to date before its commands are written. bool create_bindless(PFN_vkGetDeviceProcAddr get_device) { leonida::BindlessFeatures features{}; features.update_after_bind = true; // VulkanDeviceInfo::bindless promises it features.partially_bound = state_.info.bindless_partially_bound; features.null_descriptor = state_.info.null_descriptor; features.shader_image_int64_atomics = state_.info.shader_image_int64_atomics; // The descriptor-table hash kind every shader of this device probes with, chosen once here, before the table's // first key: each loaded module's index.json meta may say `descriptor_hash` (descriptor_table.h), and when the // library mixes kinds the majority wins; LEONIDA_DESCRIPTOR_HASH overrides. The module index is read here // rather than at the first pipeline so the choice is fixed before any descriptor can be registered. leonida::DescriptorHashCensus hash_modules{}; leonida::DescriptorHashKind descriptor_hash = leonida::DescriptorHashKind::fnv1a; if (const leonida::ShaderLibrary* library = state_.library()) { hash_modules = library->descriptor_hash_census(); descriptor_hash = library->descriptor_hash_kind(); } leonida::DescriptorHashKind override_kind = descriptor_hash; if (leonida::descriptor_hash_kind_from_env(std::getenv("LEONIDA_DESCRIPTOR_HASH"), &override_kind)) { std::fprintf(stderr, "[rt] d3d12: descriptor hash: %s (LEONIDA_DESCRIPTOR_HASH; %zu fnv1a_fmix32 / %zu fnv1a " "modules)\n", leonida::descriptor_hash_kind_name(override_kind), hash_modules.fnv1a_fmix32, hash_modules.fnv1a); descriptor_hash = override_kind; } else if (hash_modules.fnv1a_fmix32 && hash_modules.fnv1a) { std::fprintf(stderr, "[rt] d3d12: descriptor hash: %zu fnv1a_fmix32 / %zu fnv1a modules; using %s\n", hash_modules.fnv1a_fmix32, hash_modules.fnv1a, leonida::descriptor_hash_kind_name(descriptor_hash)); } else { std::fprintf(stderr, "[rt] d3d12: descriptor hash: %s (all %zu modules)\n", leonida::descriptor_hash_kind_name(descriptor_hash), hash_modules.total()); } // Which entry layout the loaded modules read (descriptor_table.h): a tagged module reads the kind word next to // each index and uses it to tell which array that index is bound in (a 3D T# read by a 2D op is not another // image), and the inserts below fill it. A plain library reads only the index, exactly as before. The kind // word is additive, so one tagged module needs the tagged layout whatever the plain count (the library's // vote); chosen once here, like the hash kind, and LEONIDA_DESCRIPTOR_TABLE overrides. leonida::DescriptorTableCensus table_modules{}; leonida::DescriptorTableLayout descriptor_table = leonida::DescriptorTableLayout::tagged; if (const leonida::ShaderLibrary* library = state_.library()) { table_modules = library->descriptor_table_census(); if (table_modules.total() > 0) descriptor_table = library->descriptor_table_layout(); } leonida::DescriptorTableLayout override_table = descriptor_table; if (leonida::descriptor_table_layout_from_env(std::getenv("LEONIDA_DESCRIPTOR_TABLE"), &override_table)) { std::fprintf(stderr, "[rt] d3d12: descriptor table: %s (LEONIDA_DESCRIPTOR_TABLE; %zu tagged / %zu plain modules)\n", leonida::descriptor_table_layout_name(override_table), table_modules.tagged, table_modules.plain); descriptor_table = override_table; // Under a plain table a tagged module reads no kind at all, so every image an instruction reads through // another dimension's array takes that array's fallback. That is what the override asks for; say so. if (override_table == leonida::DescriptorTableLayout::plain && table_modules.tagged) std::fprintf(stderr, "[rt] d3d12: LEONIDA_DESCRIPTOR_TABLE forces the plain descriptor table while %zu " "module(s) read the kind word; their image lookups through another dimension's array " "take the fallback\n", table_modules.tagged); } else if (table_modules.tagged && table_modules.plain) { std::fprintf(stderr, "[rt] d3d12: descriptor table: %zu tagged / %zu plain modules; using %s\n", table_modules.tagged, table_modules.plain, leonida::descriptor_table_layout_name(descriptor_table)); } else { std::fprintf(stderr, "[rt] d3d12: descriptor table: %s (all %zu modules)\n", leonida::descriptor_table_layout_name(descriptor_table), table_modules.total()); } state_.descriptor_table_tagged = descriptor_table == leonida::DescriptorTableLayout::tagged; // Whether the loaded modules read a T#'s index from its dword 6 (shader_library.h, TsharpIndexCensus): one such // module needs the word in every heap. Older modules find heap T#s by their words in the hash table, which the // word changes, so a library with both kinds is reported: its older modules read the fallback for those T#s. if (const leonida::ShaderLibrary* library = state_.library()) { const leonida::TsharpIndexCensus& census = library->tsharp_index_census(); state_.tsharp_index_words = census.dword6 > 0; if (census.dword6 && census.none) std::fprintf(stderr, "[rt] d3d12: T# index word: %zu modules read it, %zu older ones look heap T#s up in the " "hash table and miss them (the heaps carry the word); translate the library again\n", census.dword6, census.none); else std::fprintf(stderr, "[rt] d3d12: T# index word: %s (all %zu modules)\n", census.dword6 ? "written into the heaps' T#s" : "not read", census.total()); const leonida::WritesBufferCensus& wb_census = library->writes_buffer_census(); std::fprintf(stderr, "[rt] d3d12: writes_buffer metadata: %s (%zu of %zu modules)\n", wb_census.all_present() ? "gating passive mirror write-back" : "incomplete (conservative write-back)", wb_census.present, wb_census.total()); } const auto get_properties = reinterpret_cast( state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); if (get_properties) { VkPhysicalDeviceVulkan12Properties indexed{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES}; VkPhysicalDeviceVulkan11Properties v11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES, &indexed}; VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &v11}; get_properties(state_.info.physical, &properties); features.ms_samples = {VK_SAMPLE_COUNT_4_BIT, state_.ms_fallback_samples(VK_FORMAT_R32_UINT), state_.ms_fallback_samples(VK_FORMAT_R32_SINT)}; // Past maxPerSetDescriptors, ask the driver about the grown layout (D3D-219: Intel's Xe-LP reports 6159). const auto layout_support = reinterpret_cast( get_device(state_.info.device, "vkGetDescriptorSetLayoutSupport")); std::function layout_supported; // MoltenVK's vkGetDescriptorSetLayoutSupport compares every layout with maxPerSetDescriptors (1212, the // limit without argument buffers) and rejects even 1212 itself, while it creates and samples a 65536-image, // 4096-sampler update-after-bind set correctly (docs/d3d12_vulkan.md section 5). There size_bindings' // per-type update-after-bind limits, which MoltenVK takes from Metal's argument-buffer limits, decide. VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES}; VkPhysicalDeviceProperties2 driver_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver}; get_properties(state_.info.physical, &driver_properties); if (driver.driverID == VK_DRIVER_ID_MOLTENVK) layout_supported = [](const leonida::BindlessFeatures&) { return true; }; else if (layout_support) layout_supported = [&](const leonida::BindlessFeatures& candidate) { const leonida::bindless::SetLayout layout(candidate); VkDescriptorSetLayoutSupport support{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT}; layout_support(state_.info.device, &layout.info, &support); return support.supported == VK_TRUE; }; if (!leonida::bindless::size_bindings(features, properties.properties.limits, v11, indexed, layout_supported)) std::fprintf(stderr, "[rt] d3d12: the device's descriptor limits are below the bindless set's default " "sizes; it holds less\n"); } namespace b = leonida::bindless; std::fprintf(stderr, "[rt] d3d12: bindless set: %u 2D images, %u samplers, %u 2D-array, %u 3D, %u 1D, " "%u storage indices in 2D%s\n", features.counts[b::sampled_binding(leonida::ImageDimension::dim_2d)], features.counts[b::sampler_binding], features.counts[b::sampled_binding(leonida::ImageDimension::dim_2d_array)], features.counts[b::sampled_binding(leonida::ImageDimension::dim_3d)], features.counts[b::sampled_binding(leonida::ImageDimension::dim_1d)], features.counts[b::storage_binding(leonida::ImageDimension::dim_2d, 0)], features.shader_image_int64_atomics ? ", r64ui binding 29 enabled" : ""); std::fprintf(stderr, "[rt] d3d12: bindless table policy: spare generations, host-memory fallback, a degraded " "flush instead of a refused submission\n"); // D3D12 promises a shader holds a full shader-visible sampler heap. Past this many distinct S#s, CreateSampler // logs that the array is full and a shader reads the fallback (clamping) sampler. if (features.counts[b::sampler_binding] < D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE + 1) std::fprintf(stderr, "[rt] d3d12: the bindless set holds fewer samplers than a full shader-visible " "sampler heap (%u of %u besides the fallback): its limits or " "vkGetDescriptorSetLayoutSupport allow no more\n", features.counts[b::sampler_binding] - 1, unsigned(D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE)); state_.bindless = std::make_unique(get_device, state_.info.device, state_.memory, features, descriptor_hash, state_.families); if (!state_.bindless->ok() || !state_.context->vk.vkCreateSampler) { state_.bindless.reset(); return false; } state_.context->set_bindless_release( [](void* user, std::uint32_t dim, std::uint32_t idx) { auto* st = static_cast(user); bool notify_room = false; { std::lock_guard lock(st->descriptor_mutex); if (st->bindless) { const auto dimension = static_cast(dim); const bool check_2d_mirror = dimension != leonida::ImageDimension::dim_2d; const bool was_sampled_full = st->bindless->free_images(dimension) == 0; const bool was_storage_full = st->bindless->storage_capacity(dimension) > 0 && st->bindless->free_storage_images(dimension) == 0; const bool was_2d_sampled_full = check_2d_mirror && st->bindless->free_images(leonida::ImageDimension::dim_2d) == 0; const bool was_2d_storage_full = check_2d_mirror && st->bindless->storage_capacity(leonida::ImageDimension::dim_2d) > 0 && st->bindless->free_storage_images(leonida::ImageDimension::dim_2d) == 0; st->bindless->remove_image(dimension, idx); notify_room = (was_sampled_full && st->bindless->free_images(dimension) > 0) || (was_storage_full && st->bindless->free_storage_images(dimension) > 0) || (was_2d_sampled_full && st->bindless->free_images(leonida::ImageDimension::dim_2d) > 0) || (was_2d_storage_full && st->bindless->free_storage_images(leonida::ImageDimension::dim_2d) > 0); } } if (notify_room) st->note_slot_change(leonida::SlotChange::texture_room, 0, 1); }, &state_); state_.context->set_bindless_prepare([this](VkCommandBuffer command_buffer) { if (!state_.bindless->needs_prepare()) return true; std::unique_lock lock(state_.descriptor_mutex); if (!state_.bindless->needs_prepare()) return true; if (!state_.bindless->fallbacks_ready()) state_.bindless->record_fallback_init(command_buffer); auto& context = *state_.context; if (state_.bindless_legacy_idle && state_.bindless->flush_replaces_table()) { // The wait of before D3D-314, kept for comparing frame times: nothing that uses the set still runs // after it, so the generations flush() retires are free at once. { std::lock_guard submit(context.submit_mutex()); const leonida::SubmitMutex::SubmitTurn turn(context.submit_mutex(), false); // the compile gate context.observe_result(context.vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle"); } state_.bindless_idle_waits.fetch_add(1, std::memory_order_relaxed); state_.bindless->release_retired(); } else if (state_.bindless->has_retired()) { // Generations of the table that an earlier flush replaced: free those whose submissions are done. // Nothing waits; the rest stay for a later submit. completed_retire_ticket() takes submit_mutex_, // which comes after the resource, tracker and descriptor locks held here. state_.bindless->release_retired(context.completed_retire_ticket()); // A queue whose work is stalled (a fence only the CPU signals, long async work) keeps its ticket from // completing, and each replacing flush adds a generation. Past the cap wait, once the oldest is in the // way, for the submissions up to its ticket (the queues' timelines, not the device), with the // descriptor lock released: the thread that signals such a fence may need it. constexpr std::size_t max_retired = 8; if (state_.bindless->retired_count() > max_retired) { if (!state_.bindless_cap_logged.exchange(true)) std::fprintf(stderr, "[rt] d3d12: more than %zu retired bindless table generations: waiting " "for the queues that still use the oldest\n", max_retired); const std::uint64_t oldest = state_.bindless->oldest_retired_ticket(); lock.unlock(); const std::uint64_t completed = context.wait_retire_ticket(oldest); lock.lock(); state_.bindless->release_retired(completed); } } // Under tracker_mutex_ (held from here to the submit) no other ExecuteCommandLists has recorded work that // is not yet submitted, so every submission that can have bound the set being replaced has a ticket up to // the one read here. // A generation that cannot be made (VRAM full) does not fail the submission: the set frees what completed // and retries, rewrites the table in place when nothing runs, or keeps the previous table (vulkan_bindless.h). auto& set = *state_.bindless; const std::uint64_t host_fallbacks = set.table_host_fallbacks(); const std::uint32_t free_before_flush = set.total_free_images(); const bool flushed = set.flush(command_buffer, context.submitted_retire_ticket(), [&context] { return context.completed_retire_ticket(); }); const bool freed_by_flush = flushed && set.total_free_images() > free_before_flush; if (flushed && set.last_flush_replaced()) context.note_bindless_upload(); const auto table_state = [&] { return std::to_string(set.table().size()) + " of " + std::to_string(set.table().capacity()) + " slots used, " + std::to_string(set.table_buffer_bytes() / 1024) + " KiB in " + (set.table_in_device_local_memory() ? "device-local" : "host") + " memory; " + std::to_string(set.generations_made()) + " generations made, " + std::to_string(set.retired_count()) + " retired, " + std::to_string(set.spare_count()) + " spare, " + std::to_string(set.spares_reused()) + " reused; " + state_.bindless_diag_summary_locked(); }; if (set.table_buffer_bytes() != state_.bindless_logged_table_bytes) { state_.bindless_logged_table_bytes = set.table_buffer_bytes(); std::fprintf(stderr, "[rt] d3d12: bindless table: %s\n", table_state().c_str()); } if (set.table_host_fallbacks() != host_fallbacks && !state_.bindless_host_logged) { state_.bindless_host_logged = true; std::fprintf(stderr, "[rt] d3d12: bindless table buffer placed in host memory: device-local memory " "is full (%s)\n", table_state().c_str()); } if (set.last_flush_degraded()) { // Logged at the first and each power of two: how often it happens without flooding the log. const std::uint64_t n = set.degraded_flushes(); if ((n & (n - 1)) == 0) std::fprintf(stderr, "[rt] d3d12: bindless table generation not made (%s: %d), %llu times: the " "batch runs with the previous table, keys added since read the fallback " "(%s)\n", set.last_failure() ? set.last_failure() : "?", int(set.last_failure_result()), static_cast(n), table_state().c_str()); } lock.unlock(); if (freed_by_flush) state_.note_slot_change(leonida::SlotChange::texture_room, 0, 1); return flushed; }); state_.context->set_bindless_current([this]() { return state_.bindless ? state_.bindless->current_set() : VK_NULL_HANDLE; }); { char text[8] = {}; size_t length = 0; state_.bindless_legacy_idle = getenv_s(&length, text, "LEONIDA_BINDLESS_IDLE_WAIT") == 0 && length > 1 && text[0] != '0'; } state_.context->set_bindless_commit([this](bool submitted) { if (!state_.bindless || !state_.bindless->needs_commit()) return; std::lock_guard lock(state_.descriptor_mutex); if (state_.bindless) state_.bindless->table_upload_result(submitted); }); return true; } // LEONIDA_ARENA_MB sets its size (default 256, at most 4095, and no more than the device's maxBufferSize and // maxMemoryAllocationSize allow: src/arena_size.h): it holds every default-heap buffer, shader-visible // descriptor heap and shader program. M0-M3 keep it host-visible (section 3.3, memory type policy). bool create_arena() { auto& vk = state_.context->vk; if (!vk.vkGetBufferDeviceAddress) return false; char text[16] = {}; size_t length = 0; bool set = getenv_s(&length, text, "LEONIDA_ARENA_MB") == 0 && length > 1; // A value the CRT's copy of the environment does not give (or one past this buffer): asked of Windows too, // then report the size applied to the arena. if (!set) { const DWORD n = GetEnvironmentVariableA("LEONIDA_ARENA_MB", text, sizeof(text)); set = n > 0 && n < sizeof(text); if (set) std::fprintf(stderr, "[rt] d3d12: LEONIDA_ARENA_MB was read from the process environment, not the CRT's\n"); } // A sparse buffer where the device can bind one on a queue of its own (src/arena_backing.h): memory is then // bound in blocks as allocations need it, and maxMemoryAllocationSize bounds a block, not the arena. A device // without it, or whose sparse address space is smaller than the arena (llvmpipe: 2 GiB), keeps one // allocation behind the whole arena, reached through the same accessors. // // Every buffer outside the arena that a shader reaches (geometry copies, title windows and shadows outside it, // upload and readback buffers) is named by its device address minus heap_base, in a V#'s 48 bits and in root // views. A driver may place a sparse buffer anywhere relative to ordinary ones: RADV gives sparse buffers a // range of their own 64 TiB above them (Mesa 26.3.1: 0xffffc00100200000 against 0xffff800100010000), so with a // sparse arena every other buffer has a negative offset. Shaders that sign-extend the 48-bit base reach it // (every address RADV hands out lies in one 2^47 half of the 48-bit space, so any two are within 2^47 of // each other); older ones, which zero-extend, do not. So the arena is sparse only when every loaded module // sign-extends (VsharpBaseCensus), and each block outside it is checked against that range when it is made. leonida::VsharpBaseCensus bases{}; if (const leonida::ShaderLibrary* library = state_.library()) bases = library->vsharp_base_census(); g_pack_signed_vsharp_offsets.store(bases.signed_offsets(), std::memory_order_relaxed); std::fprintf(stderr, "[rt] d3d12: V# bases: %s offsets from heap_base (%zu of %zu modules sign-extend)%s\n", signed_vsharp_offsets() ? "signed" : "unsigned", bases.sign_extended, bases.total(), import_below_arena() && !bases.signed_offsets() ? " (LEONIDA_IMPORT_BELOW_ARENA)" : ""); const bool sparse_capable = state_.info.arena_bind_queue && state_.info.features.sparseBinding && state_.info.features.sparseResidencyBuffer && state_.info.residency_non_resident_strict && vk.vkQueueBindSparse; state_.arena_sparse_capable = sparse_capable; if (sparse_capable && !signed_vsharp_offsets()) std::fprintf(stderr, "[rt] d3d12: GPU address arena: one allocation, not sparse: %zu of the %zu loaded " "modules read a V# base unsigned, so no buffer may lie below the arena (translate the " "shaders again to bind the arena's memory as it is used)\n", bases.zero_extended, bases.total()); const leonida::ArenaLimits sparse_limits{state_.info.max_buffer_size, 0}; bool sparse = sparse_capable && signed_vsharp_offsets() && leonida::decide_arena_size(set ? text : nullptr, sparse_limits).bytes <= state_.info.sparse_address_space; leonida::ArenaLimits limits = sparse ? sparse_limits : leonida::ArenaLimits{state_.info.max_buffer_size, state_.info.max_memory_allocation_size}; leonida::ArenaSize size = leonida::decide_arena_size(set ? text : nullptr, limits); auto& arena = state_.arena; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = size.bytes; if (sparse) info.flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT | // A D3D12 heap in the arena lends its blocks' memory to reserved resources' tiles too. (state_.info.features.sparseResidencyAliased ? VK_BUFFER_CREATE_SPARSE_ALIASED_BIT : 0); info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; // Default-heap buffers live here, and any of them can be a SetPredication buffer. if (state_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; // With ray tracing, AS result, scratch and build-input buffers are default-heap ranges of the arena. if (state_.info.ray_tracing) info.usage |= VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; state_.share(info); VkMemoryRequirements requirements{}; const auto create_buffer = [&] { if (info.size <= kArenaReserved || vk.vkCreateBuffer(state_.info.device, &info, nullptr, &arena.buffer) != VK_SUCCESS) { arena.buffer = VK_NULL_HANDLE; return false; } vk.vkGetBufferMemoryRequirements(state_.info.device, arena.buffer, &requirements); arena.indirect_arguments = (info.usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) != 0; return true; }; if (!create_buffer()) return false; // The arena must stay host-visible and coherent (CPU writes/reads of V#s, descriptor tables, uploads and // arena fallbacks). Drivers such as NVIDIA Vulkan restrict sparse buffers to DEVICE_LOCAL-only memory types: // when the sparse buffer's memoryTypeBits excludes every HOST_VISIBLE | HOST_COHERENT type, fall back to a // single non-sparse allocation rather than failing the first sparse block bind. if (sparse) { bool has_host_coherent = false; for (std::uint32_t t = 0; t < state_.memory.memoryTypeCount; ++t) { if ((requirements.memoryTypeBits >> t & 1u) && (state_.memory.memoryTypes[t].propertyFlags & leonida::kArenaRequiredMemory) == leonida::kArenaRequiredMemory) { has_host_coherent = true; break; } } if (!has_host_coherent) { std::fprintf(stderr, "[rt] d3d12: GPU address arena: one allocation, not sparse: sparse buffers on this " "device expose no host-visible coherent memory type (memoryTypeBits=0x%x)\n", requirements.memoryTypeBits); vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); arena.buffer = VK_NULL_HANDLE; sparse = false; state_.arena_sparse_capable = false; limits = leonida::ArenaLimits{state_.info.max_buffer_size, state_.info.max_memory_allocation_size}; size = leonida::decide_arena_size(set ? text : nullptr, limits); info.flags = 0; info.size = size.bytes; if (!create_buffer()) return false; } } // The allocation is requirements.size, which alignment can make larger than the buffer: past // maxMemoryAllocationSize, make the buffer smaller by that much once. if (limits.max_allocation_size && requirements.size > limits.max_allocation_size) { vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); size = leonida::decide_arena_size(set ? text : nullptr, limits, requirements.size - info.size); info.size = size.bytes; if (!create_buffer()) return false; if (requirements.size > limits.max_allocation_size) { vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); arena.buffer = VK_NULL_HANDLE; return false; } } // RT-ARENA-DEVICE-LOCAL-STAGED: LEONIDA_DEVICE_LOCAL_ARENA=auto|1|0. char stage_env[16] = {}; const DWORD stage_env_len = GetEnvironmentVariableA("LEONIDA_DEVICE_LOCAL_ARENA", stage_env, sizeof(stage_env)); const char* stage_arg = (stage_env_len > 0 && stage_env_len < sizeof(stage_env)) ? stage_env : nullptr; const leonida::ArenaStagingMode stage_mode = leonida::parse_arena_staging_mode(stage_arg); // With Resizable BAR, keep the arena where its buffer may still use DEVICE_LOCAL | HOST_VISIBLE memory // A large buffer can exclude that type, or require more bytes than its heap can hold. (A sparse arena's memory // comes in blocks, which any heap holds.) Skip shrinking when LEONIDA_DEVICE_LOCAL_ARENA=1 forces staging. if (!sparse && stage_mode != leonida::ArenaStagingMode::force && leonida::resizable_bar(state_.memory)) { const VkDeviceSize asked = info.size; const VkDeviceSize fitted = leonida::device_local_arena_bytes(asked, [&](VkDeviceSize bytes) { if (bytes == asked) return leonida::device_local_arena_fits(state_.memory, requirements); VkBufferCreateInfo probe = info; probe.size = bytes; VkBuffer buffer = VK_NULL_HANDLE; if (vk.vkCreateBuffer(state_.info.device, &probe, nullptr, &buffer) != VK_SUCCESS) return false; VkMemoryRequirements r{}; vk.vkGetBufferMemoryRequirements(state_.info.device, buffer, &r); vk.vkDestroyBuffer(state_.info.device, buffer, nullptr); return (!limits.max_allocation_size || r.size <= limits.max_allocation_size) && leonida::device_local_arena_fits(state_.memory, r); }); if (fitted != asked) { vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); info.size = fitted; if (!create_buffer()) return false; size.bytes = fitted; size.capped |= leonida::arena_cap_bar; } } if (size.capped) std::fprintf(stderr, "[rt] d3d12: GPU address arena: %llu MiB of the %llu MiB asked for, capped by the " "device's %s\n", static_cast(size.bytes >> 20), static_cast(size.requested >> 20), leonida::arena_cap_name(size.capped)); if (sparse) { arena.sparse_memory_types = requirements.memoryTypeBits; DeviceState* const st = &state_; leonida::ArenaBackingHooks hooks; if (state_.sparse_unbind_zero_page) { if (!state_.info.features.sparseResidencyAliased) { std::fprintf(stderr, "[rt] d3d12: sparse arena: zero-page unbind workaround requested but " "sparseResidencyAliased is unavailable; falling back to VK_NULL_HANDLE unbinds\n"); } else { const VkDeviceSize zero_bytes = std::max(64 * 1024, requirements.alignment); if (zero_bytes > leonida::kArenaBlockBytes || (leonida::kArenaBlockBytes % zero_bytes) != 0) { std::fprintf(stderr, "[rt] d3d12: sparse arena: sparse alignment %llu does not divide %llu-byte " "arena blocks; falling back to VK_NULL_HANDLE unbinds\n", static_cast(requirements.alignment), static_cast(leonida::kArenaBlockBytes)); } else { arena.zero_page = state_.allocate_sparse_zero_page(zero_bytes, requirements.memoryTypeBits, leonida::memory_breakdown::Consumer::arena); if (arena.zero_page) { hooks.zero_page = arena.zero_page; hooks.zero_page_bytes = zero_bytes; std::fprintf(stderr, "[rt] d3d12: sparse arena unbinds alias a %llu KiB zero page (cross-queue " "sparse unbind workaround)\n", static_cast(zero_bytes >> 10)); } else { std::fprintf(stderr, "[rt] d3d12: sparse arena: failed to allocate %llu KiB sparse unbind zero " "page (memoryTypeBits=0x%x); falling back to VK_NULL_HANDLE unbinds\n", static_cast(zero_bytes >> 10), requirements.memoryTypeBits); } } } } // A unit's memory: the arena's memory type (the first unit picks it, as the one allocation did), with a // device address, mapped once for its life. hooks.make = [st, requirements](VkDeviceSize bytes, VkDeviceMemory& memory, std::uint8_t*& host) { VkMemoryRequirements unit = requirements; unit.size = bytes; if (st->arena.memory_type_known) unit.memoryTypeBits &= 1u << st->arena.memory_type; std::uint32_t type = 0; { leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::arena); memory = st->allocate(unit, leonida::kArenaRequiredMemory, leonida::kArenaPreferredMemory, nullptr, true, &type); } void* mapped = nullptr; if (!memory) return false; if (st->context->vk.vkMapMemory(st->info.device, memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { st->context->vk.vkFreeMemory(st->info.device, memory, nullptr); memory = VK_NULL_HANDLE; return false; } host = static_cast(mapped); if (!st->arena.memory_type_known) { st->arena.memory_type = type; st->arena.memory_type_known = true; } return true; }; hooks.destroy = [st](VkDeviceMemory memory) { st->context->vk.vkFreeMemory(st->info.device, memory, nullptr); }; // On the arena's own queue, which nothing else uses (VulkanDeviceInfo::arena_bind_queue): idle means // this bind is done, so the range is bound (or unbound) before the allocation is handed out (or the // memory freed). Under the arena's lock, the only place binds are made, which is the queue's external // synchronisation. hooks.bind = [st](const VkSparseMemoryBind* binds, std::uint32_t count) { auto& f = st->context->vk; const VkSparseBufferMemoryBindInfo buffer_binds{st->arena.buffer, count, binds}; VkBindSparseInfo bind{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO}; bind.bufferBindCount = 1; bind.pBufferBinds = &buffer_binds; VkResult result = st->context->observe_result( f.vkQueueBindSparse(st->info.arena_bind_queue, 1, &bind, VK_NULL_HANDLE), "vkQueueBindSparse (arena)"); if (result == VK_SUCCESS) result = st->context->observe_result(f.vkQueueWaitIdle(st->info.arena_bind_queue), "vkQueueWaitIdle (arena binds)"); if (result == VK_ERROR_DEVICE_LOST) st->context->mark_device_lost(); return result == VK_SUCCESS; }; if (!arena.backing.init_sparse(info.size, leonida::kArenaBlockBytes, std::move(hooks))) { vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); if (arena.zero_page) vk.vkFreeMemory(state_.info.device, arena.zero_page, nullptr); arena.buffer = VK_NULL_HANDLE; arena.zero_page = VK_NULL_HANDLE; return false; } } else { void* mapped = nullptr; if (stage_mode != leonida::ArenaStagingMode::off) { VkBufferCreateInfo stage_info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; stage_info.size = info.size; stage_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; state_.share(stage_info); VkBuffer candidate_staging = VK_NULL_HANDLE; if (vk.vkCreateBuffer(state_.info.device, &stage_info, nullptr, &candidate_staging) == VK_SUCCESS) { VkMemoryRequirements stage_reqs{}; vk.vkGetBufferMemoryRequirements(state_.info.device, candidate_staging, &stage_reqs); const leonida::ArenaStagingDecision decision = leonida::decide_arena_staging(stage_arg, state_.memory, requirements, stage_reqs); if (decision.use_staged) { VkMemoryRequirements dev_reqs = requirements; dev_reqs.memoryTypeBits = 1u << decision.device_memory_type; VkMemoryRequirements host_reqs = stage_reqs; host_reqs.memoryTypeBits = 1u << decision.host_memory_type; { leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::arena); arena.memory = state_.allocate(dev_reqs, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, nullptr, true, &arena.memory_type); } { leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::upload); arena.staging_memory = arena.memory ? state_.allocate(host_reqs, leonida::kArenaRequiredMemory, 0, nullptr, false, &arena.staging_memory_type) : VK_NULL_HANDLE; } if (arena.memory && arena.staging_memory && vk.vkBindBufferMemory(state_.info.device, candidate_staging, arena.staging_memory, 0) == VK_SUCCESS && vk.vkMapMemory(state_.info.device, arena.staging_memory, 0, VK_WHOLE_SIZE, 0, &mapped) == VK_SUCCESS && vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) == VK_SUCCESS) { arena.staging_buffer = candidate_staging; candidate_staging = VK_NULL_HANDLE; arena.staged = true; arena.staging.init(info.size); } else { if (mapped && arena.staging_memory) vk.vkUnmapMemory(state_.info.device, arena.staging_memory); if (arena.staging_memory) vk.vkFreeMemory(state_.info.device, arena.staging_memory, nullptr); if (arena.memory) vk.vkFreeMemory(state_.info.device, arena.memory, nullptr); arena.staging_memory = VK_NULL_HANDLE; arena.memory = VK_NULL_HANDLE; mapped = nullptr; } } if (candidate_staging) vk.vkDestroyBuffer(state_.info.device, candidate_staging, nullptr); } } if (!arena.staged) { { leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::arena); arena.memory = state_.allocate(requirements, leonida::kArenaRequiredMemory, leonida::kArenaPreferredMemory, nullptr, true, &arena.memory_type); } if (!arena.memory || vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) != VK_SUCCESS || vk.vkMapMemory(state_.info.device, arena.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { // Without an arena every buffer keeps its own memory; a leftover handle would make them addressable // with heap base 0, so their VAs would be raw device addresses above 4 GiB. vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); if (arena.memory) vk.vkFreeMemory(state_.info.device, arena.memory, nullptr); arena.buffer = VK_NULL_HANDLE; arena.memory = VK_NULL_HANDLE; return false; } } arena.memory_type_known = true; arena.mapped = static_cast(mapped); arena.backing.init_fixed(info.size, arena.staged ? arena.staging_memory : arena.memory, arena.mapped); } if (arena.staged) { std::fprintf(stderr, "[rt] d3d12: GPU address arena: %llu MiB in DEVICE_LOCAL VRAM (type %u, heap %u) with " "HOST_VISIBLE staging mirror (type %u, heap %u) (LEONIDA_ARENA_MB %s, " "LEONIDA_DEVICE_LOCAL_ARENA %s)\n", static_cast(info.size >> 20), unsigned(arena.memory_type), unsigned(state_.memory.memoryTypes[arena.memory_type].heapIndex), unsigned(arena.staging_memory_type), unsigned(state_.memory.memoryTypes[arena.staging_memory_type].heapIndex), set ? text : "unset", stage_arg ? stage_arg : "auto"); } else { std::fprintf(stderr, "[rt] d3d12: GPU address arena: %llu MiB of address range (LEONIDA_ARENA_MB %s), %s\n", static_cast(info.size >> 20), set ? text : "unset", sparse ? "sparse: memory bound in 2 MiB blocks as allocations need it" : "one allocation behind all of it"); } // LEONIDA_ARENA_NULL_MB= (for compute-on boots): the first n MiB of the arena, at heap_base + 0, are zeroed // and never handed out, and the zero page and the quad indices move above them. A translated shader whose // address arithmetic starts from a null base (a scalar or flat load the translator does not bounds-check) // reads or writes there, not in a buffer of the title's or the shared zero page and quad indices, which sat // at offset 0 (world-start compute faults read heap_base + ~0 on both platforms). const VkDeviceSize null_bytes = [&] { char text[16] = {}; std::size_t n = 0; if (getenv_s(&n, text, "LEONIDA_ARENA_NULL_MB") != 0 || n <= 1) return VkDeviceSize(0); const VkDeviceSize bytes = VkDeviceSize(std::strtoull(text, nullptr, 10)) << 20; return bytes + kArenaReserved < info.size / 2 ? bytes : VkDeviceSize(0); }(); // The head of the arena (the null region, the zero page, the quad indices and the address guard's page), // which shaders read and nothing allocates: backed for the arena's life. const VkDeviceSize head = std::max(null_bytes + kArenaReserved, address_guard_enabled() ? leonida::address_guard::kGuardEnd : 0); std::uint8_t* head_host = nullptr; { std::lock_guard lock(arena.mutex); if (arena.backing.acquire(0, head, true)) head_host = arena.backing.host(0, head); } if (!head_host) { std::fprintf(stderr, "[rt] d3d12: GPU address arena: no memory for its first %llu KiB\n", static_cast(head >> 10)); arena.backing.clear(); vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); if (arena.memory) vk.vkFreeMemory(state_.info.device, arena.memory, nullptr); if (arena.zero_page) vk.vkFreeMemory(state_.info.device, arena.zero_page, nullptr); arena.buffer = VK_NULL_HANDLE; arena.memory = VK_NULL_HANDLE; arena.zero_page = VK_NULL_HANDLE; return false; } std::memset(head_host, 0, std::size_t(null_bytes + kZeroPage)); // the null region and the zero page { auto* indices = reinterpret_cast(head_host + null_bytes + kZeroPage); for (std::uint32_t i = 0; i < kQuadIndexCount; i += kQuadIndicesPerQuad) { const std::uint32_t base = i / kQuadIndicesPerQuad * 4; std::transform(leonida::quad_triangle_indices.begin(), leonida::quad_triangle_indices.end(), indices + i, [base](std::uint32_t index) { return base + index; }); } } state_.arena_mark_dirty(0, null_bytes + kArenaReserved); if (arena.staged) { state_.external_windows.set_staged(true); state_.context->set_arena_upload( [st = &state_](VkCommandBuffer cmd) -> bool { if (!st->arena.staged) return false; auto& vk = st->context->vk; bool any = false; if (st->arena.staging.drain(st->arena.last_upload)) { vk.vkCmdCopyBuffer(cmd, st->arena.staging_buffer, st->arena.buffer, static_cast(st->arena.last_upload.size()), st->arena.last_upload.data()); any = true; } if (st->external_windows.record_uploads(cmd, vk)) any = true; if (!any) return false; VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; vk.vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &barrier, 0, nullptr, 0, nullptr); return true; }, [st = &state_](bool submitted) { if (!st->arena.last_upload.empty()) { if (!submitted) st->arena.staging.requeue(st->arena.last_upload); st->arena.last_upload.clear(); } st->external_windows.commit_uploads(submitted); }); } if (null_bytes) std::fprintf(stderr, "[rt] d3d12: arena null region: the first %llu MiB at heap_base are zeroed and never " "allocated (LEONIDA_ARENA_NULL_MB)\n", static_cast(null_bytes >> 20)); VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = arena.buffer; arena.address = vk.vkGetBufferDeviceAddress(state_.info.device, &address); arena.size = info.size; // The GPU address arena is the console's address space: the title names it by offset, so the label path // has to find it (src/gpu_label_memory.h). Its address space starts at 0. A label store to it goes through // value_sink::arena (write_arena_value), which resolves the offset itself, so the region's allocation base is // only its identity: the arena's device address, not a host pointer. leonida::label::memory().track(0, static_cast(arena.size), static_cast(arena.address), true); { // Under the arena's lock: an insert rebalances the tree and rewrites child links, which a walk on // another thread must not see half done. std::lock_guard lock(arena.mutex); // LEONIDA_ADDRESS_GUARD: the guard header and sinks at [0x70000, 0x80000) are never handed out either // (inside the null region when there is one, else just past the quad indices). arena.first = head; arena.blocks.reset(arena.first, arena.size); char check[2] = {}; size_t check_length = 0; arena.check_all = getenv_s(&check_length, check, "LEONIDA_ARENA_CHECK") == 0 && check_length > 1 && check[0] != '0'; } arena.peak_end = arena.first; if (address_guard_enabled() && !state_.create_address_guard()) std::fprintf(stderr, "[rt] d3d12: LEONIDA_ADDRESS_GUARD=1 but the address guard could not be set up; " "guarded shaders check nothing\n"); char log[4] = {}; length = 0; arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; state_.context->set_heap_base(arena.address, arena.size); leonida::fsdraw::note_arena(&state_, arena.size, [st = &state_](std::uint64_t va, void* out, std::size_t n) { return st->arena.backing.with_host(va, n, [&](const std::uint8_t* host) { std::memcpy(out, host, n); }); }); leonida::fsdraw::backing_hook().store(&fsdraw_backing, std::memory_order_release); state_.context->set_zero_page(arena.buffer, null_bytes, kZeroPage); state_.context->set_quad_indices(arena.buffer, null_bytes + kZeroPage, kQuadIndexCount); // Copy only registered title data. Each immutable upload stays alive in the queue command slot // until that submission's timeline value completes; a large indexed frame cannot wrap over itself. state_.context->set_geometry_provider([st=&state_](std::uint64_t va,std::uint64_t bytes, leonida::VulkanContext::GeometryUpload& result) { if (!va || !bytes || bytes>UINTPTR_MAX-va || !st->arena_ready() || bytes>st->arena.size) return false; std::uint64_t lo{},hi{}; if (!leonida::title_va_aliases().title_memory(va,lo,hi) || bytes>hi-va) { return false; } for(std::uint64_t at=va;at(at),®ion,sizeof(region)) || region.State!=MEM_COMMIT || (region.Protect & (PAGE_NOACCESS|PAGE_GUARD)) || !(region.Protect & (PAGE_READONLY|PAGE_READWRITE|PAGE_WRITECOPY))) return false; at=reinterpret_cast(region.BaseAddress)+region.RegionSize; } struct Lease { DeviceState* state{}; VkDeviceSize offset{},bytes{}; ~Lease(){if(bytes)state->arena_release(offset,bytes,DeviceState::arena_buffer);} }; auto lease=std::make_shared(); if (!st->arena_allocate(bytes,256,lease->offset,DeviceState::arena_buffer)) return false; lease->state=st;lease->bytes=bytes; std::uint8_t* const host=st->arena_host(lease->offset,bytes); if (!host || !leonida::title_frames::for_each_part(std::uintptr_t(va), std::size_t(bytes), [&](std::uintptr_t at, std::size_t n, std::uint8_t* frame) { if (frame) return copy_guarded_host(host + (at - va), frame, n, false); SIZE_T copied{}; return ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(at), host + (at - va), SIZE_T(n), &copied) && copied == n; })) return false; st->arena_mark_dirty(lease->offset, bytes); result={va,bytes,st->arena.buffer,lease->offset,std::move(lease)}; return true; }); return true; } ~Device() override { leonida::memory_figures::withdraw_vram_reader(&state_); // waits for a read of this device in progress { // Before anything goes: an exit save in progress finishes with this device first. std::lock_guard lock(exit_cache_mutex); std::erase(exit_cache_devices, &state_); } state_.close_order_log(); // the pipelines are gone by now (each held this device) leonida::value_sink::clear_arena(&state_); // first: it waits for a value write into the arena in progress raw_images_.clear(); geometry_refresher_.reset(); // its refresh uses state_.geometry title_filler_.reset(); // its fills use the title-texture registry { // Release device-owned slot-70 textures (still live or waiting in retired_title_textures_) before // vkDeviceWaitIdle + drain_deleted_resources so all Vulkan images/views/memory are destroyed cleanly. std::vector owned_release; { std::lock_guard lock(state_.title_texture_mutex); for (auto& [when, r] : retired_title_textures_) if (r) owned_release.push_back(r); retired_title_textures_.clear(); retired_backing_ = 0; retired_earliest_ns_.store(0, std::memory_order_release); for (auto it = state_.title_textures.begin(); it != state_.title_textures.end();) { if (it->second && it->second->owned) { state_.clear_partial_budget(*it->second); if (it->second->resource) { owned_release.push_back(it->second->resource); it->second->resource = nullptr; } it = state_.title_textures.erase(it); } else { ++it; } } } for (Resource* r : owned_release) r->Release(); state_.drain_titles_gone(); } // Background pipeline work first, before anything it uses goes. Every PSO is gone (each held this device), // but a PSO released while its build ran is deleted on the worker after that build; the device's startup // cache checkpoint may also be queued or running. cancel() drops what is queued and waits for both. The last // device then stops and joins the compiler's thread. { if (state_.context) state_.context->set_batch_compile_runner({}); auto& compiler = PipelineCompiler::instance(); if (compiler.running_here(&state_)) { // A build job of this device released the device's last reference from inside the build, which // goes on using the device when this returns. Nothing does this; stop rather than free under it. std::fprintf(stderr, "[rt] d3d12: device released from inside one of its own pipeline builds\n"); std::abort(); } compiler.cancel(&state_); compiler_use_.release(); } leonida::title_va_aliases().clear_hooks(&state_); leonida::title_va_aliases().remove_listener(&state_); { std::lock_guard lock(state_.title_window_mutex); for (const auto& window : state_.title_windows) leonida::title_va_aliases().remove(window.start, window.shader_va); state_.title_windows.clear(); } for (auto& [shape, image] : state_.zero_images) if (image) image->Release(); state_.zero_images.clear(); if (state_.context) { { std::lock_guard lock(state_.context->submit_mutex()); const leonida::SubmitMutex::SubmitTurn turn(state_.context->submit_mutex(), false); // the compile gate state_.context->observe_result(state_.context->vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle"); } state_.context->drain_deleted_resources(UINT64_MAX); state_.context->set_pipeline_workers(nullptr); // before the pipeline cache is written and destroyed state_.context->set_bindless_release(nullptr, nullptr); state_.context->set_bindless_current(nullptr); // the retired generations go with state_.bindless below } if (state_.context) { if (state_.gpu_resolver) state_.gpu_resolver->halt(); // it calls into the geometry copies state_.context->set_arena_upload(nullptr, nullptr); ShadowPages::gpu_copy = nullptr; state_.geometry.release(state_); state_.external_windows.release(state_); std::lock_guard upload(state_.title_upload_mutex); state_.title_upload.release(state_); } state_.staging_queue.reset(); // they use the context state_.staging_copy_queue.reset(); if (state_.context) { std::lock_guard lock(state_.shared_layout_mutex); for (const auto& [key, layout] : state_.shared_pipeline_layouts) if (layout && state_.context->vk.vkDestroyPipelineLayout) state_.context->vk.vkDestroyPipelineLayout(state_.info.device, layout, nullptr); state_.shared_pipeline_layouts.clear(); } if (state_.context && state_.bindless) { // Every texture is gone by now (each held this device), and its views with it; samplers remain. std::lock_guard lock(state_.descriptor_mutex); for (const auto& [key, entry] : state_.sampler_entries) state_.context->vk.vkDestroySampler(state_.info.device, entry.sampler, nullptr); state_.sampler_entries.clear(); state_.bindless.reset(); } state_.report_arena(); state_.destroy_address_guard(); if (state_.context) state_.destroy_page_mirror(); state_.destroy_rebar_readback(); if (state_.context && state_.arena.buffer) { state_.context->set_arena_upload(nullptr, nullptr); leonida::fsdraw::forget_arena(&state_); auto& vk = state_.context->vk; if (state_.arena.staging_buffer) vk.vkDestroyBuffer(state_.info.device, state_.arena.staging_buffer, nullptr); if (state_.arena.staging_memory) vk.vkFreeMemory(state_.info.device, state_.arena.staging_memory, nullptr); vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); { std::lock_guard lock(state_.arena.mutex); state_.arena.backing.clear(); // a sparse arena's blocks; the buffer that used them is gone } if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); if (state_.arena.zero_page) { vk.vkFreeMemory(state_.info.device, state_.arena.zero_page, nullptr); state_.arena.zero_page = VK_NULL_HANDLE; } } state_.finish_heavy_cache(); if (state_.pipeline_cache_handle) { // Nothing should be building into the cache now (the compiler's jobs for this device are gone, and so // is every PSO). If something is, its pipelines are half in the cache: keep the previous session file. if (const unsigned building = state_.active_compiles.load()) std::fprintf(stderr, "[rt] d3d12: %u pipeline build(s) still running at device teardown; " "pipeline_cache.session.bin not written\n", building); else if (!compile_helper::build_host) save_session_pipeline_cache(state_.context->vk, state_.info.device, state_.pipeline_cache_handle); state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr); } state_.context.reset(); state_.image_memory.reset(); // the context's deferred queue gave its ranges back if (owned_.device) owned_.destroy_device(owned_.device, nullptr); if (owned_.instance) { leonida::address_binding::uninstall_messenger(owned_.instance); owned_.destroy_instance(owned_.instance, nullptr); } } bool ok() const { return state_.context && state_.context->loaded(); } // gta6rt --precompile-pipelines builds against the device's own state (precompile_compute_pipelines). DeviceState& build_state() { return state_; } const VulkanDeviceInfo& info() const { return state_.info; } // Acceleration-structure resources work: KHR builds, or the XDXR records (which need the GPU address arena). bool acceleration_structures() const { return state_.info.ray_tracing || (state_.info.xdxr_acceleration_structures && state_.info.buffer_device_address); } bool upload_in_vram() const { return state_.upload_in_vram; } leonida::VulkanContext& context() { return *state_.context; } const leonida::BindlessSet* bindless() const { return state_.bindless.get(); } DeviceState& state() { return state_; } const DeviceState& state() const { return state_; } HRESULT create_native_graphics(const leonida::native_pso::GraphicsDesc& desc, REFIID iid, void** out) { const auto* shaders = state_.library(); if (!shaders) return E_NOTIMPL; return state_.native_graphics.create(shaders->directory(), desc, out, [&](const auto& pc, const auto& mesh, const auto& containers) { return shared_native_graphics(pc, mesh, containers, iid, out); }); } // A fresh public PSO has its own COM identity, private data and name. Equal native descriptions can // hold one compiled backend PSO while either public object lives. The device only holds weak references. HRESULT prepare_console_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& source, REFIID iid, void** out, std::unique_ptr record) { if (!out)return E_POINTER;*out=nullptr; PipelineStream stream{}; if(const auto hr=parse_pipeline_stream(source,stream);FAILED(hr))return hr; const auto* library=state_.library();if(!library)return E_FAIL; const auto verify=[&](const char* name,const D3D12_SHADER_BYTECODE& code) { if(!code.BytecodeLength)return true; if(!code.pShaderBytecode)return false; const std::span bytes{static_cast(code.pShaderBytecode),code.BytecodeLength}; const std::string identity=std::string(name)+leonida::sha256_hex(bytes); {std::lock_guard lock(verified_program_mutex_);if(verified_programs_.count(identity))return true;} auto program=leonida::compute_program(bytes); if(program.bytes.empty())return false; bool ambiguous=false; const auto candidates=library->program_candidates(name,program,&ambiguous); if(candidates.empty() || ambiguous)return false; {std::lock_guard lock(verified_program_mutex_);verified_programs_.insert(identity);} return true; }; if(stream.has_cs) { if(!stream.compute.CS.BytecodeLength || !verify("cs",stream.compute.CS))return E_INVALIDARG; } else { const auto& g=stream.graphics; if(stream.as.BytecodeLength || g.HS.BytecodeLength || g.DS.BytecodeLength)return E_NOTIMPL; if((bool(g.VS.BytecodeLength)==bool(stream.ms.BytecodeLength)) || g.NumRenderTargets>8 || !verify("vs",g.VS)||!verify("gs",g.GS)||!verify("ms",stream.ms)||!verify("ps",g.PS))return E_INVALIDARG; } if(!record) record=rt::d3d12_xs::PsoStreamRecord::capture(source); if(!record)return E_INVALIDARG; auto* pipeline=new PipelineState(state_); pipeline->attach_device(identity()); pipeline->set_cache_key(stream.has_cs?pipeline_key(stream.compute):pipeline_key(stream.graphics)); if(state_.order_log||state_.prewarm_plan) pipeline->set_order_key(order_key(stream)); if(!rt::d3d12_xs::attach_pso_record(pipeline,std::move(record))){pipeline->Release();return E_OUTOFMEMORY;} pipeline->set_pending_stream(stream.has_cs); pipeline->prewarm_pending_stream(); return hand_out(pipeline,iid,out); } HRESULT shared_native_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc, D3D12_SHADER_BYTECODE mesh, std::span containers, REFIID iid, void** out) { auto key = pipeline_key(pc); if (mesh.BytecodeLength) key += leonida::sha256_hex({static_cast(mesh.pShaderBytecode), mesh.BytecodeLength}); std::shared_ptr compiled; { std::lock_guard lock(native_pipeline_mutex_); const auto found = native_pipelines_.find(key); if (found != native_pipelines_.end()) compiled = found->second.lock(); } if (!compiled) { ID3D12PipelineState* raw = nullptr; HRESULT hr; if(state_.info.prepare_on_bind) { rt::d3d12_xs::native_pipeline_detail::Stream native; rt::d3d12_xs::native_pipeline_detail::build_stream(pc,mesh,native); const auto source=native.desc(); auto record=rt::d3d12_xs::PsoStreamRecord::capture(source,containers); hr=record?prepare_console_stream(source,__uuidof(ID3D12PipelineState),reinterpret_cast(&raw),std::move(record)):E_INVALIDARG; } else { hr = mesh.BytecodeLength ? rt::d3d12_xs::native_pipeline_detail::create_mesh(this, pc, mesh, __uuidof(ID3D12PipelineState), reinterpret_cast(&raw)) : CreateGraphicsPipelineState(&pc, IID_PPV_ARGS(&raw)); } if (FAILED(hr)) return hr; if (!raw) return E_FAIL; auto* owner = PipelineState::from(raw); if (!owner) { raw->Release(); return E_NOINTERFACE; } compiled = std::shared_ptr(owner, [](PipelineState* p) { p->Release(); }); std::lock_guard lock(native_pipeline_mutex_); if (native_pipelines_.size() >= 16384) native_pipelines_.clear(); auto& cached = native_pipelines_[key]; if (auto concurrent = cached.lock()) compiled = std::move(concurrent); else cached = compiled; } if(!compiled->ensure_native_source(pc,mesh,containers)) return E_FAIL; auto* view = new PipelineState(state_); view->attach_device(identity()); if(!rt::d3d12_xs::share_pso_record(compiled.get(),view)) { view->Release(); return E_OUTOFMEMORY; } view->share_native_graphics(std::move(compiled)); return hand_out(view, iid, out); } IUnknown* holder() { return identity(); } // Console-extended CreateDescriptorHeap (Xbox slot 14): a heap at the title's console address. The proxy's // handler (set_console_descriptor_heap_handler) calls this; a normal PC create never does. HRESULT create_console_descriptor_heap(const D3D12_DESCRIPTOR_HEAP_DESC* desc, D3D12_GPU_VIRTUAL_ADDRESS console_address, std::uint64_t console_size, REFIID riid, void** out) { auto* heap = new DescriptorHeap(state_, *desc, console_address, console_size); heap->attach_device(identity()); if (!heap->ok()) { heap->Release(); return E_OUTOFMEMORY; } return hand_out(heap, riid, out); } bool bind_sampler(const leonida::gfx10::SamplerWords& words) { return state_.bind_sampler(words); } // Xbox device slots 70/71 (rt::d3d12::write_placed_buffer_view): the slot is zeroed first, as Create*View does. bool resolve_xdxr_build(leonida::BuildAccelerationStructure& build) { return state_.resolve_xdxr_build(build); } bool resolve_xdxr_copy(leonida::CopyAccelerationStructure& copy) { return state_.resolve_xdxr_copy(copy); } bool resolve_xdxr_postbuild(leonida::AccelerationStructurePostbuild& info) { return state_.resolve_xdxr_postbuild(info); } bool write_placed_buffer_view(bool unordered, const void* view, std::uint64_t address, std::uint64_t width, D3D12_CPU_DESCRIPTOR_HANDLE destination) { struct PlacedWrite { DeviceState& state; SIZE_T ptr; bool unordered; ~PlacedWrite() { state.arena_mark_dirty_ptr(reinterpret_cast(ptr), kDescriptorSize); if (rt::compute_probe::enabled()) state.probe_api(ptr, 1, unordered ? "slot71" : "slot70"); } } probe{state_, destination.ptr, unordered}; std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); if (unordered) { D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; std::memcpy(&desc, view, sizeof(desc)); return write_buffer_uav_at(address, width, &desc, 0, destination); } D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; std::memcpy(&desc, view, sizeof(desc)); return desc.ViewDimension == D3D12_SRV_DIMENSION_BUFFER && write_buffer_srv(address, width, &desc, destination, true); } // ---- Textures the title keeps in its own memory (TitleTexture) ---- // Xbox device slot 70 with a texture description (rt::d3d12::write_placed_texture_view): the view's T#, of the // slot-133 texture placed at `address` or of an image made for that memory and filled from it. False leaves the // slot a null view (zeros); every reason is counted and logged once per format and layout. bool write_placed_texture_view(const std::uint32_t* resource_words, const std::uint32_t* view_words, std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE destination) { ArenaDirtySlot dirty_slot{state_, destination.ptr}; std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); rt::xg_xs::ResourceDesc d{}; std::memcpy(&d, resource_words, sizeof(d)); D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; std::memcpy(&srv, view_words, sizeof(srv)); if (!srv.Shader4ComponentMapping) srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; std::array words{}; std::memcpy(words.data(), resource_words, sizeof(words)); words[1] = words[2] = words[3] = words[13] = 0; // struct padding and alignment say nothing about the texels bool written = false; { std::lock_guard lock(state_.title_texture_mutex); const InTitleTextures inside; TitleTextureStats& stats = title_stats_; ++stats.views; ++stats.asked[{d.format, d.layout, d.dimension, d.mips}]; const std::uint64_t refusals = stats.refusals; written = place_title_view(d, words, srv, address, destination); if (texture_probe()) std::fprintf(stderr, "[rt] texture-probe: SRV dest %llx va %llx %llux%ux%u fmt %u view %u mips %u ok %u\n", (unsigned long long)destination.ptr, (unsigned long long)address, (unsigned long long)d.width, d.height, unsigned(d.depth_or_array), d.format, unsigned(srv.Format), unsigned(d.mips), unsigned(written)); if (!written && stats.refusals == refusals) refuse_title_view("no reason recorded", d, address); if (!written) ++stats.null_views; if (leonida::fsdraw::enabled() && (stats.views == 64 || !(stats.views % 2048))) log_title_census("slot-70 texture views"); } state_.drain_titles_gone(); return written; } // Slot 71 names GPU-writable memory. Its contents belong to the existing image. bool write_placed_texture_uav(const std::uint32_t* words, const std::uint32_t* view, std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE dest) { ArenaDirtySlot dirty_slot{state_, dest.ptr}; static const bool enabled = [] { const char* v = std::getenv("LEONIDA_PLACED_TEXTURE_UAV"); return !v || std::strcmp(v, "0"); }(); std::memset(reinterpret_cast(dest.ptr), 0, kDescriptorSize); if (!enabled || !address) return false; rt::xg_xs::ResourceDesc d{}; D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; std::memcpy(&d, words, sizeof(d)); std::memcpy(&uav, view, sizeof(uav)); std::lock_guard lock(state_.title_texture_mutex); auto it = state_.title_textures.find(address); if (it == state_.title_textures.end()) it = state_.title_textures.find(leonida::title_gpu_views::other_view(address)); Resource* candidate = matching_gpu_placement(d, address, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); if (!candidate && it != state_.title_textures.end() && !it->second->owned) candidate = it->second->resource; if (!candidate) return false; Resource& r = *candidate; const auto& rd = r.desc(); if (!TitleGpuPlacements::matches(d, r) || !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return false; if (uav.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE3D) { const auto& volume = uav.Texture3D; if (rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D || volume.MipSlice >= rd.MipLevels) return false; const UINT depth = std::max(1u, UINT(rd.DepthOrArraySize) >> volume.MipSlice); if (volume.FirstWSlice || (volume.WSize != UINT_MAX && volume.WSize != depth)) return false; TextureView v{}; v.type = leonida::gfx10::ImageType::image_3d; v.format = uav.Format; v.first_mip = volume.MipSlice; v.mip_count = 1; write_image_descriptor(r, v, dest, ImageViewUse::storage); } else { CreateUnorderedAccessView(&r, nullptr, &uav, dest); } leonida::gfx10::ImageWords result{}; std::memcpy(result.data(), reinterpret_cast(dest.ptr), sizeof(result)); if (!leonida::gfx10::is_image(result)) return false; std::lock_guard descriptors(state_.descriptor_mutex); if (!state_.bindless) return true; const auto entry = state_.image_entries.find(leonida::gfx10::tsharp_key(result)); if (entry != state_.image_entries.end() && entry->second.storage) return true; std::memset(reinterpret_cast(dest.ptr), 0, kDescriptorSize); return false; } // Console byte footprint claimed by a GPU-written texture in `gpu_owned`. For single-sample textures with an exact // known XG layout (non-guessed `existing_entry` or `title_xg_layout()`), return that exact footprint so packed // composites like 128x128 BC3 claim only their exact console span instead of Vulkan's padded alignment. On the // guessed `title_layout()` fallback (RTs, depth-stencil, unknown-layout SW_64KB_S, MSAA, D24S8/D32S8), keep // `max(layout.size, max(image_backing_bytes, unbound_bytes))` so we never under-claim a 64 KiB tile or deferred // allocation. static std::uint64_t gpu_owned_span(const Resource& res, const TitleTexture* existing_entry) { const D3D12_RESOURCE_DESC& desc = res.desc(); const std::uint64_t backing = (std::max)(res.image_backing_bytes(), res.unbound_bytes()); if (desc.SampleDesc.Count <= 1) { if (existing_entry && existing_entry->layout_known && !existing_entry->layout_guessed && existing_entry->layout.layout.size) return existing_entry->layout.layout.size; rt::xg_xs::Texture xg_layout{}; std::array xg_words{}; if (title_xg_layout(res, xg_layout, xg_words) && xg_layout.layout.size) return xg_layout.layout.size; } rt::xg_xs::ResourceDesc d{}; d.dimension = std::uint32_t(desc.Dimension); d.width = desc.Width; d.height = desc.Height; d.depth_or_array = desc.DepthOrArraySize; d.mips = desc.MipLevels; d.format = std::uint32_t(desc.Format); d.samples = 1; rt::xg_xs::Texture layout{}; const char* why = nullptr; std::uint64_t span = (std::max)(std::uint64_t(title_layout(d, layout, why) ? layout.layout.size : 0), backing); // On Xbox Series, render targets (SW_64KB_R_X) and depth-stencil targets (SW_64KB_Z_X) occupy 64 KiB tiles // even when a PC Vulkan driver's image memory requirement is smaller (e.g. 16 KiB for a 64x64 RGBA8 RT). if (span && (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL))) span = (span + rt::xg_xs::kTileBytes - 1) & ~std::uint64_t(rt::xg_xs::kTileBytes - 1); return span; } // A slot-133 texture the title placed at `address` (create_at_host_address): slot-70 views at that address are // of its image; unless the GPU writes it, the image is filled from the memory with the view's layout. void register_title_texture(Resource* texture, std::uint64_t address) { const D3D12_RESOURCE_DESC& desc = texture->desc(); auto entry = std::make_shared(); entry->address = address; entry->cpu = leonida::title_gpu_views::to_cpu(address); entry->set_resource(texture); entry->attachment_4k = desc.Width == 3840 && desc.Height == 2160 && (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); entry->gpu_written = (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) != 0 || desc.SampleDesc.Count > 1; if (!entry->gpu_written) { // Until a slot-70 view says how it is laid out: the description's own (Layout 0, XG's default). rt::xg_xs::ResourceDesc d{}; d.dimension = std::uint32_t(desc.Dimension); d.width = desc.Width; d.height = desc.Height; d.depth_or_array = desc.DepthOrArraySize; d.mips = desc.MipLevels; d.format = std::uint32_t(desc.Format); d.samples = 1; const char* why = nullptr; if (title_xg_layout(*texture, entry->layout, entry->desc)) { entry->layout_known = entry->layout_from_xg = true; } else { entry->layout_known = entry->layout_guessed = title_layout(d, entry->layout, why) && title_layout_fits(entry->layout, d, *texture, why); std::memcpy(entry->desc.data(), &d, sizeof(d)); entry->desc[1] = entry->desc[2] = entry->desc[3] = entry->desc[13] = 0; } } // The memory a GPU-written texture covers: what the console's GPU renders there, our GPU renders into the image // instead. For single-sample textures use the exact XG console footprint when known (so packed composites like // 128x128 BC3 claim only their exact 0x6000 span rather than Vulkan's padded image_backing_bytes alignment). std::uint64_t gpu_span = 0; if (entry->gpu_written) { gpu_span = gpu_owned_span(*texture, nullptr); } texture->mark_title_texture(); { std::lock_guard lock(state_.title_texture_mutex); if (gpu_span) state_.add_gpu_owned(texture, address, entry->cpu, gpu_span); if (entry->gpu_written && !(address & 0xff) && texture->image_address() != address) { std::lock_guard descriptors(state_.descriptor_mutex); state_.gpu_placements.add(address, texture); state_.note_texture_change(leonida::SlotChange::texture_added, address); } auto& slot = state_.title_textures[address]; if (entry->gpu_written && slot && slot->resource && !slot->owned && !slot->gpu_written) { // A render target placed over a texture the title placed first: the texture keeps its entry (it is // filled from memory again once the target goes, drop_gpu_owned), and its T#s are bound again, to // the target's image where they fit (bind_title_image). std::lock_guard descriptors(state_.descriptor_mutex); state_.forget_image_views_locked(slot->resource->image_address()); ++title_stats_.registered; return; } if (slot && slot->owned) retire_title_texture(*slot); if (slot) state_.clear_partial_budget(*slot); state_.index_texture(*entry); slot = std::move(entry); ++title_stats_.registered; } } // Promotes a slot-133 title-placed texture written by GPU CopyTextureRegion, CopyResource, or // ResolveSubresource[Region] to GPU-written (block-compressed textures such as ped BC7/BC3 composites cannot carry // ALLOW_RENDER_TARGET/ALLOW_UNORDERED_ACCESS at creation). Untracks it from texture_watch, registers it in // gpu_owned and gpu_placements (so both address and other_view(address) resolve to it), and forgets any cached // views of a non-GPU-written alias at other_view(address). For partial copies/resolves onto a texture already // eligible for CPU fills, syncs pending CPU bytes once before the GPU copy runs so unmodified mips/texels stay // intact. void mark_title_texture_gpu_written(leonida::ResourceId id, std::uint64_t address, bool partial) { if (!id || !address) return; std::lock_guard lock(state_.title_texture_mutex); const InTitleTextures inside; auto it = state_.title_textures.find(address); if (it == state_.title_textures.end() || !it->second->resource || it->second->resource->id() != id) { const std::uint64_t other = leonida::title_gpu_views::other_view(address); if (!other) return; it = state_.title_textures.find(other); if (it == state_.title_textures.end() || !it->second->resource || it->second->resource->id() != id) return; } TitleTexture& entry = *it->second; if (entry.gpu_written || entry.owned) return; Resource* r = entry.resource; // For partial GPU copies/resolves onto a slot-133 texture (e.g. a BC3/BC7 composite where only a subset of // mips or texels is overwritten by CopyTextureRegion), pre-fill from readable title memory even when the // texture has not been mapped/drawn yet so unwritten mips keep their title texels instead of staying zero. if (partial && entry.layout_known && !state_.over_gpu_owned(entry.cpu, entry.cpu + title_texture_active_span(entry))) { if (entry.fills == 0 && entry.memory.pending()) entry.memory.retry(); fill_title_texture(entry); if (!entry.resource || entry.resource != r) return; } entry.gpu_written = true; entry.stale = false; entry.filled_from = 0; state_.clear_partial_budget(entry); state_.texture_watch.untrack(entry.address); // Never publish views on an unbound deferred VkImage (VUID-vkCreateImageView-image-01020): clear any pending // partial clamp so prepare() / bind_placed_memory() binds, initializes, and publishes at mip 0, and only // unclamp directly when the image is already backed. r->clear_placed_publish_from(); if (r->deferred_stream() && !r->unbound_bytes()) r->publish_streamed_texture(0); const std::uint64_t gpu_span = gpu_owned_span(*r, &entry); if (gpu_span) state_.add_gpu_owned(r, entry.address, entry.cpu, gpu_span); if (!(entry.address & 0xff)) { std::lock_guard descriptors(state_.descriptor_mutex); state_.gpu_placements.add(entry.address, r); if (const std::uint64_t other = leonida::title_gpu_views::other_view(entry.address)) { const auto other_it = state_.title_textures.find(other); if (other_it != state_.title_textures.end() && other_it->second->resource && other_it->second->resource != r && !other_it->second->gpu_written) state_.forget_image_views_locked(other_it->second->resource->image_address()); } state_.note_texture_change(leonida::SlotChange::texture_added, entry.address); } } // Before every submission (VulkanContext::set_before_execute), on the submitting thread: the textures something // says may have changed since their last fill are read and, when their bytes differ from that fill's, uploaded // (fill_title_texture). What says so (TitleTextureWatch, title_texture_watch.h): a write to their pages (a fault // on a tile armed read-only, at every address it is mapped at), a mapping change over them, their creation or a // new layout, the title's Unmap, and the writes XG and DirectStorage note (title_texel_writes). A texture nobody // wrote costs nothing here. Memory a guard cannot watch (not committed, or no write-fault handler) is the one // fallback: its textures are read at every refresh and uploaded only when their bytes differ. // // Ordering: a write the title finished before it called ExecuteCommandLists is in this pass, and its upload is // submitted before this submission's command buffers, behind all earlier work on every queue on the GPU and with // no CPU wait (TitleImageUpload, write_staged_title_image); this submission's draws, on whichever queue, see it. // Every changed texture of the pass goes in, with no budget: the planes of a video frame land together. void refresh_title_textures(bool mirror_just_synced = false, std::uint64_t mirror_synced_serial = 0) { if (t_in_title_textures) return; using clock = std::chrono::steady_clock; const auto now = clock::now(); const std::int64_t now_ns = std::chrono::duration_cast(now.time_since_epoch()).count(); // O(1) lock-free dirty fast-path: return immediately without locking title_texture_mutex or scanning when // nothing changed since the last pass, no retired textures are due, and the 10-second log is not due. { const std::int64_t due_retire = retired_earliest_ns_.load(std::memory_order_acquire); const std::int64_t last_log = title_last_log_ns_.load(std::memory_order_acquire); const bool log_due = (now_ns - last_log) >= 10'000'000'000ll; if (!log_due && (due_retire == 0 || now_ns < due_retire) && !state_.texture_watch.may_have_work() && !leonida::title_texel_writes::state().pending.load(std::memory_order_acquire) && leonida::title_memory_map::generation() == title_map_generation_atomic_.load(std::memory_order_acquire) && !state_.titles_named_pending.load(std::memory_order_acquire) && !state_.titles_gone_pending.load(std::memory_order_acquire) && title_refresh_in_flight_.load(std::memory_order_seq_cst) == 0) { title_fast_passes_.fetch_add(1, std::memory_order_relaxed); return; } } // Waits for a slot-70 view that is filling a texture: skipping would leave this submission a write behind. // No deadlock: before_execute holds no lock, and the registry's holders never wait for this thread. std::unique_lock lock(state_.title_texture_mutex); const auto locked = clock::now(); title_refresh_in_flight_.fetch_add(1, std::memory_order_seq_cst); struct TitleRefreshGuard { std::atomic& n; ~TitleRefreshGuard() { n.fetch_sub(1, std::memory_order_release); } } in_flight{title_refresh_in_flight_}; std::optional inside(std::in_place); TitleTextureStats& stats = title_stats_; stats.lock_wait_ns += std::uint64_t(std::chrono::duration_cast(locked - now).count()); auto& watch = state_.texture_watch; const std::uint64_t fast_skips = title_fast_passes_.exchange(0, std::memory_order_relaxed); stats.fast_passes += fast_skips; stats.passes += fast_skips + 1; title_split_passes_ += fast_skips + 1; title_pass_ = true; // A fill this pass makes can retire an image (title_texture_gone while this thread holds the registry): the // entry stops naming the resource and is erased by drain_titles_gone after the pass. Entries are looked up by // key each time, and one without a resource is passed over. // state_.title_partial_bytes is maintained incrementally on back/fill/retire/evict/destroy (no O(N) map walk). bool overflow = false; auto written = leonida::title_texel_writes::take(overflow); stats.written_ranges += written.size(); title_map_changes_.clear(); std::uint64_t map_now = 0; const bool map_all = !leonida::title_memory_map::changes_since( title_map_generation_, map_now, 0, UINTPTR_MAX, [&](std::uintptr_t from, std::uintptr_t to) { title_map_changes_.emplace_back(from, to); }); title_map_generation_ = map_now; title_map_generation_atomic_.store(map_now, std::memory_order_release); stats.map_ranges += title_map_changes_.size(); stats.map_all += map_all; // A mapping change: the textures over it probe their memory again (TextureReadability) and invalidate cached // write_combined status. Partial-mip upgrades are detected in Stage 2b after the single cached readability // probe (avoiding uncached per-texture VirtualQuery loops here). const auto remapped = [&](std::uint64_t key) { const auto it = state_.title_textures.find(key); if (it != state_.title_textures.end()) { TitleTexture& t = *it->second; t.memory.retry(); t.write_combined_known = false; } }; // A pure texel write (XG CopyIntoSubresource / DirectStorage / slot-31 copy): do NOT invalidate cached // readability on already-filled full-mip textures; only retry when pending, partially filled, or never filled // (preserves check_pending_stream_views and partial mip chain promotion). const auto texel_written = [&](std::uint64_t key) { const auto it = state_.title_textures.find(key); if (it != state_.title_textures.end()) { TitleTexture& t = *it->second; if (t.memory.pending() || t.filled_from != 0 || !t.fills) { t.memory.retry(); } } }; if (map_all) { watch.note_changed_and_for_each(0, UINTPTR_MAX, remapped, true); } else { if (!title_map_changes_.empty()) { leonida::merge_title_writes(title_map_changes_); for (const auto& [from, to] : title_map_changes_) watch.note_changed_and_for_each(from, to, remapped, false); } if (overflow) { watch.note_changed_and_for_each(0, UINTPTR_MAX, texel_written, false); } else if (!written.empty()) { leonida::merge_title_writes(written); for (const auto& [from, to] : written) watch.note_changed_and_for_each(from, to, texel_written, false); } } if (state_.titles_named_pending.load(std::memory_order_acquire)) { std::vector named; std::vector> view_mips; { std::lock_guard named_lock(state_.titles_named_mutex); named.swap(state_.titles_named); view_mips.swap(state_.titles_view_mips); state_.titles_named_pending.store(false, std::memory_order_release); } for (const auto& [address, min_mip] : view_mips) { auto it = state_.title_textures.find(address); if (it == state_.title_textures.end()) { if (const std::uint64_t other = leonida::title_gpu_views::other_view(address)) it = state_.title_textures.find(other); } if (it == state_.title_textures.end() || !it->second->resource || it->second->gpu_written) continue; TitleTexture& t = *it->second; const bool lowered = t.view_mip_set && min_mip < t.view_mip; if (!t.view_mip_set || lowered) { t.view_mip = min_mip; t.view_mip_set = true; if (lowered) { t.memory.retry(); t.stale = true; state_.index_texture(t); } } } for (const std::uint64_t address : named) { const auto it = state_.title_textures.find(address); if (it != state_.title_textures.end() && it->second->resource && !watch.tracked(address)) { state_.index_texture(*it->second); ++stats.first_named; } } } title_named_.clear(); watch.collect([&](std::uint64_t key) { title_named_.push_back(key); }); const auto collected = clock::now(); stats.collect_ns += std::uint64_t(std::chrono::duration_cast(collected - locked).count()); // Not filled: with no backing yet or after a failed upload it is looked at again next pass. Memory not // readable yet waits for its mapping (xmem's change names it), except a texture the title mapped, whose // pages may be committed under the pointer Map gave without xmem (the probe answers each pass). Its tiles // are armed again then: pages committed since the last arming have no guard yet. const auto not_filled = [&](TitleTexture& t) { if ((t.stale || !t.hashed) && t.resource) { if (t.mapped) watch.note_changed(t.cpu, t.cpu + title_texture_active_span(t), true); else if (!t.memory.pending()) watch.touch(t.address); } }; // Batched texture refresh: // 1. Filter eligible textures and batch-arm all dirty tiles in one watch.examine_batch() call. // 2. Batch all TitleMirror checks/uploads in ONE page_mirror.mutex hold + ONE parallel TitleMirror::upload() // (skipping unchanged textures in ~15 ns, rejecting only pages overlapping pending xmem remaps). // 3. Hash-before-reserve for remaining CPU-checked textures on TitleReadPool using 4-lane piece hashing // (comparing both t.hash and t.mirror_hash so CPU fallback after GPU upload never re-uploads unchanged). // 4. Only reserve staging slots & detile on CPU for CPU jobs whose bytes actually changed. // 5. Record and submit all uploads of the batch in ONE batched command buffer + ONE vkQueueSubmit. std::uint64_t filled = 0; title_job_count_ = 0; std::size_t cpu_job_count = 0; std::uint64_t cpu_batch_bytes = 0; std::uint64_t gpu_scratch_bytes = 0; const auto next_title_job = [&]() -> TitleJob& { if (title_job_count_ == title_jobs_.size()) title_jobs_.emplace_back(); TitleJob& job = title_jobs_[title_job_count_++]; job.entry.reset(); job.resource = nullptr; job.slot = nullptr; job.from = 0; job.span = 0; job.hash = 0; job.previous.reset(); job.previous_mirror_hash.reset(); job.pieces.hashes.clear(); job.piece_sums.clear(); job.written.clear(); job.compare = job.whole = job.precopied = false; job.failed.store(false, std::memory_order_relaxed); job.detile_ns = 0; job.write_combined = job.trace = job.copied = job.unchanged = job.nonzero = false; job.gpu_mirror = false; job.gpu_kind = rt::d3d12::TitleImageUpload::UploadKind::cpu_slot; job.mirror_buffer = VK_NULL_HANDLE; job.mirror_offset = job.mirror_chunk_size = 0; job.mirror_timeline = VK_NULL_HANDLE; job.mirror_value = 0; job.mirror_hash = 0; job.mirror_hash_valid = false; return job; }; const auto fill_start = clock::now(); const std::uint64_t read_before = stats.read_ns, staged_before = stats.staged_ns; const auto run_batch = [&] { if (!title_job_count_) return; const auto read_start = clock::now(); TitleReadPool& pool = title_read_pool(); title_cpu_check_indices_.clear(); for (std::size_t i = 0; i < title_job_count_; ++i) { const TitleJob& job = title_jobs_[i]; if (!job.gpu_mirror || job.compare) title_cpu_check_indices_.push_back(i); } if (!title_cpu_check_indices_.empty()) { pool.run(title_cpu_check_indices_.size(), [this](std::size_t k) { read_title_job(title_jobs_[title_cpu_check_indices_[k]]); }); } // Whole CPU reads in pieces of up to kTitleChunkTiles tiles, spread over the threads (never for GPU-mirror // jobs or jobs already copied/found unchanged in read_title_job). title_chunks_.clear(); bool any_whole = false; for (std::size_t i = 0; i < title_job_count_; ++i) { TitleJob& job = title_jobs_[i]; if (!job.whole || job.gpu_mirror) continue; any_whole = true; if (job.precopied) { stats.read_bytes += job.span; continue; } job.tiled.resize(std::size_t(job.span)); job.pieces.reset(job.entry->cpu, job.span); const bool mirror_aligned = (job.entry->cpu & (leonida::shadow_keep::kPiece - 1)) == 0 && (job.span & (leonida::shadow_keep::kPiece - 1)) == 0; if (mirror_aligned) job.piece_sums.resize(std::size_t(job.span / leonida::shadow_keep::kPiece)); else job.piece_sums.clear(); job.failed.store(false, std::memory_order_relaxed); const std::size_t tiles = job.pieces.hashes.size(); for (std::size_t first = 0; first < tiles; first += kTitleChunkTiles) title_chunks_.push_back({i, first, (std::min)(tiles, first + kTitleChunkTiles)}); stats.read_bytes += job.span; } if (!title_chunks_.empty()) { pool.run(title_chunks_.size(), [this](std::size_t c) { const TitleChunk& chunk = title_chunks_[c]; read_title_chunk(title_jobs_[chunk.job], chunk.first, chunk.end); }); } // Finalize hashes inline on calling thread BEFORE reserving any upload slots (pure integer mixing, avoids // a full thread-pool wakeup barrier). if (any_whole) { for (std::size_t i = 0; i < title_job_count_; ++i) hash_title_job(title_jobs_[i]); } // Reserve staging slots ONLY for CPU jobs whose bytes actually changed (eliminating >87% wasted reserves). title_detile_indices_.clear(); { std::lock_guard upload(state_.title_upload_mutex); for (std::size_t i = 0; i < title_job_count_; ++i) { TitleJob& job = title_jobs_[i]; if (job.gpu_mirror || !job.copied || job.unchanged) continue; job.slot = state_.title_upload.reserve(state_, job.resource->title_binding(), job.entry->layout, job.from); if (job.slot) title_detile_indices_.push_back(i); } } if (!title_detile_indices_.empty()) { pool.run(title_detile_indices_.size(), [this](std::size_t k) { detile_title_job(title_jobs_[title_detile_indices_[k]]); }); } stats.read_ns += std::uint64_t( std::chrono::duration_cast(clock::now() - read_start).count()); for (std::size_t i = 0; i < title_job_count_; ++i) stats.detile_ns += title_jobs_[i].detile_ns; // Build one batch of all changed CPU slots + GPU-mirror direct/detile uploads and commit in one submit. title_batch_items_.clear(); title_batch_job_indices_.clear(); for (std::size_t i = 0; i < title_job_count_; ++i) { TitleJob& job = title_jobs_[i]; TitleTexture& t = *job.entry; if (job.gpu_mirror) { if (job.unchanged) { ++stats.unchanged_parts; t.stale = false; continue; } rt::d3d12::TitleImageUpload::BatchItem item{}; item.kind = job.gpu_kind; item.id = job.resource->id(); item.image = job.resource->title_binding(); item.layout = &t.layout; item.mirror_buffer = job.mirror_buffer; item.mirror_offset = job.mirror_offset; item.mirror_chunk_size = job.mirror_chunk_size; item.mirror_timeline = job.mirror_timeline; item.mirror_value = job.mirror_value; title_batch_items_.push_back(item); title_batch_job_indices_.push_back(i); continue; } if (!job.copied) { // the section changed after VirtualQuery: keep the last upload and retry if (job.slot) rt::d3d12::TitleImageUpload::unreserve(*job.slot); t.memory.defer(); t.stale = true; not_filled(t); continue; } if (job.whole) ++stats.read_whole; if (job.unchanged) { if (job.slot) rt::d3d12::TitleImageUpload::unreserve(*job.slot); ++(job.whole ? stats.unchanged : stats.unchanged_parts); if (job.whole) { t.pieces = std::move(job.pieces); t.hash = job.hash; t.hashed = true; t.gpu_uploaded = false; if (job.mirror_hash_valid) { t.mirror_hash = job.mirror_hash; t.mirror_hash_span = job.span; t.mirror_hash_valid = true; } } t.stale = false; continue; } if (!job.slot) { log_once("staged title texture upload failed, format", int(job.resource->format())); ++stats.fill_failures; t.stale = true; t.mirror_hash_valid = false; not_filled(t); continue; } rt::d3d12::TitleImageUpload::BatchItem item{}; item.kind = rt::d3d12::TitleImageUpload::UploadKind::cpu_slot; item.id = job.resource->id(); item.image = job.resource->title_binding(); item.layout = &t.layout; item.from = job.from; item.slot = job.slot; title_batch_items_.push_back(item); title_batch_job_indices_.push_back(i); } if (!title_batch_items_.empty()) { const auto start = clock::now(); { std::lock_guard upload(state_.title_upload_mutex); state_.title_upload.commit_batch(state_, title_batch_items_); } stats.staged_ns += std::uint64_t(std::chrono::duration_cast(clock::now() - start).count()); for (std::size_t b = 0; b < title_batch_items_.size(); ++b) { const auto& item = title_batch_items_[b]; TitleJob& job = title_jobs_[title_batch_job_indices_[b]]; TitleTexture& t = *job.entry; if (!item.ok) { log_once("staged title texture upload failed, format", int(job.resource->format())); ++stats.fill_failures; t.stale = true; t.mirror_hash_valid = false; not_filled(t); continue; } if (job.gpu_mirror) { if (job.gpu_kind == rt::d3d12::TitleImageUpload::UploadKind::mirror_linear) ++stats.gpu_linear_fills; else ++stats.gpu_detile_fills; note_filled_from(t, 0); t.gpu_uploaded = true; t.mirror_hash = job.mirror_hash; t.mirror_hash_span = job.span; t.mirror_hash_valid = true; t.hashed = true; t.pieces.hashes.clear(); t.stale = false; ++t.fills; ++stats.fills; ++stats.changed; stats.fill_bytes += job.span; filled += job.span; } else { ++stats.staged_fills; if (job.trace) std::fprintf(stderr, "[rt] ds-pool-fill cpu=%llx size=%llu staged=1 nonzero=%d\n", static_cast(t.cpu), static_cast(job.span), int(job.nonzero)); note_filled_from(t, job.from); t.gpu_uploaded = false; if (job.whole) t.pieces = std::move(job.pieces); t.mirror_hash = job.mirror_hash; t.mirror_hash_span = job.mirror_hash_valid ? job.span : 0; t.mirror_hash_valid = job.mirror_hash_valid; t.hash = job.hash; t.hashed = true; t.stale = false; ++t.fills; ++stats.fills; ++stats.changed; stats.fill_bytes += job.span; filled += job.span; } } } for (std::size_t i = 0; i < title_job_count_; ++i) { TitleJob& job = title_jobs_[i]; job.entry.reset(); job.resource = nullptr; job.slot = nullptr; const std::size_t tiled_cap = (i < 4) ? (16ull << 20) : (2ull << 20); if (job.tiled.capacity() > tiled_cap) std::vector{}.swap(job.tiled); if (job.piece_sums.capacity() > 8192) std::vector{}.swap(job.piece_sums); } title_job_count_ = 0; cpu_job_count = 0; cpu_batch_bytes = 0; gpu_scratch_bytes = 0; }; const bool gpu_detile_on = leonida::title_gpu_detile_enabled(); // Stage 1: filter eligible textures once from title_named_ (no repeated std::map lookups). title_candidate_keys_.clear(); title_candidates_.clear(); for (const std::uint64_t key : title_named_) { const auto it = state_.title_textures.find(key); if (it == state_.title_textures.end() || !it->second->resource) continue; TitleTexture& t = *it->second; if (t.gpu_written || !t.layout_known) continue; title_candidate_keys_.push_back(key); title_candidates_.push_back({it->second, 0, 0, 0, false}); } auto t_after_mirror = fill_start; if (!title_candidates_.empty()) { // Stage 2: batch-arm all dirty tiles across all candidates in ONE watch.examine_batch() call, then run // readability, partial-mip budget, and image-backing checks. watch.examine_batch(title_candidate_keys_, title_examine_results_); const auto t_after_arm = clock::now(); stats.examine_arm_ns += std::uint64_t(std::chrono::duration_cast(t_after_arm - fill_start).count()); const bool have_mirror = state_.page_mirror.mirror != nullptr; if (have_mirror) title_mirror_checks_.resize(title_candidates_.size()); bool any_mirror_active = false; leonida::TextureVqCache stage2_vq_cache; const std::uint64_t probes_before = stats.probes[0]; std::uint64_t pass_back_ns = 0; // Skip VirtualQuery in Stage 2b ONLY when `!t.mapped` AND every 64 KiB tile of `[t.cpu, t.cpu + size)` // has all 16 `Cell::restore[0..15] != 0` under `geometry_writes::state().mutex` (proving MEM_COMMIT + // readable; Look::armed alone also covers MEM_RESERVE/PAGE_NOACCESS and is never sufficient). std::vector tile_proven_readable; if (check_pages_before_read()) { bool any_need_probe = false; for (std::size_t idx = 0; idx < title_candidates_.size(); ++idx) { if (title_examine_results_[idx].look == leonida::TitleTextureWatch::Look::busy) continue; const TitleTexture& t = *title_candidates_[idx].entry; if (!t.mapped && t.memory.needs_probe(0, true, true)) { any_need_probe = true; break; } } if (any_need_probe) { tile_proven_readable.assign(title_candidates_.size(), 0); auto& gs = leonida::geometry_writes::state(); std::lock_guard gs_lock(gs.mutex); constexpr std::uintptr_t kTile = leonida::geometry_writes::tile_size; for (std::size_t idx = 0; idx < title_candidates_.size(); ++idx) { if (title_examine_results_[idx].look == leonida::TitleTextureWatch::Look::busy) continue; const TitleTexture& t = *title_candidates_[idx].entry; if (t.mapped || !t.memory.needs_probe(0, true, true)) continue; if (title_texture_active_from(t) > fill_limit(t)) continue; const std::uintptr_t cpu = static_cast(t.cpu); const std::uint64_t size = title_texture_active_span(t); if (!cpu || !size || size > (std::numeric_limits::max)() - cpu) continue; const std::uintptr_t first_tile = cpu & ~(kTile - 1); const std::uintptr_t last_tile = (cpu + static_cast(size) - 1) & ~(kTile - 1); const std::size_t n_tiles = std::size_t((last_tile - first_tile) / kTile) + 1; auto it = gs.cells.lower_bound(first_tile); std::uintptr_t tile = first_tile; bool all_restored = true; for (std::size_t ti = 0; ti < n_tiles; ++ti, tile += kTile, ++it) { if (it == gs.cells.end() || it->first != tile) { all_restored = false; break; } for (const DWORD r : it->second.restore) { if (!r) { all_restored = false; break; } } if (!all_restored) break; } if (all_restored) tile_proven_readable[idx] = 1; } } } // Per-submission budget for unmapped first-time streamed textures and partial-mip upgrades (default 16 MiB; // 0 = unlimited). Mapped textures (video planes) and already-filled dynamic updates are never deferred. static const std::uint64_t stream_budget_bytes = [] { const char* v = std::getenv("LEONIDA_TITLE_STREAM_BUDGET_MB"); const std::uint64_t mb = (v && *v) ? std::strtoull(v, nullptr, 10) : 16ull; constexpr std::uint64_t kMaxMb = (std::numeric_limits::max)() >> 20; return mb >= kMaxMb ? (std::numeric_limits::max)() : (mb << 20); }(); leonida::TitleStreamBudget stream_budget(stream_budget_bytes); for (std::size_t idx = 0; idx < title_candidates_.size(); ++idx) { TitleCandidate& cand = title_candidates_[idx]; TitleTexture& t = *cand.entry; const auto& ex = title_examine_results_[idx]; if (ex.look == leonida::TitleTextureWatch::Look::busy) { ++stats.busy; if (have_mirror) title_mirror_checks_[idx].active = false; continue; } ++stats.checked; bool readable = false; if (!tile_proven_readable.empty() && tile_proven_readable[idx]) { t.readable_from = title_texture_active_from(t); readable = t.memory.check(0, true, [&] { return true; }, true); } else { readable = title_texture_readable(t, &stage2_vq_cache); } if (!readable) { not_filled(t); if (have_mirror) title_mirror_checks_[idx].active = false; continue; } const unsigned from = fill_from(t); const std::uint64_t span = fill_bytes(t); if (from && t.unbound_bytes && state_.title_partial_bytes + t.unbound_bytes > partial_mips_budget()) { ++stats.partial_refused; t.stale = false; if (have_mirror) title_mirror_checks_[idx].active = false; continue; } const bool partial_upgrade = t.fills && from < t.filled_from; if (!stream_budget.allow(t.mapped, t.fills != 0, partial_upgrade, span)) { watch.touch(t.address); if (have_mirror) title_mirror_checks_[idx].active = false; continue; } if (t.unbound_bytes) { const auto back_start = clock::now(); bool did_back = false, did_raw = false; const bool backed_ok = back_title_texture(t, &did_back, &did_raw, from); pass_back_ns += std::uint64_t( std::chrono::duration_cast(clock::now() - back_start).count()); if (did_back) { ++stats.stage2_backed; if (did_raw) ++stats.stage2_raw_allocs; } if (!backed_ok) { not_filled(t); if (have_mirror) title_mirror_checks_[idx].active = false; continue; } } const std::size_t tiles = std::size_t(((t.cpu + span + 0xffff) & ~std::uint64_t(0xffff)) - (t.cpu & ~std::uint64_t(0xffff))) >> 16; cand.from = from; cand.span = span; cand.tiles = tiles; cand.active = true; if (have_mirror) { const bool allow_filter = ex.look == leonida::TitleTextureWatch::Look::armed; auto& mc = title_mirror_checks_[idx]; mc.cpu = t.cpu; mc.gpu = t.address; mc.bytes = span; mc.written_tiles = (allow_filter && !t.stale && t.fills && !partial_upgrade) ? &ex.written : nullptr; const bool can_tile_cmp = !t.stale && t.fills && !t.gpu_uploaded && from == t.filled_from && t.pieces.valid_for(t.cpu, span) && !ex.written.empty() && ex.written.size() <= tiles; mc.tile_cmp_written = can_tile_cmp ? &ex.written : nullptr; mc.pieces = can_tile_cmp ? &t.pieces : nullptr; mc.max_version = ex.max_version; mc.ex_armed = allow_filter; mc.active = true; any_mirror_active = true; } } const auto t_after_probe = clock::now(); const std::uint64_t probe_total_ns = std::uint64_t(std::chrono::duration_cast(t_after_probe - t_after_arm).count()); stats.examine_probe_ns += probe_total_ns; stats.examine_back_ns += pass_back_ns; stats.examine_readable_ns += probe_total_ns > pass_back_ns ? probe_total_ns - pass_back_ns : 0; stats.stage2_probes += stats.probes[0] - probes_before; // Stage 3: ONE page_mirror.mutex lock + ONE batched parallel TitleMirror::upload() for all candidates. if (have_mirror && any_mirror_active) { struct MirrorJustSyncedGuard { bool prev; explicit MirrorJustSyncedGuard(bool v) noexcept : prev(t_page_mirror_just_synced) { t_page_mirror_just_synced = v; } ~MirrorJustSyncedGuard() { t_page_mirror_just_synced = prev; } } mirror_sync_guard{mirror_just_synced}; state_.page_mirror_check_batch( title_mirror_checks_, title_mirror_feed_pages_, mirror_synced_serial, [this](std::size_t count, std::function work) { title_read_pool().run(count, std::move(work)); }); } t_after_mirror = clock::now(); stats.examine_mirror_ns += std::uint64_t( std::chrono::duration_cast(t_after_mirror - t_after_probe).count()); // Stage 4: dispatch unchanged skips, GPU mirror jobs, and CPU jobs into batched upload passes. for (std::size_t idx = 0; idx < title_candidates_.size(); ++idx) { TitleCandidate& cand = title_candidates_[idx]; if (!cand.active || !cand.entry->resource) continue; TitleTexture& t = *cand.entry; const auto& ex = title_examine_results_[idx]; const unsigned from = cand.from; const std::uint64_t span = cand.span; const std::size_t tiles = cand.tiles; bool mirror_proved_changed = false; if (have_mirror) { const auto& mc = title_mirror_checks_[idx]; if (mc.full_ok) { const bool had_mirror_hash = t.fills && t.mirror_hash_valid && from == t.filled_from && span == t.mirror_hash_span; if (had_mirror_hash && mc.mirror_hash == t.mirror_hash) { ++stats.unchanged_parts; ++stats.gpu_unchanged; t.stale = false; continue; } if (had_mirror_hash) mirror_proved_changed = true; if (gpu_detile_on && from == 0 && mc.single_chunk) { rt::d3d12::TitleImageUpload::UploadKind kind{}; bool gpu_ok = false; if (t.gpu_upload_cached_offset == mc.offset && t.gpu_upload_cached_chunk == mc.chunk_size) { gpu_ok = t.gpu_upload_cached_ok; kind = t.gpu_upload_cached_kind; } else { { std::lock_guard upload(state_.title_upload_mutex); gpu_ok = state_.title_upload.can_gpu_upload(state_, t.resource->title_binding(), t.layout, mc.offset, mc.chunk_size, kind); } t.gpu_upload_cached_offset = mc.offset; t.gpu_upload_cached_chunk = mc.chunk_size; t.gpu_upload_cached_ok = gpu_ok; t.gpu_upload_cached_kind = kind; } if (gpu_ok) { TitleJob& job = next_title_job(); job.entry = cand.entry; job.resource = t.resource; job.span = span; job.previous = (t.hashed && t.fills && !t.gpu_uploaded && t.filled_from == 0) ? std::optional(t.hash) : std::nullopt; job.gpu_mirror = true; job.gpu_kind = kind; job.mirror_buffer = mc.buffer; job.mirror_offset = mc.offset; job.mirror_chunk_size = mc.chunk_size; job.mirror_timeline = mc.timeline; job.mirror_value = mc.value; job.mirror_hash = mc.mirror_hash; job.mirror_hash_valid = true; if (!t.stale && !mirror_proved_changed && tiles > 1 && job.previous && t.pieces.valid_for(t.cpu, job.span) && !ex.written.empty() && ex.written.size() < tiles) { job.compare = true; job.written = ex.written; } if (kind == rt::d3d12::TitleImageUpload::UploadKind::mirror_detile) gpu_scratch_bytes += job.span; if (title_job_count_ >= kTitleGpuBatch || gpu_scratch_bytes >= kTitleGpuBatchBytes) run_batch(); continue; } } } else if (mc.tile_cmp > 0) { ++stats.unchanged_parts; ++stats.gpu_unchanged; t.stale = false; continue; } else if (mc.tile_cmp < 0) { mirror_proved_changed = true; } } // CPU upload path: record fallback reason for telemetry, hash-before-reserve for ALL textures // including tiles == 1 (`<= tiles`), and compare t.mirror_hash on whole reads so CPU fallback after a // GPU upload never re-uploads unchanged bytes. if (have_mirror) { const auto& mc = title_mirror_checks_[idx]; std::size_t bucket = 1; // unmirrored_other if (mc.full_ok) { bucket = mc.single_chunk ? 5 : 4; // can_gpu_rejected : multi_chunk } else if (mc.reject_reason == 1) { bucket = 0; // unmirrored_plain } else if (mc.reject_reason == 3) { bucket = 2; // in_feed } else if (mc.reject_reason == 4) { bucket = 3; // pending_bind } ++stats.cpu_fallback_by[bucket]; } else { ++stats.cpu_fallback_by[1]; // unmirrored_other } TitleJob& job = next_title_job(); job.entry = cand.entry; job.resource = t.resource; job.from = from; job.span = span; job.previous = (t.hashed && t.fills && !t.gpu_uploaded && from == t.filled_from) ? std::optional(t.hash) : std::nullopt; job.previous_mirror_hash = (t.fills && t.mirror_hash_valid && from == t.filled_from && span == t.mirror_hash_span) ? std::optional(t.mirror_hash) : std::nullopt; job.compare = !t.stale && !mirror_proved_changed && job.previous && t.pieces.valid_for(t.cpu, job.span) && !ex.written.empty() && ex.written.size() <= tiles; if (job.compare) { job.written = ex.written; } else if (!mirror_proved_changed) { ++stats.whole_by[!job.previous && !job.previous_mirror_hash ? 0 : !t.pieces.valid_for(t.cpu, job.span) ? 1 : tiles == 1 ? 2 : !ex.written.empty() ? 3 : 4]; } job.write_combined = t.is_write_combined(); job.trace = leonida::dstorage::trace_enabled() && leonida::title_gpu_views::other_view(t.cpu); ++cpu_job_count; cpu_batch_bytes += job.span; if (cpu_job_count >= kTitleBatch || cpu_batch_bytes >= kTitleBatchBytes || title_job_count_ >= kTitleGpuBatch) run_batch(); } title_candidates_.clear(); } else { t_after_mirror = clock::now(); stats.examine_arm_ns += std::uint64_t(std::chrono::duration_cast(t_after_mirror - fill_start).count()); } run_batch(); watch.update_idle_hint(); { const auto fill_end = clock::now(); const auto pass_fill = std::uint64_t(std::chrono::duration_cast(fill_end - fill_start).count()); const auto stage4_total = std::uint64_t(std::chrono::duration_cast(fill_end - t_after_mirror).count()); stats.fill_ns += pass_fill; // What is not reading or submitting: naming, arming, mirror batch sync, readability, slot reservation. const std::uint64_t other = (stats.read_ns - read_before) + (stats.staged_ns - staged_before); stats.examine_publish_ns += stage4_total > other ? stage4_total - other : 0; stats.examine_ns += pass_fill > other ? pass_fill - other : 0; } stats.filled_bytes += filled; stats.max_pass_bytes = (std::max)(stats.max_pass_bytes, filled); std::vector release; if (!retired_title_textures_.empty()) { std::int64_t next_due = 0; std::erase_if(retired_title_textures_, [&](const auto& r) { if (now - r.first < std::chrono::seconds(3)) { const std::int64_t due = std::chrono::duration_cast( (r.first + std::chrono::seconds(3)).time_since_epoch()) .count(); if (next_due == 0 || due < next_due) next_due = due; return false; } retired_backing_ -= r.second->image_backing_bytes(); release.push_back(r.second); return true; }); retired_earliest_ns_.store(next_due, std::memory_order_release); } title_pass_ = false; const std::uint64_t pass_ns = std::chrono::duration_cast(clock::now() - now).count(); stats.refresh_ns += pass_ns; stats.max_refresh_ns = (std::max)(stats.max_refresh_ns, pass_ns); if (now - stats.last_log >= std::chrono::seconds(10)) { stats.last_log = now; title_last_log_ns_.store(now_ns, std::memory_order_release); const auto& w = watch.stats(); const auto& l = title_watch_logged_; std::size_t unnamed = 0; for (const auto& [address, entry] : state_.title_textures) unnamed += entry->resource && !entry->gpu_written && entry->layout_known && !entry->owned && !entry->resource->shader_views(); std::fprintf(stderr, "[rt] d3d12: title texture refresh: %llu passes (%llu fast-path skipped); %llu textures " "written or new, %llu read whole, %llu found unchanged by their written parts alone (%llu " "GPU mirror-hashed), %llu " "left for a kernel write in progress, %llu named over tiles not armed; %llu uploaded " "(%.1f MiB; %llu CPU staged, %llu GPU linear, %llu GPU detiled), %llu read whole and " "unchanged; %llu named for the first time, %zu not named by any descriptor (not read); %llu " "written tiles, %llu arms (%llu busy, %llu refused), %llu queue overflows; %zu textures over " "%zu tiles watched, %zu tiles not armed; %.3f ms a pass, %.3f at most\n", static_cast(stats.passes), static_cast(stats.fast_passes), static_cast(stats.checked), static_cast(stats.read_whole), static_cast(stats.unchanged_parts), static_cast(stats.gpu_unchanged), static_cast(stats.busy), static_cast(w.unarmed_named - l.unarmed_named), static_cast(stats.changed), double(stats.filled_bytes) / 1048576.0, static_cast(stats.staged_fills - stats.staged_fills_logged), static_cast(stats.gpu_linear_fills), static_cast(stats.gpu_detile_fills), static_cast(stats.unchanged), static_cast(stats.first_named), unnamed, static_cast(w.written_tiles - l.written_tiles), static_cast(w.arms - l.arms), static_cast(w.arm_busy - l.arm_busy), static_cast(w.arm_failures - l.arm_failures), static_cast(w.overflows - l.overflows), watch.textures(), watch.tiles(), watch.unarmed(), double(stats.refresh_ns) * 1e-6 / double((std::max)(std::uint64_t(1), stats.passes)), double(stats.max_refresh_ns) * 1e-6); const auto& o = state_.over_gpu_target; std::fprintf(stderr, "[rt] d3d12: textures over GPU-written memory: %llu views resolved to the GPU-written image; " "not resolved: %llu format, %llu extent or samples, %llu mips or layers; %llu textures not " "filled from it\n", static_cast(o[DeviceState::kOverTargetResolved].load()), static_cast(o[DeviceState::kOverTargetFormat].load()), static_cast(o[DeviceState::kOverTargetExtent].load()), static_cast(o[DeviceState::kOverTargetRange].load()), static_cast(state_.gpu_owned_refusals)); title_watch_logged_ = w; if (leonida::fsdraw::enabled()) log_title_census("refresh"); stats.passes = stats.fast_passes = stats.checked = stats.busy = stats.changed = stats.unchanged = stats.filled_bytes = 0; stats.staged_fills_logged = stats.staged_fills; stats.gpu_linear_fills = stats.gpu_detile_fills = 0; std::fprintf(stderr, "[rt] d3d12: title textures read whole, by why: %llu never filled, %llu with no part hashes, " "%llu of one tile, %llu with every tile written, %llu with no tile written\n", static_cast(stats.whole_by[0]), static_cast(stats.whole_by[1]), static_cast(stats.whole_by[2]), static_cast(stats.whole_by[3]), static_cast(stats.whole_by[4])); stats.read_whole = stats.unchanged_parts = stats.gpu_unchanged = stats.first_named = 0; stats.whole_by = {}; const double per_pass = 1e-6 / double((std::max)(std::uint64_t(1), title_split_passes_)); std::fprintf(stderr, "[rt] d3d12: title texture pass split, ms a pass: %.3f finding what to look at (%.3f lock " "wait), %.3f naming, arming and reserving (%.3f arm, %.3f readable (%llu probes), %.3f back " "(%llu backed, %llu raw), %.3f mirror, %.3f publish), %.3f reading on %u threads (%.3f of it " "detiling, summed over them; %.1f MiB read whole a pass), %.3f recording and submitting the " "transfers\n", double(stats.collect_ns) * per_pass, double(stats.lock_wait_ns) * per_pass, double(stats.examine_ns) * per_pass, double(stats.examine_arm_ns) * per_pass, double(stats.examine_readable_ns) * per_pass, static_cast(stats.stage2_probes), double(stats.examine_back_ns) * per_pass, static_cast(stats.stage2_backed), static_cast(stats.stage2_raw_allocs), double(stats.examine_mirror_ns) * per_pass, double(stats.examine_publish_ns) * per_pass, double(stats.read_ns) * per_pass, title_read_pool_ ? title_read_pool_->threads() + 1 : 1, double(stats.detile_ns) * per_pass, double(stats.read_bytes) / 1048576.0 / double((std::max)(std::uint64_t(1), title_split_passes_)), double(stats.staged_ns) * per_pass); const auto arm_s = state_.texture_cells.arm_stats; state_.texture_cells.arm_stats = {}; std::fprintf(stderr, "[rt] d3d12: title texture arm split: %llu hot, %llu already, %llu backed, %llu fast_vp " "(%llu bridged), %llu vq (%llu cache_hit), %llu vq_vp; cpu fallback by: %llu " "unmirrored_plain, %llu unmirrored_other, %llu in_feed, %llu pending_bind, %llu multi_chunk, " "%llu can_gpu_rejected\n", static_cast(arm_s.hot), static_cast(arm_s.already), static_cast(arm_s.backed), static_cast(arm_s.fast_vp), static_cast(arm_s.bridged), static_cast(arm_s.vq), static_cast(arm_s.vq_cache), static_cast(arm_s.vq_vp), static_cast(stats.cpu_fallback_by[0]), static_cast(stats.cpu_fallback_by[1]), static_cast(stats.cpu_fallback_by[2]), static_cast(stats.cpu_fallback_by[3]), static_cast(stats.cpu_fallback_by[4]), static_cast(stats.cpu_fallback_by[5])); stats.collect_ns = stats.lock_wait_ns = stats.examine_ns = stats.examine_arm_ns = stats.examine_probe_ns = stats.examine_readable_ns = stats.examine_back_ns = stats.examine_mirror_ns = stats.examine_publish_ns = stats.read_ns = stats.detile_ns = stats.read_bytes = 0; stats.stage2_probes = stats.stage2_backed = stats.stage2_raw_allocs = 0; stats.cpu_fallback_by = {}; stats.staged_ns = 0; title_split_passes_ = 0; stats.refresh_ns = stats.max_refresh_ns = stats.max_pass_bytes = 0; } inside.reset(); lock.unlock(); state_.drain_titles_gone(); for (Resource* r : release) r->Release(); } private: struct TitleTextureStats { std::uint64_t mapped_checks = 0, mapped_changed = 0, mapped_fills = 0; // (format, Layout word, dimension, mips) of the slot-70 texture views -> views std::map, std::uint64_t> asked; std::map refused; // why a view is a null view -> views 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, unchanged = 0, busy = 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 read_whole = 0, unchanged_parts = 0, first_named = 0; std::array whole_by{}; // why read whole: first, no parts, one tile, all written, none // Why Stage 4 fell back to CPU instead of GPU mirror: unmirrored_plain, unmirrored_other, in_feed, // pending_bind, multi_chunk, can_gpu_rejected. std::array cpu_fallback_by{}; // Split of refresh_ns: waiting on title_texture_mutex (lock_wait_ns), up to the textures to look at (map // changes, notes, the watch's queue), naming and arming them (examine, mirror batch, readability, slot // reservation), the read threads' work (and of it the detile, summed over the threads), and the transfers' // recording and submission (staged_ns); bytes read whole. std::uint64_t lock_wait_ns = 0, collect_ns = 0, examine_ns = 0, read_ns = 0, detile_ns = 0, read_bytes = 0; std::uint64_t examine_arm_ns = 0, examine_probe_ns = 0, examine_readable_ns = 0, examine_back_ns = 0, examine_mirror_ns = 0, examine_publish_ns = 0; std::uint64_t stage2_probes = 0, stage2_backed = 0, stage2_raw_allocs = 0; std::uint64_t staged_fills = 0, staged_fills_logged = 0, staged_ns = 0; std::uint64_t gpu_linear_fills = 0, gpu_detile_fills = 0, gpu_unchanged = 0, fast_passes = 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, max_pass_bytes = 0, hash_ns = 0, refresh_ns = 0, max_refresh_ns = 0; // Split of refresh_ns: taking and matching the XG-written ranges, the mapped and stale textures visited every // pass (and how many), and the fills inside both. std::uint64_t written_ns = 0, every_pass_ns = 0, every_pass_visits = 0, fill_ns = 0; std::uint64_t map_ranges = 0, map_all = 0; // title memory map changes taken, passes that retried all // Readability probes (texture_memory_readable) since the last log line: [0] in refresh passes, [1] elsewhere // (slot-70 views, new images). A recheck is a probe of a texture whose memory was not readable at its last // probe; readable_now counts the rechecks that found it readable. std::array probes{}, probe_ns{}, rechecks{}, readable_now{}; std::chrono::steady_clock::time_point last_log{}; }; TitleTextureStats title_stats_; // under title_texture_mutex bool title_pass_ = false; // in refresh_title_textures, likewise struct TitleCandidate { std::shared_ptr entry; unsigned from = 0; std::uint64_t span = 0; std::size_t tiles = 0; bool active = false; }; std::vector title_named_; // refresh scratch, under title_texture_mutex std::vector title_candidate_keys_; // likewise std::vector title_candidates_; // likewise std::vector::BatchExamine> title_examine_results_; // likewise std::vector title_mirror_checks_; // likewise std::vector title_mirror_feed_pages_; // likewise std::uint64_t title_split_passes_ = 0; // passes since the split's last log line // One texture of a refresh batch: what the serial part found (the slot reserved for it, the last fill's hash) and // what a TitleReadPool thread read (read_title_job). struct TitleJob { std::shared_ptr entry; Resource* resource = nullptr; // the texture's, held by the registry for the pass rt::d3d12::TitleImageUpload::Slot* slot = nullptr; unsigned from = 0; std::uint64_t span = 0, hash = 0; std::optional previous; std::optional previous_mirror_hash; leonida::TilePieces pieces; // the texture's, then (read whole) the new ones std::vector written; // its tiles written since its last read (compare) bool compare = false, whole = false, precopied = false; std::atomic failed{false}; // a piece of a whole read could not be copied std::uint64_t detile_ns = 0; bool write_combined = false, trace = false, copied = false, unchanged = false, nonzero = false; // GPU mirror upload fields: bool gpu_mirror = false; rt::d3d12::TitleImageUpload::UploadKind gpu_kind = rt::d3d12::TitleImageUpload::UploadKind::cpu_slot; VkBuffer mirror_buffer = VK_NULL_HANDLE; VkDeviceSize mirror_offset = 0, mirror_chunk_size = 0; VkSemaphore mirror_timeline = VK_NULL_HANDLE; std::uint64_t mirror_value = 0; std::uint64_t mirror_hash = 0; bool mirror_hash_valid = false; std::vector tiled; std::vector piece_sums; std::vector columns; }; static constexpr std::size_t kTitleBatch = 64; // CPU jobs processed together (<= kMaxSlots) static constexpr std::size_t kTitleGpuBatch = 512; // total jobs (incl. GPU-mirror) per commit_batch static constexpr std::uint64_t kTitleBatchBytes = 64ull << 20; // CPU-read bytes per batch static constexpr std::uint64_t kTitleGpuBatchBytes = 128ull << 20; // GPU detile scratch bytes per batch std::deque title_jobs_; // reusable job pool, under title_texture_mutex std::size_t title_job_count_ = 0; // active jobs in current batch std::vector title_cpu_check_indices_; // indices of jobs needing CPU read_title_job std::vector title_detile_indices_; // indices of changed CPU jobs to detile std::vector title_batch_items_; std::vector title_batch_job_indices_; std::atomic title_map_generation_atomic_{0}; std::atomic retired_earliest_ns_{0}; std::atomic title_last_log_ns_{0}; std::atomic title_fast_passes_{0}; std::atomic title_refresh_in_flight_{0}; struct TitleChunk { std::size_t job, first, end; // tiles [first, end) of title_jobs_[job] }; static constexpr std::size_t kTitleChunkTiles = 16; // 1 MiB of a texture a read thread copies at a time std::vector title_chunks_; // likewise class TitleReadPool; std::unique_ptr title_read_pool_; std::once_flag title_read_pool_once_; leonida::TitleTextureWatch::Stats title_watch_logged_; // as of the last log line, likewise std::atomic refreshed_present_{~std::uint64_t(0)}; // LEONIDA_REFRESH_PER_FRAME: present of the last full refresh // LEONIDA_TITLE_FILL_ASYNC=1 (for runs that only need the title to go on): slot-70 views no longer fill or hash // the texture they name on the title's thread (speed-26/27: a title thread 68-88 % inside slot 70, in hashing, // copying and staged uploads). The texture's address is queued, and a worker of ours fills it, taking the registry // lock for one texture at a time. Until then a shader samples the image as it is: empty, or a frame behind. static bool title_fill_async() { static const bool on = [] { const char* v = std::getenv("LEONIDA_TITLE_FILL_ASYNC"); return v && std::strcmp(v, "1") == 0; }(); return on; } struct TitleFiller { std::mutex mutex; std::condition_variable wake; std::deque queue; // texture addresses std::unordered_set queued; bool stop = false; std::thread thread; std::uint64_t filled = 0, skipped = 0; std::vector tiled; // the worker's own snapshot of a texture's bytes (fill_unlocked) std::vector columns; // its detiling scratch ~TitleFiller() { { std::lock_guard lock(mutex); stop = true; } wake.notify_one(); if (thread.joinable()) thread.join(); } }; std::unique_ptr title_filler_; std::once_flag title_filler_once_; void start_title_filler() { std::call_once(title_filler_once_, [this] { title_filler_ = std::make_unique(); TitleFiller* f = title_filler_.get(); f->thread = std::thread([this, f] { run_title_filler(*f); }); }); } void queue_title_fill(std::uint64_t address) { start_title_filler(); { std::lock_guard lock(title_filler_->mutex); if (!title_filler_->queued.insert(address).second) return; title_filler_->queue.push_back(address); } title_filler_->wake.notify_one(); } void run_title_filler(TitleFiller& f) { using clock = std::chrono::steady_clock; auto since = clock::now(); for (;;) { std::uint64_t address = 0; bool fill = false; { std::unique_lock lock(f.mutex); f.wake.wait(lock, [&] { return f.stop || !f.queue.empty(); }); if (f.stop) return; fill = !f.queue.empty(); if (fill) { address = f.queue.front(); f.queue.pop_front(); f.queued.erase(address); } } if (!fill) continue; const leonida::submit_phases::WorkerScope busy(leonida::submit_phases::worker_texture_fill); bool filled = false; // A staged texture is filled without the registry lock (the title's threads creating views wait for // it: speed-31, 12 % of the main thread): its bytes, layout and resource are taken under the lock, the // copy, hash and upload are made outside it, and the result is recorded under it again if the texture // still has that resource. Others (host copies, unbound memory) are filled under the lock as before. Resource* r = nullptr; rt::xg_xs::Texture layout{}; std::uint64_t cpu = 0, fills = 0; unsigned from = 0; { std::lock_guard lock(state_.title_texture_mutex); const InTitleTextures inside; const auto it = state_.title_textures.find(address); if (it != state_.title_textures.end()) { TitleTexture& t = *it->second; if (t.resource && t.layout_known && !t.gpu_written && (t.stale || !t.hashed) && title_texture_readable(t)) { t.stale = false; if (t.resource->staged_title() && !t.unbound_bytes) { r = t.resource; r->AddRef(); layout = t.layout; cpu = t.cpu; fills = t.fills; from = fill_from(t); } else { filled = fill_title_texture(t) != 0; if (!filled) t.stale = true; } } } } if (r) { filled = fill_unlocked(address, *r, layout, cpu, fills, from, f); r->Release(); } std::size_t left = 0; { std::lock_guard lock(f.mutex); (filled ? f.filled : f.skipped) += 1; left = f.queue.size(); } if (const auto now = clock::now(); now - since >= std::chrono::seconds(10)) { std::fprintf(stderr, "[rt] d3d12: title texture fill worker: %llu filled, %llu skipped in %.0f s, %zu " "queued\n", static_cast(f.filled), static_cast(f.skipped), std::chrono::duration(now - since).count(), left); std::lock_guard lock(f.mutex); f.filled = f.skipped = 0; since = now; } } } // The fill worker's fill of a staged texture: copy, hash, reserve and detile without the registry lock, then // re-check liveness and !gpu_written under title_texture_mutex before committing the GPU transfer so a concurrent // CopyTextureRegion/CopyResource promotion can never be overwritten by a late async CPU upload. bool fill_unlocked(std::uint64_t address, Resource& r, const rt::xg_xs::Texture& layout, std::uint64_t cpu, std::uint64_t fills, unsigned from, 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)); std::uint64_t hash = 0, mirror_hash = 0; bool ok = false, nonzero = false, mirror_hash_valid = false; leonida::TilePieces pieces; std::uint64_t staged_ns = 0; rt::d3d12::TitleImageUpload::Slot* slot = nullptr; if (copied) { compute_pieces_and_mirror_hash(static_cast(cpu), span, f.tiled.data(), pieces, mirror_hash, mirror_hash_valid); hash = pieces.combined(); const auto start = std::chrono::steady_clock::now(); { std::lock_guard upload_lock(state_.title_upload_mutex); slot = state_.title_upload.reserve(state_, r.title_binding(), layout, from); } if (slot) rt::d3d12::TitleImageUpload::fill(*slot, r.title_binding(), layout, f.tiled.data(), f.columns, false, nonzero); staged_ns = std::chrono::duration_cast(std::chrono::steady_clock::now() - start) .count(); } const auto drop_slot = [&] { if (!slot) return; std::lock_guard upload_lock(state_.title_upload_mutex); rt::d3d12::TitleImageUpload::unreserve(*slot); slot = nullptr; }; std::lock_guard lock(state_.title_texture_mutex); const InTitleTextures inside; const auto it = state_.title_textures.find(address); if (it == state_.title_textures.end() || it->second->resource != &r || it->second->gpu_written) { drop_slot(); return false; // retired or promoted to GPU-written meanwhile } TitleTexture& t = *it->second; if (!copied) { t.memory.defer(); t.stale = true; return false; } if (t.fills != fills) { drop_slot(); return true; // another fill recorded itself in between: its hash is as good } if (slot) { const auto commit_start = std::chrono::steady_clock::now(); std::lock_guard upload_lock(state_.title_upload_mutex); ok = state_.title_upload.commit(state_, r.id(), r.title_binding(), layout, *slot, from); slot = nullptr; staged_ns += std::chrono::duration_cast( std::chrono::steady_clock::now() - commit_start) .count(); } title_stats_.staged_ns += staged_ns; if (!ok) { log_once("staged title texture upload failed, format", int(r.format())); ++title_stats_.fill_failures; t.stale = true; return false; } ++title_stats_.staged_fills; note_filled_from(t, from); t.gpu_uploaded = false; t.mirror_hash = mirror_hash; t.mirror_hash_span = mirror_hash_valid ? span : 0; t.mirror_hash_valid = mirror_hash_valid; t.hash = hash; t.hashed = true; t.pieces = std::move(pieces); ++t.fills; ++title_stats_.fills; title_stats_.fill_bytes += span; return true; } // LEONIDA_GEOMETRY_ASYNC: one worker runs GeometryViews::refresh whenever a submission asks and none is running. struct GeometryRefresher { std::mutex mutex; std::condition_variable wake; bool kick = false, stop = false; std::thread thread; ~GeometryRefresher() { { std::lock_guard lock(mutex); stop = true; } wake.notify_one(); if (thread.joinable()) thread.join(); } }; std::unique_ptr geometry_refresher_; std::once_flag geometry_refresher_once_; // submissions of several queues may ask at once void kick_geometry_refresh() { std::call_once(geometry_refresher_once_, [this] { geometry_refresher_ = std::make_unique(); GeometryRefresher* r = geometry_refresher_.get(); r->thread = std::thread([this, r] { for (;;) { { std::unique_lock lock(r->mutex); r->wake.wait(lock, [r] { return r->kick || r->stop; }); if (r->stop) return; r->kick = false; } const leonida::submit_phases::WorkerScope busy(leonida::submit_phases::worker_geometry); state_.geometry.refresh(DeviceState::copy_geometry); } }); }); { std::lock_guard lock(geometry_refresher_->mutex); geometry_refresher_->kick = true; } geometry_refresher_->wake.notify_one(); } std::uint64_t title_map_generation_ = 0; // under title_texture_mutex: the map changes seen leonida::TitleWriteRanges title_map_changes_; // likewise, scratch VkDeviceSize retired_backing_ = 0; std::vector> retired_title_textures_; // likewise std::vector title_tiled_, title_linear_; // scratch, under title_texture_mutex std::vector title_columns_; // The rest under title_texture_mutex. bool refuse_title_view(const char* why, const rt::xg_xs::ResourceDesc& d, std::uint64_t address) { ++title_stats_.refusals; std::uint64_t& n = title_stats_.refused[why]; static std::set> logged; if (!n++ || (logged.size() < 256 && logged.emplace(why, d.format, d.layout).second)) std::fprintf(stderr, "[rt] d3d12: slot-70 texture view is a null view (%s): dimension %u %llux%ux%u mips %u " "format %u samples %u Layout 0x%x flags 0x%x at 0x%llx\n", why, d.dimension, static_cast(d.width), d.height, unsigned(d.depth_or_array), unsigned(d.mips), d.format, d.samples, d.layout, d.flags, static_cast(address)); return false; } // The console layout of a description, as XG lays it out; false with the reason when this XG model lacks it. static bool title_layout(const rt::xg_xs::ResourceDesc& d, rt::xg_xs::Texture& out, const char*& why) { namespace xg = rt::xg_xs; const std::uint32_t mode = xg::select_mode(d); if (d.samples > 1) return why = "multisampled", false; if (mode != xg::kLinear && mode != xg::k4kbS && mode != xg::k64kbS && mode != xg::k64kbD) return why = "swizzle mode the XG model lacks", false; if (!xg::format_info(d.format).bytes) return why = "format the XG model lacks", false; xg::ResourceDesc plain = d; plain.flags &= ~(xg::kRenderTarget | xg::kDepthStencil); if (!xg::build_texture(plain, out)) return why = "description the XG model refuses", false; return true; } // The image a layout fills: the same extent, mips, layers and element (texel or 4x4 block) size. static bool title_layout_fits(const rt::xg_xs::Texture& layout, const rt::xg_xs::ResourceDesc& d, const Resource& r, const char*& why) { const D3D12_RESOURCE_DESC& desc = r.desc(); const leonida::BlockFormat element = r.copy_element(); if (desc.Width != d.width || desc.Height != d.height || desc.DepthOrArraySize != d.depth_or_array || desc.MipLevels != layout.layout.mips || UINT(desc.Dimension) != d.dimension) return why = "texture of another extent, mips or layers at the address", false; if (element.bytes != layout.format.bytes || element.block != layout.format.side) return why = "image element differs from the console's", false; return true; } // Caller holds title_texture_mutex, which the registered resource takes before destruction. Resource* matching_gpu_placement(const rt::xg_xs::ResourceDesc& d, std::uint64_t address, D3D12_RESOURCE_FLAGS required = D3D12_RESOURCE_FLAG_NONE) { std::lock_guard descriptors(state_.descriptor_mutex); const bool exact_only = (required & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) != 0; const Format asked_fmt = texture_storage_format(DXGI_FORMAT(d.format), false); return state_.gpu_placements.find(address, leonida::title_gpu_views::other_view(address), [&](const Resource& r) { if ((r.desc().Flags & required) != required) return false; if (TitleGpuPlacements::matches(d, r)) return true; if (exact_only) return false; const auto& rd = r.desc(); if (UINT(rd.Dimension) != d.dimension || rd.Width != d.width || rd.Height != d.height || rd.DepthOrArraySize != d.depth_or_array || (d.mips && rd.MipLevels != d.mips) || rd.SampleDesc.Count != d.samples) return false; if (format_family(rd.Format) != format_family(DXGI_FORMAT(d.format))) return false; // Never cross depth/stencil vs color in the format_family fallback (e.g. D32_FLOAT vs R32_UINT). if (r.aspects() != VK_IMAGE_ASPECT_COLOR_BIT || asked_fmt.format == VK_FORMAT_UNDEFINED || asked_fmt.aspects != VK_IMAGE_ASPECT_COLOR_BIT || asked_fmt.typeless) return false; // Only match when r's VkImage can legally take a VkImageView in asked_fmt.format // (VUID-VkImageViewCreateInfo-image-01762): same VkFormat, typeless color image (MUTABLE_FORMAT_BIT), // or an explicit view format list naming asked_fmt.format. if (asked_fmt.format == r.format()) return true; if (vulkan_format(rd.Format, false).typeless) return true; return r.has_view_format_list() && r.allows_view_format(asked_fmt.format); }); } // Exact physical layout equivalence between two built console layouts (mode, size, mips, array, slice_bytes, // tile/block dimensions, and per-mip offsets/pitches/extents). Used so a format-compatible slot-70 view on an // already-confirmed slot-133 texture does not invalidate hashed/mirror_hash_valid/gpu_uploaded. static bool title_layout_equal(const rt::xg_xs::Texture& a, const rt::xg_xs::Texture& b) { if (a.mode != b.mode || a.tile_width != b.tile_width || a.tile_height != b.tile_height || a.tile_depth != b.tile_depth || a.array != b.array || a.slab_bytes != b.slab_bytes || a.format.bytes != b.format.bytes || a.format.side != b.format.side || a.layout.dimension != b.layout.dimension || a.layout.size != b.layout.size || a.layout.alignment != b.layout.alignment || a.layout.mips != b.layout.mips || a.layout.planes != b.layout.planes) return false; const auto& pa = a.layout.plane[0]; const auto& pb = b.layout.plane[0]; if (pa.size != pb.size || pa.slice_bytes != pb.slice_bytes || pa.standard_mips != pb.standard_mips || pa.tail_mips != pb.tail_mips) return false; for (unsigned m = 0; m < a.layout.mips && m < rt::xg_xs::kMaxMips; ++m) { const auto& ma = pa.mips[m]; const auto& mb = pb.mips[m]; if (ma.offset != mb.offset || ma.size != mb.size || ma.slice_bytes != mb.slice_bytes || ma.pitch_texels != mb.pitch_texels || ma.pitch_bytes != mb.pitch_bytes || ma.padded_width != mb.padded_width || ma.padded_height != mb.padded_height || ma.padded_depth != mb.padded_depth || ma.width_elements != mb.width_elements || ma.height_elements != mb.height_elements || ma.depth != mb.depth || ma.in_tail != mb.in_tail || ma.swizzle != mb.swizzle || ma.tile_depth != mb.tile_depth || a.volume_mips[m].macro_offset != b.volume_mips[m].macro_offset || a.volume_mips[m].tail_x != b.volume_mips[m].tail_x || a.volume_mips[m].tail_y != b.volume_mips[m].tail_y) return false; } return true; } bool place_title_view(const rt::xg_xs::ResourceDesc& d, const std::array& words, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv, std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE destination) { if (!address) return refuse_title_view("no address", d, address); const auto write = [&](const TitleTexture& t) { const bool written = write_title_srv(*t.resource, srv, destination, d, address); if (written && !t.gpu_written && t.memory.pending()) ++title_stats_.pending_views; return written; }; auto& textures = state_.title_textures; unsigned view_mip = 0; if (srv.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D) { view_mip = leonida::effective_min_mip(srv.Texture2D.MostDetailedMip, srv.Texture2D.ResourceMinLODClamp); } else if (srv.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY) { view_mip = leonida::effective_min_mip(srv.Texture2DArray.MostDetailedMip, srv.Texture2DArray.ResourceMinLODClamp); } const auto note_view_mip = [&](TitleTexture& tex, bool already_reindexed) { unsigned effective_mip = view_mip; // If an API SRV or console-heap T# already bound this slot-133 texture before its first slot-70 view, // never narrow active_span past the finest mip already seen by those descriptors. if (!tex.owned && !tex.view_mip_set && tex.resource && tex.resource->shader_views() > 0) effective_mip = (std::min)(effective_mip, tex.resource->min_shader_view_mip()); const bool first_nonzero = !tex.view_mip_set && effective_mip > 0; const bool lowered = tex.view_mip_set && effective_mip < tex.view_mip; if (!tex.view_mip_set || lowered) { tex.view_mip = effective_mip; tex.view_mip_set = true; if (lowered || first_nonzero || !tex.fills) tex.memory.retry(); if (lowered) tex.stale = true; if (!already_reindexed && (lowered || first_nonzero)) state_.index_texture(tex); } }; 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(); // A GPU-written texture placed at the address with this description answers before the texture registered // there (bind_title_image says why); with no view of it in the view's format, the registered one does. if (Resource* gpu = matching_gpu_placement(d, address); gpu && (!t || t->resource != gpu)) { ++title_stats_.of_slot133; if (!t) return write_title_srv(*gpu, srv, destination, d, address); if (write_title_srv(*gpu, srv, destination, d, address)) { ++state_.over_gpu_target[DeviceState::kOverTargetResolved]; return true; } ++state_.over_gpu_target[DeviceState::kOverTargetFormat]; } const bool can_replace = !(d.flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) && d.dimension >= rt::xg_xs::kTexture1D && d.dimension <= rt::xg_xs::kTexture3D && d.samples <= 1; // Evicts stale incompatible gpu_owned entries sitting at the exact same CPU base address (whether registered // under `address`, `other_view(address)`, or shadowed behind a non-GPU-written slot-133 entry). Runs only after // `matching_gpu_placement(d, address)` failed to match a compatible live GPU target, and only when the new // slot-70 view has a valid non-GPU-written XG layout incompatible with the old resource. const auto evict_incompatible_gpu_owned_at_base = [&]() -> bool { if (!can_replace) return false; const char* layout_why = nullptr; rt::xg_xs::Texture layout{}; if (!title_layout(d, layout, layout_why)) return false; const std::uintptr_t base_cpu = leonida::title_gpu_views::to_cpu(address); std::vector> stale_owners; for (const auto& [owner_ptr, range] : state_.gpu_owned) { if (range.begin != base_cpu || !owner_ptr) continue; auto* owner = const_cast(static_cast(owner_ptr)); const D3D12_RESOURCE_DESC& od = owner->desc(); // Never evict a live depth/stencil target or a same-extent mip-subset RT/UAV. if (od.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) continue; if (d.width == od.Width && d.height == od.Height && d.mips > 0 && d.mips < od.MipLevels) continue; const char* fit_why = nullptr; if (od.SampleDesc.Count > 1 || !title_layout_fits(layout, d, *owner, fit_why)) stale_owners.emplace_back(owner, range.address); } if (stale_owners.empty()) return false; for (const auto& [owner, reg_addr] : stale_owners) { { std::lock_guard descriptors(state_.descriptor_mutex); state_.gpu_placements.remove(reg_addr, owner); if (reg_addr != address && owner->image_address() == reg_addr) { const auto img_it = state_.images_by_address.find(reg_addr); if (img_it != state_.images_by_address.end() && img_it->second == owner) { state_.images_by_address.erase(img_it); state_.forget_image_views_locked(reg_addr); } else { state_.note_texture_change(leonida::SlotChange::texture_gone, reg_addr); } } else { state_.note_texture_change(leonida::SlotChange::texture_gone, reg_addr); } } if (reg_addr != address) { const auto reg_it = textures.find(reg_addr); if (reg_it != textures.end() && reg_it->second->resource == owner && !reg_it->second->owned) { state_.clear_partial_budget(*reg_it->second); state_.texture_watch.untrack(reg_addr); textures.erase(reg_it); } } state_.drop_gpu_owned(owner); static std::atomic stale_gpu_logged{0}; if (stale_gpu_logged.fetch_add(1, std::memory_order_relaxed) < 32) { const D3D12_RESOURCE_DESC& old_d = owner->desc(); std::fprintf(stderr, "[rt] d3d12: evicted stale gpu_owned slot-133 texture at 0x%llx (%llux%ux%u mips %u " "fmt %d) for incompatible slot-70 view at 0x%llx (%llux%ux%u mips %u fmt %u)\n", static_cast(reg_addr), static_cast(old_d.Width), old_d.Height, unsigned(old_d.DepthOrArraySize), unsigned(old_d.MipLevels), int(old_d.Format), static_cast(address), static_cast(d.width), d.height, unsigned(d.depth_or_array), unsigned(d.mips), d.format); } } return true; }; if (t && !t->owned) { // the title's slot-133 texture ++title_stats_.of_slot133; // When a non-GPU-written slot-70 view reuses a VA still held by a stale non-owned slot-133 texture of an // incompatible shape or format, evict the stale registry mapping and create an owned slot-70 texture // instead of emitting a null view. The old slot-133 Resource* remains title-owned (COM refcount untouched, // never destroyed while in flight; title_texture_gone/forget_image_of check resource identity). const auto evict_and_replace = [&]() -> bool { const auto cur = textures.find(address); if (cur == textures.end()) return false; std::shared_ptr evicted = cur->second; state_.texture_watch.untrack(address); textures.erase(cur); TitleTexture* replacement = make_title_texture(d, words, srv, address, view_mip, {}, /*index_now=*/false); if (!replacement) { textures[address] = std::move(evicted); state_.index_texture(*textures[address]); return false; } if (evicted->gpu_written && evicted->resource) { { std::lock_guard descriptors(state_.descriptor_mutex); state_.gpu_placements.remove(address, evicted->resource); state_.note_texture_change(leonida::SlotChange::texture_gone, address); } state_.drop_gpu_owned(evicted->resource); } state_.clear_partial_budget(*evicted); evict_incompatible_gpu_owned_at_base(); state_.index_texture(*replacement); static std::atomic evicted_logged{0}; if (evicted_logged.fetch_add(1, std::memory_order_relaxed) < 32 && evicted->resource) { const D3D12_RESOURCE_DESC& old_d = evicted->resource->desc(); std::fprintf(stderr, "[rt] d3d12: evicted stale slot-133 texture at 0x%llx (%llux%ux%u mips %u fmt %d) " "for incompatible slot-70 view (%llux%ux%u mips %u fmt %u)\n", static_cast(address), static_cast(old_d.Width), old_d.Height, unsigned(old_d.DepthOrArraySize), unsigned(old_d.MipLevels), int(old_d.Format), static_cast(d.width), d.height, unsigned(d.depth_or_array), unsigned(d.mips), d.format); } return write(*replacement); }; bool shape_incompatible = false; if (!t->gpu_written && (t->layout_guessed || t->layout_from_xg || !t->layout_known || t->desc != words)) { const char* why = nullptr; rt::xg_xs::Texture layout; const bool have_layout = title_layout(d, layout, why); if (have_layout && title_layout_fits(layout, d, *t->resource, why)) { const bool same_layout = t->layout_known && !t->layout_guessed && !t->layout_from_xg && title_layout_equal(t->layout, layout); if (same_layout) { t->desc = words; } else { static std::atomic logged{0}; if (t->mapped && logged.fetch_add(1, std::memory_order_relaxed) < 32) std::fprintf(stderr, "[rt] d3d12: a slot-70 view gives mapped slot-133 texture 0x%llx its layout: " "Layout 0x%x (XG mode %u; was %s)\n", static_cast(address), d.layout, layout.mode, t->layout_guessed ? "guessed" : "unknown"); t->memory.retry(); t->write_combined_known = false; t->gpu_uploaded = false; t->mirror_hash_valid = false; t->invalidate_gpu_upload_cache(); t->layout = layout; t->desc = words; t->layout_known = true; t->layout_guessed = t->layout_from_xg = false; t->hashed = false; note_view_mip(*t, /*already_reindexed=*/true); state_.index_texture(*t); } } else if (have_layout && can_replace) { shape_incompatible = true; } else { refuse_title_view(why, d, address); // counted; the view of its image is still written } } else if (t->gpu_written && can_replace) { const char* why = nullptr; rt::xg_xs::Texture layout; if (title_layout(d, layout, why) && (t->resource->desc().SampleDesc.Count > 1 || !title_layout_fits(layout, d, *t->resource, why))) shape_incompatible = true; } if (shape_incompatible) return evict_and_replace(); if (!t->gpu_written && t->layout_known) { note_view_mip(*t, /*already_reindexed=*/false); refresh_title_texture(*t); } const bool written = write_title_srv(*t->resource, srv, destination, d, address, /*count_refusal=*/!can_replace); if (written) { if (!t->gpu_written && t->memory.pending()) ++title_stats_.pending_views; return true; } if (can_replace) return evict_and_replace(); return false; } if (t && !title_texture_matches(*t, words, srv)) { std::vector formats = t->formats; const bool same_shape = [&] { auto a = t->desc, b = words; a[1] = a[2] = a[3] = a[8] = a[13] = 0; // padding, alignment and format b[1] = b[2] = b[3] = b[8] = b[13] = 0; return a == b && rt::xg_xs::format_info(t->desc[8]).bytes == rt::xg_xs::format_info(words[8]).bytes && rt::xg_xs::format_info(t->desc[8]).side == rt::xg_xs::format_info(words[8]).side; }(); retire_title_texture(*t); state_.texture_watch.untrack(address); textures.erase(address); t = make_title_texture(d, words, srv, address, view_mip, same_shape ? formats : std::vector{}, /*index_now=*/false); if (t) { evict_incompatible_gpu_owned_at_base(); state_.index_texture(*t); } } else if (t) { ++title_stats_.of_cache; note_view_mip(*t, /*already_reindexed=*/false); refresh_title_texture(*t); } else { t = make_title_texture(d, words, srv, address, view_mip, {}, /*index_now=*/false); if (t) { evict_incompatible_gpu_owned_at_base(); state_.index_texture(*t); } } return t && write(*t); } // An image made for slot-70 views serves another view when all non-format/non-padding/non-alignment description // words match and the image's mutable format list already covers both the resource format and the view's format. static bool title_texture_matches(const TitleTexture& t, const std::array& words, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv) { auto a = t.desc, b = words; a[1] = a[2] = a[3] = a[8] = a[13] = 0; b[1] = b[2] = b[3] = b[8] = b[13] = 0; if (a != b) return false; const auto has = [&](DXGI_FORMAT f) { return std::find(t.formats.begin(), t.formats.end(), f) != t.formats.end(); }; return has(DXGI_FORMAT(words[8])) && (srv.Format == DXGI_FORMAT_UNKNOWN || has(srv.Format)); } 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, unsigned view_mip, std::vector formats, bool index_now = true) { 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)) return refuse_title_view("GPU-written texture with no slot-133 texture at its address", d, address), nullptr; if (d.dimension < xg::kTexture1D || d.dimension > xg::kTexture3D) return refuse_title_view("dimension", d, address), nullptr; auto entry = std::make_shared(); const char* why = nullptr; if (!title_layout(d, entry->layout, why)) return refuse_title_view(why, d, address), nullptr; entry->address = address; entry->cpu = leonida::title_gpu_views::to_cpu(address); entry->layout_known = true; entry->owned = true; entry->view_mip = view_mip; entry->view_mip_set = true; // 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_texture(*entry, false); }); // 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). const auto add = [&](DXGI_FORMAT f) { if (f != DXGI_FORMAT_UNKNOWN && std::find(formats.begin(), formats.end(), f) == formats.end()) formats.push_back(f); }; add(DXGI_FORMAT(d.format)); if (srv.Format != DXGI_FORMAT_UNKNOWN && srv.Format != DXGI_FORMAT(d.format)) { const xg::Format a = xg::format_info(d.format), b = xg::format_info(srv.Format); if (a.bytes != b.bytes || a.side != b.side) return refuse_title_view("view format of another element size", d, address), nullptr; add(srv.Format); } D3D12_RESOURCE_DESC pc{}; pc.Dimension = D3D12_RESOURCE_DIMENSION(d.dimension); pc.Width = d.width; pc.Height = d.height; pc.DepthOrArraySize = d.depth_or_array; pc.MipLevels = UINT16(entry->layout.layout.mips); pc.Format = formats.front(); pc.SampleDesc = {1, 0}; pc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; pc.Flags = D3D12_RESOURCE_FLAG_NONE; const Format host = state_.texture_format(pc); if (host.format == VK_FORMAT_UNDEFINED) return refuse_title_view("format the layer lacks", d, address), nullptr; if (host.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return refuse_title_view("depth or stencil format", d, address), nullptr; // Keep CPU-copy semantics. Resource::create_texture selects host copies or staged uploads from Vulkan requirements. const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0, 1, 1}; static const bool defer = [] { const char* value = std::getenv("LEONIDA_TITLE_IMAGE_DEFER"); return !value || std::strcmp(value, "0"); }(); const auto origin = defer && (entry->memory.pending() || entry->readable_from > 0) ? TitleImageOrigin::pending_stream : TitleImageOrigin::streamed; void* made = nullptr; const HRESULT hr = create_committed(&heap, D3D12_HEAP_FLAG_NONE, &pc, D3D12_RESOURCE_STATE_COMMON, formats.size() > 1 ? UINT32(formats.size()) : 0, formats.data(), __uuidof(ID3D12Resource), &made, std::nullopt, origin); Resource* r = SUCCEEDED(hr) && made ? Resource::from(static_cast(made)) : nullptr; if (!r) { if (made) static_cast(made)->Release(); log_once("an image for a slot-70 texture view could not be made; HRESULT", int(hr)); return refuse_title_view("image not created", d, address), nullptr; } if (!title_layout_fits(entry->layout, d, *r, why)) { r->Release(); return refuse_title_view(why, d, address), nullptr; } // Owned internally by this Device (in state_.title_textures / retired_title_textures_, never handed out as a // public COM child): detach its device self-reference so Device -> owned TitleTexture -> Device cannot form a // COM refcount cycle that prevents ~Device() from running. ~Device() releases all owned/retired entries. if (IUnknown* self_ref = r->detach_device()) self_ref->Release(); r->place_at_title_address(reinterpret_cast(static_cast(address))); entry->desc = words; entry->set_resource(r); entry->formats = std::move(formats); if (entry->memory.pending() && entry->readable_from <= fill_limit(*entry)) entry->memory.retry(); // some mips do for this view title_stats_.unreadable += entry->memory.pending(); // Defer slot-70 uploads to batched refresh_title_textures() (GPU detile + single batched vkQueueSubmit // before GPU submission) instead of running a synchronous single-texture CPU upload inside CreateSRV. // state_.index_texture(*entry) tracks and touches the watch since entry->stale == true. entry->stale = true; const bool readable = title_fill_async() && title_texture_readable(*entry); ++title_stats_.made; TitleTexture* t = entry.get(); if (index_now) state_.index_texture(*entry); state_.title_textures[address] = std::move(entry); if (readable) queue_title_fill(address); return t; } void retire_title_texture(TitleTexture& t) { if (!t.owned || !t.resource) return; // Its T#s leave the hash table now (a later texture at the address takes them over); the image itself goes // a few seconds later, when no submission can still read it. Only while it still holds the address: a // slot-133 texture placed there since (register_title_texture retires this entry right after the placement // took the address over) keeps it, or every T# naming the address would find no texture. state_.clear_partial_budget(t); if (t.resource->image_address()) state_.forget_image_of(t.resource->image_address(), t.resource); retired_backing_ += t.resource->image_backing_bytes(); const auto retired_at = std::chrono::steady_clock::now(); retired_title_textures_.emplace_back(retired_at, t.resource); const std::int64_t due = std::chrono::duration_cast( (retired_at + std::chrono::seconds(3)).time_since_epoch()) .count(); const std::int64_t prev = retired_earliest_ns_.load(std::memory_order_acquire); if (prev == 0 || due < prev) retired_earliest_ns_.store(due, std::memory_order_release); t.resource = nullptr; ++title_stats_.retired; } // LEONIDA_TITLE_PARTIAL_MIPS (default ON; set 0 to opt out). A 2D single-slice texture whose larger mips are not // readable is filled from the first mip that is, with every smaller one. Views whose effective minimum mip // (MostDetailedMip and ResourceMinLODClamp) is at or above that mip finalize immediately; finer views either clamp // to the filled mip via VK_EXT_image_view_min_lod (and upgrade when finer mips arrive) or stay on the fallback. // LEONIDA_TITLE_PARTIAL_MIPS_MB bounds the image memory held by textures filled in part. static bool partial_mips() { return title_partial_mips_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; } // 2D single-slice non-GPU-written textures with a known non-guessed layout (slot-70 deferred streams and // non-GPU-written slot-133 textures) may hold a resident mip tail [from .. mips-1]. static bool partial_texture(const TitleTexture& t) { if (!partial_mips() || t.gpu_written || !t.layout_known || t.layout_guessed || !t.resource) return false; if (t.layout.layout.dimension != rt::xg_xs::kTexture2D || t.layout.array != 1 || t.layout.layout.mips <= 1) return false; if (t.owned) return t.resource->deferred_stream() || (t.view_mip_set && t.view_mip > 0); return t.resource->deferred_stream() || t.resource->image_backing_bytes() != 0 || t.resource->unbound_bytes() != 0; } // The largest first mip a fill may start at: what is filled already is never left half old. // With VK_EXT_image_view_min_lod, any partially readable mip chain (readable_from < mips) can be filled and views // requesting finer mips are clamped to filled_from until finer mips arrive; otherwise require view_mip >= from. unsigned fill_limit(const TitleTexture& t) const { if (!partial_texture(t)) return 0; if (t.fills) return t.filled_from; const unsigned max_mip = t.layout.layout.mips - 1; if (state_.info.image_view_min_lod && (t.resource->deferred_stream() || !t.owned)) return max_mip; return (std::min)(t.view_mip, max_mip); } unsigned fill_from(const TitleTexture& t) const { return (std::min)(t.readable_from, fill_limit(t)); } std::uint64_t fill_bytes(const TitleTexture& t) const { 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.resource && (!t.fills || from < t.filled_from)) { if (t.resource->deferred_stream()) t.resource->publish_streamed_texture(from); else if (from > 0) t.resource->enable_partial_stream(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.backing_bytes && !t.partial_budget_counted) { state_.title_partial_bytes += t.backing_bytes; t.partial_budget_counted = true; } else if (!from && t.partial_budget_counted) { state_.clear_partial_budget(t); } t.filled_from = from; } static bool texture_probe() { static const bool enabled = [] { const char* v = std::getenv("LEONIDA_TEXTURE_PROBE"); return v && std::strcmp(v, "0"); }(); return enabled; } static bool check_pages_before_read() { static const bool enabled = [] { const char* v = std::getenv("LEONIDA_TEXTURE_PAGE_CHECK"); return !v || std::strcmp(v, "0"); }(); return enabled; } static bool refresh_mapped_pages() { static const bool enabled = [] { const char* value = std::getenv("LEONIDA_REFRESH_MAPPED_TEXTURES"); return !value || std::strcmp(value, "0"); }(); return enabled; } // 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, leonida::TextureVqCache* vq_cache = nullptr) { const auto start = std::chrono::steady_clock::now(); const std::uint64_t probe_bytes = title_texture_active_span(t); t.readable_from = rt::xg_xs::first_mip_within( t.layout, leonida::texture_memory_readable_bytes(std::uintptr_t(t.cpu), probe_bytes, commit, vq_cache)); 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( std::chrono::steady_clock::now() - start).count(); ++s.probes[where]; s.rechecks[where] += waited; s.readable_now[where] += waited && readable; return readable; } // A mapped texture can lose its pages between views or between refreshes. bool title_texture_readable(TitleTexture& t, leonida::TextureVqCache* vq_cache = nullptr) { const bool guard = check_pages_before_read(); if (!guard && !t.memory.pending()) return true; const bool mapped = t.mapped && refresh_mapped_pages(); if (!title_pass_ && guard) t.memory.sync_map(title_map_generation_, static_cast(t.cpu), title_texture_active_span(t)); const auto commit = mapped ? leonida::kernel_writes::state().committer.load(std::memory_order_acquire) : nullptr; const bool waited = t.memory.pending(); // 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. Keep cache_failure = guard && !mapped (a mapped plane may commit // via raw VirtualAlloc without notifying title_memory_map), while enabling cache_success = guard (unmaps // notify title_memory_map and reads are SEH-guarded). return t.memory.check(0, guard && !mapped, [&] { return probe_title_texture(t, waited, commit, mapped ? nullptr : vq_cache); }, guard); } // At a slot-70 view of a texture: defer uploads to the batched refresh_title_textures() pass before GPU // submission (setting stale = true AND touching texture_watch so the O(1) fast-path never skips it). void refresh_title_texture(TitleTexture& t) { // LEONIDA_TITLE_FILL_ASYNC=1: a view does not fill; the texture goes to the fill worker. if (title_fill_async()) { if (!t.hashed || t.stale) queue_title_fill(t.address); return; } // If a deferred pending_stream image's pages have now arrived, back its VkImage and publish its views // immediately so existing and new slot-70 descriptors get their bindless indices, while still deferring the // texel upload to the batched refresh_title_textures() pass before GPU submission. bool checked_readable = false; bool is_readable = false; bool need_upgrade = false; if (t.unbound_bytes || (t.resource && t.resource->deferred_stream())) { checked_readable = true; is_readable = title_texture_readable(t); if (is_readable) { const unsigned from = fill_from(t); if (t.fills && from < t.filled_from) { // Finer mips just became readable for an already-filled partial texture: mark stale so the next // refresh uploads them and note_filled_from() upgrades the views AFTER the texels land. need_upgrade = true; } else if (!t.fills) { if ((!from || !t.unbound_bytes || state_.title_partial_bytes + t.unbound_bytes <= partial_mips_budget()) && back_title_texture(t, nullptr, nullptr, from)) { if (t.resource && t.resource->deferred_stream()) { // On the staged (!host_transfer) path, register_bound_texture() leaves the image in // VK_IMAGE_LAYOUT_UNDEFINED: ensure note_shader_image() moves it out of UNDEFINED ahead of // any shader submission even if the subsequent texture upload is deferred. if (!t.resource->host_transfer()) state_.context->note_shader_image(t.resource->id()); t.resource->publish_streamed_texture(from); } } } } } if ((!t.hashed || t.stale || need_upgrade) && (!t.memory.pending() || (checked_readable ? is_readable : title_texture_readable(t)))) { t.stale = true; state_.texture_watch.touch(t.address); } } // Snapshot the footprint (that of the mips the fill is for), then upload it through the title upload // (TitleImageUpload): the transfer is submitted at once, ordered on the GPU after all earlier work and before every // later submission, and nothing waits for the GPU on the CPU (VulkanContext::write_staged_title_image). It never // re-enters the D3D12 submit callbacks, so the refresh before a submission may use it. A concurrent unmap defers // the fill. std::uint64_t fill_title_texture(TitleTexture& t) { const rt::xg_xs::Texture& layout = t.layout; 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 && state_.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), t.is_write_combined())) { // The section changed after VirtualQuery. Preserve the last complete upload and retry. t.memory.defer(); t.stale = true; return 0; } if (!back_title_texture(t, nullptr, nullptr, from)) return 0; // Every byte: a texture is read only when something says it changed, so this is its one read; bytes equal to // the last fill's (a write to another texture in the same 64 KiB tile, or the same texels again) are not // uploaded again. Uses 4-lane 256-byte piece hashing so both per-tile hashes and the full-texture mirror_hash // are computed in one pass and match TitleMirror::range_sum() bit-for-bit on 256B-aligned textures. leonida::TilePieces new_pieces; std::uint64_t mirror_hash = 0; bool mirror_hash_valid = false; compute_pieces_and_mirror_hash(static_cast(t.cpu), span, title_tiled_.data(), new_pieces, mirror_hash, mirror_hash_valid); const std::uint64_t hash = new_pieces.combined(); if (t.hashed && t.fills && !t.gpu_uploaded && from == t.filled_from && hash == t.hash) { ++title_stats_.unchanged; t.pieces = std::move(new_pieces); if (mirror_hash_valid) { t.mirror_hash = mirror_hash; t.mirror_hash_span = span; t.mirror_hash_valid = true; } t.stale = false; return 0; } const bool trace_pool = leonida::dstorage::trace_enabled() && leonida::title_gpu_views::other_view(t.cpu); bool nonzero = false; const auto start = std::chrono::steady_clock::now(); const bool 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())); if (!ok) { ++title_stats_.fill_failures; t.stale = true; return 0; } if (trace_pool) std::fprintf(stderr, "[rt] ds-pool-fill cpu=%llx size=%llu staged=1 nonzero=%d\n", static_cast(t.cpu), static_cast(span), int(nonzero)); note_filled_from(t, from); t.gpu_uploaded = false; t.mirror_hash = mirror_hash; t.mirror_hash_span = mirror_hash_valid ? span : 0; t.mirror_hash_valid = mirror_hash_valid; t.pieces = std::move(new_pieces); t.hash = hash; t.hashed = true; t.stale = false; ++t.fills; ++title_stats_.fills; title_stats_.fill_bytes += span; return span; } // A texture whose image has no memory yet gets it before its first fill. False (and stale) when it cannot. bool back_title_texture(TitleTexture& t, bool* did_back = nullptr, bool* did_raw_alloc = nullptr, unsigned publish_from = 0) { if (!t.unbound_bytes) return true; if (t.owned ? !t.resource->back_streamed_texture() : !t.resource->back_placed_texture(publish_from)) { t.stale = true; return false; } if (did_back) *did_back = true; if (did_raw_alloc && t.resource) *did_raw_alloc = !t.resource->pooled_image(); t.mirror_hash_valid = false; t.set_resource(t.resource); if (publish_from && t.backing_bytes && !t.partial_budget_counted) { state_.title_partial_bytes += t.backing_bytes; t.partial_budget_counted = true; } return true; } // Computes TilePieces (per-tile 256-byte piece-sum digests) and, when 256B-aligned, the full-texture // TitleMirror::range_sum()-compatible digest in a single pass over `tiled` (4-lane ~18 GB/s). static void compute_pieces_and_mirror_hash(std::uintptr_t cpu, std::uint64_t span, const std::uint8_t* tiled, leonida::TilePieces& pieces, std::uint64_t& out_mirror_hash, bool& out_mirror_valid) { constexpr std::uint64_t kPiece = leonida::shadow_keep::kPiece; const bool mirror_aligned = (cpu & (kPiece - 1)) == 0 && (span & (kPiece - 1)) == 0 && span != 0; out_mirror_valid = mirror_aligned; std::uint64_t full_h = mirror_aligned ? (14695981039346656037ull ^ span) : 0; pieces.cpu = cpu; pieces.span = span; pieces.hashes.clear(); pieces.hashes.reserve(leonida::TilePieces::tiles(cpu, span)); for (std::uintptr_t tile = cpu & ~(leonida::TilePieces::kTile - 1); tile < cpu + span; tile += leonida::TilePieces::kTile) { const auto [offset, length] = leonida::TilePieces::part(cpu, span, tile); std::uint64_t tile_h = 14695981039346656037ull ^ length; for (std::uint64_t off = 0; off < length; off += kPiece) { const std::size_t n = static_cast((std::min)(kPiece, length - off)); const std::uint64_t s = leonida::shadow_keep::sum_of(tiled + offset + off, n); tile_h = (tile_h ^ s) * 1099511628211ull; tile_h ^= tile_h >> 29; if (mirror_aligned) { full_h = (full_h ^ s) * 1099511628211ull; full_h ^= full_h >> 29; } } pieces.hashes.push_back(tile_h); } out_mirror_hash = full_h; } // Guarded 256-byte piece-sum digest for title memory: copies the written tile slice (<= 64 KiB, hot in L1/L2) via // copy_guarded (SEH-safe under clang-cl/Wine, MOVNTDQA for write-combined pages, and handles xmem title_frames) // and delegates directly to leonida::mirror_range_sum_bytes() -> shadow_keep::sum_of(). That keeps CPU tile // hashes 100% bit-for-bit identical to TitleMirror::range_sum() regardless of SIMD implementation (scalar, SSE2, // or AVX2) in shadow_keep::sum_of(). static bool hash_title_piece_guarded(std::uintptr_t from, std::uint64_t bytes, bool write_combined, std::vector& scratch, std::uint64_t& out) { if (!bytes) { out = 0; return true; } if (scratch.size() < bytes) scratch.resize(std::size_t(bytes)); if (!copy_guarded(scratch.data(), reinterpret_cast(from), std::size_t(bytes), write_combined)) return false; out = leonida::mirror_range_sum_bytes(scratch.data(), bytes); return true; } // A pass's first-stage hash check of one texture, on a TitleReadPool thread (before any staging slot is reserved): // hashes only the written tiles (including 1-tile textures!). If unchanged, no staging reserve happens. For all // 1-tile CPU-compared textures (cached or write-combined), copies once into the reusable job.tiled buffer so a // changed 1-tile texture is never read twice and skips read_title_chunk completely. Reads job.entry->pieces // directly without deep-copying its hash vector. void read_title_job(TitleJob& job) { const TitleTexture& t = *job.entry; job.whole = false; job.precopied = false; if (job.gpu_mirror && !job.compare) return; if (job.compare) { if (!job.gpu_mirror && job.written.size() == 1 && t.pieces.hashes.size() == 1 && job.span <= leonida::TilePieces::kTile) { job.tiled.resize(std::size_t(job.span)); if (!copy_guarded(job.tiled.data(), reinterpret_cast(t.cpu), std::size_t(job.span), job.write_combined)) { job.copied = false; return; } const std::uint64_t h = leonida::mirror_range_sum_bytes(job.tiled.data(), job.span); if (h == t.pieces.hashes[0]) { job.copied = job.unchanged = true; return; } job.pieces.reset(t.cpu, job.span); job.pieces.hashes[0] = h; const bool mirror_aligned = (t.cpu & (leonida::shadow_keep::kPiece - 1)) == 0 && (job.span & (leonida::shadow_keep::kPiece - 1)) == 0; job.mirror_hash = mirror_aligned ? h : 0; job.mirror_hash_valid = mirror_aligned; job.copied = true; job.precopied = true; job.whole = true; return; } if (t.pieces.unchanged(job.written, [&](std::uintptr_t from, std::uint64_t bytes) { std::uint64_t h = 0; return hash_title_piece_guarded(from, bytes, job.write_combined, job.tiled, h) ? std::optional(h) : std::nullopt; })) { job.copied = job.unchanged = true; return; } } if (!job.gpu_mirror) job.whole = true; } // The bytes of tiles [first, end) of a texture read whole (its parts), and their hashes: a texture of many tiles // is read by several threads at once (a 4K video plane, a streamed texture), not by one. Computes each 256-byte // piece sum once into job.piece_sums (when 256B-aligned) and mixes each tile's hash simultaneously. void read_title_chunk(TitleJob& job, std::size_t first, std::size_t end) { const TitleTexture& t = *job.entry; const std::uintptr_t base = t.cpu & ~std::uintptr_t(0xffff); const auto [from, unused] = leonida::TilePieces::part(t.cpu, job.span, base + first * 0x10000); const auto [last_offset, last_length] = leonida::TilePieces::part(t.cpu, job.span, base + (end - 1) * 0x10000); const std::uint64_t to = last_offset + last_length; if (!copy_guarded(job.tiled.data() + from, reinterpret_cast(t.cpu + from), std::size_t(to - from), job.write_combined)) { job.failed.store(true, std::memory_order_relaxed); return; } constexpr std::uint64_t kPiece = leonida::shadow_keep::kPiece; const bool store_sums = !job.piece_sums.empty(); for (std::size_t i = first; i < end; ++i) { const auto [offset, length] = leonida::TilePieces::part(t.cpu, job.span, base + i * 0x10000); std::uint64_t tile_h = 14695981039346656037ull ^ length; std::size_t piece_idx = store_sums ? static_cast(offset / kPiece) : 0; for (std::uint64_t off = 0; off < length; off += kPiece) { const std::size_t n = static_cast((std::min)(kPiece, length - off)); const std::uint64_t s = leonida::shadow_keep::sum_of(job.tiled.data() + offset + off, n); tile_h = (tile_h ^ s) * 1099511628211ull; tile_h ^= tile_h >> 29; if (store_sums) job.piece_sums[piece_idx++] = s; } job.pieces.hashes[i] = tile_h; } } // After whole-read chunks finish: combine the piece hashes (and mirror_hash from precomputed 256-byte sums) and // determine if bytes changed (BEFORE reserving any staging slot). Runs inline on the calling thread. void hash_title_job(TitleJob& job) { if (!job.whole || job.gpu_mirror) return; if (!job.precopied) { job.copied = !job.failed.load(std::memory_order_relaxed); if (!job.copied) return; if (!job.piece_sums.empty()) { job.mirror_hash = leonida::mirror_range_sum_from_pieces(job.piece_sums.data(), job.piece_sums.size(), job.span); job.mirror_hash_valid = true; } } job.hash = job.pieces.combined(); const bool same_hash = job.previous && *job.previous == job.hash; const bool same_mirror = job.previous_mirror_hash && job.mirror_hash_valid && *job.previous_mirror_hash == job.mirror_hash; job.unchanged = same_hash || same_mirror; } // Parallel CPU detile into the staging slot reserved ONLY for changed CPU jobs. void detile_title_job(TitleJob& job) { const auto detile_start = std::chrono::steady_clock::now(); job.nonzero = false; rt::d3d12::TitleImageUpload::fill(*job.slot, job.resource->title_binding(), job.entry->layout, job.tiled.data(), job.columns, job.trace, job.nonzero); job.detile_ns = std::uint64_t(std::chrono::duration_cast( std::chrono::steady_clock::now() - detile_start) .count()); } // A few threads of ours for the refresh's reads: run(n, f) calls f(0..n-1) on them and on the calling thread, // and returns when all are done. Runs count <= 1 directly inline with zero mutex/condvar/wakeup overhead. class TitleReadPool { public: explicit TitleReadPool(unsigned threads) { for (unsigned i = 0; i < threads; ++i) threads_.emplace_back([this] { serve(); }); } ~TitleReadPool() { { std::lock_guard lock(mutex_); stop_ = true; } wake_.notify_all(); for (auto& thread : threads_) thread.join(); } TitleReadPool(const TitleReadPool&) = delete; TitleReadPool& operator=(const TitleReadPool&) = delete; void run(std::size_t count, std::function work) { if (!count) return; if (count == 1 || threads_.empty()) { for (std::size_t i = 0; i < count; ++i) work(i); return; } { std::lock_guard lock(mutex_); work_ = std::move(work); count_ = count; next_.store(0, std::memory_order_relaxed); busy_ = threads_.size(); ++generation_; } wake_.notify_all(); drain(work_); std::unique_lock lock(mutex_); done_.wait(lock, [&] { return busy_ == 0; }); work_ = nullptr; } private: void drain(const std::function& work) { for (std::size_t i; (i = next_.fetch_add(1, std::memory_order_relaxed)) < count_;) work(i); } void serve() { std::uint64_t seen = 0; for (;;) { std::function work; { std::unique_lock lock(mutex_); wake_.wait(lock, [&] { return stop_ || generation_ != seen; }); if (stop_) return; seen = generation_; work = work_; } { const leonida::submit_phases::WorkerScope busy(leonida::submit_phases::worker_texture_reads); drain(work); } std::lock_guard lock(mutex_); if (!--busy_) done_.notify_all(); } } std::mutex mutex_; std::condition_variable wake_, done_; std::function work_; std::size_t count_ = 0, busy_ = 0; std::atomic next_{0}; std::uint64_t generation_ = 0; bool stop_ = false; std::vector threads_; public: unsigned threads() const { return unsigned(threads_.size()); } }; TitleReadPool& title_read_pool() { std::call_once(title_read_pool_once_, [this] { const unsigned cores = std::max(1u, std::thread::hardware_concurrency()); title_read_pool_ = std::make_unique(std::clamp(cores / 4, 1u, 7u)); }); return *title_read_pool_; } static bool title_memory_write_combined(std::uint64_t address) { MEMORY_BASIC_INFORMATION region{}; return VirtualQuery(reinterpret_cast(static_cast(address)), ®ion, sizeof(region)) && (region.Protect & PAGE_WRITECOMBINE); } bool write_title_srv(Resource& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& srv, D3D12_CPU_DESCRIPTOR_HANDLE dest, const rt::xg_xs::ResourceDesc& d, std::uint64_t address, bool count_refusal = true) { CreateShaderResourceView(static_cast(&r), &srv, dest); const auto* w = reinterpret_cast(dest.ptr); const auto written = [w] { return (w[0] | w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7]) != 0; }; if (written()) return true; // A slot-133 texture made in a stand-in format (an R9G9B9E5 target as R11G11B10F, console_format_stand_ins) // has no view in the console format: the view in the texture's own format reads what it holds. if (srv.Format != DXGI_FORMAT_UNKNOWN && srv.Format == r.desc().Format) { D3D12_SHADER_RESOURCE_VIEW_DESC own = srv; own.Format = DXGI_FORMAT_UNKNOWN; CreateShaderResourceView(static_cast(&r), &own, dest); if (written()) { log_once("a slot-70 view in another format than its texture's reads it in the texture's own format; " "view format", int(srv.Format)); return true; } } if (!count_refusal) return false; static std::atomic logged{0}; if (logged.fetch_add(1, std::memory_order_relaxed) < 16) std::fprintf(stderr, "[rt] d3d12: slot-70 view of a title texture at 0x%llx refused by the SRV checks: view format " "%d dimension %d mapping 0x%x (texture format %d)\n", static_cast(address), int(srv.Format), int(srv.ViewDimension), unsigned(srv.Shader4ComponentMapping), int(r.desc().Format)); return refuse_title_view("SRV refused for the texture", d, address); } // One line of what slot 70 was asked for, and one of what the refresh did since the last line (NOTES: step 4). void log_title_census(const char* when) { TitleTextureStats& s = title_stats_; std::vector>> asked; for (const auto& [key, n] : s.asked) asked.emplace_back(n, key); std::sort(asked.rbegin(), asked.rend()); std::string census; for (std::size_t i = 0; i < asked.size() && i < 24; ++i) { char text[64]; std::snprintf(text, sizeof(text), "%s%u/0x%x/%u/%u:%llu", i ? " " : "", asked[i].second[0], asked[i].second[1], asked[i].second[2], asked[i].second[3], static_cast(asked[i].first)); census += text; } std::string refused; for (const auto& [why, n] : s.refused) refused += (refused.empty() ? "" : "; ") + why + " " + std::to_string(n); std::size_t owned = 0, slot133 = 0, mapped = 0, filled = 0; VkDeviceSize owned_bytes = 0, placed_bytes = 0, host_heap_bytes = 0; for (const auto& [address, t] : state_.title_textures) { (t->owned ? owned : slot133) += 1; if (!t->owned && t->resource && t->unbound_bytes) t->set_resource(t->resource); mapped += t->mapped; filled += t->fills > 0; (t->owned ? owned_bytes : placed_bytes) += t->backing_bytes; if (!t->device_local) host_heap_bytes += t->backing_bytes; } if (leonida::mem_probe::interval_seconds()) log_title_image_uses(state_.title_textures, retired_title_textures_.size(), retired_backing_, state_.zero_image_bytes.load()); if (leonida::mem_probe::interval_seconds()) std::fprintf(stderr, "[rt] mem-probe: registered image backing: %.1f MiB from slot 70, %.1f MiB from slot " "133, %.1f MiB total on non-device-local types; staged fills %llu, %.3f s, buffer %.1f MiB\n", double(owned_bytes) / 1048576.0, double(placed_bytes) / 1048576.0, double(host_heap_bytes) / 1048576.0, static_cast(s.staged_fills), double(s.staged_ns) / 1e9, double(state_.title_upload.capacity()) / 1048576.0); std::fprintf(stderr, "[rt] d3d12: title textures (%s): %llu slot-70 texture views (%zu kinds), %llu of slot-133 textures, " "%llu of images made for them (%llu made, %llu over memory not readable yet, %llu retired), %llu " "null views; registry %zu images " "(%zu made, %zu slot 133 of %llu registered, %zu mapped, %zu filled); %llu fills %.1f MiB, %llu " "failed\n", when, static_cast(s.views), s.asked.size(), static_cast(s.of_slot133), static_cast(s.of_cache), static_cast(s.made), static_cast(s.unreadable), static_cast(s.retired), static_cast(s.null_views), state_.title_textures.size(), owned, slot133, 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)); } std::fprintf(stderr, "[rt] d3d12: slot-70 views awaiting readable memory: %llu\n", static_cast(s.pending_views)); std::fprintf(stderr, "[rt] d3d12: title textures census (format/Layout/dimension/mips:views): %s\n", census.c_str()); if (!refused.empty()) std::fprintf(stderr, "[rt] d3d12: title textures null views by reason: %s\n", refused.c_str()); std::string maps; std::size_t listed = 0; for (const auto& [address, t] : state_.title_textures) { if (!t->mapped || !t->resource || listed++ >= 16) continue; const D3D12_RESOURCE_DESC& rd = t->resource->desc(); char text[160]; std::snprintf(text, sizeof(text), "%s0x%llx %llux%u fmt %d layout %s mode %u, %u T#s, %llu fills", maps.empty() ? "" : "; ", static_cast(address), static_cast(rd.Width), rd.Height, int(rd.Format), t->layout_guessed ? "guessed" : t->layout_from_xg ? "XG" : t->layout_known ? "viewed" : "none", t->layout.mode, t->resource->shader_views(), static_cast(t->fills)); maps += text; } if (!maps.empty()) std::fprintf(stderr, "[rt] d3d12: title textures mapped: %s\n", maps.c_str()); if (s.passes) { std::fprintf(stderr, "[rt] d3d12: title texture refresh: %llu passes, %llu XG-written ranges, %llu textures " "checked (%.1f MiB read for hashes), %llu changed, %llu deferred, %.1f MiB filled (%.2f MiB a " "pass on average, %.2f MiB at most)\n", static_cast(s.passes), static_cast(s.written_ranges), static_cast(s.checked), double(s.hashed) / 1048576.0, static_cast(s.changed), static_cast(s.deferred), double(s.filled_bytes) / 1048576.0, double(s.filled_bytes) / 1048576.0 / double(s.passes), double(s.max_pass_bytes) / 1048576.0); const double ms_per_ns_per_pass = 1e-6 / double(s.passes); std::fprintf(stderr, "[rt] title texture hash time %.3f ms/pass; refresh total %.3f ms/pass\n", double(s.hash_ns) * ms_per_ns_per_pass, double(s.refresh_ns) * ms_per_ns_per_pass); // What the passes cost and why: the probes of memory (texture_memory_readable) and the textures that // wait for readable memory, now. std::size_t waiting = 0, waiting_stale = 0, waiting_mapped = 0, stale = 0; for (const auto& [address, t] : state_.title_textures) { if (t->gpu_written || !t->layout_known || !t->resource) continue; stale += t->stale; if (!t->memory.pending()) continue; ++waiting; waiting_stale += t->stale; waiting_mapped += t->mapped; } const double per_pass = 1.0 / double(s.passes); std::fprintf(stderr, "[rt] title texture rechecks: %.1f probes a pass (%.3f ms/pass), %.1f of waiting textures a " "pass (%llu found readable now); %zu textures wait for readable memory (%zu stale, %zu " "mapped), %zu stale in all; max pass %.3f ms; outside passes %llu probes (%.3f ms), %llu of " "waiting textures, %llu found readable\n", double(s.probes[0]) * per_pass, double(s.probe_ns[0]) * ms_per_ns_per_pass, double(s.rechecks[0]) * per_pass, static_cast(s.readable_now[0]), waiting, waiting_stale, waiting_mapped, stale, double(s.max_refresh_ns) * 1e-6, static_cast(s.probes[1]), double(s.probe_ns[1]) * 1e-6, static_cast(s.rechecks[1]), static_cast(s.readable_now[1])); // passes, checked, changed and filled_bytes belong to the refresh's own 10 s line, which resets them: reset // here too (LEONIDA_FSDRAW_PROBE prints this census far more often) they read 0 uploads there (run 64). s.hashed = s.deferred = 0; std::fprintf(stderr, "[rt] title texture pass split: written ranges and map changes %.3f ms/pass (%.1f map ranges a " "pass, %llu passes probed all), mapped and stale textures %.3f ms/pass (%.1f visited a pass), " "fills %.3f ms/pass\n", double(s.written_ns) * ms_per_ns_per_pass, double(s.map_ranges) * per_pass, static_cast(s.map_all), double(s.every_pass_ns) * ms_per_ns_per_pass, double(s.every_pass_visits) * per_pass, double(s.fill_ns) * ms_per_ns_per_pass); s.written_ns = s.every_pass_ns = s.every_pass_visits = s.fill_ns = s.map_ranges = s.map_all = 0; s.hash_ns = s.refresh_ns = s.max_refresh_ns = 0; s.written_ranges = 0; s.probes = s.probe_ns = s.rechecks = s.readable_now = {}; } } public: void own(const OwnedRuntime& owned) { owned_ = owned; } void set_outer(IUnknown* outer) { outer_ = outer; } // The buffer resource holding console VA `va`, with a reference added for the caller, or null when no resource this // layer made holds it. `start` and `size` are the resource's first VA and byte size. // Only this layer's own buffers have a VA in the registry (the swapchain's are images, a copy's staging binding has // no VA), so an ID found by VA is the ID3D12Resource pointer of a Resource (resource_id). ID3D12Resource* add_ref_buffer_at(std::uint64_t va, std::uint64_t bytes, std::uint64_t& start, std::uint64_t& size) { leonida::ResourceId id = 0; ID3D12Resource* found = nullptr; const bool ok = state_.context->buffer_resource_at(va, bytes, id, start, size, [&](leonida::ResourceId candidate) { auto* resource = static_cast(reinterpret_cast(candidate)); if (!resource->try_add_ref()) return false; found = resource; return true; }); return ok ? found : nullptr; } class RawTileReader { public: RawTileReader(std::uint64_t address, std::size_t size) : address_(address), size_(size), cache_(std::min(size, block_size * slots)) { tags_.fill(SIZE_MAX); } bool copy(std::size_t offset, std::uint8_t* to, std::size_t bytes) { if (offset > size_ || bytes > size_ - offset) return false; while (bytes) { const auto block = offset / block_size; const auto slot = block % slots; const auto base = block * block_size; const auto available = std::min(block_size, size_ - base); auto* window = cache_.data() + slot * block_size; if (tags_[slot] != block) { // A page xmem's frame table holds (no host view: src/title_frames.h) is read through its frame. const auto from = static_cast(address_ + base); if (!leonida::title_frames::for_each_part(from, available, [&](std::uintptr_t at, std::size_t n, std::uint8_t* frame) { if (frame) return copy_guarded_host(window + (at - from), frame, n, false); SIZE_T copied{}; return ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(at), window + (at - from), n, &copied) && copied == n; })) return false; tags_[slot]=block; } const auto n=std::min(bytes,available-(offset-base)); std::memcpy(to,window+offset-base,n); offset+=n;to+=n;bytes-=n; } return true; } private: static constexpr std::size_t block_size = 64 * 1024, slots = 8; std::uint64_t address_; std::size_t size_; std::vector cache_; std::array tags_; }; bool raw_texture_view(const D3D12_RESOURCE_DESC& raw, const D3D12_SHADER_RESOURCE_VIEW_DESC& view, std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE destination) { namespace ct = leonida::console_texture; if (!address || !destination.ptr || (address & 255) || raw.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return false; Resource* placed = nullptr; { std::lock_guard lock(state_.title_image_mutex); auto [begin, end] = state_.title_images.equal_range(address); for (auto it = begin; it != end; ++it) { const auto& shape = it->second->desc(); if (raw.Width == shape.Width && raw.Height == shape.Height && raw.Format == shape.Format && raw.DepthOrArraySize == shape.DepthOrArraySize && raw.MipLevels == shape.MipLevels && raw.SampleDesc.Count == shape.SampleDesc.Count && it->second->try_add_ref()) { placed = it->second; break; } } } if (placed) { CreateShaderResourceView(placed, &view, destination); placed->Release(); return true; } // Raw sampled surfaces have no COM owner. Only consume the full span of a retained title allocation // and a layout the console texture computer can actually untile. if (view.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D || raw.DepthOrArraySize != 1 || raw.MipLevels != 1 || raw.SampleDesc.Count != 1 || (unsigned(raw.Flags) & 0x0f) || raw.Width > ct::kMaxExtent || raw.Height > ct::kMaxExtent || (view.Format != raw.Format && view.Format != DXGI_FORMAT_UNKNOWN)) return false; const UINT mode = unsigned(raw.Layout); if (mode != 0 && mode != 1 && (mode & ~255u) != 256u) return false; const UINT swizzle = mode == 0 ? ct::kSw4kbS : mode == 1 ? ct::kLinear : mode & 255u; ct::TextureDesc d{}; d.width = static_cast(raw.Width); d.height = raw.Height; d.format = unsigned(raw.Format); d.swizzle = swizzle; const auto texture = ct::Texture::make(d); if (!texture || texture->planes.size() != 1 || !texture->planes[0].layout.addressable()) return false; const auto fmt = ct::format(d.format); if (!fmt || fmt->stencil) return false; const auto& level = texture->planes[0].layout; const auto& mip = level.mips[0]; const std::size_t row = std::size_t(mip.width) * fmt->bytes, bytes = row * mip.height; std::uint64_t lo = 0, hi = 0; if (!bytes || row > UINT_MAX || bytes > UINT_MAX || texture->size > SIZE_MAX || !leonida::title_va_aliases().title_memory(address, lo, hi) || texture->size > hi - address) return false; // Bound CPU and transfer scratch per upload. The full title surface can be hundreds of // megabytes; the title already owns its source, and the copy on the GPU is the one sampled. RawTileReader source(address,static_cast(texture->size)); constexpr std::size_t stripe_bytes = 2 * 1024 * 1024; const UINT max_rows = static_cast(std::min(mip.height, std::max(1,stripe_bytes/row))); std::vector linear(row*max_rows); std::vector columns; if (swizzle != ct::kLinear) { std::uint64_t origin{}; if (level.offset(0,0,0,0,origin)!=ct::Error::ok) return false; columns.resize(mip.width); for (UINT x=0; x(state_, clean, heap, D3D12_HEAP_FLAG_NONE); const Format backing = state_.texture_format(clean); if (backing.format == VK_FORMAT_UNDEFINED || backing.typeless || FAILED(resource->create_texture(backing))) { raw_images_.erase(key); return false; } resource->set_raw_image_address(address); cached.resource = std::move(resource); } const UINT stripes = (mip.height + max_rows - 1) / max_rows; cached.fingerprints.resize(stripes); for (UINT first=0, strip=0; firstbytes,fmt->bytes)) return false; } } const std::span content(linear.data(),used); const auto digest = leonida::sha256_hex(content); if (cached.fingerprints[strip] == digest) continue; const UINT bottom = std::min(raw.Height,(first+rows)*fmt->block); const D3D12_BOX box{0,first*fmt->block,0,UINT(raw.Width),bottom,1}; const HRESULT hr = cached.resource->WriteToSubresource(0,&box,linear.data(),UINT(row),UINT(used)); if (FAILED(hr)) return false; cached.fingerprints[strip] = digest; } CreateShaderResourceView(cached.resource.get(), &view, destination); return true; } UINT STDMETHODCALLTYPE GetNodeCount() override { return 1; } // The Vulkan physical device's LUID, which is the DXGI adapter's on Windows. Zero (logged) when the driver has // none to report (deviceLUIDValid false). LUID STDMETHODCALLTYPE GetAdapterLuid() override { return state_.luid; } // The CUSTOM equivalent of a standard heap type, from the D3D12 documentation's table for the architecture // D3D12_FEATURE_ARCHITECTURE reports. NUMA (a discrete GPU): DEFAULT is GPU-only memory in L1, UPLOAD // write-combined and READBACK write-back system memory in L0, GPU_UPLOAD write-combined L1. UMA (an integrated // GPU, CacheCoherentUMA FALSE): the same pages, all in L0, as the host runtime answers on a Radeon 780M (AMD // 32.0.13030.13001). The pool only names the answer; memory is chosen by the CPU page property either way. CUSTOM // and unknown types have // no equivalent and get an all-zero answer (D3D12 reports them through the debug layer), with node 0 in both node // masks as the host runtime gives it (d3d12_fence_timing_test compares CUSTOM, an unknown type and node mask 2). D3D12_HEAP_PROPERTIES STDMETHODCALLTYPE GetCustomHeapProperties(UINT node_mask, D3D12_HEAP_TYPE type) override { D3D12_HEAP_PROPERTIES properties{}; properties.CreationNodeMask = properties.VisibleNodeMask = 1; if (node_mask > 1) { log_once("GetCustomHeapProperties node mask", int(node_mask)); return properties; } switch (type) { case D3D12_HEAP_TYPE_DEFAULT: properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE; properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L1; break; case D3D12_HEAP_TYPE_UPLOAD: properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE; properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; break; case D3D12_HEAP_TYPE_READBACK: properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; break; case D3D12_HEAP_TYPE_GPU_UPLOAD: properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE; properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L1; break; default: log_once("GetCustomHeapProperties heap type without a custom equivalent:", int(type)); return properties; } if (state_.uma) properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; properties.Type = D3D12_HEAP_TYPE_CUSTOM; return properties; } HRESULT STDMETHODCALLTYPE SetEventOnMultipleFenceCompletion(ID3D12Fence* const* fences, const UINT64* values, UINT count, D3D12_MULTIPLE_FENCE_WAIT_FLAGS flags, HANDLE event) override { return set_event_on_multiple_fence_completion(*state_.context, fences, values, count, flags, event, identity()); } HRESULT STDMETHODCALLTYPE GetDeviceRemovedReason() override { if (removed_.load(std::memory_order_acquire)) return DXGI_ERROR_DEVICE_REMOVED; return (state_.context && state_.context->is_device_lost()) ? DXGI_ERROR_DEVICE_REMOVED : S_OK; } // Residency and power (D3D-33, docs/d3d12_vulkan.md section 4.1). Vulkan has no residency API: memory from // vkAllocateMemory stays usable by the device until vkFreeMemory, and paging under pressure is the kernel // driver's job (WDDM on Windows), invisible to the application. So every pageable object of this device is // always resident, MakeResident has nothing to do and Evict, which D3D12 documents as a hint the runtime may // defer, can be dropped. Only the arguments are checked; the objects themselves are not touched. HRESULT STDMETHODCALLTYPE MakeResident(UINT count, ID3D12Pageable* const* objects) override { return count && !objects ? E_INVALIDARG : S_OK; } HRESULT STDMETHODCALLTYPE Evict(UINT count, ID3D12Pageable* const* objects) override { return count && !objects ? E_INVALIDARG : S_OK; } // Device1: priorities only order what the OS evicts first under memory pressure. VK_EXT_pageable_device_local_memory // could pass them on, but it is optional and changes no result, so they are accepted and dropped. Any UINT is a // valid priority (the D3D12_RESIDENCY_PRIORITY values are named points, the low 24 bits a refinement). As on the // host runtime (d3d12_residency_test, RTX 3060 / 610.88), only objects that own their memory take one: committed // resources and heaps. A placed resource (a reserved one too, by the same rule; not measured), a descriptor heap, a query heap or a fence is E_INVALIDARG. // The host also removes its device then (DXGI_ERROR_INVALID_CALL); the layer doesn't, since a console title that // sets priorities on its placed resources would lose its device over a hint. HRESULT STDMETHODCALLTYPE SetResidencyPriority(UINT count, ID3D12Pageable* const* objects, const D3D12_RESIDENCY_PRIORITY* priorities) override { if (count && (!objects || !priorities)) return E_INVALIDARG; for (UINT i = 0; i < count; ++i) { if (from(objects[i])) continue; const Resource* resource = from(objects[i]); if (!resource || !resource->committed()) return E_INVALIDARG; } return S_OK; } // Device3: the asynchronous MakeResident. The objects are already resident, so the work is complete at once // and the fence is signalled from the CPU now. The caller's queue Wait on it must not hang, which is why the // signal is kept although the residency part is a no-op. DENY_OVERBUDGET cannot fail: nothing is paged in. A // null fence is accepted, as the host runtime does: there is nothing to signal. HRESULT STDMETHODCALLTYPE EnqueueMakeResident(D3D12_RESIDENCY_FLAGS flags, UINT count, ID3D12Pageable* const* objects, ID3D12Fence* fence, UINT64 value) override { if ((count && !objects) || (flags & ~D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET)) return E_INVALIDARG; return fence ? fence->Signal(value) : S_OK; } // Stable power state pins GPU clocks for profiling, a developer-mode feature on Windows. Vulkan has no clock // control (vendor tools do it outside the API), and the game's frame does not depend on the clocks, so the // request is accepted. Success is what D3D12 returns on a machine where the call is allowed. HRESULT STDMETHODCALLTYPE SetStablePowerState(BOOL) override { return S_OK; } // Device6: lets the driver run background shader recompilation and profiling-guided optimisation. Vulkan // drivers do that, if at all, without an API to steer it, so there is nothing to start or stop. The completion // event is set at once, since no measurement is running, and no further measurements are wanted. HRESULT STDMETHODCALLTYPE SetBackgroundProcessingMode(D3D12_BACKGROUND_PROCESSING_MODE mode, D3D12_MEASUREMENTS_ACTION action, HANDLE event, BOOL* further_measurements) override { if (unsigned(mode) > unsigned(D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_PROFILING_BY_SYSTEM) || unsigned(action) > unsigned(D3D12_MEASUREMENTS_ACTION_DISCARD_PREVIOUS)) return E_INVALIDARG; if (further_measurements) *further_measurements = FALSE; if (event) SetEvent(event); return S_OK; } // STUB HRESULT STDMETHODCALLTYPE EnumerateMetaCommands(UINT* count, D3D12_META_COMMAND_DESC*) override { if (!count) return E_INVALIDARG; *count = 0; return S_OK; } HRESULT STDMETHODCALLTYPE EnumerateMetaCommandParameters(REFGUID, D3D12_META_COMMAND_PARAMETER_STAGE, UINT*, UINT*, D3D12_META_COMMAND_PARAMETER_DESC*) override { return E_INVALIDARG; } HRESULT STDMETHODCALLTYPE CreateMetaCommand(REFGUID, UINT, const void*, SIZE_T, REFIID, void** out) override { if (out) *out = nullptr; return E_INVALIDARG; } // STUB D3D12_DRIVER_MATCHING_IDENTIFIER_STATUS STDMETHODCALLTYPE CheckDriverMatchingIdentifier( D3D12_SERIALIZED_DATA_TYPE type, const D3D12_SERIALIZED_DATA_DRIVER_MATCHING_IDENTIFIER*) override { return type == D3D12_SERIALIZED_DATA_RAYTRACING_ACCELERATION_STRUCTURE ? D3D12_DRIVER_MATCHING_IDENTIFIER_UNRECOGNIZED : D3D12_DRIVER_MATCHING_IDENTIFIER_UNSUPPORTED_TYPE; } // STUB void STDMETHODCALLTYPE RemoveDevice() override { removed_.store(true, std::memory_order_release); } HRESULT STDMETHODCALLTYPE CreateCommandQueue(const D3D12_COMMAND_QUEUE_DESC* desc, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device::CreateCommandQueue"; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); // As the host runtime: no bundle queues, the three D3D12 priorities (realtime refused, below), one flag and // one node. A valid description without an output is E_UNEXPECTED there, not a capability check. if (desc->Type == D3D12_COMMAND_LIST_TYPE_BUNDLE || UINT(desc->Type) > D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE || (desc->Priority != D3D12_COMMAND_QUEUE_PRIORITY_NORMAL && desc->Priority != D3D12_COMMAND_QUEUE_PRIORITY_HIGH && desc->Priority != D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME) || (desc->Flags & ~D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT) || desc->NodeMask > 1) { log_once("CreateCommandQueue refused (type, priority, flags or node mask), type", desc->Type); return d3d12_trace::result(method, E_INVALIDARG); } // Global realtime priority needs SeIncreaseBasePriorityPrivilege enabled in the effective token, as on the // Windows D3D12 runtime; without it, this answer. Vulkan queue priorities (and VK_KHR_global_priority) are // fixed at vkCreateDevice time before CreateCommandQueue is called, so a privileged request leases from the // device's pre-created VkQueue pool like D3D12_COMMAND_QUEUE_PRIORITY_HIGH and logs the approximation once. if (desc->Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME && !has_global_realtime_privilege()) { log_once("CreateCommandQueue refused (global realtime priority), type", desc->Type); return d3d12_trace::result(method, DXGI_ERROR_ACCESS_DENIED); } if (!out) return d3d12_trace::result(method, E_UNEXPECTED); *out = nullptr; if (desc->Type != D3D12_COMMAND_LIST_TYPE_DIRECT && desc->Type != D3D12_COMMAND_LIST_TYPE_COMPUTE && desc->Type != D3D12_COMMAND_LIST_TYPE_COPY) return d3d12_trace::result(method, E_INVALIDARG); if (desc->Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME) log_once("CreateCommandQueue: global realtime priority runs on a standard-priority Vulkan queue, type", desc->Type); // Caller-owned devices that only provide the legacy queue cannot acquire more handles from their VkDevice. if (state_.info.command_queues.empty()) return d3d12_trace::result(method, create_command_queue(*state_.context, state_.info.queue, state_.info.queue_family, *desc, riid, out, identity(), state_.clock_for(state_.info.queue_family))); // A VkQueue of the type's own family first, then the graphics family; shared when every one is in use. const bool compute = desc->Type == D3D12_COMMAND_LIST_TYPE_COMPUTE; const bool copy = desc->Type == D3D12_COMMAND_LIST_TYPE_COPY; auto& own_users = compute ? compute_users_ : copy_users_; const auto& own_queues = compute ? state_.info.compute_queues : state_.info.copy_queues; const std::uint32_t own_family = compute ? state_.info.compute_family : state_.info.copy_family; const std::span own = compute || copy ? std::span(own_users) : std::span(); std::vector* users = nullptr; std::size_t slot = 0; std::uint32_t sharing = 0; // other D3D12 queues already on the chosen VkQueue { std::lock_guard lock(queue_mutex_); const auto chosen = leonida::pick_queue_slot({own, queue_users_}); if (chosen.pool == SIZE_MAX) return d3d12_trace::result(method, E_OUTOFMEMORY); // no VkQueue at all users = chosen.pool == 0 ? &own_users : &queue_users_; slot = chosen.index; sharing = (*users)[slot]++; } const bool own_pool = users != &queue_users_; if (sharing) log_once("CreateCommandQueue: every Vulkan queue of the family is in use; this D3D12 queue shares one with " "the others on it (their batches run in submission order), type", desc->Type); // Child holds a device reference until after the lease has been released. std::shared_ptr lease(nullptr, [this, users, slot](void*) { std::lock_guard lock(queue_mutex_); --(*users)[slot]; }); const VkQueue queue = own_pool ? own_queues[slot] : state_.info.command_queues[slot]; const std::uint32_t family = own_pool ? own_family : state_.info.queue_family; return d3d12_trace::result(method, create_command_queue(*state_.context, queue, family, *desc, riid, out, identity(), state_.clock_for(family), std::move(lease))); } HRESULT STDMETHODCALLTYPE CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device::CreateCommandAllocator"; return d3d12_trace::result(method, create_command_allocator(type, riid, out, identity())); } HRESULT STDMETHODCALLTYPE CreateCommandList(UINT node_mask, D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator* allocator, ID3D12PipelineState* state, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device::CreateCommandList"; if (out) *out = nullptr; if (node_mask & ~1u) return d3d12_trace::result(method, E_INVALIDARG); // one node, as the host answers // The initial pipeline state is set as SetPipelineState would set it (a bundle's is its first deferred call). HRESULT hr = create_command_list(type, allocator, riid, out, identity(), state); return d3d12_trace::result(method, hr); } // Device4: a list created closed, without an allocator. HRESULT STDMETHODCALLTYPE CreateCommandList1(UINT node_mask, D3D12_COMMAND_LIST_TYPE type, D3D12_COMMAND_LIST_FLAGS, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device4::CreateCommandList1"; // The host runtime's order ("command list1:" cases): one node and a type up to VIDEO_ENCODE (non-zero // D3D12_COMMAND_LIST_FLAGS are ignored by the host runtime), then a null output is E_UNEXPECTED. if (out) *out = nullptr; if ((node_mask & ~1u) || UINT(type) > UINT(D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE)) return d3d12_trace::result(method, E_INVALIDARG); if (!out) return d3d12_trace::result(method, E_UNEXPECTED); ID3D12CommandAllocator* allocator = nullptr; HRESULT hr = create_command_allocator(type, IID_PPV_ARGS(&allocator), identity()); if (FAILED(hr)) return d3d12_trace::result(method, hr); ID3D12GraphicsCommandList* list = nullptr; hr = create_command_list(type, allocator, IID_PPV_ARGS(&list), identity()); allocator->Release(); if (FAILED(hr)) return d3d12_trace::result(method, hr); list->Close(); hr = list->QueryInterface(riid, out); list->Release(); return d3d12_trace::result(method, hr); } HRESULT STDMETHODCALLTYPE CreateFence(UINT64 initial, D3D12_FENCE_FLAGS flags, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device::CreateFence"; // As the host runtime: known flags only, cross-adapter only when shared, and no non-monitored fences // (refused there even with both sharing flags). A null output is a capability check. constexpr UINT known = D3D12_FENCE_FLAG_SHARED | D3D12_FENCE_FLAG_SHARED_CROSS_ADAPTER | D3D12_FENCE_FLAG_NON_MONITORED; if ((UINT(flags) & ~known) || (flags & D3D12_FENCE_FLAG_NON_MONITORED) || ((flags & D3D12_FENCE_FLAG_SHARED_CROSS_ADAPTER) && !(flags & D3D12_FENCE_FLAG_SHARED))) { log_once("CreateFence refused, flags", int(flags)); return d3d12_trace::result(method, E_INVALIDARG); } if (!out) return d3d12_trace::result(method, S_FALSE); return d3d12_trace::result(method, create_fence(*state_.context, initial, flags, riid, out, identity())); } HRESULT STDMETHODCALLTYPE CreateCommandSignature(const D3D12_COMMAND_SIGNATURE_DESC* desc, ID3D12RootSignature* root_signature, REFIID riid, void** out) override { if (out) *out = nullptr; // The host refuses these with E_INVALIDARG (compare_invalid_arguments, "command signature:"): one node, a // known type per argument, exactly one draw or dispatch and it comes last, a root signature for root // arguments, and a stride that is a multiple of 4 and holds every argument. if (!desc || desc->NumArgumentDescs == 0 || !desc->pArgumentDescs || (desc->NodeMask & ~1u)) return E_INVALIDARG; UINT64 size = 0; // packed bytes; a large Num32BitValuesToSet must not wrap past ByteStride UINT64 creation_padding = 0; for (UINT i = 0; i < desc->NumArgumentDescs; ++i) { const D3D12_INDIRECT_ARGUMENT_DESC& arg = desc->pArgumentDescs[i]; switch (arg.Type) { case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW: size += sizeof(D3D12_DRAW_ARGUMENTS); break; case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: size += sizeof(D3D12_DRAW_INDEXED_ARGUMENTS); break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH: size += sizeof(D3D12_DISPATCH_ARGUMENTS); break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_RAYS: size += sizeof(D3D12_DISPATCH_RAYS_DESC); break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH: size += sizeof(D3D12_DISPATCH_MESH_ARGUMENTS); break; case D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW: size += sizeof(D3D12_VERTEX_BUFFER_VIEW); break; case D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW: size += sizeof(D3D12_INDEX_BUFFER_VIEW); break; case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT: size += UINT64{4} * arg.Constant.Num32BitValuesToSet; break; // Tier 1.1 generates the incrementing value: it occupies no argument-buffer bytes. // Preserve the existing creation-time stride check on this tier-1.0 device; this is not tier-1.1 support. case compat::kIndirectArgumentIncrementingConstant: creation_padding += 4; break; case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW: case D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW: case D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW: size += sizeof(D3D12_GPU_VIRTUAL_ADDRESS); break; default: return E_INVALIDARG; } if (size + creation_padding > desc->ByteStride) return E_INVALIDARG; const bool draw = arg.Type <= D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH || arg.Type == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_RAYS || arg.Type == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; const bool root_argument = !draw && arg.Type != D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW && arg.Type != D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW; if (draw != (i + 1 == desc->NumArgumentDescs) || (root_argument && !root_signature)) return E_INVALIDARG; } if (desc->ByteStride % 4) return E_INVALIDARG; if (!out) return E_UNEXPECTED; // the host's answer for a valid description and no output leonida::IndirectKind kind; switch (desc->pArgumentDescs[desc->NumArgumentDescs - 1].Type) { case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW: kind = leonida::IndirectKind::draw; break; case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: kind = leonida::IndirectKind::draw_indexed; break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH: kind = leonida::IndirectKind::dispatch; break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH: // As DispatchMesh: only a device with mesh shaders (MeshShaderTier 1) takes it. if (!state_.info.mesh_shader) return E_NOTIMPL; kind = leonida::IndirectKind::dispatch_mesh; break; default: return E_NOTIMPL; } return create_command_signature(kind, desc->ByteStride, static_cast(size), riid, out, identity(), {desc->pArgumentDescs, desc->NumArgumentDescs - 1}); } void STDMETHODCALLTYPE GetRaytracingAccelerationStructurePrebuildInfo( const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS* desc, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO* out) override { if (!out) return; *out = {}; if (!desc) return; if (desc->Type != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL && desc->Type != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL) return; if (desc->DescsLayout != D3D12_ELEMENTS_LAYOUT_ARRAY && desc->DescsLayout != D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS) return; const bool is_tlas = (desc->Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL); if (!is_tlas && desc->NumDescs > 0) { if (desc->DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY) { if (!desc->pGeometryDescs) return; } else { if (!desc->ppGeometryDescs) return; for (UINT i = 0; i < desc->NumDescs; ++i) if (!desc->ppGeometryDescs[i]) return; } } auto& vk = state_.context->vk; if (state_.context->xdxr_acceleration_structures()) { // XDXR records: the layout depends only on the triangle or instance count and on whether the nodes are // BOX16 (MINIMIZE_MEMORY, bottom level; xdxr_build.h). Its size has room for the most nodes a tree of // that many elements can have; a build's own size, in its header, is what COMPACTED_SIZE reports. An // update refits (no sort); the build's scratch size covers it. leonida::BuildAccelerationStructure build{}; build.is_tlas = is_tlas; if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY) build.build_flags |= VK_BUILD_ACCELERATION_STRUCTURE_LOW_MEMORY_BIT_KHR; if (build.is_tlas) { build.instance_count = desc->NumDescs; } else { for (UINT i = 0; i < desc->NumDescs; ++i) { const D3D12_RAYTRACING_GEOMETRY_DESC* gd = (desc->DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS) ? desc->ppGeometryDescs[i] : &desc->pGeometryDescs[i]; if (gd->Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES) continue; leonida::RtTriangleGeometry t{}; t.vertex_count = gd->Triangles.VertexCount; t.index_count = gd->Triangles.IndexCount; t.index_type = gd->Triangles.IndexFormat == DXGI_FORMAT_UNKNOWN ? 0u : 1u; build.triangles.push_back(t); } } leonida::XdxrLayout layout; if (!layout.compute(leonida::VulkanContext::xdxr_elements(build), build.is_tlas, leonida::VulkanContext::xdxr_box16(build))) return; out->ResultDataMaxSizeInBytes = layout.size; out->ScratchDataSizeInBytes = layout.scratch; out->UpdateScratchDataSizeInBytes = layout.scratch; return; } if (!state_.info.ray_tracing || !vk.vkGetAccelerationStructureBuildSizesKHR) return; std::vector geoms; std::vector max_prims; if (is_tlas) { VkAccelerationStructureGeometryKHR g{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR}; g.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR; g.geometry.instances.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR; g.geometry.instances.arrayOfPointers = desc->DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS ? VK_TRUE : VK_FALSE; geoms.push_back(g); max_prims.push_back(desc->NumDescs); } else { for (UINT i = 0; i < desc->NumDescs; ++i) { const D3D12_RAYTRACING_GEOMETRY_DESC* gd = (desc->DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS) ? (desc->ppGeometryDescs ? desc->ppGeometryDescs[i] : nullptr) : (desc->pGeometryDescs ? &desc->pGeometryDescs[i] : nullptr); if (!gd || gd->Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES) continue; VkAccelerationStructureGeometryKHR g{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR}; g.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR; g.flags = (gd->Flags & D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE) ? VK_GEOMETRY_OPAQUE_BIT_KHR : 0u; auto& tr = g.geometry.triangles; tr.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR; tr.vertexFormat = (gd->Triangles.VertexFormat == DXGI_FORMAT_R32G32_FLOAT) ? VK_FORMAT_R32G32_SFLOAT : VK_FORMAT_R32G32B32_SFLOAT; tr.vertexStride = gd->Triangles.VertexBuffer.StrideInBytes; tr.maxVertex = gd->Triangles.VertexCount ? (gd->Triangles.VertexCount - 1u) : 0u; tr.indexType = (gd->Triangles.IndexFormat == DXGI_FORMAT_R16_UINT) ? VK_INDEX_TYPE_UINT16 : ((gd->Triangles.IndexFormat == DXGI_FORMAT_R32_UINT) ? VK_INDEX_TYPE_UINT32 : VK_INDEX_TYPE_NONE_KHR); geoms.push_back(g); const std::uint32_t prims = (gd->Triangles.IndexFormat != DXGI_FORMAT_UNKNOWN && gd->Triangles.IndexCount >= 3) ? (gd->Triangles.IndexCount / 3u) : (gd->Triangles.VertexCount / 3u); max_prims.push_back(prims); } } if (geoms.empty()) return; VkAccelerationStructureBuildGeometryInfoKHR bgi{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR}; bgi.type = is_tlas ? VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR : VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR; if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE) bgi.flags |= VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR; if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_TRACE) bgi.flags |= VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR; if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_BUILD) bgi.flags |= VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR; if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY) // as the build gets it bgi.flags |= VK_BUILD_ACCELERATION_STRUCTURE_LOW_MEMORY_BIT_KHR; bgi.geometryCount = static_cast(geoms.size()); bgi.pGeometries = geoms.data(); VkAccelerationStructureBuildSizesInfoKHR sizes{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR}; vk.vkGetAccelerationStructureBuildSizesKHR(state_.info.device, VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, &bgi, max_prims.data(), &sizes); out->ResultDataMaxSizeInBytes = sizes.accelerationStructureSize; out->ScratchDataSizeInBytes = sizes.buildScratchSize; out->UpdateScratchDataSizeInBytes = sizes.updateScratchSize; } HRESULT STDMETHODCALLTYPE CreateDescriptorHeap(const D3D12_DESCRIPTOR_HEAP_DESC* desc, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device::CreateDescriptorHeap"; if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); // As the host runtime: a null output is a capability check, answered before the rules below (S_FALSE even // for a shader-visible RTV heap). Zero descriptors are allowed, RTV and DSV heaps are never shader-visible, // one flag and one node. if (!out) return d3d12_trace::result(method, S_FALSE); if ((desc->Flags & ~D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) || desc->NodeMask > 1 || ((desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && (desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_RTV || desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_DSV))) { log_once("CreateDescriptorHeap refused (flags or node mask), type", desc->Type); return d3d12_trace::result(method, E_INVALIDARG); } auto* heap = new DescriptorHeap(state_, *desc); heap->attach_device(identity()); if (!heap->ok()) { heap->Release(); return d3d12_trace::result(method, E_OUTOFMEMORY); } return d3d12_trace::result(method, hand_out(heap, riid, out)); } HRESULT STDMETHODCALLTYPE CreateQueryHeap(const D3D12_QUERY_HEAP_DESC* desc, REFIID riid, void** out) override { if (out) *out = nullptr; // The host runtime's order (compare_invalid_arguments, "query heap:"): the description first, refused with // E_INVALIDARG for no queries, a node other than node 0 or a type past PIPELINE_STATISTICS1 (7; 6 has no // name in the SDK but the host takes it), then E_UNEXPECTED for a null output. A known type this layer // can't create stays E_NOTIMPL. if (!desc || !desc->Count || desc->NodeMask > 1 || UINT(desc->Type) > UINT(D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS1)) return E_INVALIDARG; if (!out) return E_UNEXPECTED; auto* heap = new QueryHeap(state_); heap->attach_device(identity()); if (const HRESULT hr = heap->create(*desc); FAILED(hr)) { heap->Release(); return hr; } return hand_out(heap, riid, out); } HRESULT STDMETHODCALLTYPE CreateRootSignature(UINT node_mask, const void* blob, SIZE_T size, REFIID riid, void** out) override { // The host runtime answers a null output with S_FALSE before it looks at the blob or the node mask // (compare_invalid_arguments, "root signature:"). Otherwise it refuses a node other than node 0, and a DXBC // container whose own size (the dword at +24) is not the size passed. if (!out) return S_FALSE; *out = nullptr; if (!blob || !size || (node_mask & ~1u)) return E_INVALIDARG; const auto* bytes = static_cast(blob); if (size >= 28 && std::memcmp(bytes, "DXBC", 4) == 0) { std::uint32_t container_size = 0; std::memcpy(&container_size, bytes + 24, sizeof(container_size)); if (container_size != size) return E_INVALIDARG; } // The repository's root-signature model (runtime/src/root_signature.h): parse the RTS0 blob, then pack // the parameters into the 32 user-data dwords in the console layout. pack_stage() refuses what it cannot // place (past s31: the console spills those to memory, in a layout that is still open), and so does this. const rt::rootsig::DecodeResult parsed = rt::rootsig::parse_rts0(bytes, size); if (!parsed.ok) { std::fprintf(stderr, "[rt] d3d12: root signature not understood: %s\n", parsed.error.c_str()); return E_INVALIDARG; } // Two layouts, one per bind point (RootArgumentLayout): graphics takes the console layout of vertex and // pixel shaders (s8, one dword per table) where it fits without a spill and keeps pack() otherwise, compute // the console layout pack_stage() measured (D3D-448). The signature is refused only when neither can place it. // A mesh shader reads the same graphics block from its s16 (the translator's root window, push dword 8 = s16), // so its 16-dword window only needs checking (D3D-448-GRAPHICS). const rt::rootsig::PackResult packed = rt::rootsig::pack(parsed.sig); // LEONIDA_GRAPHICS_STAGE_LAYOUT=0 keeps pack() for every graphics signature. const rt::rootsig::StagePackResult pixel = local_graphics_stage_layout() ? rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Pixel) : rt::rootsig::StagePackResult{}; const rt::rootsig::StagePackResult mesh = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Mesh); const rt::rootsig::StagePackResult compute = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Compute); if (!pixel.ok && packed.ok && local_graphics_stage_layout()) { static std::atomic kept{0}; const unsigned n = ++kept; if (n == 1 || (n & (n - 1)) == 0) std::fprintf(stderr, "[rt] d3d12: root signature keeps the s0 graphics layout: %s (%u so far)\n", pixel.error.c_str(), n); } const bool graphics_ok = pixel.ok || packed.ok; if (!graphics_ok && !compute.ok) { std::fprintf(stderr, "[rt] d3d12: root signature refused: %s (compute: %s)\n", packed.error.c_str(), compute.error.c_str()); return E_INVALIDARG; } if (!graphics_ok) std::fprintf(stderr, "[rt] d3d12: root signature usable for compute only: %s\n", packed.error.c_str()); else if (pixel.ok && !mesh.ok) { static std::atomic too_large{0}; const unsigned n = ++too_large; if (n == 1 || (n & (n - 1)) == 0) std::fprintf(stderr, "[rt] d3d12: root signature too large for a mesh shader's root window: %s (%u so far)\n", mesh.error.c_str(), n); } if (!compute.ok) std::fprintf(stderr, "[rt] d3d12: root signature usable for graphics only: %s\n", compute.error.c_str()); RootArgumentLayout layout; layout.flags = parsed.sig.flags; layout.graphics_console = pixel.ok; layout.graphics_ok = graphics_ok; layout.mesh_ok = pixel.ok && mesh.ok; layout.compute_ok = compute.ok; if (compute.ok && !compute.spill_dwords) layout.compute_arguments_end = compute.end_sgpr; // Vertex, pixel and geometry shaders share the s8 layout and one user-data block (a non-compute stage // refuses a spill, so pixel.ok means every argument is inline). if (pixel.ok) layout.graphics_arguments_end = pixel.end_sgpr; for (std::size_t i = 0; i < parsed.sig.params.size(); ++i) { std::uint32_t first = UINT32_MAX; if (pixel.ok) { first = pixel.first_sgpr[i]; } else { for (std::uint32_t d = 0; packed.ok && d < packed.dword_count; ++d) if (packed.provenance[d].param_index == i) { first = d; break; } } layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values, compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr, table_descriptor_count(parsed.sig.params[i])}); } register_static_samplers(parsed.sig); auto* signature = new RootSignature( std::move(layout), leonida::sha256_hex({static_cast(blob), size})); signature->attach_device(identity()); return hand_out(signature, riid, out); } // PC slot 11; the Xbox ABI reaches it through device slots 62 and 67 (the proxy forwards). HRESULT STDMETHODCALLTYPE CreateComputePipelineState(const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, void** out) override { if (!out) return E_POINTER; *out = nullptr; if (!desc) return E_INVALIDARG; leonida::cached_pso::Key key = pipeline_key(*desc); if (const HRESULT hr = check_cached_pso(state_.pso_identity, key, desc->CachedPSO); FAILED(hr)) return hr; auto* pipeline = new PipelineState(state_); pipeline->attach_device(identity()); pipeline->set_cache_key(std::move(key)); if (const HRESULT hr = pipeline->create_compute(*desc); FAILED(hr)) { pipeline->Release(); return hr; } return hand_out(pipeline, riid, out); } HRESULT STDMETHODCALLTYPE CreateGraphicsPipelineState(const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, REFIID riid, void** out) override { if (!out) return E_POINTER; *out = nullptr; if (!desc) return E_INVALIDARG; leonida::cached_pso::Key key = pipeline_key(*desc); if (const HRESULT hr = check_cached_pso(state_.pso_identity, key, desc->CachedPSO); FAILED(hr)) return hr; auto* pipeline = new PipelineState(state_); pipeline->attach_device(identity()); pipeline->set_cache_key(std::move(key)); if (const HRESULT hr = pipeline->create_graphics(*desc); FAILED(hr)) { pipeline->Release(); return hr; } return hand_out(pipeline, riid, out); } // Device1: in-memory pipeline library (docs/d3d12_vulkan.md sections 3.6 and 4). HRESULT STDMETHODCALLTYPE CreatePipelineLibrary(const void* blob, SIZE_T size, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device1::CreatePipelineLibrary"; // A refused blob leaves *out as it was, as the host runtime does; a wrong interface nulls it (hand_out). if (size > 0) { const HRESULT checked = PipelineLibrary::check_blob(blob, size); if (FAILED(checked)) return d3d12_trace::result(method, checked); } if (!out) return d3d12_trace::result(method, S_FALSE); *out = nullptr; auto* lib = new PipelineLibrary(); lib->attach_device(identity()); return d3d12_trace::result(method, hand_out(lib, riid, out)); } // Device9: process-wide shader cache sessions (in-memory and disk-backed) and control (D3D-34). HRESULT STDMETHODCALLTYPE CreateShaderCacheSession(const D3D12_SHADER_CACHE_SESSION_DESC* desc, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device9::CreateShaderCacheSession"; if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); const GUID zero_guid{}; if (std::memcmp(&desc->Identifier, &zero_guid, sizeof(GUID)) == 0) return d3d12_trace::result(method, E_INVALIDARG); if (desc->Mode != D3D12_SHADER_CACHE_MODE_MEMORY && desc->Mode != D3D12_SHADER_CACHE_MODE_DISK) return d3d12_trace::result(method, E_INVALIDARG); constexpr UINT kKnownFlags = D3D12_SHADER_CACHE_FLAG_DRIVER_VERSIONED | D3D12_SHADER_CACHE_FLAG_USE_WORKING_DIR; if (UINT(desc->Flags) & ~kKnownFlags) return d3d12_trace::result(method, E_INVALIDARG); if (!out) return d3d12_trace::result(method, S_FALSE); std::wstring disk_path; if (desc->Mode == D3D12_SHADER_CACHE_MODE_DISK) { VkPhysicalDeviceProperties props{}; if (state_.info.get_instance_proc && state_.info.instance && state_.info.physical) { if (const auto get_props = reinterpret_cast( state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties"))) get_props(state_.info.physical, &props); } const auto path = shader_cache_disk_path(*desc, props); if (path.empty()) return d3d12_trace::result(method, E_FAIL); disk_path = path.wstring(); } const ShaderCacheKey key{desc->Identifier, desc->Mode, std::move(disk_path)}; auto& registry = process_shader_cache_registry(); const UINT max_file_bytes = desc->MaximumValueFileSizeBytes ? desc->MaximumValueFileSizeBytes : ShaderCacheStore::kDefaultMaxValueFileBytes; std::shared_ptr store; if (const HRESULT hr = registry.acquire(key, desc->Version, max_file_bytes, store); FAILED(hr)) return d3d12_trace::result(method, hr); auto* session = new ShaderCacheSession(*desc, key, registry, std::move(store)); session->attach_device(identity()); return d3d12_trace::result(method, hand_out(session, riid, out)); } HRESULT STDMETHODCALLTYPE ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAGS kinds, D3D12_SHADER_CACHE_CONTROL_FLAGS control) override { constexpr auto method = "ID3D12Device9::ShaderCacheControl"; constexpr UINT kKnownKinds = D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CACHE_FOR_DRIVER | D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CONVERSIONS | D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_DRIVER_MANAGED | D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED; constexpr UINT kKnownControls = D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE | D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE | D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR; if (!kinds || (UINT(kinds) & ~kKnownKinds) || !control || (UINT(control) & ~kKnownControls)) return d3d12_trace::result(method, E_INVALIDARG); if ((control & D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE) && (control & D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE)) return d3d12_trace::result(method, E_INVALIDARG); auto& registry = process_shader_cache_registry(); if (kinds & D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED) { if (control & D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR) registry.clear_all(); if (control & D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) registry.disabled.store(true, std::memory_order_relaxed); if (control & D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE) registry.disabled.store(false, std::memory_order_relaxed); } return d3d12_trace::result(method, S_OK); } // ID3D12Device2: a PSO from a pipeline state stream. A CS makes a compute PSO, an MS a mesh PSO, a VS the same // graphics PSO CreateGraphicsPipelineState makes (parse_pipeline_stream). HRESULT STDMETHODCALLTYPE CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** out) override { constexpr const char* method = "ID3D12Device2::CreatePipelineState"; d3d12_trace::stream_refusal = nullptr; d3d12_xs::used_console_stream = false; const auto finish = [&](HRESULT hr) { if (hr == E_NOTIMPL) d3d12_trace::record("PipelineStream::Refused", d3d12_trace::stream_refusal ? d3d12_trace::stream_refusal : "other backend state"); return d3d12_trace::result(method, hr); }; if (!out) return finish(E_POINTER); *out = nullptr; if (!desc) return finish(E_INVALIDARG); PipelineStream stream; HRESULT parsed = parse_pipeline_stream(*desc, stream); // A stream the PC reading refuses, or leaves with an AS and no MS (no valid PC stream), is read again with the // console's numbering (parse_pipeline_stream), and that reading is taken when it holds a mesh shader (its 24) // and no AS. A stream the PC reading accepts as valid is never read differently. LEONIDA_XS_STREAM_ENUM=pc // keeps the PC reading alone (such PSOs are then refused, as before). if ((FAILED(parsed) || (stream.as.pShaderBytecode && !stream.ms.pShaderBytecode)) && console_stream_enum_enabled()) { const char* pc_reason = d3d12_trace::stream_refusal; PipelineStream console; if (SUCCEEDED(parse_pipeline_stream(*desc, console, true)) && !console.as.pShaderBytecode && is_mesh_container(console.ms)) { log_once("console pipeline stream: type 24 contains a mesh shader; DXIL kind", 13); d3d12_xs::used_console_stream = true; d3d12_trace::stream_refusal = nullptr; stream = console; parsed = S_OK; } else { d3d12_trace::stream_refusal = pc_reason; } } if (FAILED(parsed)) return finish(parsed); auto* pipeline = new PipelineState(state_); pipeline->attach_device(identity()); if (state_.order_log || state_.prewarm_plan) pipeline->set_order_key(order_key(stream)); const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute) : pipeline->create_graphics(stream.graphics, &stream.ms, &stream.as, stream.back_masks ? &stream.back_stencil : nullptr, stream.depth_bounds); if (FAILED(hr)) { pipeline->Release(); return finish(hr); } const HRESULT result = hand_out(pipeline, riid, out); if (SUCCEEDED(result) && stream.ms.pShaderBytecode) d3d12_trace::record("PipelineStream::Mesh", "accepted"); return finish(result); } UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE type) override { return descriptor_increment(type); } void STDMETHODCALLTYPE CreateRenderTargetView(ID3D12Resource* resource, const D3D12_RENDER_TARGET_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device::CreateRenderTargetView"); if (!destination.ptr) return; leonida::TargetView view{}; leonida::ResourceId rid = 0; D3D12_RESOURCE_DESC rd{}; const Resource* r = Resource::from(resource); if (r) { rid = r->id(); rd = const_cast(r)->GetDesc(); } else if (resource && state_.context->has_resource(resource_id(resource))) { rid = resource_id(resource); rd = resource->GetDesc(); } if (rid) { view = {rid, 0, 0, rd.DepthOrArraySize}; if (rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) { view = volume_rtv(rid, rd, desc); } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1D) { view = line_target_view(rid, rd, desc->Texture1D.MipSlice, 0, 1); } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1DARRAY) { view = line_target_view(rid, rd, desc->Texture1DArray.MipSlice, desc->Texture1DArray.FirstArraySlice, desc->Texture1DArray.ArraySize); } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2D) { view = {rid, desc->Texture2D.MipSlice, 0, 1}; } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMS) { view = {rid, 0, 0, 1}; } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DARRAY) { view = {rid, desc->Texture2DArray.MipSlice, desc->Texture2DArray.FirstArraySlice, view_slices(rd, desc->Texture2DArray.FirstArraySlice, desc->Texture2DArray.ArraySize)}; } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY) { // Multisample textures have one mip, so only the slice range is chosen (as for the DSV). view = {rid, 0, desc->Texture2DMSArray.FirstArraySlice, view_slices(rd, desc->Texture2DMSArray.FirstArraySlice, desc->Texture2DMSArray.ArraySize)}; } else if (desc) { log_once("render-target view dimension not supported:", desc->ViewDimension); view = {}; } // A TYPELESS color texture of any family takes RTVs in its family's formats (D3D-275; RGBA8 only before). const bool typeless_color = vulkan_format(rd.Format, false).typeless && !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); const bool typed_rgba8 = rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM || rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || rd.Format == DXGI_FORMAT_R8G8B8A8_UINT; // An RGBA8 or BGRA8 texture whose castable list names the RTV's format in the other channel order, or // across B8G8R8X8 and B8G8R8A8, gets an RTV in that format. const DXGI_FORMAT asked = desc && desc->Format != DXGI_FORMAT_UNKNOWN ? desc->Format : rd.Format; const bool cast_listed = r && asked != rd.Format && rgba8_any_order(rd.Format) && rgba8_any_order(asked) && r->lists_castable_format(asked); // A typed BGRA8 or B8G8R8X8 texture with a castable list refuses an RTV in another format the list // doesn't name, as a typed RGBA8 texture does. Without a list it keeps the image's format, as before. const bool typed_bgra8_listed = r && !typed_rgba8 && rgba8_any_order(rd.Format) && r->has_castable_formats(); if (rd.Format == DXGI_FORMAT_A8_UNORM || (desc && desc->Format == DXGI_FORMAT_A8_UNORM)) { // Only an A8 render target stored as VK_FORMAT_A8_UNORM_KHR takes an RTV, in its own format: the // attachment view is the image's. const bool plain_2d = !desc || desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2D || desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DARRAY; if (!r || !r->a8_as_alpha() || rd.Format != DXGI_FORMAT_A8_UNORM || !plain_2d || (desc && desc->Format != DXGI_FORMAT_UNKNOWN && desc->Format != DXGI_FORMAT_A8_UNORM)) view = {}; } else if (r && rd.Format==DXGI_FORMAT_B4G4R4A4_UNORM && r->format()==VK_FORMAT_R8G8B8A8_UNORM) { if(!desc || desc->Format==DXGI_FORMAT_UNKNOWN || desc->Format==rd.Format) view.format=leonida::ColorViewFormat::resource; } else if (r && r->uint_backed() == VK_FORMAT_A1R5G5B5_UNORM_PACK16) { // An R16_UINT-backed B5G5R5A1 UAV texture (Format::uint_backed) renders through an A1R5G5B5 view, in // its own format only. if (desc && desc->Format != DXGI_FORMAT_UNKNOWN && desc->Format != rd.Format) view = {}; else view.format = static_cast(VK_FORMAT_A1R5G5B5_UNORM_PACK16); } else if (r && (r->uint_backed() == VK_FORMAT_R8G8B8A8_SRGB || r->uint_backed() == VK_FORMAT_B8G8R8A8_SRGB)) { // A UNORM-backed sRGB UAV texture (texture_format) renders and clears through its sRGB view, or // through the UNORM twin it is made of when the view asks for that (the console allows the cast). const VkFormat wanted = desc && desc->Format != DXGI_FORMAT_UNKNOWN ? vulkan_format(desc->Format, false).format : r->uint_backed(); if (wanted == r->uint_backed() || wanted == r->format()) view.format = static_cast(wanted); else view = {}; } else if (rd.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP || (desc && desc->Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP)) { if (rd.Format != DXGI_FORMAT_R9G9B9E5_SHAREDEXP || !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || (desc && desc->Format != DXGI_FORMAT_UNKNOWN && desc->Format != rd.Format)) view = {}; } else if (typeless_color || typed_rgba8 || cast_listed || typed_bgra8_listed) { const DXGI_FORMAT requested = asked; // A typed UNORM RGBA8 resource with a castable list may be viewed in a listed family format // (D3D-85's committed path, D3D-90's placed one): its image is mutable and lists the view // format, so the reinterpretation is the typeless path's. Only a UNORM image is advertised, // as that is what the clear path reinterprets. const bool listed = requested == rd.Format || (r && r->has_view_format_list() && r->allows_view_format(vulkan_format(requested, false).format)); if (typeless_color || cast_listed || (requested != rd.Format && listed && (rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM || rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB))) { const bool msaa = rd.SampleDesc.Count > 1; const bool plain_1d = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1D; const bool array_1d = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1DARRAY; const bool plain_2d = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2D; const bool array_2d = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DARRAY; const bool ms = msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMS; const bool ms_array = msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; const UINT plane = plain_2d ? desc->Texture2D.PlaneSlice : array_2d ? desc->Texture2DArray.PlaneSlice : 0; const bool dim_ok = ((plain_1d || array_1d) && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D) || ((plain_2d || array_2d || ms || ms_array) && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D); // Subtraction keeps malformed layer ranges from overflowing during validation. if (!dim_ok || plane || !view.resource || view.mip >= rd.MipLevels || !view.layer_count || view.first_layer >= rd.DepthOrArraySize || view.layer_count > rd.DepthOrArraySize - view.first_layer || !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) { view = {}; } else { // The view's own format, of the resource's family (B8G8R8X8 and B8G8R8A8 are two families // that share Vulkan formats) or named by its castable list; the clear and the attachment // view reinterpret the image in it. const Format named = vulkan_format(requested, false); const int family = leonida::detail::typeless_view_family(named.format); const bool same_family = alpha_unused(requested) == alpha_unused(rd.Format) && family == leonida::detail::typeless_view_family(vulkan_format(rd.Format, false).format); if (named.typeless || named.rgb96 || !family || !(same_family || cast_listed)) view = {}; else view.format = static_cast(named.format); if (view.resource) { const auto format = vulkan_format(requested, false); VkFormatProperties properties{}; state_.format_properties(state_.info.physical, format.format, &properties); if (!(properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) view = {}; } } } else if (requested != rd.Format) { view = {}; // No typed-resource format casting is advertised by this backend. } if (!view.resource) log_once("unsupported typeless or RGBA8 RTV format/subresource:", int(requested)); } } else if (resource) { stub("ID3D12Device::CreateRenderTargetView(resource from another device)"); } std::memcpy(reinterpret_cast(destination.ptr), &view, sizeof(view)); } void STDMETHODCALLTYPE CreateDepthStencilView(ID3D12Resource* resource, const D3D12_DEPTH_STENCIL_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device::CreateDepthStencilView"); if (!destination.ptr) return; leonida::TargetView view{}; if (const Resource* r = Resource::from(resource)) { const D3D12_RESOURCE_DESC rd = const_cast(r)->GetDesc(); view = {r->id(), 0, 0, rd.DepthOrArraySize}; if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE1D) { view = line_target_view(r->id(), rd, desc->Texture1D.MipSlice, 0, 1); } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE1DARRAY) { view = line_target_view(r->id(), rd, desc->Texture1DArray.MipSlice, desc->Texture1DArray.FirstArraySlice, desc->Texture1DArray.ArraySize); } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2D) { view = {r->id(), desc->Texture2D.MipSlice, 0, 1}; } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DMS) { view = {r->id(), 0, 0, 1}; } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DARRAY) { view = {r->id(), desc->Texture2DArray.MipSlice, desc->Texture2DArray.FirstArraySlice, view_slices(rd, desc->Texture2DArray.FirstArraySlice, desc->Texture2DArray.ArraySize)}; } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY) { // Multisample textures have one mip, so only the slice range is chosen. view = {r->id(), 0, desc->Texture2DMSArray.FirstArraySlice, view_slices(rd, desc->Texture2DMSArray.FirstArraySlice, desc->Texture2DMSArray.ArraySize)}; } else if (desc) { log_once("depth-stencil view dimension not supported:", desc->ViewDimension); view = {}; } if (r->desc().Format == DXGI_FORMAT_A8_UNORM || (desc && desc->Format == DXGI_FORMAT_A8_UNORM)) view = {}; if (desc && view.resource) { view.read_only_depth = (desc->Flags & D3D12_DSV_FLAG_READ_ONLY_DEPTH) != 0; view.read_only_stencil = (desc->Flags & D3D12_DSV_FLAG_READ_ONLY_STENCIL) != 0; } } else if (resource) { stub("ID3D12Device::CreateDepthStencilView(resource from another device)"); } std::memcpy(reinterpret_cast(destination.ptr), &view, sizeof(view)); } // A descriptor is its slot's bytes (a TargetView in RTV and DSV heaps, otherwise what the shader loads), so a // copy is a byte copy. D3D12 walks the destination and source ranges together, one descriptor at a time; a // null size array means every range holds one descriptor. Whichever side runs out first ends the copy. void STDMETHODCALLTYPE CopyDescriptors(UINT destination_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* destinations, const UINT* destination_sizes, UINT source_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* sources, const UINT* source_sizes, D3D12_DESCRIPTOR_HEAP_TYPE type) override { if (!destinations || !sources) return; const UINT step = descriptor_increment(type); UINT d = 0, s = 0, d_at = 0, s_at = 0; // the range on each side, and the position in it while (d < destination_ranges && s < source_ranges) { if (d_at >= (destination_sizes ? destination_sizes[d] : 1) || !destinations[d].ptr) { ++d; d_at = 0; } else if (s_at >= (source_sizes ? source_sizes[s] : 1) || !sources[s].ptr) { ++s; s_at = 0; } else { auto* dst = reinterpret_cast(destinations[d].ptr) + std::size_t(d_at) * step; std::memmove(dst, reinterpret_cast(sources[s].ptr) + std::size_t(s_at++) * step, step); state_.arena_mark_dirty_ptr(dst, step); state_.probe_api(destinations[d].ptr + SIZE_T(d_at++) * step, 1); // LOCAL DIAGNOSTIC } } } void STDMETHODCALLTYPE CopyDescriptorsSimple(UINT count, D3D12_CPU_DESCRIPTOR_HANDLE destination, D3D12_CPU_DESCRIPTOR_HANDLE source, D3D12_DESCRIPTOR_HEAP_TYPE type) override { if (!destination.ptr || !source.ptr) return; const UINT step = descriptor_increment(type); std::memmove(reinterpret_cast(destination.ptr), reinterpret_cast(source.ptr), std::size_t(count) * step); state_.arena_mark_dirty_ptr(reinterpret_cast(destination.ptr), std::size_t(count) * step); state_.probe_api(destination.ptr, count); // LOCAL DIAGNOSTIC state_.probe_view("CopyDescriptorsSimple", destination.ptr, count); } // A constant-buffer view is a 16-byte GFX10 raw buffer V# in the first half of the slot (zeros in the rest). // A null description, zero address, or zero size leaves the whole slot zeroed (null V#: reads return 0). void STDMETHODCALLTYPE CreateConstantBufferView(const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { write_constant_buffer_view(desc,destination,false); } void write_constant_buffer_view(const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination, bool vector_rows) { d3d12_trace::record("ID3D12Device::CreateConstantBufferView"); if (!destination.ptr) return; ProbeApiWrite probe_note{state_, destination.ptr, 1, "CreateConstantBufferView"}; // LOCAL DIAGNOSTIC std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); if (!desc || !desc->BufferLocation || !desc->SizeInBytes) return; leonida::gfx10::Buffer buffer{}; buffer.address = desc->BufferLocation; const bool indexed = vector_rows && desc->SizeInBytes % 16 == 0; // A vector ALU fetch selects a 16-byte constant register with IDXEN. Scalar SMEM // still sees the very same byte extent, NUM_RECORDS * STRIDE. buffer.stride = indexed ? 16u : 0u; buffer.num_records = indexed ? desc->SizeInBytes / 16u : desc->SizeInBytes; buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); buffer.oob_select = indexed ? leonida::gfx10::OobSelect::structured_with_offset : leonida::gfx10::OobSelect::raw; static const bool console_form = [] { wchar_t value[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_CBV_RAW", value, 2) == 1 && value[0] == L'1'); }(); const uint64_t rows = (uint64_t(desc->SizeInBytes) + 15) / 16; buffer.address = state_.vsharp_address(buffer.address, console_form ? rows * 16 : desc->SizeInBytes, leonida::TitleVaAliases::created_view, true, false, nullptr, nullptr, nullptr, false); // No backing for the title's memory: a zero-size V# (loads 0, stores dropped), never the raw address. const bool backed = buffer.address != 0; if (!backed) { buffer.stride = 0, buffer.num_records = 0; leonida::note_unbacked_view("constant-buffer view", desc->BufferLocation, desc->SizeInBytes); } leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); // The console's constant-buffer V# is a table of 16-byte rows: the title's own inline form of this descriptor // (it writes one itself instead of calling here, depending on a device flag) is {base, stride 16, records // (size + 15) / 16, fourth word 0x0002403C} (docs/re/notes/gfxgeom.md), and its shaders index rows through // the stride: the batched Scaleform vertex shader reads its X and Y transform rows as base + index * stride. // With the raw form (stride 0) both rows are the same 16 bytes and every batched triangle collapses onto the // line x = y. LEONIDA_CBV_RAW=1 restores the raw form. if (console_form && backed) { words[1] = (words[1] & 0xFFFFu) | (16u << 16); words[2] = UINT(rows); words[3] = 0x0002403Cu; } std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC: the CBVs the title makes, where they go and what V# they get static std::atomic made{0}; const std::uint64_t n = ++made; if (n <= 8 || n % 600 == 0 || n % 600 == 1) std::fprintf(stderr, "[rt] fsdraw: CBV #%llu dest 0x%llx location 0x%llx size %u -> V# base 0x%llx [%s]\n", static_cast(n), static_cast(destination.ptr), static_cast(desc->BufferLocation), desc->SizeInBytes, static_cast(buffer.address), leonida::fsdraw::hex_words(words.data(), words.size()).c_str()); } leonida::fsdraw::note_cbv(buffer.address, desc->BufferLocation, desc->SizeInBytes); // LOCAL DIAGNOSTIC } // A buffer shader-resource view of the `width` bytes at console VA `base_va`: a 16-byte GFX10 V# in the first // half of the slot (raw, structured, or typed). False, the slot left as it was (zeros), for a view the layer // cannot write. A resource's VA, or memory the title placed itself (Xbox device slot 70). bool write_buffer_srv(UINT64 base_va, UINT64 width, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination, bool placed = false) { if (!base_va || !desc->Buffer.NumElements || (desc->Buffer.Flags & ~D3D12_BUFFER_SRV_FLAG_RAW)) return false; leonida::gfx10::Buffer buffer{}; if (desc->Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) { if (desc->Format != DXGI_FORMAT_R32_TYPELESS || desc->Buffer.StructureByteStride != 0) return false; if (desc->Buffer.FirstElement > width / 4) return false; const UINT64 byte_off = desc->Buffer.FirstElement * 4; const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * 4; if (byte_size > width - byte_off || byte_size > UINT32_MAX) return false; buffer.address = base_va + byte_off; buffer.stride = 0; buffer.num_records = std::uint32_t(byte_size); buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); buffer.oob_select = leonida::gfx10::OobSelect::raw; } else if (desc->Buffer.StructureByteStride != 0) { if (desc->Format != DXGI_FORMAT_UNKNOWN || desc->Buffer.StructureByteStride > 16383) return false; const UINT64 stride = desc->Buffer.StructureByteStride; if (desc->Buffer.FirstElement > width / stride) return false; const UINT64 byte_off = desc->Buffer.FirstElement * stride; const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * stride; if (byte_size > width - byte_off) return false; buffer.address = base_va + byte_off; buffer.stride = std::uint32_t(stride); buffer.num_records = desc->Buffer.NumElements; buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); // Check the field offset against the record stride, as for structured UAVs (five-star-recomp 3d287ab). buffer.oob_select = leonida::gfx10::OobSelect::structured_with_offset; } else { const Format fmt = vulkan_format(desc->Format, false); if (fmt.format == VK_FORMAT_UNDEFINED || fmt.typeless || !(fmt.aspects & VK_IMAGE_ASPECT_COLOR_BIT)) { log_once("buffer SRV format not supported:", int(desc->Format)); return false; } const VkFormat named = fmt.rgb96 ? rgb96_named_format(fmt.format) : fmt.format; const std::uint32_t code = leonida::gfx10::format_from_vulkan(named); const leonida::BlockFormat bf = footprint_block(fmt, VK_IMAGE_ASPECT_COLOR_BIT); if (!code || bf.block != 1 || !bf.bytes || bf.bytes > 16383) { log_once("buffer SRV format not supported:", int(desc->Format)); return false; } const UINT64 stride = bf.bytes; if (desc->Buffer.FirstElement > width / stride) return false; const UINT64 byte_off = desc->Buffer.FirstElement * stride; const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * stride; if (byte_size > width - byte_off) return false; buffer.address = base_va + byte_off; buffer.stride = std::uint32_t(stride); buffer.num_records = desc->Buffer.NumElements; buffer.format = code; const leonida::gfx10::Swizzle channels = leonida::gfx10::format_swizzle(named); for (unsigned i = 0; i < 4; ++i) { const UINT from = D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(i, desc->Shader4ComponentMapping); buffer.swizzle[i] = from < 4 ? channels[from] : from == D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0 ? leonida::gfx10::select_zero : leonida::gfx10::select_one; } buffer.oob_select = leonida::gfx10::OobSelect::structured; } const auto bytes = std::uint64_t(buffer.num_records) * (buffer.stride ? buffer.stride : 1); const auto copy = placed ? state_.geometry_va(buffer.address, bytes, true) : 0; if (copy) { // CPU readers and descriptor copies retain the guest address. The heap's shader mirror // rewrites it at the original slot, just as it does for a descriptor written by the title. if (!state_.has_console_descriptor_copy(destination.ptr)) buffer.address = copy; } else { const std::uint64_t target = buffer.address; buffer.address = state_.vsharp_address(buffer.address, bytes, leonida::TitleVaAliases::created_view, true, false, nullptr, nullptr, nullptr, false); // No backing: no records, so loads return 0 and stores are dropped (never a raw title base). if (!buffer.address) { buffer.stride = 0, buffer.num_records = 0; leonida::note_unbacked_view("buffer SRV", target, bytes); } } const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); return true; } // A shader-resource view of a texture is a T# in the slot (docs section 3.4): the shader loads those eight // dwords through its descriptor table and finds the image by them. A buffer SRV writes a 16-byte GFX10 V# in the // first half of the slot (raw, structured, or typed). A slot left as zeros is a null descriptor. void STDMETHODCALLTYPE CreateShaderResourceView(ID3D12Resource* resource, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device::CreateShaderResourceView"); using leonida::gfx10::ImageType; if (!destination.ptr) return; ProbeApiWrite probe_note{state_, destination.ptr, 1, "CreateShaderResourceView"}; // LOCAL DIAGNOSTIC std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); const Resource* r = Resource::from(resource); if (!r) { if (resource) stub("ID3D12Device::CreateShaderResourceView(resource from another device)"); return; } if (r->desc().Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) { log_once("shader-resource view denied by resource flags; format", int(r->desc().Format)); return; } // A placed texture whose memory waits for its first use is a texture all the same, and asking for its image // would bind that memory here, before write_image_descriptor can remember the view (prepare_on_bind). if (!r->deferrable_sample() && !r->descriptor_image()) { if (!desc) { log_once("buffer SRV requires a description; width", int(r->desc().Width)); return; } if (desc->ViewDimension != D3D12_SRV_DIMENSION_BUFFER) { log_once("shader-resource view dimension not supported for buffer:", desc->ViewDimension); return; } if (!valid_shader_4_component_mapping(desc->Shader4ComponentMapping)) { log_once("invalid buffer shader-resource view component mapping:", int(desc->Shader4ComponentMapping)); return; } write_buffer_srv(const_cast(r)->GetGPUVirtualAddress(), r->desc().Width, desc, destination); return; } TextureView view{}; if (!desc) { const bool array = r->desc().DepthOrArraySize > 1; if (r->desc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && !array) { view.type = ImageType::image_1d; view.layer_count = 1; } else if (r->desc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) view.type = ImageType::image_3d; else if (r->desc().SampleDesc.Count > 1) view.type = array ? ImageType::image_2d_msaa_array : ImageType::image_2d_msaa; else if (array) view.type = ImageType::image_2d_array; } else { view.format = desc->Format; view.mapping = desc->Shader4ComponentMapping; switch (desc->ViewDimension) { case D3D12_SRV_DIMENSION_TEXTURE1D: view.type = ImageType::image_1d; view.first_mip = desc->Texture1D.MostDetailedMip; view.mip_count = desc->Texture1D.MipLevels; view.layer_count = 1; view.min_lod = desc->Texture1D.ResourceMinLODClamp; break; case D3D12_SRV_DIMENSION_TEXTURE3D: view.type = leonida::gfx10::ImageType::image_3d; view.first_mip = desc->Texture3D.MostDetailedMip; view.mip_count = desc->Texture3D.MipLevels; view.min_lod = desc->Texture3D.ResourceMinLODClamp; break; case D3D12_SRV_DIMENSION_TEXTURE2DMS: view.type = ImageType::image_2d_msaa; view.layer_count = 1; break; case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: view.type = ImageType::image_2d_msaa_array; view.first_layer = desc->Texture2DMSArray.FirstArraySlice; view.layer_count = desc->Texture2DMSArray.ArraySize; break; case D3D12_SRV_DIMENSION_TEXTURE2D: view.first_mip = desc->Texture2D.MostDetailedMip; view.mip_count = desc->Texture2D.MipLevels; view.layer_count = 1; view.plane = desc->Texture2D.PlaneSlice; view.min_lod = desc->Texture2D.ResourceMinLODClamp; break; case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: view.type = ImageType::image_2d_array; view.first_mip = desc->Texture2DArray.MostDetailedMip; view.mip_count = desc->Texture2DArray.MipLevels; view.first_layer = desc->Texture2DArray.FirstArraySlice; view.layer_count = desc->Texture2DArray.ArraySize; view.plane = desc->Texture2DArray.PlaneSlice; view.min_lod = desc->Texture2DArray.ResourceMinLODClamp; break; case D3D12_SRV_DIMENSION_TEXTURECUBE: view.type = ImageType::cube; view.first_mip = desc->TextureCube.MostDetailedMip; view.mip_count = desc->TextureCube.MipLevels; view.layer_count = 6; view.min_lod = desc->TextureCube.ResourceMinLODClamp; break; case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: view.type = ImageType::cube; view.first_mip = desc->TextureCubeArray.MostDetailedMip; view.mip_count = desc->TextureCubeArray.MipLevels; view.first_layer = desc->TextureCubeArray.First2DArrayFace; view.layer_count = desc->TextureCubeArray.NumCubes == ~0u ? ~0u : desc->TextureCubeArray.NumCubes < ~0u / 6 ? desc->TextureCubeArray.NumCubes * 6 : 0u; view.min_lod = desc->TextureCubeArray.ResourceMinLODClamp; break; default: log_once("shader-resource view dimension not supported:", desc->ViewDimension); return; } } write_image_descriptor(*r, view, destination, ImageViewUse::sampled); if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC: the texture SRVs the title makes, where they go and the T# they get static std::atomic made{0}; const std::uint64_t n = ++made; if (n <= 8 || n % 600 == 0 || n % 600 == 1) { std::uint32_t w[8]; std::memcpy(w, reinterpret_cast(destination.ptr), sizeof w); std::fprintf(stderr, "[rt] fsdraw: SRV #%llu dest 0x%llx resource 0x%llx format %d dim %d -> [%s] bindless %s\n", static_cast(n), static_cast(destination.ptr), static_cast(r->id()), desc ? int(desc->Format) : -1, desc ? int(desc->ViewDimension) : -1, leonida::fsdraw::hex_words(w, 8).c_str(), leonida::fsdraw::has_tsharp(w) ? "yes" : "NO"); } } } // An unordered-access view of a buffer is a V# in the slot (docs section 3.4): the shader loads those four dwords // through its descriptor table and reaches the bytes by the console VA in them. A structured view (format // UNKNOWN and a stride) is `stride` and a record count, a raw one (R32_TYPELESS with the RAW flag) is a byte count, // a typed one (any other format) is the format's GFX10_FORMAT code with the element size as the stride and an // element count: the V# a buffer_load_format / buffer_store_format / buffer_atomic reads (OOB_SELECT 1, so the // index is checked against NUM_RECORDS, docs/buffer_bounds.md). A slot left as zeros is a null descriptor. // A UAV counter (docs section 3.4, "UAV counters") is a second, raw V# of 4 bytes in the slot's upper 16 bytes: the // counter resource's address plus CounterOffsetInBytes. Append and consume are atomics a shader does on it. void write_buffer_uav(ID3D12Resource* resource, ID3D12Resource* counter, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) { namespace g = leonida::gfx10; const D3D12_RESOURCE_DESC& rd = Resource::from(resource)->desc(); if (!(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { log_once("unordered-access view of a buffer created without ALLOW_UNORDERED_ACCESS; flags", int(rd.Flags)); return; } if (!desc || desc->ViewDimension != D3D12_UAV_DIMENSION_BUFFER) { log_once("unordered-access view of a buffer needs a buffer view description; dimension", desc ? int(desc->ViewDimension) : -1); return; } // D3D12: a counter belongs to a structured view and sits in a buffer that allows unordered access, 4096-byte // aligned with room for its 4 bytes; with no counter resource the offset is 0. if (counter || desc->Buffer.CounterOffsetInBytes) { const Resource* c = counter ? Resource::from(counter) : nullptr; const bool valid = c && !c->image() && desc->Format == DXGI_FORMAT_UNKNOWN && (c->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !(desc->Buffer.CounterOffsetInBytes % D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT) && UINT64(desc->Buffer.CounterOffsetInBytes) + 4 <= c->desc().Width; if (!valid) { log_once("unordered-access view counter refused (a structured view, a buffer that allows unordered " "access, a 4096-aligned offset inside it); offset", int(desc->Buffer.CounterOffsetInBytes)); return; } } const UINT64 va = resource->GetGPUVirtualAddress(); const UINT64 counter_va = counter ? counter->GetGPUVirtualAddress() : 0; if (!va || (counter && !counter_va)) return; write_buffer_uav_at(va, rd.Width, desc, counter ? counter_va + desc->Buffer.CounterOffsetInBytes : 0, destination); } // A buffer unordered-access view of the `width` bytes at console VA `va` (a resource's, or memory the title // placed itself: Xbox device slot 71), with its counter's V# when `counter_va` is not 0. False, the slot left as // it was (zeros), for a view the layer cannot write. bool write_buffer_uav_at(UINT64 va, UINT64 width, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, UINT64 counter_va, D3D12_CPU_DESCRIPTOR_HANDLE destination) { namespace g = leonida::gfx10; if (!va || !desc || desc->ViewDimension != D3D12_UAV_DIMENSION_BUFFER) return false; const D3D12_BUFFER_UAV& view = desc->Buffer; const bool structured = desc->Format == DXGI_FORMAT_UNKNOWN; const bool raw = desc->Format == DXGI_FORMAT_R32_TYPELESS && (view.Flags & D3D12_BUFFER_UAV_FLAG_RAW); const bool typed = !structured && !raw; // Raw/structured buffer UAVs carry GFX10_FORMAT_32_UINT (matching CBVs, raw/structured SRVs, and Xbox // hardware) so tbuffer_*_format ops pass RDNA2's non-zero descriptor_format validity check. std::uint32_t format_code = g::format_from_vulkan(VK_FORMAT_R32_UINT), element_bytes = 0; g::Swizzle channels = g::identity_swizzle; if (typed) { // D3D12: a typed view has no RAW flag; its format is one of the typed-UAV formats the layer can name. const Format mapped = vulkan_format(desc->Format, false); const auto* layout = mapped.format != VK_FORMAT_UNDEFINED && !mapped.typeless && !mapped.rgb96 && !(view.Flags & D3D12_BUFFER_UAV_FLAG_RAW) ? leonida::uav_clear::layout(mapped.format) : nullptr; format_code = layout ? g::format_from_vulkan(mapped.format) : 0; if (!format_code || format_code >= 128) { // the V#'s FORMAT is 7 bits log_once("typed buffer unordered-access view format not supported; format", int(desc->Format)); return false; } element_bytes = layout->bytes; channels = g::format_swizzle(mapped.format); } const UINT64 unit = structured ? view.StructureByteStride : typed ? element_bytes : 4; if (!unit || unit > 0x3fff || view.FirstElement > width / unit || (UINT64(view.FirstElement) + view.NumElements) > width / unit || UINT64(view.NumElements) * (structured || typed ? 1 : 4) > ~0u) { log_once("unordered-access view of a buffer outside the resource or with a bad stride; elements", int(view.NumElements)); return false; } g::Buffer buffer{}; buffer.address = va + view.FirstElement * unit; buffer.stride = structured || typed ? std::uint32_t(unit) : 0; buffer.num_records = std::uint32_t(structured || typed ? view.NumElements : UINT64(view.NumElements) * 4); buffer.format = format_code; buffer.swizzle = channels; buffer.oob_select = typed ? g::OobSelect::structured : structured ? g::OobSelect::structured_with_offset : g::OobSelect::raw; const std::uint64_t target = buffer.address; buffer.address = state_.vsharp_address(buffer.address, std::uint64_t(buffer.num_records) * (buffer.stride ? buffer.stride : 1)); // No backing: no records, so loads return 0 and stores are dropped (never a raw title base). if (!buffer.address) { buffer.stride = 0, buffer.num_records = 0; leonida::note_unbacked_view("buffer UAV", target, std::uint64_t(view.NumElements) * (unit ? unit : 1)); } const g::BufferWords words = g::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); if (counter_va) { g::Buffer counter_buffer{}; counter_buffer.address = state_.vsharp_address(counter_va, 4); counter_buffer.num_records = counter_buffer.address ? 4 : 0; if (!counter_buffer.address) leonida::note_unbacked_view("UAV counter", counter_va, 4); counter_buffer.format = g::format_from_vulkan(VK_FORMAT_R32_UINT); counter_buffer.oob_select = g::OobSelect::raw; const g::BufferWords counter_words = g::encode(counter_buffer); std::memcpy(reinterpret_cast(destination.ptr) + sizeof(words), counter_words.data(), sizeof(counter_words)); } return true; } // An unordered-access view of a texture is a T# too, of one mip; set 0 also holds it as a storage image. void STDMETHODCALLTYPE CreateUnorderedAccessView(ID3D12Resource* resource, ID3D12Resource* counter, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device::CreateUnorderedAccessView"); if (!destination.ptr) return; ProbeApiWrite probe_note{state_, destination.ptr, 1, "CreateUnorderedAccessView"}; // LOCAL DIAGNOSTIC std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); const Resource* r = Resource::from(resource); if (!r || !r->belongs_to(state_)) { if (resource) stub("ID3D12Device::CreateUnorderedAccessView(resource from another device)"); return; } if (r->storage_image()) r = r->storage_image(); if (!r->image()) return write_buffer_uav(resource, counter, desc, destination); if (counter) { log_once("unordered-access view of a texture with a counter resource; dimension", int(r->desc().Dimension)); return; } const bool depth_uav = r->depth_stencil_uav(0) != nullptr; if (!depth_uav && !(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { log_once("unordered-access view of a texture created without ALLOW_UNORDERED_ACCESS; flags", int(r->desc().Flags)); return; } TextureView view{}; view.mip_count = 1; namespace g = leonida::gfx10; if (!desc) { const auto& shape = r->desc(); if (shape.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) view.type = g::ImageType::image_3d; else if (shape.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D) { view.type = shape.DepthOrArraySize > 1 ? g::ImageType::image_1d_array : g::ImageType::image_1d; if (view.type == g::ImageType::image_1d) view.layer_count = 1; } else if (shape.DepthOrArraySize > 1) view.type = g::ImageType::image_2d_array; } else { view.format = desc->Format; switch (desc->ViewDimension) { case D3D12_UAV_DIMENSION_TEXTURE1D: view.type = g::ImageType::image_1d; view.first_mip = desc->Texture1D.MipSlice; view.layer_count = 1; break; case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: view.type = g::ImageType::image_1d_array; view.first_mip = desc->Texture1DArray.MipSlice; view.first_layer = desc->Texture1DArray.FirstArraySlice; view.layer_count = desc->Texture1DArray.ArraySize; break; case D3D12_UAV_DIMENSION_TEXTURE2D: view.first_mip = desc->Texture2D.MipSlice; view.layer_count = 1; view.plane = desc->Texture2D.PlaneSlice; break; case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: view.type = g::ImageType::image_2d_array; view.first_mip = desc->Texture2DArray.MipSlice; view.first_layer = desc->Texture2DArray.FirstArraySlice; view.layer_count = desc->Texture2DArray.ArraySize; view.plane = desc->Texture2DArray.PlaneSlice; break; case D3D12_UAV_DIMENSION_TEXTURE3D: view.type = g::ImageType::image_3d; view.first_mip = desc->Texture3D.MipSlice; view.first_layer = desc->Texture3D.FirstWSlice; view.layer_count = desc->Texture3D.WSize; break; default: log_once("unordered-access view dimension not supported:", desc->ViewDimension); return; } } if (depth_uav) { const UINT layers = r->desc().DepthOrArraySize; if (!desc || !(desc->ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY || (desc->ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2D && layers == 1)) || view.first_mip || !view.layer_count || view.first_layer >= layers || (view.layer_count != UINT_MAX && view.layer_count > layers - view.first_layer)) { log_once("Xbox depth-stencil UAV requires a valid mip-zero 2D or array view; dimension", desc ? int(desc->ViewDimension) : 0); return; } const Resource* storage = r->depth_stencil_uav(view.plane); const bool valid_format = storage && (storage->desc().Format == DXGI_FORMAT_R16_TYPELESS ? (view.format == DXGI_FORMAT_R16_UINT || view.format == DXGI_FORMAT_R16_UNORM) : view.format == storage->desc().Format); if (!valid_format) { log_once("unsupported Xbox depth-stencil UAV plane or format; format", int(view.format)); return; } view.plane = 0; // The chosen shadow is a single-plane colour image with the same array layers. write_image_descriptor(*storage, view, destination, ImageViewUse::depth_stencil_uav); return; } // B8G8R8X8 has no typed UAV, so no format of its family gives an unordered-access view. if (alpha_unused(r->desc().Format) || alpha_unused(view.format)) { log_once("unordered-access view of a B8G8R8X8 format; format", int(view.format)); return; } // A texture UAV must name a typed format; a typeless view format is only valid for raw buffer UAVs. if (vulkan_format(view.format, false).typeless) { log_once("unordered-access view of a texture with a typeless format; format", int(view.format)); return; } write_image_descriptor(*r, view, destination, ImageViewUse::storage); state_.context->note_shader_image(r->id()); } // A sampler is a 16-byte S# (kSamplerDescriptorSize); the shader finds the sampler by those four dwords. void STDMETHODCALLTYPE CreateSampler(const D3D12_SAMPLER_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device::CreateSampler"); if (!destination.ptr) return; std::memset(reinterpret_cast(destination.ptr), 0, kSamplerDescriptorSize); if (!desc) { state_.arena_mark_dirty_ptr(reinterpret_cast(destination.ptr), kSamplerDescriptorSize); return; } const leonida::gfx10::SamplerWords words = leonida::gfx10::encode(sampler_descriptor(*desc, &state_)); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); state_.arena_mark_dirty_ptr(reinterpret_cast(destination.ptr), kSamplerDescriptorSize); state_.bind_sampler(words); } // CreateSampler with a UINT border colour and non-normalized coordinates (D3D-28). A description the PC runtime // refuses leaves the slot as it was, as the runtime itself does (without the debug layer) on an RTX 4090 and // on WARP: docs/d3d12_vulkan.md section 3.2. void STDMETHODCALLTYPE CreateSampler2(const D3D12_SAMPLER_DESC2* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { d3d12_trace::record("ID3D12Device11::CreateSampler2"); if (!destination.ptr || !desc) return; const char* refusal = sampler2_refusal(*desc); if (refusal) { log_once(refusal, desc->Flags); return; } const leonida::gfx10::SamplerWords words = sampler2_words(*desc); std::memset(reinterpret_cast(destination.ptr), 0, kSamplerDescriptorSize); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); state_.arena_mark_dirty_ptr(reinterpret_cast(destination.ptr), kSamplerDescriptorSize); state_.bind_sampler(words); } // The S# of a D3D12_SAMPLER_DESC2 that sampler2_refusal accepts. leonida::gfx10::SamplerWords sampler2_words(const D3D12_SAMPLER_DESC2& desc) { const bool uint_border = desc.Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR; D3D12_SAMPLER_DESC base{desc.Filter, desc.AddressU, desc.AddressV, desc.AddressW, desc.MipLODBias, desc.MaxAnisotropy, desc.ComparisonFunc, {}, desc.MinLOD, desc.MaxLOD}; if (!uint_border) std::memcpy(base.BorderColor, desc.FloatBorderColor, sizeof(base.BorderColor)); leonida::gfx10::Sampler sampler = sampler_descriptor(base, uint_border ? nullptr : &state_); if (uint_border) { // The S#'s border types are the float ones', plus the layer's integer mark (kIntegerBorderPtr), which // gives the integer border its own key and VK_BORDER_COLOR_INT_* in Vulkan. namespace g = leonida::gfx10; const UINT* c = desc.UintBorderColor; const bool black = c[0] == 0 && c[1] == 0 && c[2] == 0; if (black && c[3] == 0) { sampler.border_color = g::BorderColor::transparent_black; } else if (black && c[3] == 1) { sampler.border_color = g::BorderColor::opaque_black; } else if (c[0] == 1 && c[1] == 1 && c[2] == 1 && c[3] == 1) { sampler.border_color = g::BorderColor::opaque_white; } else { sampler.border_color = g::BorderColor::table; sampler.border_color_index = state_.register_border_color(true, c); } sampler.integer_border = true; } sampler.unnormalized = desc.Flags & D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES; return leonida::gfx10::encode(sampler); } // A root signature's static samplers take no root argument: a shader that uses one holds its S# by value // (docs/d3d12_vulkan.md section 3.5). So each gets a sampler in set 0 and a key in the hash table here, as // CreateSampler gives a heap slot's S#; without them the shader's lookup misses and it samples through the // fallback sampler. A static sampler is a D3D12_SAMPLER_DESC2 whose border colour is one of five named ones // (D3D12_STATIC_BORDER_COLOR; the two UINT ones can be in a blob of any version, the flags only in 1.2), or // transparent black with the UINT flag. void register_static_samplers(const rt::rootsig::RootSignature& signature) { for (const rt::rootsig::StaticSampler& s : signature.static_samplers) { D3D12_SAMPLER_DESC2 desc{}; desc.Filter = D3D12_FILTER(s.filter); desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE(s.address_u); desc.AddressV = D3D12_TEXTURE_ADDRESS_MODE(s.address_v); desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE(s.address_w); desc.MipLODBias = s.mip_lod_bias; desc.MaxAnisotropy = s.max_anisotropy; desc.ComparisonFunc = D3D12_COMPARISON_FUNC(s.comparison_func); desc.MinLOD = s.min_lod; desc.MaxLOD = s.max_lod; desc.Flags = D3D12_SAMPLER_FLAGS(s.flags); const bool white = s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE || s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT; if (s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK_UINT || s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT) { desc.Flags |= D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR; desc.UintBorderColor[0] = desc.UintBorderColor[1] = desc.UintBorderColor[2] = white ? 1u : 0u; desc.UintBorderColor[3] = 1; } else if (s.border_color == D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK && (desc.Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR)) { // The integer border the enum has no value for: the 1.2 flag on transparent black is UINT (0,0,0,0), // which D3D12 serializes and creates. UintBorderColor is already zero. } else if (s.border_color > D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT || (desc.Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR)) { // A value past the enum, or the UINT flag with the float opaque black or white (D3D12 refuses to // serialize that pair): not a sampler D3D12 defines. log_once("static sampler not registered: border colour and flags do not go together; border colour", int(s.border_color)); continue; } else { desc.FloatBorderColor[0] = desc.FloatBorderColor[1] = desc.FloatBorderColor[2] = white ? 1.0f : 0.0f; desc.FloatBorderColor[3] = s.border_color == D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK ? 0.0f : 1.0f; } if (sampler2_refusal(desc)) { log_once("static sampler not registered: a sampler CreateSampler2 refuses; flags", int(desc.Flags)); continue; } if (!state_.bind_sampler(sampler2_words(desc))) log_once("static sampler not registered: no room in the bindless set; register", int(s.shader_register)); } } // Why the PC runtime refuses a D3D12_SAMPLER_DESC2, or null. The non-normalized rules are its debug layer's // messages, which match Vulkan's for unnormalizedCoordinates; AddressW is free in both. static const char* sampler2_refusal(const D3D12_SAMPLER_DESC2& desc) { if (desc.Flags & ~UINT(D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR | D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES)) return "CreateSampler2 refused: unknown sampler flags; flags"; if (!(desc.Flags & D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES)) return nullptr; if (D3D12_DECODE_MIN_FILTER(desc.Filter) != D3D12_DECODE_MAG_FILTER(desc.Filter) || D3D12_DECODE_MIP_FILTER(desc.Filter) != D3D12_FILTER_TYPE_POINT || D3D12_DECODE_IS_ANISOTROPIC_FILTER(desc.Filter) || D3D12_DECODE_FILTER_REDUCTION(desc.Filter) == D3D12_FILTER_REDUCTION_TYPE_COMPARISON) return "CreateSampler2 refused: non-normalized sampler filter; flags"; const auto clamps = [](D3D12_TEXTURE_ADDRESS_MODE m) { return m == D3D12_TEXTURE_ADDRESS_MODE_CLAMP || m == D3D12_TEXTURE_ADDRESS_MODE_BORDER; }; if (!clamps(desc.AddressU) || !clamps(desc.AddressV)) return "CreateSampler2 refused: non-normalized sampler address mode; flags"; if (desc.MinLOD != 0 || desc.MaxLOD != 0 || desc.MipLODBias != 0) return "CreateSampler2 refused: non-normalized sampler LOD; flags"; return nullptr; } HRESULT STDMETHODCALLTYPE CreateCommittedResource(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { return create_committed_validated("ID3D12Device::CreateCommittedResource", heap, heap_flags, desc, state, clear, 0, nullptr, riid, out); } // Reserved buffers use sparse binding where available. Textures and fallback buffers are fully backed. // The description rules are D3D12's: buffers are ROW_MAJOR, textures 64KB_UNDEFINED_SWIZZLE with a tile shape // (64KB_STANDARD_SWIZZLE needs StandardSwizzle64KBSupported, which CheckFeatureSupport reports as FALSE). The // Xbox tiled layout word 0x101 (slot 76, section 4.2) is accepted as 64KB_UNDEFINED_SWIZZLE; that the console // uses it for reserved resources too is an assumption. HRESULT STDMETHODCALLTYPE CreateReservedResource(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { return create_reserved("ID3D12Device::CreateReservedResource", desc, state, clear, 0, nullptr, riid, out); } // Device4. Protected sessions are not supported. HRESULT STDMETHODCALLTYPE CreateReservedResource1(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, ID3D12ProtectedResourceSession* session, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device4::CreateReservedResource1"; if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); if (session) return d3d12_trace::result(method, refuse_protected_session("CreateReservedResource1")); return create_reserved(method, desc, state, clear, 0, nullptr, riid, out); } // Device10: an initial layout instead of a state (resources start in their first use's layout here anyway), and a // castable-format list forwarded to the backing texture. HRESULT STDMETHODCALLTYPE CreateReservedResource2(const D3D12_RESOURCE_DESC* desc, D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear, ID3D12ProtectedResourceSession* session, UINT32 castable_formats, const DXGI_FORMAT* castable, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device10::CreateReservedResource2"; if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); if (session) return d3d12_trace::result(method, refuse_protected_session("CreateReservedResource2")); if (const char* why = barrier_layout_refusal(*desc, layout)) { log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); return d3d12_trace::result(method, E_INVALIDARG); } return create_reserved(method, desc, D3D12_RESOURCE_STATE_COMMON, clear, castable_formats, castable, riid, out); } // Tiling of a reserved resource or a tiled (64KB_UNDEFINED_SWIZZLE) texture (src/resource_tiling.h). Anything // else, as on the PC runtime, has no tiles: every output is zero and no subresource tiling is written. void STDMETHODCALLTYPE GetResourceTiling(ID3D12Resource* resource, UINT* total, D3D12_PACKED_MIP_INFO* packed, D3D12_TILE_SHAPE* shape, UINT* count, UINT first, D3D12_SUBRESOURCE_TILING* tilings) override { leonida::ResourceTiling tiling; Resource* r = Resource::from(resource); const bool ok = r && (r->reserved() || is_tiled_layout(r->GetDesc().Layout)) && resource_tiling(r->GetDesc(), tiling); if (total) *total = ok ? tiling.total_tiles : 0; if (packed) *packed = ok ? D3D12_PACKED_MIP_INFO{UINT8(tiling.standard_mips), UINT8(tiling.packed_mips), tiling.packed_tiles, tiling.packed_start} : D3D12_PACKED_MIP_INFO{}; if (shape) *shape = ok ? D3D12_TILE_SHAPE{tiling.shape.width, tiling.shape.height, tiling.shape.depth} : D3D12_TILE_SHAPE{}; if (!count) return; const UINT available = ok && first < tiling.subresources.size() ? UINT(tiling.subresources.size() - first) : 0; const UINT n = tilings ? std::min(*count, available) : 0; for (UINT i = 0; i < n; ++i) { const leonida::SubresourceTiling& s = tiling.subresources[first + i]; tilings[i] = {s.width, UINT16(s.height), UINT16(s.depth), s.start}; } *count = n; } // The 1/2/3 variants (D3D-28) are the same calls with newer arguments, answered as the PC runtime answers them // (probed on an RTX 4090; docs/d3d12_vulkan.md section 3.2 has the table). The initial state or layout is not // used: new textures are tracked as UNDEFINED and moved on first use, and buffers have no layout. HRESULT STDMETHODCALLTYPE CreateCommittedResource1(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, ID3D12ProtectedResourceSession* session, REFIID riid, void** out) override { if (out) *out = nullptr; if (session) return refuse_protected_session("CreateCommittedResource1"); return CreateCommittedResource(heap, heap_flags, desc, state, clear, riid, out); } HRESULT STDMETHODCALLTYPE CreateCommittedResource2(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC1* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, ID3D12ProtectedResourceSession* session, REFIID riid, void** out) override { if (out) *out = nullptr; if (!desc) return E_INVALIDARG; if (session) return refuse_protected_session("CreateCommittedResource2"); if (texture_mip_region(*desc)) return E_INVALIDARG; const D3D12_RESOURCE_DESC base = resource_desc(*desc); return CreateCommittedResource(heap, heap_flags, &base, state, clear, riid, out); } HRESULT STDMETHODCALLTYPE CreateCommittedResource3(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear, ID3D12ProtectedResourceSession* session, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device10::CreateCommittedResource3"; if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); if (session) return d3d12_trace::result(method, refuse_protected_session("CreateCommittedResource3")); if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); // A count with a null array is no list (as on the PC runtime). The layer reports relaxed format casting, so // a real list is passed through; only buffers are refused. D3D12_RESOURCE_DESC base = resource_desc(*desc); if (const char* why = barrier_layout_refusal(base, layout)) { log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); return d3d12_trace::result(method, E_INVALIDARG); } // The Xbox slot-127 bridge forwards the logical texture to Device10. Validate its layout above, // then allocate the depth attachment and enable the typed storage planes before returning it. std::optional storage_heap_flags; if (xbox_depth_uav(base)) { storage_heap_flags = heap_flags & D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; heap_flags &= ~*storage_heap_flags; base.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; } // D3D12_BARRIER_LAYOUT has no acceleration-structure value; an AS buffer's state comes through the // legacy CreateCommittedResource path. Buffers here start COMMON, as before. return create_committed_validated(method, heap, heap_flags, &base, D3D12_RESOURCE_STATE_COMMON, clear, castable_count, castable, riid, out, storage_heap_flags); } // Device9. The creator ID only groups queues for tools; one creator is as good as another here. HRESULT STDMETHODCALLTYPE CreateCommandQueue1(const D3D12_COMMAND_QUEUE_DESC* desc, REFIID, REFIID riid, void** out) override { return CreateCommandQueue(desc, riid, out); } // Device8. A texture with a mip region gets the failure answer (every output all ones), as on the PC runtime; // a buffer's mip region is ignored. void STDMETHODCALLTYPE GetCopyableFootprints1(const D3D12_RESOURCE_DESC1* desc, UINT first, UINT count, UINT64 base, D3D12_PLACED_SUBRESOURCE_FOOTPRINT* layouts, UINT* rows, UINT64* row_sizes, UINT64* total) override { const D3D12_RESOURCE_DESC base_desc = desc ? resource_desc(*desc) : D3D12_RESOURCE_DESC{}; const bool usable = desc && !texture_mip_region(*desc); GetCopyableFootprints(usable ? &base_desc : nullptr, first, count, base, layouts, rows, row_sizes, total); } // Heaps and placed resources (section 3.3). A heap reserves its size in the arena, so a buffer placed at a // 64 KiB-aligned offset is simply that offset into the arena, and its console VA is the heap's place plus it. // Existing-memory heaps and lifetime trackers. The host refuses a null address, a file mapping that is not a // handle and a null lifetime owner with E_INVALIDARG on WARP, NVIDIA and Intel (d3d12_existing_heap_test). Docs: // https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromaddress // // OpenExistingHeapFromAddress answers as the host runtime does on an RTX 4090 and WARP (d3d12_existing_heap_test // open_cases): the address must be the base of a VirtualAlloc allocation that is committed read-write over its // whole size; an address inside it, a partly committed or reserved-only allocation, a read-only one and an // uncached one are E_INVALIDARG. The heap is the allocation's size, 64 KiB aligned, CUSTOM / L0 with WRITE_BACK // (WRITE_COMBINE for a PAGE_WRITECOMBINE range), flags SHARED | // SHARED_CROSS_ADAPTER | ALLOW_SHADER_ATOMICS. Its backing is that memory itself, imported with // VK_EXT_external_memory_host, so the GPU sees the caller's writes. Without the extension, or when the range is // not aligned to minImportedHostPointerAlignment or no memory type takes it, the call stays E_NOTIMPL, and // CheckFeatureSupport(EXISTING_HEAPS) reports the extension's absence. The console title opens the 64 KiB // graphics region it has just committed with XMemVirtualAlloc this way, right after its first queue and fence. HRESULT STDMETHODCALLTYPE OpenExistingHeapFromAddress(const void* address, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device3::OpenExistingHeapFromAddress"; if (out) *out = nullptr; if (!address || !out) return d3d12_trace::result(method, E_INVALIDARG); SIZE_T size = 0; DWORD protect = 0; if (!existing_allocation_size(address, size, protect)) return d3d12_trace::result(method, E_INVALIDARG); if (!state_.get_host_pointer_properties) { log_once("OpenExistingHeapFromAddress (no VK_EXT_external_memory_host; existing heaps are not supported)", 0); return d3d12_trace::result(method, E_NOTIMPL); } const VkDeviceSize alignment = state_.info.host_pointer_alignment; if ((reinterpret_cast(address) | size) & (alignment - 1)) { log_once("OpenExistingHeapFromAddress: range not aligned to minImportedHostPointerAlignment; alignment", int(alignment)); return d3d12_trace::result(method, E_NOTIMPL); } VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; if (state_.get_host_pointer_properties(state_.info.device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, address, &host) != VK_SUCCESS || !host.memoryTypeBits) { log_once("OpenExistingHeapFromAddress: no memory type imports this host range", 0); return d3d12_trace::result(method, E_NOTIMPL); } VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; import.pHostPointer = const_cast(address); VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; VkDeviceMemory memory = VK_NULL_HANDLE; std::uint32_t memory_type = 0; // Host-visible and coherent first, as the caller's pages are; then any type the driver offers. for (const VkMemoryPropertyFlags want : {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), VkMemoryPropertyFlags(0)}) { for (std::uint32_t i = 0; i < state_.memory.memoryTypeCount && !memory; ++i) { if (!(host.memoryTypeBits & (1u << i)) || (state_.memory.memoryTypes[i].propertyFlags & want) != want) continue; VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; allocate.allocationSize = size; allocate.memoryTypeIndex = i; if (state_.context->vk.vkAllocateMemory(state_.info.device, &allocate, nullptr, &memory) == VK_SUCCESS) memory_type = i; else memory = VK_NULL_HANDLE; } if (memory) break; } if (!memory) { log_once("OpenExistingHeapFromAddress: importing the host range failed; size in KiB", int(size / 1024)); return d3d12_trace::result(method, E_OUTOFMEMORY); } D3D12_HEAP_DESC desc{}; desc.SizeInBytes = size; desc.Properties.Type = D3D12_HEAP_TYPE_CUSTOM; desc.Properties.CPUPageProperty = (protect & PAGE_WRITECOMBINE) ? D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE : D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; desc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; desc.Flags = D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER | D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; auto* heap = new Heap(state_, desc, memory, memory_type, address); heap->attach_device(identity()); return d3d12_trace::result(method, hand_out(heap, riid, out)); } // The size of the VirtualAlloc allocation `address` starts, and its protection, when the whole of it is committed // PAGE_READWRITE, or PAGE_READWRITE | PAGE_WRITECOMBINE: what the host runtime accepts (a write-combined range // opens as a WRITE_COMBINE heap). False for an address inside an allocation, a reserved or free page, another // protection (read-only, PAGE_NOCACHE), or two protections in one allocation. static bool existing_allocation_size(const void* address, SIZE_T& size, DWORD& protect) { MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(address, ®ion, sizeof(region)) || region.AllocationBase != address) return false; protect = region.Protect; if (protect != PAGE_READWRITE && protect != (PAGE_READWRITE | PAGE_WRITECOMBINE)) return false; size = 0; const char* at = static_cast(address); while (VirtualQuery(at + size, ®ion, sizeof(region)) && region.AllocationBase == address) { if (region.State != MEM_COMMIT || region.Protect != protect) return false; size += region.RegionSize; } return size != 0; } // create_buffer_at_host_address (Xbox device slot 133). The heap the resource reports is CUSTOM / WRITE_BACK / L0, // what OpenExistingHeapFromAddress gives the same pages, since the CPU keeps writing them. // A D3D12_BARRIER_LAYOUT (what Xbox slot 133 passes, as PC CreatePlacedResource2 does) as the legacy initial state // of an equivalent committed resource. UNDEFINED (0xFFFFFFFF) and anything unlisted give COMMON. static D3D12_RESOURCE_STATES state_for_barrier_layout(std::uint32_t layout) { switch (layout) { case 1: return D3D12_RESOURCE_STATE_GENERIC_READ; case 2: return D3D12_RESOURCE_STATE_RENDER_TARGET; case 3: return D3D12_RESOURCE_STATE_UNORDERED_ACCESS; case 4: return D3D12_RESOURCE_STATE_DEPTH_WRITE; case 5: return D3D12_RESOURCE_STATE_DEPTH_READ; case 6: return D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; case 7: return D3D12_RESOURCE_STATE_COPY_SOURCE; case 8: return D3D12_RESOURCE_STATE_COPY_DEST; case 9: return D3D12_RESOURCE_STATE_RESOLVE_SOURCE; case 10: return D3D12_RESOURCE_STATE_RESOLVE_DEST; default: return D3D12_RESOURCE_STATE_COMMON; } } // TitleVaAliases::want_buffer: a vertex or index view names `va` in the title's own memory and no buffer covers // it. A buffer over the 64 KiB-aligned committed pages around it is made the way slot 133 makes one (the pages // imported, or a shadow copied from them before every submission) and kept until the device goes, up to // LEONIDA_TITLE_BUFFERS_MB (512 by default). void make_title_buffer(std::uint64_t va, std::uint64_t bytes) { if (!&context()) return; // The page mirror holds these pages: the draw reads them there (VulkanContext's mirror lookup), no buffer. if (state_.page_mirror_resolve(va, std::max(bytes, 1))) return; static const bool check_size = [] { wchar_t flag[2]{}; return !(GetEnvironmentVariableW(L"LEONIDA_TITLE_BUFFER_COVERAGE", flag, 2) == 1 && flag[0] == L'0'); }(); // A stream pool's GPU-only alias: the buffer is made over the CPU view of the same pages (rule B), where the // host reads the frames, so it is host-importable and shared with every other view naming that range instead // of leaving a second, queue-mapped copy of it behind. va = leonida::title_gpu_views::to_host_view(static_cast(va), static_cast(std::max(bytes, 1))); const auto covered = [&] { return state_.context->knows_buffer_va(va, check_size ? bytes : 1); }; if (covered()) return; std::uint64_t lo = 0, hi = 0; if (!leonida::title_va_aliases().title_memory(va, lo, hi)) return; std::lock_guard lock(title_buffer_mutex_); if (covered()) return; static const std::uint64_t cap = [] { char text[16] = {}; size_t length = 0; const bool set = getenv_s(&length, text, "LEONIDA_TITLE_BUFFERS_MB") == 0 && length > 1; return (set ? std::strtoull(text, nullptr, 10) : 512ull) << 20; }(); constexpr std::uint64_t align = 65536, most = 64ull << 20; const std::uint64_t start = std::max(va & ~(align - 1), lo); std::uint64_t end = std::min(hi, (va + std::clamp(bytes, 1, most) + align - 1) & ~(align - 1)); for (std::uint64_t at = start; at < end;) { // the committed, readable part only // A page xmem's frame table holds (no host view: src/title_frames.h) is read through its frame. bool table = false; const std::uint64_t run = leonida::title_frames::run_end(std::uintptr_t(at), std::uintptr_t(end), table); if (table) { at = run; continue; } MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(reinterpret_cast(static_cast(at)), ®ion, sizeof(region)) || region.State != MEM_COMMIT || !region.Protect || (region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) { end = at; break; } at = reinterpret_cast(region.BaseAddress) + region.RegionSize; } // If the request runs into an uncommitted page or the size limit, reuse its backed prefix. if (end <= va || (check_size && state_.context->knows_buffer_va(va, end - va))) return; if (title_buffer_bytes_ + (end - start) > cap) { log_once("vertex or index data in the title's memory is past LEONIDA_TITLE_BUFFERS_MB, left unresolved; MiB so far:", int(title_buffer_bytes_ >> 20)); return; } D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; desc.Width = end - start; desc.Height = 1; desc.DepthOrArraySize = 1; desc.MipLevels = 1; desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; ID3D12Resource* made = nullptr; const HRESULT hr = create_at_host_address(reinterpret_cast(static_cast(start)), desc, 0xFFFFFFFFu, __uuidof(ID3D12Resource), reinterpret_cast(&made), nullptr); if (FAILED(hr) || !made) { log_once("a buffer over the title's memory for a vertex or index view could not be made; HRESULT", int(hr)); return; } title_buffers_.push_back(made); title_buffer_bytes_ += end - start; if (title_buffers_.size() <= 8 || !(title_buffers_.size() & (title_buffers_.size() - 1))) std::fprintf(stderr, "[rt] d3d12: a %llu KiB buffer over the title's memory at 0x%llx for a vertex or index view " "at 0x%llx (%zu such buffers, %llu MiB)\n", static_cast((end - start) >> 10), static_cast(start), static_cast(va), title_buffers_.size(), static_cast(title_buffer_bytes_ >> 20)); } std::mutex title_buffer_mutex_; std::vector title_buffers_; // kept: the title's views name their addresses frame after frame std::uint64_t title_buffer_bytes_ = 0; HRESULT create_at_host_address(void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, void** out, const D3D12_CLEAR_VALUE* clear) { constexpr auto method = "Xbox CreatePlacedResourceX (device slot 133)"; if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { // A texture cannot be placed on the title's pages (the PC GPU does not sample the console layout): it gets // a committed texture of the same description, so the title has its resource instead of asserting (found // in review). Its GPU VA is still the title's address: the console answers a placed texture's // GetGPUVirtualAddress with the address the title placed it at, and a title turns that into the CPU // pointer it clears the texture through (docs/d3d12_vulkan.md 3.3). It is registered by that address // (register_title_texture): slot-70 views of the address are of its image, which, unless the GPU writes // it, is filled from the title's memory with the views' layout (TitleTexture). log_once("a title-placed texture (device slot 133) is a committed texture whose GPU VA is the title " "address, filled from the title's pages unless the GPU writes it; dimension", int(desc.Dimension)); // The title's barrier layout (slot 133's third argument, measured by @dracbat) is checked against the // description as CreateCommittedResource checks a state; one it refuses (or UNDEFINED) gives COMMON, so // the title still gets its texture. The image itself starts undefined either way: the first command that // uses it moves it to that command's layout (vulkan_replay.h, initialize), as for every texture here. const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; const D3D12_RESOURCE_STATES initial = state_for_barrier_layout(layout); // The console lets a depth-stencil target allow unordered access too; no PC GPU stores to a depth // format, so the texture is made without it (as slot 25 and slot 76 size and make it). Its UAVs then // write no descriptor. D3D12_RESOURCE_DESC made = desc; if ((made.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) && (made.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { made.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; log_once("a title-placed depth-stencil texture is made without unordered access; format", made.Format); } // A texture the GPU never writes holds what the title writes into its memory (XG copies, Map): its image // is filled from there (TitleTexture), so it is made where host copies reach it (CUSTOM write-back: still // device-local memory, created with host-transfer usage when the format allows). const bool gpu_written = (made.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) || made.SampleDesc.Count > 1; const D3D12_HEAP_PROPERTIES host_copied{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0, 1, 1}; const D3D12_HEAP_PROPERTIES* heap = gpu_written ? &fallback : &host_copied; // The title views 32-bit unordered-access targets as R9G9B9E5 (it packs E5 values into them from compute; // seen in its slot-70 views): castable, so that view exists. Made without the list if Vulkan refuses it. const bool r32 = made.Format == DXGI_FORMAT_R32_TYPELESS || made.Format == DXGI_FORMAT_R32_FLOAT || made.Format == DXGI_FORMAT_R32_UINT || made.Format == DXGI_FORMAT_R32_SINT; const DXGI_FORMAT castable[] = {made.Format, DXGI_FORMAT_R9G9B9E5_SHAREDEXP}; const UINT32 cast_count = r32 && (made.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && made.SampleDesc.Count == 1 ? 2 : 0; HRESULT hr = create_committed_validated(nullptr, heap, D3D12_HEAP_FLAG_NONE, &made, initial, nullptr, cast_count, castable, riid, out, std::nullopt, TitleImageOrigin::placed); if (FAILED(hr) && cast_count) hr = create_committed_validated(nullptr, heap, D3D12_HEAP_FLAG_NONE, &made, initial, nullptr, 0, nullptr, riid, out, std::nullopt, TitleImageOrigin::placed); if (FAILED(hr) && initial != D3D12_RESOURCE_STATE_COMMON) hr = create_committed_validated(nullptr, heap, D3D12_HEAP_FLAG_NONE, &made, D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out, std::nullopt, TitleImageOrigin::placed); if (FAILED(hr) && heap != &fallback) { log_once("a title-placed texture the GPU does not write could not be made on a host-copied heap; " "format", made.Format); hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &made, D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out, std::nullopt, TitleImageOrigin::placed); } if (SUCCEEDED(hr) && out && *out) { // The interface handed out is the Resource itself (hand_out); ask it back and tell it its address. ID3D12Resource* made = nullptr; if (SUCCEEDED(static_cast(*out)->QueryInterface(__uuidof(ID3D12Resource), reinterpret_cast(&made))) && made) { if (auto* texture = Resource::from(made)) { static const bool distinct = [] { const char* v = std::getenv("LEONIDA_PLACED_IMAGE_KEYS"); return !v || std::strcmp(v, "0"); }(); texture->place_at_title_address(address, distinct && gpu_written); register_title_texture(texture, reinterpret_cast(address)); texture->set_title_address(reinterpret_cast(address)); } made->Release(); } } if (FAILED(hr)) { // The title asserts when a texture it places cannot be made: say which one, in full. static std::atomic logged{0}; if (logged.fetch_add(1, std::memory_order_relaxed) < 32) std::fprintf(stderr, "[rt] d3d12: slot 133 texture not created (hr 0x%08x, layout %u): dim %d format %d " "%llux%ux%u mips %u samples %u layout %d flags 0x%x at %p\n", unsigned(hr), unsigned(layout), int(desc.Dimension), int(desc.Format), static_cast(desc.Width), unsigned(desc.Height), unsigned(desc.DepthOrArraySize), unsigned(desc.MipLevels), unsigned(desc.SampleDesc.Count), int(desc.Layout), unsigned(desc.Flags), address); } return d3d12_trace::result(method, hr); } D3D12_HEAP_PROPERTIES heap{}; heap.Type = D3D12_HEAP_TYPE_CUSTOM; heap.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; heap.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; auto* resource = new Resource(state_, desc, heap, D3D12_HEAP_FLAG_NONE); resource->attach_device(identity()); // Title memory the page mirror holds: the buffer is the mirror's chunk there (no import, no shadow). if (SUCCEEDED(resource->create_mirror_buffer(address))) return d3d12_trace::result(method, hand_out(resource, riid, out)); const HRESULT hr = resource->create_host_buffer(address); if (hr == E_INVALIDARG) { resource->Release(); return d3d12_trace::result(method, hr); } if (FAILED(hr)) { // The driver would not import these pages: RADV refuses a view of a pagefile-backed section, the form // xmem's physical pages take (found in review on an RX 9070 XT under Wine), and a device without // VK_EXT_external_memory_host has no import at all; write-combined and uncommitted pages are not tried, // and some drivers stop importing after a budget (create_shadow_buffer). The title then gets a shadow // buffer at its VA, brought up to date from its pages before every submission. resource->Release(); resource = new Resource(state_, desc, heap, D3D12_HEAP_FLAG_NONE); resource->attach_device(identity()); const HRESULT shadow = resource->create_shadow_buffer(address); if (SUCCEEDED(shadow)) { log_once("a title-placed buffer (device slot 133) could not import its pages, so it is a shadow " "copied from them before every submission; HRESULT", int(hr)); return d3d12_trace::result(method, hand_out(resource, riid, out)); } // No memory for the shadow either: the boot goes on with an ordinary DEFAULT buffer of the same // description, as #6915's stand-in did. The title gets a resource, but neither its VA nor its writes at // `address` reach it. resource->Release(); log_once("a title-placed buffer (device slot 133) could neither import its pages nor get a shadow, so it " "is an ordinary buffer the title's writes do not reach; HRESULT", int(shadow)); const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; return d3d12_trace::result(method, create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, 0, nullptr, riid, out, std::nullopt)); } return d3d12_trace::result(method, hand_out(resource, riid, out)); } HRESULT STDMETHODCALLTYPE OpenExistingHeapFromFileMapping(HANDLE file_mapping, REFIID, void** out) override { constexpr auto method = "ID3D12Device3::OpenExistingHeapFromFileMapping"; if (out) *out = nullptr; DWORD flags = 0; if (!file_mapping || !out || !GetHandleInformation(file_mapping, &flags)) return d3d12_trace::result(method, E_INVALIDARG); log_once("OpenExistingHeapFromFileMapping (existing heaps are not supported)", 0); return d3d12_trace::result(method, E_NOTIMPL); } HRESULT STDMETHODCALLTYPE CreateLifetimeTracker(ID3D12LifetimeOwner* owner, REFIID, void** out) override { constexpr auto method = "ID3D12Device5::CreateLifetimeTracker"; if (out) *out = nullptr; if (!owner || !out) return d3d12_trace::result(method, E_INVALIDARG); log_once("CreateLifetimeTracker (not supported)", 0); return d3d12_trace::result(method, E_NOTIMPL); } HRESULT STDMETHODCALLTYPE CreateHeap(const D3D12_HEAP_DESC* desc, REFIID riid, void** out) override { if (out) *out = nullptr; if (!desc) return E_INVALIDARG; if (const char* why = heap_desc_refusal(*desc, state_.uma)) { log_once((std::string("CreateHeap refused (") + why + "), heap type").c_str(), int(desc->Properties.Type)); return E_INVALIDARG; } if (!state_.arena_ready()) { log_once("heaps need the GPU address arena (bufferDeviceAddress); heap size in KiB:", int(desc->SizeInBytes / 1024)); return E_NOTIMPL; } auto* heap = new Heap(state_, *desc); heap->attach_device(identity()); if (!heap->reserved()) { log_once("GPU address arena full (raise LEONIDA_ARENA_MB); heap size in KiB:", int(desc->SizeInBytes / 1024)); heap->Release(); return E_OUTOFMEMORY; } if (!out) { heap->Release(); return S_FALSE; } return hand_out(heap, riid, out); } HRESULT STDMETHODCALLTYPE CreatePlacedResource(ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { return create_placed("ID3D12Device::CreatePlacedResource", heap_interface, heap_offset, desc, state, clear, 0, nullptr, riid, out); } // Device8: the DESC1 placed variant without a castable list. A texture with a mip region gets the failure // answer, as on the PC runtime; a buffer's mip region is ignored. HRESULT STDMETHODCALLTYPE CreatePlacedResource1(ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC1* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device8::CreatePlacedResource1"; if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); const D3D12_RESOURCE_DESC base = resource_desc(*desc); return create_placed(method, heap_interface, heap_offset, &base, state, clear, 0, nullptr, riid, out); } // Device10: an initial layout instead of a state, and the castable-format list, which the placed texture's // Vulkan image takes exactly as the committed path's does. A count with a null array is no list (as on the // PC runtime); the layer reports RelaxedFormatCastingSupported, so a real list is passed through. HRESULT STDMETHODCALLTYPE CreatePlacedResource2(ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) override { constexpr auto method = "ID3D12Device10::CreatePlacedResource2"; if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); const D3D12_RESOURCE_DESC base = resource_desc(*desc); if (const char* why = barrier_layout_refusal(base, layout)) { log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); return d3d12_trace::result(method, E_INVALIDARG); } // An initial layout replaces the state, so the state rules are not this call's. return create_placed(method, heap_interface, heap_offset, &base, D3D12_RESOURCE_STATE_COMMON, clear, castable_count, castable, riid, out); } // The placed path every CreatePlacedResource variant shares. A castable-format list reaches the placed // texture's Vulkan image as the committed path's does (create_committed): a buffer with a list is // E_INVALIDARG, and so is a format with no Vulkan mapping. // The arguments are answered as the host runtime answers them (d3d12_vulkan_device_test's // compare_placed_reserved, RTX 3060 / 610.88): the description, initial state and clear value rules // CreateCommittedResource has, then the placement: a buffer at a 64 KiB-aligned offset, a texture at a // multiple of its GetResourceAllocationInfo alignment (4 KiB for a small texture), in a heap aligned at least // as much, and the whole resource inside the heap. Only then is a null output E_UNEXPECTED, with nothing made. HRESULT create_placed(const char* method, ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { if (out) *out = nullptr; auto* heap = Heap::from(heap_interface); if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG); const bool from_xbox_d16s8 = desc->Format == xbox_d16s8; D3D12_RESOURCE_DESC canonical = *desc; canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 desc = &canonical; // Its clear value too, or the clear format's family (118) would not match the resource's (D24S8) below. D3D12_CLEAR_VALUE canonical_clear{}; if (clear) { canonical_clear = *clear; canonical_clear.Format = pc_format(canonical_clear.Format); clear = &canonical_clear; } if (heap->host_address()) { // An existing heap is not an arena range, and the placed path addresses resources by arena offset. log_once("a placed resource in an existing heap (OpenExistingHeapFromAddress) is not supported yet; " "dimension", int(desc->Dimension)); return d3d12_trace::result(method, E_NOTIMPL); } if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { log_once("castable formats on a placed buffer are invalid; count", int(castable_count)); return d3d12_trace::result(method, E_INVALIDARG); } // The description, state and clear value rules of a committed resource, but on a default heap: the heap's // DENY flags are checked against the resource below, and the host takes any initial state for a buffer in // an upload or readback heap (COPY_DEST in an upload heap, GENERIC_READ in a readback heap), where a // committed buffer must start in GENERIC_READ or COPY_DEST. UAV access is refused there all the same. const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; const char* why = committed_resource_refusal(default_heap, D3D12_HEAP_FLAG_NONE, *desc, state, clear, acceleration_structures(), state_.uma); const D3D12_HEAP_TYPE heap_type = heap->properties().Type; if (!why && (heap_type == D3D12_HEAP_TYPE_UPLOAD || heap_type == D3D12_HEAP_TYPE_READBACK) && (desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) why = "UAV access in an upload or readback heap"; if (why) { log_once((std::string(method) + " refused (" + why + "), dimension").c_str(), int(desc->Dimension)); return d3d12_trace::result(method, E_INVALIDARG); } const bool tiled = is_tiled_layout(desc->Layout); const bool msaa = desc->SampleDesc.Count > 1; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { if (heap->flags() & D3D12_HEAP_FLAG_DENY_BUFFERS) return d3d12_trace::result(method, E_INVALIDARG); if (heap_offset % D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) { log_once("placed buffer offset not 64 KiB aligned:", int(heap_offset)); return d3d12_trace::result(method, E_INVALIDARG); } if (desc->Width > heap->bytes() || heap_offset > heap->bytes() - desc->Width) return d3d12_trace::result(method, E_INVALIDARG); } else { if (heap->properties().Type == D3D12_HEAP_TYPE_UPLOAD || heap->properties().Type == D3D12_HEAP_TYPE_READBACK) return d3d12_trace::result(method, E_INVALIDARG); const bool rt_ds = (desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0; if (rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES)) return d3d12_trace::result(method, E_INVALIDARG); if (!rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES)) return d3d12_trace::result(method, E_INVALIDARG); if (tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) return d3d12_trace::result(method, E_INVALIDARG); if (msaa && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return d3d12_trace::result(method, E_INVALIDARG); // Extents, mips, samples, layout and alignment, as GetResourceAllocationInfo answers them (the sample // quality is the description rules' above, as in CreateCommittedResource). D3D12_RESOURCE_DESC checked = *desc; checked.SampleDesc.Quality = 0; const D3D12_RESOURCE_ALLOCATION_INFO alloc = allocation(checked); if (alloc.SizeInBytes == UINT64_MAX || heap->alignment() < alloc.Alignment || heap_offset % alloc.Alignment) { log_once("placed texture refused (size, alignment or room in the heap), dimension", int(desc->Dimension)); return d3d12_trace::result(method, E_INVALIDARG); } const UINT64 fit_bytes = (tiled || msaa) ? alloc.SizeInBytes : min_placed_texture_bytes(checked, state_.texture_format(checked), alloc.Alignment, alloc.SizeInBytes); if (fit_bytes > heap->bytes() || heap_offset > heap->bytes() - fit_bytes) { log_once("placed texture refused (size, alignment or room in the heap), dimension", int(desc->Dimension)); return d3d12_trace::result(method, E_INVALIDARG); } if (tiled && static_cast(desc->Layout) == kXboxTiledLayout) { log_once("placed resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension", int(desc->Dimension)); } } if (!out) return d3d12_trace::result(method, E_UNEXPECTED); const bool buffer = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER; if (buffer && !heap->use_as_placed_resource(true)) { log_once("placed buffer refused: heap uses a separate allocation for sparse tiles", 1); return d3d12_trace::result(method, E_NOTIMPL); } // Only buffers are addressable, as in D3D12: a placed texture keeps a null VA and its own Vulkan image, which // create_texture makes for 1D, 2D and 3D alike (arrays and mips included), as for a committed texture. const VkDeviceSize placed_va = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? heap->offset() + heap_offset : 0; auto* resource = new Resource(state_, *desc, heap->properties(), heap->flags(), placed_va); if (from_xbox_d16s8) resource->mark_console_d16s8(); resource->attach_device(identity()); HRESULT hr = E_NOTIMPL; if (buffer) { hr = resource->create_placed_buffer(heap->arena_range()); } else { hr = S_OK; const Format format = state_.texture_format(*desc); if (format.format == VK_FORMAT_UNDEFINED) { hr = E_INVALIDARG; } else { std::vector cast_formats; hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats, false, from_xbox_d16s8); if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats); if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); } } if (SUCCEEDED(hr) && !buffer && !heap->use_as_placed_resource(false)) { log_once("placed resource refused: heap uses a separate allocation for sparse tiles", 1); hr = E_NOTIMPL; } if (FAILED(hr)) { resource->Release(); return d3d12_trace::result(method, hr); } return d3d12_trace::result(method, hand_out(resource, riid, out)); } // Footprints for copies through a buffer: rows padded to D3D12_TEXTURE_DATA_PITCH_ALIGNMENT (512 for planar // depth-stencil), subresources placed at D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, block-compressed sizes rounded up to whole blocks, depth-stencil // formats as two planes. d3d12_vulkan_device_test compares every output with the PC runtime's. void STDMETHODCALLTYPE GetCopyableFootprints(const D3D12_RESOURCE_DESC* desc, UINT first, UINT count, UINT64 base, D3D12_PLACED_SUBRESOURCE_FOOTPRINT* layouts, UINT* rows, UINT64* row_sizes, UINT64* total) override { const auto fail = [&] { for (UINT i = 0; i < count; ++i) { if (layouts) std::memset(&layouts[i], 0xff, sizeof(layouts[i])); if (rows) rows[i] = ~0u; if (row_sizes) row_sizes[i] = ~0ull; } if (total) *total = ~0ull; }; if (!desc || !xr_bias_compatible(*desc) || rgb96_refused(*desc)) return fail(); const auto align = [](UINT64 value, UINT64 to) { return (value + to - 1) / to * to; }; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { // The PC runtime refuses any buffer field that isn't its one valid value (all measured on WARP, Width, // Height, Format, MipLevels 0, Layout and Count 0 also on an NVIDIA GPU). It doesn't look at Flags, so a // buffer with the render-target flag still gets its footprint (D3D-122). if (first != 0 || count != 1 || !desc->Width || desc->Height != 1 || desc->DepthOrArraySize != 1 || desc->MipLevels != 1 || desc->Format != DXGI_FORMAT_UNKNOWN || desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR || desc->SampleDesc.Count != 1 || desc->SampleDesc.Quality != 0 || (desc->Alignment && desc->Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT)) return fail(); if (layouts) layouts[0] = {base, {DXGI_FORMAT_UNKNOWN, UINT(desc->Width), 1, 1, UINT(align(desc->Width, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT))}}; if (rows) rows[0] = 1; if (row_sizes) row_sizes[0] = desc->Width; if (total) *total = desc->Width; return; } const bool volume = desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const bool one_d = desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; if (!volume && !one_d && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) { log_once("GetCopyableFootprints dimension not supported:", desc->Dimension); return fail(); } if (one_d && desc->Height != 1) return fail(); // Structural checks only, as measured on the PC runtime (D3D-122). Not allocation()'s: the footprint path // accepts extra mips, 2D ROW_MAJOR and Quality > 0 at one sample, and extent limits, alignment and // multisample quality differ between adapters, so those stay unchecked. const UINT samples = desc->SampleDesc.Count; const bool multisample_ok = desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc->MipLevels == 1 && desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR && !(samples & (samples - 1)) && (desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); if (!desc->Width || !desc->Height || !desc->DepthOrArraySize || !samples || (samples > 1 && !multisample_ok)) return fail(); const Format format = texture_storage_format(desc->Format, true); // typeless depth families are planar either way UINT mips = desc->MipLevels; const UINT depth = volume ? desc->DepthOrArraySize : 1; if (!mips) for (UINT64 size = std::max({desc->Width, desc->Height, depth}); size; size >>= 1) ++mips; const UINT planes = (format.aspects & VK_IMAGE_ASPECT_STENCIL_BIT) ? 2 : 1; const UINT per_plane = mips * (volume ? 1 : desc->DepthOrArraySize); if (!format.format || UINT64(first) + count > UINT64(per_plane) * planes) return fail(); // Subresources are aligned to D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT counting from BaseOffset, not from 0: the // PC runtime moves the whole layout by BaseOffset, so an unaligned base (513) keeps the same relative offsets // and the same total. Measured by compare_footprints in d3d12_vulkan_device_test. UINT64 offset = 0, end = 0; for (UINT i = 0; i < count; ++i) { const UINT index = first + i, plane = index / per_plane, mip = index % mips; const VkImageAspectFlags aspect = planes == 2 ? (plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT) : format.aspects; const leonida::BlockFormat block = footprint_block(format, aspect); if (!block.bytes) return fail(); // D3D12 takes any MipLevels, and the PC runtime's own shifts wrap past the type's width: a 16x16 texture // with 40 mips reports subresource 32 as 1x16 and 33 as 1x8, a volume's depth likewise (measured on an // RTX 5060 Ti, compare_footprints). The masks give the same answers without shifting a 32-bit (or the // 64-bit Width) value by its width or more, which C++ leaves undefined. const UINT width = std::max(1, UINT(desc->Width >> (mip & 63))); const UINT height = one_d ? 1 : std::max(1, desc->Height >> (mip & 31)); const UINT blocks_wide = (width + block.block - 1) / block.block; const UINT blocks_high = (height + block.block - 1) / block.block; const UINT64 row_size = UINT64(blocks_wide) * block.bytes; // Measured against the PC runtime (d3d12_vulkan_device_test): planar depth-stencil rows are padded to // 512 bytes, every other format's to D3D12_TEXTURE_DATA_PITCH_ALIGNMENT (256). const UINT pitch = UINT(align(row_size, planes == 2 ? 2 * D3D12_TEXTURE_DATA_PITCH_ALIGNMENT : D3D12_TEXTURE_DATA_PITCH_ALIGNMENT)); offset = align(offset, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); DXGI_FORMAT footprint_format = desc->Format; if (planes == 2) footprint_format = plane ? DXGI_FORMAT_R8_TYPELESS : (desc->Format==xbox_d16s8?DXGI_FORMAT_R16_TYPELESS:DXGI_FORMAT_R32_TYPELESS); const UINT slices = std::max(1u, depth >> (mip & 31)); if (layouts) layouts[i] = {base + offset, {footprint_format, blocks_wide * block.block, blocks_high * block.block, slices, pitch}}; if (rows) rows[i] = blocks_high; if (row_sizes) row_sizes[i] = row_size; const UINT64 total_rows = UINT64(blocks_high) * slices; end = offset + (total_rows - 1) * pitch + row_size; offset += total_rows * pitch; } if (total) *total = end; } // How much heap memory resources need and how to align them, for applications that suballocate heaps (section // 4.1). Buffers follow D3D12's fixed rule. A texture's size is what the Vulkan image it becomes needs, rounded up // to D3D12's alignment for it; the alignment itself is D3D12's, since placed textures bind their own memory // (section 4.2). Several resources are laid out one after another, each at its own alignment. An invalid // description gives SizeInBytes = UINT64_MAX, as on D3D12. d3d12_vulkan_device_test compares with the PC runtime. // A visible mask above 1 names a node the single-node adapter lacks: the same invalid answer, also for no // resources at all, and the per-resource array is left untouched (host runtime and WARP, measured). D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo( UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC* descs) override { if (visible_mask > 1) return kInvalidAllocation; return place(count, descs, [&](UINT i) { return descs[i]; }, nullptr); } D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo1( UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) override { if (visible_mask > 1) return kInvalidAllocation; return place(count, descs, [&](UINT i) { return descs[i]; }, each); } D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo2( UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC1* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) override { if (visible_mask > 1) return kInvalidAllocation; return place(count, descs, [&](UINT i) { const D3D12_RESOURCE_DESC1& d = descs[i]; if (d.SamplerFeedbackMipRegion.Width || d.SamplerFeedbackMipRegion.Height || d.SamplerFeedbackMipRegion.Depth) { log_once("GetResourceAllocationInfo2 sampler feedback not supported, format", d.Format); return D3D12_RESOURCE_DESC{}; // an unknown dimension: invalid } return D3D12_RESOURCE_DESC{d.Dimension, d.Alignment, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels, d.Format, d.SampleDesc, d.Layout, d.Flags}; }, each); } template static HRESULT write_supported_feature(const char* method, void* data, UINT size, BOOL supported) { if (size != sizeof(FeatureData)) return d3d12_trace::result(method, E_INVALIDARG); static_cast(data)->Supported = supported; return d3d12_trace::result(method, S_OK); } HRESULT STDMETHODCALLTYPE CheckFeatureSupport(D3D12_FEATURE feature, void* data, UINT size) override { constexpr auto method = "ID3D12Device::CheckFeatureSupport"; log_once("CheckFeatureSupport feature", feature); if (!data) return d3d12_trace::result(method, E_INVALIDARG); constexpr VkSampleCountFlags d3d12_multisample_sample_counts = VK_SAMPLE_COUNT_2_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_16_BIT | VK_SAMPLE_COUNT_32_BIT; switch (feature) { case D3D12_FEATURE_FEATURE_LEVELS: { if (size != sizeof(D3D12_FEATURE_DATA_FEATURE_LEVELS)) return d3d12_trace::result(method, E_INVALIDARG); auto* levels = static_cast(data); // The host (hardware and WARP) refuses an empty or missing list before reading it. if (!levels->NumFeatureLevels || !levels->pFeatureLevelsRequested) return d3d12_trace::result(method, E_INVALIDARG); D3D_FEATURE_LEVEL best = D3D_FEATURE_LEVEL(0); for (UINT i = 0; i < levels->NumFeatureLevels; ++i) if (levels->pFeatureLevelsRequested[i] <= D3D_FEATURE_LEVEL_12_1) best = std::max(best, levels->pFeatureLevelsRequested[i]); levels->MaxSupportedFeatureLevel = best; // 0 with DXGI_ERROR_UNSUPPORTED, as the host writes it if (!best) return d3d12_trace::result(method, DXGI_ERROR_UNSUPPORTED); return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_ARCHITECTURE: case D3D12_FEATURE_ARCHITECTURE1: { const bool v1 = feature == D3D12_FEATURE_ARCHITECTURE1; if (size != (v1 ? sizeof(D3D12_FEATURE_DATA_ARCHITECTURE1) : sizeof(D3D12_FEATURE_DATA_ARCHITECTURE))) return d3d12_trace::result(method, E_INVALIDARG); auto* arch = static_cast(data); const UINT node = arch->NodeIndex; if (node != 0) return d3d12_trace::result(method, E_INVALIDARG); // The host GPU's architecture (question 11): not tile-based; UMA on an integrated GPU, as the host runtime // answers there (Radeon 780M, AMD 32.0.13030.13001: UMA 1, CacheCoherentUMA 0), else a discrete one. The // console is UMA; the layer keeps upload heaps host-visible either way, so the game's upload path works. // CacheCoherentUMA stays FALSE: the AMD iGPU measured reports it so, and FALSE only steers an application // to write-combined uploads, which every UMA adapter accepts. arch->TileBasedRenderer = FALSE; arch->UMA = state_.uma ? TRUE : FALSE; arch->CacheCoherentUMA = FALSE; if (v1) arch->IsolatedMMU = TRUE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS: { constexpr UINT kConsoleOptionsSize = sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS) + sizeof(UINT); if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS) && size != kConsoleOptionsSize) return d3d12_trace::result(method, E_INVALIDARG); D3D12_FEATURE_DATA_D3D12_OPTIONS pc_opts{}; // Answer what the layer will actually honour, not what the GPU offers: docs/d3d12_vulkan.md 4.1 says a // false "supported" is worse than a false "unsupported" at boot, and the PSO paths refuse these same // features when they are missing (logic ops, per the mapping vkd3d-proton's // d3d12_device_caps_init_feature_options uses). pc_opts.DoublePrecisionFloatShaderOps = state_.info.features.shaderFloat64; pc_opts.OutputMergerLogicOp = state_.info.features.logicOp; pc_opts.MinPrecisionSupport = D3D12_SHADER_MIN_PRECISION_SUPPORT_NONE; pc_opts.TiledResourcesTier = D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED; pc_opts.ResourceBindingTier = D3D12_RESOURCE_BINDING_TIER_3; // Bindless descriptor indexing supported // No VK_EXT_shader_stencil_export is enabled and the translator emits no stencil-ref write, so a pixel // shader that writes the stencil ref would be refused: answer unsupported, the direction 4.1 prefers. pc_opts.PSSpecifiedStencilRefSupported = FALSE; pc_opts.TypedUAVLoadAdditionalFormats = TRUE; // POPS: the translator only declares PixelInterlockOrderedEXT, enabled exactly when the GPU offers // VK_EXT_fragment_shader_interlock and its fragmentShaderPixelInterlock feature. pc_opts.ROVsSupported = state_.info.fragment_shader_interlock; pc_opts.ConservativeRasterizationTier = state_.conservative_raster_tier; pc_opts.MaxGPUVirtualAddressBitsPerResource = 40; pc_opts.StandardSwizzle64KBSupported = FALSE; pc_opts.CrossNodeSharingTier = D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED; pc_opts.CrossAdapterRowMajorTextureSupported = FALSE; // A translated vertex shader writing a layer or viewport index needs both Vulkan 1.2 features enabled // (vkCreateShaderModule refuses the module without them, VUID-...-pCode-08740). pc_opts.VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation = state_.info.shader_output_layer && state_.info.shader_output_viewport_index; pc_opts.ResourceHeapTier = D3D12_RESOURCE_HEAP_TIER_1; std::memcpy(data, &pc_opts, sizeof(pc_opts)); if (size == kConsoleOptionsSize) { // Console titles query D3D12_FEATURE_D3D12_OPTIONS with a 0x40-byte (16-dword) buffer // (docs/d3d12_xs_surface.md §7.1): fill the 0x3C-byte PC prefix and zero the trailing 4 bytes. std::memset(static_cast(data) + sizeof(pc_opts), 0, sizeof(UINT)); } return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS1: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS1)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); const DeviceState::SubgroupFacts& facts = state_.subgroup_facts(); *opts = {}; opts->WaveOps = facts.wave_ops; opts->WaveLaneCountMin = facts.lane_min; opts->WaveLaneCountMax = facts.lane_max; // D3D12 counts every lane of the device here, and Vulkan has no such number. This is one full wave // (section 4.1): a game that sizes work from it plans for less parallelism than the GPU has, not more. opts->TotalLaneCount = facts.lane_max; opts->ExpandedComputeResourceStates = TRUE; // Vulkan has no resource states to expand return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS8: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS8)) return d3d12_trace::result(method, E_INVALIDARG); // Vulkan BC image extents are in texels; only the transfer footprints round up to blocks. auto* opts = static_cast(data); opts->UnalignedBlockTexturesSupported = state_.info.texture_compression_bc; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS2: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS2)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->DepthBoundsTestSupported = state_.info.features.depthBounds ? TRUE : FALSE; opts->ProgrammableSamplePositionsTier = state_.sample_positions_tier; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS3: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS3)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->CopyQueueTimestampQueriesSupported = state_.copy_timestamps_supported(); // Only typeless resources set VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. opts->CastingFullyTypedFormatSupported = FALSE; opts->WriteBufferImmediateSupportFlags = D3D12_COMMAND_LIST_SUPPORT_FLAG_NONE; opts->ViewInstancingTier = D3D12_VIEW_INSTANCING_TIER_NOT_SUPPORTED; opts->BarycentricsSupported = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS4: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS4)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; // GetResourceAllocationInfo implements D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT (64 KiB). opts->MSAA64KBAlignedTextureSupported = TRUE; opts->SharedResourceCompatibilityTier = D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_0; opts->Native16BitShaderOpsSupported = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS5: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS5)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->SRVOnlyTiledResourceTier3 = FALSE; opts->RenderPassesTier = D3D12_RENDER_PASS_TIER_0; opts->RaytracingTier = D3D12_RAYTRACING_TIER_NOT_SUPPORTED; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS7: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS7)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; // Tier 1 is mesh PSOs and DispatchMesh, on VK_EXT_mesh_shader. Amplification shaders are part of the tier // but refused at PSO creation (the game has none); OPTIONS9's mesh statistics and full-range render // target array index stay FALSE. opts->MeshShaderTier = state_.info.mesh_shader ? D3D12_MESH_SHADER_TIER_1 : D3D12_MESH_SHADER_TIER_NOT_SUPPORTED; opts->SamplerFeedbackTier = D3D12_SAMPLER_FEEDBACK_TIER_NOT_SUPPORTED; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS9: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS9)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->MeshShaderPipelineStatsSupported = FALSE; opts->MeshShaderSupportsFullRangeRenderTargetArrayIndex = FALSE; opts->AtomicInt64OnTypedResourceSupported = FALSE; opts->AtomicInt64OnGroupSharedSupported = FALSE; opts->DerivativesInMeshAndAmplificationShadersSupported = FALSE; opts->WaveMMATier = D3D12_WAVE_MMA_TIER_NOT_SUPPORTED; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS11: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS11)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->AtomicInt64OnDescriptorHeapResourceSupported = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS13: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS13)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->UnrestrictedBufferTextureCopyPitchSupported = FALSE; opts->UnrestrictedVertexElementAlignmentSupported = FALSE; opts->InvertedViewportHeightFlipsYSupported = FALSE; opts->InvertedViewportDepthFlipsZSupported = FALSE; opts->TextureCopyBetweenDimensionsSupported = FALSE; opts->AlphaBlendFactorSupported = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS14: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS14)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->AdvancedTextureOpsSupported = FALSE; opts->WriteableMSAATexturesSupported = FALSE; // DEPTH_STENCIL2's per-face masks go to VkStencilOpState, and OMSetFrontAndBackStencilRef sets each // face's reference (VK_DYNAMIC_STATE_STENCIL_REFERENCE with a face mask). opts->IndependentFrontAndBackStencilRefMaskSupported = TRUE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS15: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS15)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->TriangleFanSupported = FALSE; opts->DynamicIndexBufferStripCutSupported = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS16: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS16)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->DynamicDepthBiasSupported = FALSE; opts->GPUUploadHeapSupported = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS12: { // Vulkan 1.3's VkImageFormatListCreateInfo gives a mutable image the same relaxed format casting that // D3D12's castable-format lists describe. The layer also implements enhanced barriers (Barrier). if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS12)) return E_INVALIDARG; auto* opts = static_cast(data); *opts = {}; opts->MSPrimitivesPipelineStatisticIncludesCulledPrimitives = D3D12_TRI_STATE_UNKNOWN; opts->EnhancedBarriersSupported = TRUE; opts->RelaxedFormatCastingSupported = TRUE; return S_OK; } case D3D12_FEATURE_D3D12_OPTIONS17: { // Non-normalized samplers are core Vulkan (unnormalizedCoordinates), with the restrictions // CreateSampler2 checks. No manual write tracking, as the RTX 4090 answers too. if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS17)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->NonNormalizedCoordinateSamplersSupported = TRUE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS18: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS18)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->RenderPassesValid = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_D3D12_OPTIONS19: { if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS19)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->MismatchingOutputDimensionsSupported = FALSE; opts->SupportedSampleCountsWithNoOutputs = state_.no_output_sample_counts; opts->PointSamplingAddressesNeverRoundUp = FALSE; opts->RasterizerDesc2Supported = FALSE; opts->NarrowQuadrilateralLinesSupported = FALSE; opts->AnisoFilterWithPointMipSupported = state_.info.sampler_anisotropy ? TRUE : FALSE; opts->MaxSamplerDescriptorHeapSize = D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE; opts->MaxSamplerDescriptorHeapSizeWithStaticSamplers = D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE; opts->MaxViewDescriptorHeapSize = D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_2; opts->ComputeOnlyCustomHeapSupported = FALSE; return d3d12_trace::result(method, S_OK); } case compat::kFeatureOptions20: { if (size != sizeof(compat::FeatureDataOptions20)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->ComputeOnlyWriteWatchSupported = FALSE; opts->RecreateAtTier = compat::kRecreateAtTierNotSupported; return d3d12_trace::result(method, S_OK); } case compat::kFeatureOptions21: { if (size != sizeof(compat::FeatureDataOptions21)) return d3d12_trace::result(method, E_INVALIDARG); auto* opts = static_cast(data); *opts = {}; opts->WorkGraphsTier = compat::kWorkGraphsTierNotSupported; opts->ExecuteIndirectTier = compat::kExecuteIndirectTier1_0; opts->SampleCmpGradientAndBiasSupported = FALSE; opts->ExtendedCommandInfoSupported = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT: { if (size != sizeof(D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT)) return d3d12_trace::result(method, E_INVALIDARG); auto* va = static_cast(data); // The console and PC BDA support 48-bit GPU virtual addresses (section 4.1). va->MaxGPUVirtualAddressBitsPerResource = 40; va->MaxGPUVirtualAddressBitsPerProcess = 48; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_FORMAT_INFO: { if (size != sizeof(D3D12_FEATURE_DATA_FORMAT_INFO)) return E_INVALIDARG; auto* info = static_cast(data); // Plane count describes the DXGI layout even when the backend cannot create the texture. switch (info->Format) { case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: case DXGI_FORMAT_R24G8_TYPELESS: case DXGI_FORMAT_D24_UNORM_S8_UINT: case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: case DXGI_FORMAT_X24_TYPELESS_G8_UINT: case DXGI_FORMAT_NV12: case DXGI_FORMAT_P010: case DXGI_FORMAT_P016: case DXGI_FORMAT_NV11: info->PlaneCount = 2; break; case DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE: case DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE: case DXGI_FORMAT_A4B4G4R4_UNORM: info->PlaneCount = 1; break; default: // Native D3D12 accepts UNKNOWN but rejects R1_UNORM and the gaps in the enum. if (UINT(info->Format) > DXGI_FORMAT_B4G4R4A4_UNORM || info->Format == DXGI_FORMAT_R1_UNORM) return E_INVALIDARG; info->PlaneCount = 1; } return S_OK; } case D3D12_FEATURE_FORMAT_SUPPORT: { if (size != sizeof(D3D12_FEATURE_DATA_FORMAT_SUPPORT)) return d3d12_trace::result(method, E_INVALIDARG); auto* fs = static_cast(data); fs->Support1 = D3D12_FORMAT_SUPPORT1_NONE; fs->Support2 = D3D12_FORMAT_SUPPORT2_NONE; // The host runtime's format table (compare_invalid_arguments, "format support:"): a value it has no entry // for is E_FAIL, not unsupported: past B4G4R4A4_UNORM (115) up to 188, which includes the planar video // formats P208/V208/V408 (130-132), and from 192 up; 189-191 are the sampler-feedback formats and // A4B4G4R4. UNKNOWN is a buffer format (raw and structured buffers). const UINT format_value = static_cast(fs->Format); if (format_value > static_cast(DXGI_FORMAT_B4G4R4A4_UNORM) && !(rt::d3d12_xs::console_feature_query() && format_value >= 118 && format_value <= 120) && (format_value < 189 || format_value > 191)) return d3d12_trace::result(method, E_FAIL); if (fs->Format == DXGI_FORMAT_UNKNOWN) { fs->Support1 = D3D12_FORMAT_SUPPORT1_BUFFER; return d3d12_trace::result(method, S_OK); } // The plane formats a shader reads a depth-stencil texture through (CreateShaderResourceView takes them on // R24G8/R32G8X24 and D24S8/D32S8 textures) have no image of their own, so the lookups below find nothing. // The host reports them as sampled 2D and cube textures with mips, the depth plane also filtered and // compared. Left out, as for the depth formats themselves: 1D, and multisample loads. const bool depth_plane = fs->Format == xbox_d16_plane || fs->Format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || fs->Format == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; if (depth_plane || fs->Format == xbox_s8_plane || fs->Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT || fs->Format == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT) { const bool d24 = fs->Format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || fs->Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT; VkFormat family = vulkan_format(d24 ? DXGI_FORMAT_D24_UNORM_S8_UINT : DXGI_FORMAT_D32_FLOAT_S8X24_UINT, true).format; if(fs->Format==xbox_d16_plane || fs->Format==xbox_s8_plane)family=state_.depth_backing(VK_FORMAT_D16_UNORM_S8_UINT); if (family == VK_FORMAT_D24_UNORM_S8_UINT && !state_.depth_usable(family)) family = VK_FORMAT_D32_SFLOAT_S8_UINT; VkFormatProperties props{}; if (state_.format_properties) state_.format_properties(state_.info.physical, family, &props); if (!(props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) return d3d12_trace::result(method, DXGI_ERROR_UNSUPPORTED); fs->Support1 = D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | D3D12_FORMAT_SUPPORT1_SHADER_LOAD | D3D12_FORMAT_SUPPORT1_MIP; if (depth_plane && (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)) fs->Support1 |= D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE | D3D12_FORMAT_SUPPORT1_SHADER_GATHER | D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_COMPARISON | D3D12_FORMAT_SUPPORT1_SHADER_GATHER_COMPARISON; return d3d12_trace::result(method, S_OK); } const Format fmt = texture_storage_format(fs->Format, false); const Format depth_fmt = vulkan_format(fs->Format, true); VkFormat vk_fmt = fmt.format != VK_FORMAT_UNDEFINED ? fmt.format : depth_fmt.format; // Report what creation makes: a D24 texture on a GPU without Vulkan D24 (AMD) is a D32_SFLOAT_S8_UINT // image (texture_format), so its features are D32S8's. Asking D24 itself gave Support1 = 0 there, // although CreateCommittedResource(ALLOW_DEPTH_STENCIL) succeeds. vk_fmt=state_.depth_backing(vk_fmt); if (vk_fmt == VK_FORMAT_D24_UNORM_S8_UINT && !state_.depth_usable(vk_fmt)) vk_fmt = VK_FORMAT_D32_SFLOAT_S8_UINT; if (vk_fmt == VK_FORMAT_UNDEFINED || !state_.format_properties) { return d3d12_trace::result(method, DXGI_ERROR_UNSUPPORTED); } if (fs->Format == DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM) { // The host reports this display format as 2D, display, cast-within-bit-layout, back-buffer-cast and // video-processor output, and no shader reads. The layer has the 2D resource and the bit-compatible // view cast; it has no display scan-out or video processor, so it reports only what it provides. fs->Support1 = D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_CAST_WITHIN_BIT_LAYOUT; return S_OK; } VkFormatProperties props{}; state_.format_properties(state_.info.physical, vk_fmt, &props); VkFormatFeatureFlags optimal = props.optimalTilingFeatures; VkFormatFeatureFlags buffer = props.bufferFeatures; if (fmt.rgb96) { // Textures are RGBA32 images that are sampled and copied, nothing else yet (no render target, // no unordered access: creation refuses them). Buffers hold the real 12-byte format; the PC // runtime (WARP) has no typed unordered access of these formats, in buffers either. optimal &= VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; VkFormatProperties narrow{}; state_.format_properties(state_.info.physical, rgb96_named_format(vk_fmt), &narrow); buffer = narrow.bufferFeatures & ~VkFormatFeatureFlags(VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT | VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT); } D3D12_FORMAT_SUPPORT1 s1 = D3D12_FORMAT_SUPPORT1_NONE; D3D12_FORMAT_SUPPORT2 s2 = D3D12_FORMAT_SUPPORT2_NONE; if (fs->Format == DXGI_FORMAT_A8_UNORM) { if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { fs->Support1 = D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | D3D12_FORMAT_SUPPORT1_SHADER_LOAD; if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) fs->Support1 |= D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE | D3D12_FORMAT_SUPPORT1_SHADER_GATHER; VkImageFormatProperties limits{}; const VkImageUsageFlags usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; if (state_.image_format_properties && state_.image_format_properties(state_.info.physical, vk_fmt, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usage, 0, &limits) == VK_SUCCESS && limits.maxMipLevels > 1) fs->Support1 |= D3D12_FORMAT_SUPPORT1_MIP; // Render targets are stored as VK_FORMAT_A8_UNORM_KHR, which the device checked can blend. if (state_.info.a8_render_target) fs->Support1 |= D3D12_FORMAT_SUPPORT1_RENDER_TARGET | D3D12_FORMAT_SUPPORT1_BLENDABLE; } return d3d12_trace::result(method, S_OK); } // D3D12 disallows typed buffer views for the RGBA8 and BGRA8 sRGB formats (including BGRX8). // Vulkan can still advertise buffer features for their backing formats. if (buffer != 0 && vk_fmt != VK_FORMAT_R8G8B8A8_SRGB && vk_fmt != VK_FORMAT_B8G8R8A8_SRGB) s1 |= D3D12_FORMAT_SUPPORT1_BUFFER; // Only what CreateGraphicsPipelineState's input layouts accept (vertex_format). VkFormat vertex_vk = VK_FORMAT_UNDEFINED; UINT vertex_bytes = 0; if ((buffer & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT) && vertex_format(fs->Format, vertex_vk, vertex_bytes)) s1 |= D3D12_FORMAT_SUPPORT1_IA_VERTEX_BUFFER; if (fs->Format == DXGI_FORMAT_R16_UINT || fs->Format == DXGI_FORMAT_R32_UINT) s1 |= D3D12_FORMAT_SUPPORT1_IA_INDEX_BUFFER; if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | D3D12_FORMAT_SUPPORT1_SHADER_LOAD; } if (buffer & VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_SHADER_LOAD; } if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE; } if (optimal & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_RENDER_TARGET; // A D3D12 multisample resolve needs the same image usages as TextureCreateInfo: colour // attachment plus transfer source/destination (and the ordinary sampled usage). VkImageFormatProperties image_properties{}; const VkImageUsageFlags usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; const VkImageCreateFlags flags = fmt.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; if (state_.image_format_properties && state_.image_format_properties(state_.info.physical, vk_fmt, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usage, flags, &image_properties) == VK_SUCCESS && (image_properties.sampleCounts & d3d12_multisample_sample_counts)) { s1 |= D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RENDERTARGET | D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RESOLVE; if ((optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && !fmt.typeless && fmt.aspects == VK_IMAGE_ASPECT_COLOR_BIT && leonida::gfx10::format_from_vulkan(vk_fmt) && state_.bindless && state_.bindless->supports_ms_class(DeviceState::numeric_class(vk_fmt))) s1 |= D3D12_FORMAT_SUPPORT1_MULTISAMPLE_LOAD; } } if(fs->Format==DXGI_FORMAT_B4G4R4A4_UNORM && !(optimal&VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) && state_.color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM))s1|=D3D12_FORMAT_SUPPORT1_RENDER_TARGET; if (optimal & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_BLENDABLE; } if (optimal & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL; } // B8G8R8X8 has no typed UAV in D3D12 (texture_format refuses it), whatever the BGRA8 image could do. if (!alpha_unused(fs->Format) && ((optimal & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) || (buffer & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT))) { s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; // A typed UAV texture read is not a storage-image read: the translator reads it through the // texture's sampled binding with the T#'s numeric type (rdna2spirv.py image_read_typed), so a // format that can be stored can be read. Typed buffer UAVs share the store side's limits: a buffer // UAV is a typed V# the layer writes itself (write_buffer_uav, no VkBufferView), and rdna2spirv.py // FORMATS decodes only some buffer formats. s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE | D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD; // Image atomics go through the r32ui storage view, which an R32_UINT UAV view gets // (StorageViews::r32ui). Today that is 2D UAVs only: the translator's image atomics cover 2D and 3D, // the bindless set has r32ui slots for those two, and the layer creates no 3D UAV views yet. There // is no image_atomic_swap, so no exchange. if (vk_fmt == VK_FORMAT_R32_UINT && (optimal & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)) { s2 |= D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_ADD | D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_BITWISE_OPS | D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_COMPARE_STORE_OR_COMPARE_EXCHANGE | D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_SIGNED_MIN_OR_MAX | D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_UNSIGNED_MIN_OR_MAX; } } { // D3D12's per-format rules, as native D3D12 reports them (RX 9070 XT, AMD 26.11.2, and WARP): // the Vulkan feature bits above say what the image can do, not what D3D12 lets the format do. const Format& chosen = fmt.format != VK_FORMAT_UNDEFINED ? fmt : depth_fmt; const bool depth = (chosen.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; const bool block_compressed = vk_fmt >= VK_FORMAT_BC1_RGB_UNORM_BLOCK && vk_fmt <= VK_FORMAT_BC7_SRGB_BLOCK; // Gathers read the sampled view like a sample does (OpImageGather); the host reports one with the other. if (s1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE) s1 |= D3D12_FORMAT_SUPPORT1_SHADER_GATHER; // Comparison sampling and gathers (SampleCmp, GatherCmp with a comparison sampler) are D3D12's for the // depth-plane view formats only; R32_FLOAT and R16_UNORM are the views of D32 and D16 textures. if ((s1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE) && (fs->Format == DXGI_FORMAT_R32_FLOAT || fs->Format == DXGI_FORMAT_R16_UNORM)) s1 |= D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_COMPARISON | D3D12_FORMAT_SUPPORT1_SHADER_GATHER_COMPARISON; // A mip chain where the image can have one (asked with its sampled or depth-stencil usage). if (s1 & (D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL)) { const VkImageUsageFlags usage = depth ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : VK_IMAGE_USAGE_SAMPLED_BIT; VkImageFormatProperties limits{}; if (state_.image_format_properties && state_.image_format_properties(state_.info.physical, vk_fmt, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usage, chosen.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0, &limits) == VK_SUCCESS && limits.maxMipLevels > 1) s1 |= D3D12_FORMAT_SUPPORT1_MIP; // Depth formats multisample as depth-stencil targets; the colour-attachment check above never // sees them. Same usages as MULTISAMPLE_QUALITY_LEVELS and resource creation ask for. if (depth && !chosen.typeless && (s1 & D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL) && state_.image_format_properties && state_.image_format_properties(state_.info.physical, vk_fmt, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, 0, &limits) == VK_SUCCESS && (limits.sampleCounts & d3d12_multisample_sample_counts)) s1 |= D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RENDERTARGET; } // No resolve of integer formats (ResolveSubresource takes float, UNORM and SNORM only). if (DeviceState::numeric_class(vk_fmt) != 0) s1 &= ~D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RESOLVE; // Block-compressed textures are 2D, 3D or cubes: 1D has no 4x4 blocks. if (block_compressed) s1 &= ~D3D12_FORMAT_SUPPORT1_TEXTURE1D; // Depth formats are 2D and cube resources whose shaders read and write them through a colour view // (R32_FLOAT, R24_UNORM_X8_TYPELESS, ...): not 3D, not shader resources or UAVs themselves (NVIDIA // gives D32_SFLOAT and D16_UNORM STORAGE_IMAGE). Native D3D12 also allows 1D, but the layer refuses // 1D depth-stencil resources (CreateCommittedResource). if (depth) { s1 &= ~(D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_SHADER_LOAD | D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE | D3D12_FORMAT_SUPPORT1_SHADER_GATHER | D3D12_FORMAT_SUPPORT1_BUFFER | D3D12_FORMAT_SUPPORT1_IA_VERTEX_BUFFER | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); s2 = D3D12_FORMAT_SUPPORT2_NONE; } // A TYPELESS format is only storage: views give it a type, so it is a texture with mips and // nothing a view would do (no buffer, shader, render-target or UAV use of its own). if (chosen.typeless) { s1 &= D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | D3D12_FORMAT_SUPPORT1_MIP; s2 = D3D12_FORMAT_SUPPORT2_NONE; } } if (fs->Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && state_.r9g9b9e5_uav_emulated) { s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; // Reads go through the sampled E5B9G9R9 view, like every typed UAV read (see above). s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE | D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD; } if (fs->Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) { // Keep the native attachment and resolve bits. Blending and shader multisample loads remain masked. s1 &= ~(D3D12_FORMAT_SUPPORT1_BLENDABLE | D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL | D3D12_FORMAT_SUPPORT1_MULTISAMPLE_LOAD); } fs->Support1 = s1; fs->Support2 = s2; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS: { if (size != sizeof(D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS)) return d3d12_trace::result(method, E_INVALIDARG); auto* levels = static_cast(data); // RTX 5070 / 621.14/621.24: a format outside the runtime's table (and R1_UNORM) fails with the caller's // output untouched; a known format clears it before the sample count is checked. const UINT format_id = UINT(levels->Format); if (levels->Format == DXGI_FORMAT_R1_UNORM || !(format_id <= DXGI_FORMAT_B4G4R4A4_UNORM || (rt::d3d12_xs::console_feature_query() && format_id >= 118 && format_id <= 120) || (format_id >= DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE && format_id <= DXGI_FORMAT_A4B4G4R4_UNORM))) return d3d12_trace::result(method, E_FAIL); levels->NumQualityLevels = 0; // TILED_RESOURCE asks about tiled (reserved, 64KB_UNDEFINED_SWIZZLE) textures. Measured natively on an // RX 7800 XT, a Radeon iGPU and WARP: 1x and 4x keep the plain answer, every other count has none, and a // format without a tile shape (96-bit) has none at any count. That is GetResourceAllocationInfo's rule // here (tiled MSAA is 4x only). 128-bit formats at 4x: the AMD drivers answer 0, WARP and the RTX 5070 Ti // allocate them; this follows the latter, as the allocation path does. // RTX 5070 / 621.14: undefined flag bits are ignored; bad counts fail, known formats have 1x. const bool tiled = (levels->Flags & D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_TILED_RESOURCE) != 0; if (levels->SampleCount == 0 || levels->SampleCount > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT) return d3d12_trace::result(method, E_FAIL); Format format = texture_storage_format(levels->Format, false); if (levels->SampleCount == 1) { levels->NumQualityLevels = tiled && format.rgb96 ? 0 : 1; return d3d12_trace::result(method, S_OK); } if ((levels->SampleCount & (levels->SampleCount - 1)) != 0) return d3d12_trace::result(method, S_OK); const bool alpha_only = levels->Format == DXGI_FORMAT_A8_UNORM; if (alpha_only && levels->SampleCount != 1) return d3d12_trace::result(method, S_OK); if (levels->Format == DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM && levels->SampleCount != 1) return d3d12_trace::result(method, S_OK); // single-sample 2D only; no quality levels if (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) { D3D12_RESOURCE_DESC depth_desc{}; depth_desc.Format = levels->Format; depth_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; format = state_.texture_format(depth_desc); // includes the D24-to-D32 fallback used by creation } if (format.format == VK_FORMAT_UNDEFINED || !state_.image_format_properties) return d3d12_trace::result(method, S_OK); if (format.rgb96) return d3d12_trace::result(method, S_OK); // no 96-bit render targets yet // Vulkan exposes one standard sample pattern per supported count, so each supported count maps to // one D3D12 quality level (quality index 0). Query the matching colour or depth/stencil attachment // usage, plus the transfer and sampled usages used by the resource implementation. VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; if (format.aspects & VK_IMAGE_ASPECT_COLOR_BIT) { if (!alpha_only) usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; } else if (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; else return d3d12_trace::result(method, DXGI_ERROR_UNSUPPORTED); const VkImageCreateFlags flags = format.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; VkImageFormatProperties image_properties{}; const VkResult result = state_.image_format_properties(state_.info.physical, format.format, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usage, flags, &image_properties); const VkSampleCountFlagBits samples = VkSampleCountFlagBits(levels->SampleCount); if (result == VK_SUCCESS && (image_properties.sampleCounts & samples)) levels->NumQualityLevels = 1; if (tiled && levels->SampleCount != 1 && levels->SampleCount != 4) levels->NumQualityLevels = 0; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_SHADER_MODEL: { if (size != sizeof(D3D12_FEATURE_DATA_SHADER_MODEL)) return E_INVALIDARG; auto* model = static_cast(data); // Measured against the host PC runtime: a request above the supported model is clamped down to it, 5.1 // is echoed because it is D3D12's own baseline (WARP and the RTX 5070 both answer it with S_OK), and a // value below it is refused with E_INVALIDARG (0x5f crashed the host, so the test does not probe it). // Refuse the same way instead of echoing an unrepresentable value back: below 5.1, and between 5.1 and // 6.0, where no runtime defines a model (0x52-0x5f; E_INVALIDARG on the host runtime of an RTX 5070). const UINT requested = static_cast(model->HighestShaderModel); if (requested < D3D_SHADER_MODEL_5_1 || (requested > D3D_SHADER_MODEL_5_1 && requested < D3D_SHADER_MODEL_6_0)) return E_INVALIDARG; if (model->HighestShaderModel > kHighestShaderModel) model->HighestShaderModel = kHighestShaderModel; return S_OK; } case D3D12_FEATURE_ROOT_SIGNATURE: { if (size != sizeof(D3D12_FEATURE_DATA_ROOT_SIGNATURE)) return E_INVALIDARG; auto* root = static_cast(data); // 1.0 to 1.2 are defined (1.2 by number: not every SDK names it). The host refuses anything else and leaves // the value alone (RTX 4070 Laptop 621.24 and WARP), so only 1.2 is clamped. const UINT requested = static_cast(root->HighestVersion); if (requested < static_cast(D3D_ROOT_SIGNATURE_VERSION_1_0) || requested > 0x3) return E_INVALIDARG; if (root->HighestVersion > kHighestRootSignatureVersion) root->HighestVersion = kHighestRootSignatureVersion; return S_OK; } case D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT: { if (size != sizeof(D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT)) return d3d12_trace::result(method, E_INVALIDARG); auto* prot = static_cast(data); prot->Support = D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAG_NONE; if (prot->NodeIndex != 0) return d3d12_trace::result(method, E_INVALIDARG); return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_TYPE_COUNT: { if (size != sizeof(D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPE_COUNT)) return d3d12_trace::result(method, E_INVALIDARG); auto* prot_count = static_cast(data); if (prot_count->NodeIndex != 0) return d3d12_trace::result(method, E_INVALIDARG); prot_count->Count = 0; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_TYPES: { if (size != sizeof(D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPES)) return d3d12_trace::result(method, E_INVALIDARG); const auto* prot_types = static_cast(data); // Zero protected resource session types exist, so only Count == 0 on node 0 matches TYPE_COUNT. if (prot_types->NodeIndex != 0 || prot_types->Count != 0) return d3d12_trace::result(method, E_INVALIDARG); return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_SHADER_CACHE: { if (size != sizeof(D3D12_FEATURE_DATA_SHADER_CACHE)) return d3d12_trace::result(method, E_INVALIDARG); static_cast(data)->SupportFlags = D3D12_SHADER_CACHE_SUPPORT_NONE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_COMMAND_QUEUE_PRIORITY: { if (size != sizeof(D3D12_FEATURE_DATA_COMMAND_QUEUE_PRIORITY)) return d3d12_trace::result(method, E_INVALIDARG); auto* prio = static_cast(data); prio->PriorityForTypeIsSupported = FALSE; if (UINT(prio->CommandListType) > D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE || (prio->Priority != D3D12_COMMAND_QUEUE_PRIORITY_NORMAL && prio->Priority != D3D12_COMMAND_QUEUE_PRIORITY_HIGH && prio->Priority != D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME)) return d3d12_trace::result(method, E_INVALIDARG); // DIRECT/COMPUTE/COPY report NORMAL only: all VkQueues share priority 1.0f (HIGH has no distinct scheduling) // and GLOBAL_REALTIME is refused in CreateCommandQueue. const bool supported_type = prio->CommandListType == D3D12_COMMAND_LIST_TYPE_DIRECT || prio->CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || prio->CommandListType == D3D12_COMMAND_LIST_TYPE_COPY; const bool supported_priority = prio->Priority == D3D12_COMMAND_QUEUE_PRIORITY_NORMAL; prio->PriorityForTypeIsSupported = (supported_type && supported_priority) ? TRUE : FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_EXISTING_HEAPS: return write_supported_feature( method, data, size, state_.get_host_pointer_properties ? TRUE : FALSE); case D3D12_FEATURE_SERIALIZATION: { if (size != sizeof(D3D12_FEATURE_DATA_SERIALIZATION)) return d3d12_trace::result(method, E_INVALIDARG); auto* ser = static_cast(data); ser->HeapSerializationTier = D3D12_HEAP_SERIALIZATION_TIER_0; if (ser->NodeIndex != 0) return d3d12_trace::result(method, E_INVALIDARG); return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_CROSS_NODE: { if (size != sizeof(D3D12_FEATURE_DATA_CROSS_NODE)) return d3d12_trace::result(method, E_INVALIDARG); auto* cross = static_cast(data); cross->SharingTier = D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED; cross->AtomicShaderInstructions = FALSE; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_DISPLAYABLE: { if (size != sizeof(D3D12_FEATURE_DATA_DISPLAYABLE)) return d3d12_trace::result(method, E_INVALIDARG); auto* disp = static_cast(data); disp->DisplayableTexture = FALSE; disp->SharedResourceCompatibilityTier = D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_0; return d3d12_trace::result(method, S_OK); } case D3D12_FEATURE_QUERY_META_COMMAND: // EnumerateMetaCommands reports 0 meta-commands, so any query is rejected (as on host D3D12). return d3d12_trace::result(method, E_INVALIDARG); case compat::kFeaturePredication: return write_supported_feature( method, data, size, state_.info.conditional_rendering ? TRUE : FALSE); case compat::kFeatureApplicationSpecificDriverState: return write_supported_feature(method, data, size, FALSE); case compat::kFeatureBytecodeBypassHashSupported: return write_supported_feature(method, data, size, FALSE); default: // Not answered yet. The log above lists every query; answers are added as the trace asks for them. return d3d12_trace::result(method, E_INVALIDARG); } } private: IUnknown* identity() { return (outer_ && !rt::d3d12_xs::in_internal_device_child()) ? outer_ : static_cast(this); } static constexpr D3D12_RESOURCE_ALLOCATION_INFO kInvalidAllocation{UINT64_MAX, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT}; bool xbox_depth_uav(const D3D12_RESOURCE_DESC& desc) const { return rt::d3d12_xs::depth_uav_description(desc) && rt::d3d12_xs::is_device_proxy(outer_); } // Lays `count` resources out one after another; `each` (optional) gets every resource's offset, size and // alignment. As on the PC runtime, the total is rounded up to the largest alignment (1 for no resources) and // saturates near 2^64 rather than wrapping. template D3D12_RESOURCE_ALLOCATION_INFO place(UINT count, const Desc* descs, Get get, D3D12_RESOURCE_ALLOCATION_INFO1* each) { D3D12_RESOURCE_ALLOCATION_INFO total{0, 1}; bool failed = count && !descs; for (UINT i = 0; i < count; ++i) { D3D12_RESOURCE_ALLOCATION_INFO one = kInvalidAllocation; if (!failed) { auto desc = get(i); // The boot stack charges XMem for the guest placement; storage planes are private to Vulkan. if (xbox_depth_uav(desc)) desc.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; one = allocation(desc); if (one.SizeInBytes == UINT64_MAX) log_refused_allocation(get(i)); } failed = failed || one.SizeInBytes == UINT64_MAX; if (failed) { if (each) each[i] = {UINT64_MAX, one.Alignment, UINT64_MAX}; continue; } const UINT64 offset = align_up(total.SizeInBytes, one.Alignment); if (each) each[i] = {offset, one.Alignment, one.SizeInBytes}; total = {one.SizeInBytes > UINT64_MAX - offset ? UINT64_MAX : offset + one.SizeInBytes, std::max(total.Alignment, one.Alignment)}; } return failed ? kInvalidAllocation : D3D12_RESOURCE_ALLOCATION_INFO{align_up(total.SizeInBytes, total.Alignment), total.Alignment}; } // A title that gets "invalid" for a description it believes in usually stops right there (GTA VI asserts on a // size above 4 GiB), so every distinct refused description is logged in full. A small-alignment probe // (Alignment 4096) the title retries without is expected, and marked as such. static void log_refused_allocation(const D3D12_RESOURCE_DESC& desc) { static std::mutex mutex; static std::set seen; char line[256]; std::snprintf(line, sizeof line, "dim %d format %d %llux%ux%u mips %u samples %u/%u layout %d flags 0x%x alignment %llu%s", int(desc.Dimension), int(desc.Format), static_cast(desc.Width), unsigned(desc.Height), unsigned(desc.DepthOrArraySize), unsigned(desc.MipLevels), unsigned(desc.SampleDesc.Count), unsigned(desc.SampleDesc.Quality), int(desc.Layout), unsigned(desc.Flags), static_cast(desc.Alignment), desc.Alignment == D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT ? " (small-alignment probe)" : ""); std::lock_guard lock(mutex); if (seen.size() < 64 && seen.insert(line).second) std::fprintf(stderr, "[rt] d3d12: GetResourceAllocationInfo refused: %s\n", line); } D3D12_RESOURCE_ALLOCATION_INFO allocation(const D3D12_RESOURCE_DESC& asked) const { if (xbox_depth_storage_desc(asked) && outer_ && rt::d3d12_xs::is_device_proxy(outer_)) { const auto depth = allocation(depth_storage_part(asked, false)); const auto colour = allocation(depth_storage_part(asked, true)); if (depth.SizeInBytes == UINT64_MAX || colour.SizeInBytes == UINT64_MAX) return kInvalidAllocation; return {std::max(depth.SizeInBytes, colour.SizeInBytes), std::max(depth.Alignment, colour.Alignment)}; } D3D12_RESOURCE_DESC desc = asked; desc.Format = pc_format(desc.Format); // the console's D16S8 family as D24S8 return allocation_of(desc); } // One resource's size and alignment, or kInvalidAllocation for a description D3D12 (or this device) rejects. D3D12_RESOURCE_ALLOCATION_INFO allocation_of(const D3D12_RESOURCE_DESC& desc) const { constexpr UINT64 align_4k = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT, align_64k = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, align_msaa_64k = D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, align_msaa_4m = D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT; constexpr D3D12_RESOURCE_FLAGS attachment = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { // Host D3D12 accepts ALLOW_RENDER_TARGET, ALLOW_CROSS_ADAPTER, UAV, DENY_SHADER_RESOURCE, // RAYTRACING_ACCELERATION_STRUCTURE and 0x400 on buffers; refuses ALLOW_DEPTH_STENCIL, // ALLOW_SIMULTANEOUS_ACCESS, VIDEO_DECODE_REFERENCE_ONLY and other flags (D3D-467). constexpr UINT buffer_flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE | 0x400; if (!desc.Width || desc.Width > UINT64_MAX - align_64k || desc.Height != 1 || desc.DepthOrArraySize != 1 || desc.MipLevels != 1 || desc.Format != DXGI_FORMAT_UNKNOWN || desc.SampleDesc.Count != 1 || desc.SampleDesc.Quality != 0 || desc.Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR || (desc.Alignment && desc.Alignment != align_64k) || (UINT(desc.Flags) & ~buffer_flags)) return kInvalidAllocation; return {align_up(desc.Width, align_64k), align_64k}; } const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; if (!volume && !one_d && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) { if (desc.Dimension != D3D12_RESOURCE_DIMENSION_UNKNOWN) log_once("GetResourceAllocationInfo dimension not supported:", desc.Dimension); return kInvalidAllocation; } if (one_d && desc.Height != 1) return kInvalidAllocation; const UINT samples = desc.SampleDesc.Count, depth = volume ? desc.DepthOrArraySize : 1; const UINT64 max_extent = volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION; const UINT max_layers = volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION; if (!desc.Width || !desc.Height || !desc.DepthOrArraySize || desc.Width > max_extent || desc.Height > max_extent || desc.DepthOrArraySize > max_layers || !samples || samples > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT || (samples & (samples - 1)) || (samples > 1 && desc.SampleDesc.Quality != 0) || desc.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return kInvalidAllocation; const UINT16 full = full_mips(desc.Width, desc.Height, depth); D3D12_RESOURCE_DESC resolved = desc; if (!resolved.MipLevels) resolved.MipLevels = full; if (resolved.MipLevels > full) return kInvalidAllocation; const bool depth_stencil = desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; if ((desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && !depth_stencil) return kInvalidAllocation; if (samples > 1 && (volume || one_d || resolved.MipLevels != 1 || !(desc.Flags & attachment) || (desc.Flags & attachment) == attachment || (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) return kInvalidAllocation; // The PC runtime: simultaneous access only single-sampled and without depth-stencil, and no volume depth. if (((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) && (depth_stencil || samples > 1)) || (volume && depth_stencil)) return kInvalidAllocation; const bool tiled = is_tiled_layout(desc.Layout); if (tiled) { if (one_d || (samples > 1 && samples != 4)) return kInvalidAllocation; if (desc.Alignment && desc.Alignment != align_64k) return kInvalidAllocation; } else if (desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN) { log_once("GetResourceAllocationInfo layout as UNKNOWN:", desc.Layout); } const Format format = state_.texture_format(desc); if (!format.format) { log_once("GetResourceAllocationInfo format not supported yet:", desc.Format); return kInvalidAllocation; } VkMemoryRequirements need{}; const TextureCreateInfo create(resolved, format, state_.color_attachment_usable(format.format), state_.sample_grid_1, state_.info.shader_image_int64_atomics); if (!state_.memory_requirements(create.info, need)) return kInvalidAllocation; if (tiled) { leonida::ResourceTiling tiling; if (!resource_tiling(resolved, tiling)) return kInvalidAllocation; return {UINT64(tiling.total_tiles) * leonida::tile_size_in_bytes, align_64k}; } // D3D12's alignment: 64 KiB, or 4 MiB with MSAA, unless the description asks for a small one (4 KiB, 64 KiB // with MSAA). 4 KiB needs the top mip of one array slice to fit in 16 tiles of 4 KiB and the resource not to // be a render target or depth buffer; mips and array slices don't count. If it doesn't qualify, the PC // runtime calls the description invalid rather than answering with 64 KiB. The MSAA 64 KiB alignment has no // size limit there. Both measured in d3d12_vulkan_device_test. UINT64 alignment = 0; if (samples > 1) { if (desc.Alignment && desc.Alignment != align_msaa_64k && desc.Alignment != align_msaa_4m) return kInvalidAllocation; alignment = desc.Alignment ? desc.Alignment : align_msaa_4m; } else { if (desc.Alignment && desc.Alignment != align_4k && desc.Alignment != align_64k) return kInvalidAllocation; if (desc.Alignment == align_4k && ((desc.Flags & attachment) || !small_tiles_fit(desc, format, need.size))) return kInvalidAllocation; alignment = desc.Alignment ? desc.Alignment : align_64k; } return {align_up(need.size, alignment), alignment}; } // Whether 16 tiles of 4 KiB (leonida::small_tile_shape; 4096 bytes of a row for 1D) cover the top mip of one // array slice, the PC runtime's test for D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT. static bool small_tiles_fit(const D3D12_RESOURCE_DESC& desc, const Format& format, VkDeviceSize vulkan_size) { const leonida::BlockFormat block = leonida::block_format(format.format, VK_IMAGE_ASPECT_COLOR_BIT); const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; leonida::TileShape shape = leonida::small_tile_shape(volume, block.bytes); if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && shape.width) shape = {4096 / block.bytes, 1, 1}; // shortcut: untileable element sizes (3- and 12-byte formats) keep the whole-resource 64 KiB test; measure // them on the PC runtime if a game asks for one. if (!shape.width) return vulkan_size <= D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; const auto tiles = [](UINT64 texels, UINT64 per_block, UINT64 per_tile) { return ((texels + per_block - 1) / per_block + per_tile - 1) / per_tile; }; return tiles(desc.Width, block.block, shape.width) * tiles(desc.Height, block.block, shape.height) * tiles(volume ? desc.DepthOrArraySize : 1, 1, shape.depth) <= 16; } // Strict lower bound on the heap bytes a non-tiled single-sample texture needs: sums uncompressed texel/block // payload across subresources and rounds to `alignment`, capped at `fallback` (Vulkan allocation size). Avoids // rejecting host-valid placed textures when Vulkan driver padding exceeds D3D12's GetResourceAllocationInfo. static UINT64 min_placed_texture_bytes(const D3D12_RESOURCE_DESC& desc, const Format& format, UINT64 alignment, UINT64 fallback) { const VkImageAspectFlags aspect = (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT : format.aspects; const leonida::BlockFormat block = footprint_block(format, aspect); if (!block.bytes || !alignment) return fallback; const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; const UINT depth = volume ? desc.DepthOrArraySize : 1; const UINT slices = volume ? 1 : desc.DepthOrArraySize; const UINT mips = desc.MipLevels ? desc.MipLevels : full_mips(desc.Width, desc.Height, depth); UINT64 per_slice = 0; for (UINT m = 0; m < mips; ++m) { const UINT64 w = std::max(1, desc.Width >> m); const UINT64 h = one_d ? 1 : std::max(1, desc.Height >> m); const UINT64 d = volume ? std::max(1, depth >> m) : 1; const UINT64 bw = (w + block.block - 1) / block.block; const UINT64 bh = (h + block.block - 1) / block.block; if (bw > UINT64_MAX / bh) return fallback; const UINT64 blocks = bw * bh; if (blocks > UINT64_MAX / d) return fallback; const UINT64 count = blocks * d; if (count > UINT64_MAX / block.bytes) return fallback; const UINT64 mip_bytes = count * block.bytes; if (per_slice > UINT64_MAX - mip_bytes) return fallback; per_slice += mip_bytes; } if (slices && per_slice > UINT64_MAX / slices) return fallback; const UINT64 total = per_slice * slices; if (total > UINT64_MAX - (alignment - 1)) return fallback; return std::min(fallback, align_up(total, alignment)); } enum class ImageViewUse { sampled, storage, depth_stencil_uav }; // Writes the view's T# into the slot and makes sure set 0 and the hash table know it. A view that cannot be // shown leaves the slot a null descriptor. void write_image_descriptor(const Resource& resource, const TextureView& view, D3D12_CPU_DESCRIPTOR_HANDLE destination, ImageViewUse use) { const bool storage = use != ImageViewUse::sampled; const bool storage_plane = use == ImageViewUse::depth_stencil_uav; namespace g = leonida::gfx10; g::Image image{}; VkFormat view_format{}; DeviceState::VolumeSlices slices{}; if (!image_descriptor(resource, view, storage, image, view_format, slices)) { return; } const bool sampled = view.type != g::ImageType::image_1d_array && !(resource.desc().Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE); const bool new_uav = storage && (view.type == g::ImageType::image_3d || view.type == g::ImageType::image_1d || view.type == g::ImageType::image_1d_array); const bool packed_storage = storage && resource.desc().Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && resource.uint_backed(); const VkFormat storage_format = storage && resource.uint_backed() ? resource.format() : view_format; if (storage) { if (!state_.storage_usable(storage_format)) { log_once("texture view format does not support storage images:", storage_format); return; } if (new_uav && state_.info.robust_image_access) { if (sampled && !state_.sampled_usable(view_format)) { log_once("texture view format does not support sampled access:", view_format); return; } // All three dimensions use Unknown-format storage writes and can use Unknown-format reads // (image_load glc, or any image_load on a 1D array). Check the actual storage view's format. // Packed RGB9E5 only exposes formatted raw R32_UINT storage, so it does not need these bits. if (!packed_storage) { constexpr auto required = VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT | VK_FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT; if ((state_.optimal_features(storage_format) & required) != required) { log_once("texture view format lacks the required formatless storage image access:", storage_format); return; } } } } if (slices.count && !(state_.info.sliced_3d_uav && state_.info.robust_image_access)) { log_once("partial Texture3D UAV requires imageSlicedViewOf3D and robustImageAccess; mip", view.first_mip); return; } g::ImageWords words = g::encode(image); if (storage && view.type == g::ImageType::image_3d) { words[4] |= g::volume_uav_flag; const UINT mip_depth = std::max(1u, image.depth >> image.first_mip); words[7] = g::volume_uav_word(slices.first, slices.count ? slices.count : mip_depth); } if (new_uav && packed_storage) { words[4] |= g::volume_uav_flag; if (view.type != g::ImageType::image_3d) words[7] = g::volume_uav_word(0, 1); words[7] |= g::packed_uav_flag; log_once("packed RGB9E5 UAV: translated storage operations are not implemented; type", int(view.type)); } const VkFormat channels_format = resource.rgba4_render_backing() ? VK_FORMAT_A4R4G4B4_UNORM_PACK16 : (resource.rgb96() ? rgb96_named_format(view_format) : view_format); if (new_uav && !state_.info.robust_image_access) { log_once("shader access to 1D and 3D UAVs requires robustImageAccess; type", int(view.type)); } else { const bool known_heap = state_.known_view_heap(destination.ptr); // A deferred view has no index yet: its slot gets the index word when the view is made // (materialize_table, write_tsharp_index_words). if (!storage && resource.deferrable_sample() && state_.info.prepare_on_bind && known_heap && !g::multisampled(image.type)) { state_.remember_sample(words,{const_cast(&resource),image,view_format,channels_format}); std::memcpy(reinterpret_cast(destination.ptr),words.data(),sizeof(words)); state_.arena_mark_dirty_ptr(reinterpret_cast(destination.ptr), sizeof(words)); return; } const auto bound = const_cast(resource).bound_image(); if (!bound) { log_once("unable to make a placed shader image resident; format", int(resource.desc().Format)); return; } const bool maybe_evictable = !storage && !known_heap && !g::multisampled(image.type) && state_.console_heap_count.load(std::memory_order_acquire) > 0 && !(resource.desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); const bool registered = state_.bind_image(words, image, bound, view_format, channels_format, storage_format, resource.aspects(), sampled, storage, slices, maybe_evictable ? static_cast(&resource) : nullptr, known_heap); if (registered && (resource.sparse_image() || storage_plane)) state_.context->note_shader_image(resource.id()); if (!registered && (g::multisampled(image.type) || storage_plane)) return; // In the layer's own heaps the bytes written here are what shaders load: dword 6 carries the index // (gfx10_descriptors.h, tsharp_index_word; 0 while the T# has none). A console heap (the title's memory) // is left as the title's own write would be: its copy gets the word when the slot is fixed. if (state_.tsharp_index_words && known_heap) words[g::kTsharpIndexDword] = state_.tsharp_index_word(words); } // The CPU UAV used by ClearUnorderedAccessView is independent of set 0. std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); state_.arena_mark_dirty_ptr(reinterpret_cast(destination.ptr), sizeof(words)); resource.note_shader_view(leonida::effective_min_mip(image.first_mip, g::image_min_lod(words))); } // Validation shared by CreateCommittedResource and CreateCommittedResource3; internal callers pass null `method` // to skip trace recording. HRESULT create_committed_validated(const char* method, const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out, std::optional storage_heap_flags = std::nullopt, TitleImageOrigin origin = TitleImageOrigin::ordinary) { const auto finish = [&](HRESULT hr) { return method ? d3d12_trace::result(method, hr) : hr; }; if (out) *out = nullptr; if (!heap || !desc) return finish(E_INVALIDARG); if (xbox_depth_storage_desc(*desc) && outer_ && rt::d3d12_xs::is_device_proxy(outer_) && heap->Type == D3D12_HEAP_TYPE_DEFAULT && (!castable_count || !castable)) { const auto depth_desc = depth_storage_part(*desc, false), colour_desc = depth_storage_part(*desc, true); const bool initial_uav = state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS; ID3D12Resource *depth = nullptr, *colour = nullptr; HRESULT hr = create_committed_validated(nullptr, heap, heap_flags, &depth_desc, initial_uav ? D3D12_RESOURCE_STATE_COMMON : state, clear, 0, nullptr, IID_PPV_ARGS(&depth)); if (FAILED(hr)) return finish(hr); hr = create_committed_validated(nullptr, heap, heap_flags, &colour_desc, initial_uav ? state : D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, IID_PPV_ARGS(&colour)); if (SUCCEEDED(hr)) { Resource::from(depth)->adopt_depth_storage(Resource::from(colour)); hr = out ? depth->QueryInterface(riid, out) : S_FALSE; } depth->Release(); return finish(hr); } if (const char* why = committed_resource_refusal(*heap, heap_flags, *desc, state, clear, acceleration_structures(), state_.uma)) { log_once((std::string(method ? method : "CreateCommittedResource") + " refused (" + why + "), dimension") .c_str(), int(desc->Dimension)); return finish(E_INVALIDARG); } // The sample quality is checked above as the host does it here: CreateCommittedResource accepts a quality on a // 1x texture while GetResourceAllocationInfo requires 0; the other texture checks stay shared with allocation. D3D12_RESOURCE_DESC checked = *desc; if (checked.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) checked.SampleDesc.Quality = 0; if (desc->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && allocation(checked).SizeInBytes == UINT64_MAX) { log_once((std::string(method ? method : "CreateCommittedResource") + " refused (texture size, mips, samples or alignment), dimension") .c_str(), int(desc->Dimension)); return finish(E_INVALIDARG); } return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out, storage_heap_flags, origin)); } // Shared by CreateCommittedResource, CreateCommittedResource3 and CreateReservedResource*. A castable-format list // is only meaningful on textures; the layer reports RelaxedFormatCastingSupported, so each format is mapped and // handed to Vulkan as a VkImageFormatListCreateInfo. A nonzero count with a null list is no list, as on the PC // runtime. HRESULT create_committed(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES initial_state, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out, std::optional storage_heap_flags = std::nullopt, TitleImageOrigin origin = TitleImageOrigin::ordinary) { if (out) *out = nullptr; if (!heap || !desc) return E_INVALIDARG; const bool from_xbox_d16s8 = desc->Format == xbox_d16s8; D3D12_RESOURCE_DESC canonical = *desc; canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 desc = &canonical; if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { log_once("castable formats on a buffer are invalid; count", int(castable_count)); return E_INVALIDARG; } auto* resource = new Resource(state_, *desc, *heap, heap_flags); if (from_xbox_d16s8) resource->mark_console_d16s8(); resource->attach_device(identity()); HRESULT hr = E_NOTIMPL; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { hr = desc->SampleDesc.Count == 1 && desc->SampleDesc.Quality == 0 ? resource->create_buffer(initial_state) : E_INVALIDARG; } else if (desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) { log_once("committed resource dimension not supported:", desc->Dimension); } else if (desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc->Height != 1) { log_once("1D texture height must be 1:", int(desc->Height)); hr = E_INVALIDARG; } else if (desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && (desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) { log_once("volume depth-stencil resources not supported, flags:", int(desc->Flags)); } else if (heap->Type == D3D12_HEAP_TYPE_UPLOAD || heap->Type == D3D12_HEAP_TYPE_READBACK) { hr = E_INVALIDARG; // D3D12 places textures on default heaps unless they are row-major } else if (const UINT samples = desc->SampleDesc.Count; !samples || samples > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT || (samples > 1 && desc->SampleDesc.Quality && desc->SampleDesc.Quality != DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN && desc->SampleDesc.Quality != DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN) || (samples > 1 && ((samples & (samples - 1)) || desc->MipLevels != 1 || desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || !(desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL))))) { hr = E_INVALIDARG; // D3D12: nonzero power-of-two sample count up to 32; MSAA needs a single-mip 2D attachment } else { hr = S_OK; const Format format = state_.texture_format(*desc); if (format.format == VK_FORMAT_UNDEFINED) { log_once("texture format not supported yet:", desc->Format); hr = E_INVALIDARG; } else { std::vector cast_formats; hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats, storage_heap_flags.has_value(), from_xbox_d16s8); if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats, origin); if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); if (SUCCEEDED(hr) && storage_heap_flags) hr = resource->enable_depth_stencil_uav(*storage_heap_flags); } } if (FAILED(hr)) { resource->Release(); return hr; } if (!out) { // a capability check: D3D12 allows a null output resource->Release(); return S_FALSE; } return hand_out(resource, riid, out); } // GetAdapterLuid's answer, and how queues read the clocks: calibrated timestamps when the caller enabled the // extension and the GPU calibrates its DEVICE domain against QueryPerformanceCounter, else the queue family's // timestamp queries. void query_luid_and_clock(PFN_vkGetDeviceProcAddr get_device) { const VulkanDeviceInfo& info = state_.info; const auto properties2 = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2")); if (properties2) { VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}; VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id}; properties2(info.physical, &properties); static_assert(sizeof(LUID) == VK_LUID_SIZE); if (id.deviceLUIDValid) std::memcpy(&state_.luid, id.deviceLUID, sizeof(LUID)); state_.uma = properties.properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; } if (!state_.luid.LowPart && !state_.luid.HighPart) log_once("the Vulkan driver reports no device LUID;", 0); state_.clock.get_device_proc = get_device; if (!info.calibrated_timestamps) return; // The KHR names first; the EXT ones are aliases with the same signatures. auto domains_of = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceCalibrateableTimeDomainsKHR")); auto calibrated = reinterpret_cast( get_device(info.device, "vkGetCalibratedTimestampsKHR")); if (!domains_of || !calibrated) { domains_of = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceCalibrateableTimeDomainsEXT")); calibrated = reinterpret_cast( get_device(info.device, "vkGetCalibratedTimestampsEXT")); } if (!domains_of || !calibrated) return; std::uint32_t count = 0; domains_of(info.physical, &count, nullptr); std::vector domains(count); domains_of(info.physical, &count, domains.data()); const auto has = [&](VkTimeDomainKHR domain) { return std::find(domains.begin(), domains.end(), domain) != domains.end(); }; if (has(VK_TIME_DOMAIN_DEVICE_KHR) && has(VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_KHR)) state_.clock.calibrated = calibrated; else log_once("calibrated timestamps lack the DEVICE or QueryPerformanceCounter domain; domains:", int(count)); } // D3D12's layout rules for reserved resources. Use sparse backing for buffers and compatible color textures. // The arguments are answered as the host runtime answers them (d3d12_vulkan_device_test's // compare_placed_reserved, RTX 3060 / 610.88): the description, initial state and clear value rules of a // committed resource on a default heap, the reserved layouts below, and only then E_UNEXPECTED for a null // output, with nothing made. HRESULT create_reserved(const char* method, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { if (out) *out = nullptr; if (!desc) return d3d12_trace::result(method, E_INVALIDARG); D3D12_RESOURCE_DESC canonical = *desc; canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 desc = &canonical; if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { log_once("castable formats on a reserved buffer are invalid; count", int(castable_count)); return d3d12_trace::result(method, E_INVALIDARG); } D3D12_RESOURCE_DESC backing = *desc; const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return d3d12_trace::result(method, E_INVALIDARG); } else { if (static_cast(desc->Layout) == kXboxTiledLayout) { log_once("reserved resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension", desc->Dimension); } else if (desc->Layout != D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) { return d3d12_trace::result(method, E_INVALIDARG); // 64KB_STANDARD_SWIZZLE too: CheckFeatureSupport reports it unsupported } backing.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; leonida::ResourceTiling tiling; backing.MipLevels = std::max(desc->MipLevels, 1); // any count: only the format is checked here if (!resource_tiling(backing, tiling)) { log_once("reserved texture format has no tile shape:", desc->Format); return d3d12_trace::result(method, E_INVALIDARG); } backing.MipLevels = desc->MipLevels; } if (const char* why = committed_resource_refusal(heap, D3D12_HEAP_FLAG_NONE, backing, state, clear, acceleration_structures(), state_.uma)) { log_once((std::string(method) + " refused (" + why + "), dimension").c_str(), int(desc->Dimension)); return d3d12_trace::result(method, E_INVALIDARG); } if (desc->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { // Extents, mips and samples, as the committed backing below checks them (GetResourceAllocationInfo). D3D12_RESOURCE_DESC checked = backing; checked.SampleDesc.Quality = 0; if (allocation(checked).SizeInBytes == UINT64_MAX) return d3d12_trace::result(method, E_INVALIDARG); } if (!out) return d3d12_trace::result(method, E_UNEXPECTED); ID3D12Resource* resource = nullptr; HRESULT hr = S_OK; if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && state_.sparse_buffer_memory_types) { auto* sparse = new Resource(state_, backing, heap, D3D12_HEAP_FLAG_NONE); sparse->attach_device(identity()); hr = sparse->create_sparse_buffer(); if (FAILED(hr)) { sparse->Release(); return d3d12_trace::result(method, hr); } resource = sparse; } else if (state_.sparse_image_tiles && backing.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && backing.Format == DXGI_FORMAT_R8G8B8A8_UNORM && backing.Width && backing.Width <= UINT32_MAX && backing.Height && backing.DepthOrArraySize == 1 && backing.MipLevels == 1 && backing.SampleDesc.Count == 1 && !backing.SampleDesc.Quality && backing.Flags == D3D12_RESOURCE_FLAG_NONE && !clear && !castable_count) { auto* sparse = new Resource(state_, backing, heap, D3D12_HEAP_FLAG_NONE); sparse->attach_device(identity()); hr = sparse->create_sparse_image(); if (SUCCEEDED(hr)) resource = sparse; else { sparse->Release(); if (hr != E_NOTIMPL) return d3d12_trace::result(method, hr); } } if (!resource) { hr = create_committed_validated(nullptr, &heap, D3D12_HEAP_FLAG_NONE, &backing, D3D12_RESOURCE_STATE_COMMON, clear, castable_count, castable, IID_PPV_ARGS(&resource)); } if (FAILED(hr)) return d3d12_trace::result(method, hr); Resource::from(resource)->make_reserved(desc->Layout); hr = resource->QueryInterface(riid, out); resource->Release(); return d3d12_trace::result(method, hr); } // The tiling of a reserved resource's description; false for formats without a tile shape (three- and // twelve-byte texels, two-plane depth-stencil). static bool resource_tiling(const D3D12_RESOURCE_DESC& desc, leonida::ResourceTiling& out) { leonida::TilingDesc tiling{}; tiling.width = desc.Width; tiling.height = desc.Height; tiling.depth_or_layers = desc.DepthOrArraySize; tiling.mips = desc.MipLevels; if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { tiling.kind = leonida::TiledKind::buffer; return leonida::resource_tiling(tiling, out); } if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) return false; tiling.kind = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? leonida::TiledKind::texture3d : leonida::TiledKind::texture2d; const Format format = vulkan_format(desc.Format, false); if (!format.format || (format.aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) return false; if (format.rgb96) return false; // the tile shape of a 12-byte texel is not measured const leonida::BlockFormat block = leonida::block_format(format.format, format.aspects); tiling.element_bytes = block.bytes; tiling.block = block.block; tiling.samples = desc.SampleDesc.Count; return leonida::resource_tiling(tiling, out); } // Host image copies are used only on images in GENERAL (D3D12's COMMON), so GENERAL must be a layout the // device copies from and to on the host. Vulkan requires it to be; check rather than assume. void load_host_image_copy(PFN_vkGetDeviceProcAddr get_device) { const VkDevice dev = state_.info.device; const auto properties2 = reinterpret_cast( state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); const auto to_image = reinterpret_cast(get_device(dev, "vkCopyMemoryToImageEXT")); const auto to_memory = reinterpret_cast(get_device(dev, "vkCopyImageToMemoryEXT")); const auto transition = reinterpret_cast(get_device(dev, "vkTransitionImageLayoutEXT")); if (!properties2 || !state_.format_properties2 || !to_image || !to_memory || !transition) { std::fprintf(stderr, "[rt] d3d12: VK_EXT_host_image_copy entry points missing; using staging copies\n"); return; } VkPhysicalDeviceHostImageCopyPropertiesEXT host{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_PROPERTIES_EXT}; VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host}; properties2(state_.info.physical, &properties); std::vector src(host.copySrcLayoutCount), dst(host.copyDstLayoutCount); host.pCopySrcLayouts = src.data(); host.pCopyDstLayouts = dst.data(); properties2(state_.info.physical, &properties); const auto general = [](const std::vector& layouts) { return std::find(layouts.begin(), layouts.end(), VK_IMAGE_LAYOUT_GENERAL) != layouts.end(); }; if (!general(src) || !general(dst)) { std::fprintf(stderr, "[rt] d3d12: host image copies do not accept GENERAL; using staging copies\n"); return; } state_.copy_memory_to_image = to_image; state_.copy_image_to_memory = to_memory; state_.transition_image_layout = transition; } // The layer reports no protected-session support, so a session is refused, as D3D12 refuses one on a device // without D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT. static HRESULT refuse_protected_session(const char* method) { log_once((std::string("protected resource session refused (not supported) by ") + method + ':').c_str(), 1); return E_INVALIDARG; } // D3D12_RESOURCE_DESC1 is D3D12_RESOURCE_DESC plus SamplerFeedbackMipRegion. static D3D12_RESOURCE_DESC resource_desc(const D3D12_RESOURCE_DESC1& desc) { return {desc.Dimension, desc.Alignment, desc.Width, desc.Height, desc.DepthOrArraySize, desc.MipLevels, desc.Format, desc.SampleDesc, desc.Layout, desc.Flags}; } // A sampler-feedback mip region on a texture, which needs a DXGI_FORMAT_SAMPLER_FEEDBACK_* resource the layer // does not have. The PC runtime ignores the region on a buffer. static bool texture_mip_region(const D3D12_RESOURCE_DESC1& desc) { const D3D12_MIP_REGION& region = desc.SamplerFeedbackMipRegion; return desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && (region.Width || region.Height || region.Depth); } // Holds the pipeline compiler's worker for the device's life (PipelineCompiler::retain). Released early by // ~Device, after its cancel; a constructor that throws releases it through this member's destructor. class CompilerUse { public: CompilerUse() { PipelineCompiler::instance().retain(); } ~CompilerUse() { release(); } CompilerUse(const CompilerUse&) = delete; CompilerUse& operator=(const CompilerUse&) = delete; void release() { if (!held_) return; held_ = false; PipelineCompiler::instance().release(); } private: bool held_ = true; }; CompilerUse compiler_use_; std::mutex queue_mutex_; // Live D3D12 queues per VkQueue of info.command_queues, compute_queues and copy_queues (pick_queue_slot). std::vector queue_users_; std::vector compute_users_; std::vector copy_users_; std::mutex verified_program_mutex_; std::unordered_set verified_programs_; std::mutex native_pipeline_mutex_; std::unordered_map> native_pipelines_; DeviceState state_; struct RawImage { std::unique_ptr resource; std::vector fingerprints; }; std::mutex raw_image_mutex_; using RawKey = std::tuple; std::map raw_images_; std::atomic removed_{false}; OwnedRuntime owned_; IUnknown* outer_ = nullptr; // the Xbox-ABI proxy, which owns a reference to this device }; } // namespace bool stop_pipeline_compiles(unsigned wait_ms) { const bool idle = PipelineCompiler::instance().stop_for_exit(std::chrono::milliseconds(wait_ms)); if (!idle) std::fprintf(stderr, "[rt] d3d12: a background pipeline build was still running after %u ms at exit\n", wait_ms); return idle; } // How long an exit save waits for the write itself (save_session_pipeline_cache). Measured fill and publish: a 77 MiB // cache about 36 ms; 1.87 GB 1.4 s and 2.9 GB 1.3-1.6 s (NVIDIA, Windows 11, NVMe), so about 2.2 s at the 4 GiB // default limit. The wait ends with the write; the bound only covers a driver or disk that blocks. constexpr unsigned kExitCacheWriteMs = 6000; bool save_pipeline_caches_at_exit(unsigned wait_ms) { if (exit_cache_saved.exchange(true)) return false; // once: a crash during the normal exit's save does not redo it std::unique_lock lock(exit_cache_mutex, std::defer_lock); if (!lock.try_lock_for(std::chrono::milliseconds(wait_ms))) { std::fprintf(stderr, "[rt] d3d12: device list busy for %u ms at exit; pipeline_cache.session.bin not written\n", wait_ms); return false; } bool wrote = false; // After the cache write, so that the order log's final append (a join and a write) never delays the cache. It // appends the last lines and prints the counts; no cache file is touched. const auto close_order_logs = [] { for (DeviceState* d : exit_cache_devices) d->close_order_log(); }; const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(wait_ms); for (DeviceState* d : exit_cache_devices) { if (!d->context || !d->pipeline_cache_handle) continue; // A build still running (a large one takes minutes; at a crash the faulting thread may be inside one) is // given until the deadline, then the cache is written without it. Unlike at teardown, the previous file is // not kept instead: the process is ending, so waiting longer is not possible and keeping the old file throws // away everything this run compiled (measured: a 1,308 s boot that ended in a title fault with 2 builds // running). The cache is not created EXTERNALLY_SYNCHRONIZED, so reading it during a build is valid; the // snapshot holds the pipelines finished so far. while (d->active_compiles.load() && std::chrono::steady_clock::now() < deadline) std::this_thread::sleep_for(std::chrono::milliseconds(5)); if (const unsigned building = d->active_compiles.load()) std::fprintf(stderr, "[rt] d3d12: %u pipeline build(s) still running at exit; writing the pipelines " "finished so far\n", building); // On a thread of its own: a driver that holds the cache until a build ends would otherwise hold the ending // process too. Past the deadline the process goes on ending; the file is published by a rename // (CacheStagingFile), so a write cut off there leaves the previous file whole. struct Write { std::mutex mutex; std::condition_variable done_cv; bool done = false; }; auto write = std::make_shared(); std::thread([write, d] { save_session_pipeline_cache(d->context->vk, d->info.device, d->pipeline_cache_handle, false, "exit"); std::lock_guard done_lock(write->mutex); write->done = true; write->done_cv.notify_all(); }).detach(); std::unique_lock write_lock(write->mutex); if (!write->done_cv.wait_for(write_lock, std::chrono::milliseconds(kExitCacheWriteMs), [&] { return write->done; })) { std::fprintf(stderr, "[rt] d3d12: pipeline cache still being written after %u ms at exit; the process " "ends without waiting for it\n", kExitCacheWriteMs); close_order_logs(); return wrote; // the device list stays as it is: the write still uses this device } wrote = true; } close_order_logs(); return wrote; } HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** out) { if (!out) return E_POINTER; *out = nullptr; auto* device = new Device(info); if (!device->ok()) { device->Release(); return E_FAIL; } return hand_out(device, riid, out); } std::shared_ptr tile_heap(ID3D12Heap* heap, const leonida::VulkanContext& context, bool image, std::uint32_t memory_types) { auto* object = Heap::from(heap); return object ? object->tiles(context, image, memory_types) : nullptr; } XboxDepthStorage xbox_depth_storage(ID3D12Resource* resource) { if (!resource || !depth_storage_count.load(std::memory_order_acquire)) return {}; std::lock_guard lock(depth_storage_mutex); const auto it = depth_storage_images.find(resource); return it == depth_storage_images.end() ? XboxDepthStorage{} : it->second; } bool is_sparse_image(ID3D12Resource* resource) { const auto* object = Resource::from(resource); return object && object->sparse_image(); } static HRESULT enable_depth_stencil_uav(ID3D12Resource* resource, D3D12_HEAP_FLAGS storage_heap_flags) { Resource* r = Resource::from(resource); return r ? r->enable_depth_stencil_uav(storage_heap_flags) : E_INVALIDARG; } leonida::ResourceId uav_image_resource(ID3D12Resource* resource, std::uint64_t address) { const Resource* r = Resource::from(resource); if (!r || !r->depth_stencil_uav(0)) return resource_id(resource); for (UINT plane = 0; plane < 2; ++plane) { const Resource* storage = r->depth_stencil_uav(plane); if (storage && storage->image_address() == address) return storage->id(); } return 0; } void set_device_outer(ID3D12Device* device, IUnknown* outer) { Device* d = Device::from(device); if (!d) return; // A caller passes what create_device_proxy returned, which is the proxy's DXGI pointer when the title asked // for IDXGIDevice1: the device's outer identity is the proxy itself either way. if (void* proxy = rt::d3d12_xs::device_proxy_primary(outer)) outer = static_cast(proxy); d->set_outer(outer); // Another job for an outer that is the Xbox-ABI proxy: its device slot 70 names a buffer by console VA only, and // this finds the layer's resource for it. if (rt::d3d12_xs::is_device_proxy(outer)) rt::d3d12_xs::set_device_resource_provider( outer, [](ID3D12Device* real, std::uint64_t va, std::uint64_t bytes, std::uint64_t* start, std::uint64_t* size) -> ID3D12Resource* { Device* device = Device::from(real); return device ? device->add_ref_buffer_at(va, bytes, *start, *size) : nullptr; }); // And for the same outer: its IDXGIDevice1::GetAdapter (d3d12_xs_device.h) hands // out this layer's adapter, the one create_dxgi_factory enumerates, so a title on the Vulkan device never gets // a host DXGI object from it. if (!rt::d3d12_xs::is_device_proxy(outer)) return; rt::d3d12_xs::set_constant_view_provider(outer, [](ID3D12Device* real, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE target) { auto* device=Device::from(real); if (!device) return false; device->write_constant_buffer_view(desc,target,true); return true; }); rt::d3d12_xs::set_raw_texture_view_provider(outer, [](ID3D12Device* real, const D3D12_RESOURCE_DESC& desc, const D3D12_SHADER_RESOURCE_VIEW_DESC& view, std::uint64_t va, D3D12_CPU_DESCRIPTOR_HANDLE out) { auto* device = Device::from(real); try { return device && device->raw_texture_view(desc, view, va, out); } catch (const std::bad_alloc&) { return false; } }); rt::d3d12_xs::set_texture_lease_provider(outer, [](IUnknown* object, void* data, std::size_t bytes, UINT layout) { if (auto* resource = Resource::from(object)) resource->use_texture_lease(data, bytes, layout); }); rt::d3d12_xs::set_descriptor_mapping_provider(outer, [](ID3D12DescriptorHeap* heap, SIZE_T start, SIZE_T bytes) { const auto* object = DescriptorHeap::from(heap); return object && object->owns_mapped_span(start, bytes); }); if(d->state().info.prepare_on_bind) { rt::d3d12_xs::set_native_stream_factory(outer,[](ID3D12Device* real,const D3D12_PIPELINE_STATE_STREAM_DESC& desc,REFIID iid,void** out,std::unique_ptr record){ return Device::from(real)->prepare_console_stream(desc,iid,out,std::move(record)); }); } rt::d3d12_xs::set_device_native_graphics_factory(outer, [](ID3D12Device* real, const leonida::native_pso::GraphicsDesc& desc, REFIID iid, void** out) { return Device::from(real)->create_native_graphics(desc, iid, out); }); rt::d3d12_xs::set_depth_stencil_uav_provider(outer, &enable_depth_stencil_uav, [](const D3D12_RESOURCE_DESC& native, std::uint32_t layout, const D3D12_CLEAR_VALUE* clear) { auto logical = native; logical.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; if (barrier_layout_refusal(logical, static_cast(layout))) return false; D3D12_HEAP_PROPERTIES heap{}; heap.Type = D3D12_HEAP_TYPE_DEFAULT; return !committed_resource_refusal(heap, D3D12_HEAP_FLAG_NONE, native, D3D12_RESOURCE_STATE_COMMON, clear, false, false); }); rt::d3d12_xs::set_device_adapter_provider(outer, [](ID3D12Device* real, REFIID riid, void** out) { IDXGIFactory1* factory = nullptr; HRESULT hr = create_dxgi_factory(real, __uuidof(IDXGIFactory1), reinterpret_cast(&factory)); if (FAILED(hr)) return hr; IDXGIAdapter* adapter = nullptr; hr = factory->EnumAdapters(0, &adapter); factory->Release(); if (FAILED(hr)) return hr; hr = adapter->QueryInterface(riid, out); adapter->Release(); return hr; }); } const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature) { const RootSignature* s = RootSignature::from(signature); return s ? &s->layout() : nullptr; } std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline) { auto* p=PipelineState::from(pipeline); return p && p->resolve_type(false) ? p->id() : 0; } std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline) { auto* p=PipelineState::from(pipeline); return p && p->resolve_type(true) ? p->id() : 0; } void request_pipeline_build(std::uintptr_t id, std::uint32_t bound_targets, bool depth_bound, bool sample_masked) { if (!id || !async_replay_compile()) return; // The id is the PSO's own ID3D12PipelineState pointer (PipelineState::id), which the list keeps a reference to. auto* pso = static_cast(reinterpret_cast(id)); pso->request_early(bound_targets, depth_bound, sample_masked); } StubPipelineKind stub_pipeline_kind(ID3D12PipelineState* pipeline, IUnknown* device) { const PipelineState* p = PipelineState::from(pipeline); if (!p || (device && p->attached_device() != device)) return StubPipelineKind::none; return p->stub_kind(); } const std::vector* pipeline_subgroup_requests(ID3D12PipelineState* pipeline) { const PipelineState* p = PipelineState::from(pipeline); return p && (p->compute() || p->graphics()) ? &p->subgroup_requests() : nullptr; } bool pipeline_stage_words(ID3D12PipelineState* pipeline, std::vector>& words, std::string& why) { const PipelineState* p = PipelineState::from(pipeline); if (!p) { why = "not a PipelineState"; return false; } return p->stage_words(words, why); } long live_pipeline_states() { return live_pipeline_state_count.load(); } bool write_placed_buffer_view(ID3D12Device* device, bool unordered, const void* view, std::uint64_t address, std::uint64_t width, D3D12_CPU_DESCRIPTOR_HANDLE destination) { Device* d = Device::from(device); if (!d || !view || !destination.ptr) return false; return d->write_placed_buffer_view(unordered, view, address, width, destination); } bool write_placed_texture_view(ID3D12Device* device, bool unordered, const std::uint32_t* resource_words, const std::uint32_t* view_words, std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE destination) { Device* d = Device::from(device); if (!d || !resource_words || !view_words || !destination.ptr) return false; if (unordered) return d->write_placed_texture_uav(resource_words, view_words, address, destination); return d->write_placed_texture_view(resource_words, view_words, address, destination); } void mark_title_texture_gpu_written(IUnknown* device, leonida::ResourceId resource, std::uint64_t address, bool partial) { if (!device || !resource || !address) return; Device* d = Device::from(device); if (!d) { if (ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device)) d = Device::from(real); } if (d) d->mark_title_texture_gpu_written(resource, address, partial); } D3D12_GPU_VIRTUAL_ADDRESS console_descriptor_table_va(D3D12_GPU_VIRTUAL_ADDRESS va) { return console_heap_ranges().shader_va(va); } bool console_descriptor_heap_range(D3D12_GPU_VIRTUAL_ADDRESS va, std::uint64_t& console_va, std::uint64_t& bytes) { return console_heap_ranges().range_of(va, console_va, bytes); } // The device a command list of this module belongs to: its attached device is the d3d12_xs proxy when the title made // the list through one (Device::identity), which does not answer Device's tag itself. Device* list_device(IUnknown* device) { if (!device) return nullptr; if (Device* d = Device::from(device)) return d; if (ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device)) return Device::from(real); static std::atomic logged{false}; if (!logged.exchange(true)) std::fprintf(stderr, "[rt] d3d12: an acceleration-structure command on a list whose device is not this " "layer's: its addresses are left as the title gave them\n"); return nullptr; } // LEONIDA_RT_AS=off (diagnostic): acceleration-structure builds and copies are not recorded at all, so no BVH is // written; traversal finds whatever the structures' memory holds. For telling a device loss in the builds apart from // one elsewhere. bool acceleration_structures_off() { static const bool off = [] { char value[8] = {}; std::size_t length = 0; const bool set = getenv_s(&length, value, "LEONIDA_RT_AS") == 0 && length > 1 && !std::strcmp(value, "off"); if (set) std::fprintf(stderr, "[rt] d3d12: LEONIDA_RT_AS=off: acceleration-structure builds and copies are dropped\n"); return set; }(); return off; } bool resolve_acceleration_structure_build(IUnknown* device, leonida::BuildAccelerationStructure& build) { if (acceleration_structures_off()) return false; Device* d = list_device(device); return !d || d->resolve_xdxr_build(build); } bool resolve_acceleration_structure_copy(IUnknown* device, leonida::CopyAccelerationStructure& copy) { if (acceleration_structures_off()) return false; Device* d = list_device(device); return !d || d->resolve_xdxr_copy(copy); } bool resolve_acceleration_structure_postbuild(IUnknown* device, leonida::AccelerationStructurePostbuild& info) { Device* d = list_device(device); return !d || d->resolve_xdxr_postbuild(info); } IUnknown* descriptor_heap_info(ID3D12DescriptorHeap* heap, D3D12_DESCRIPTOR_HEAP_DESC& desc, D3D12_GPU_VIRTUAL_ADDRESS& gpu_base) { if (!heap) return nullptr; if (ID3D12DescriptorHeap* real = rt::d3d12_xs::heap_proxy_real_heap(heap)) heap = real; const DescriptorHeap* d = DescriptorHeap::from(heap); if (!d) return nullptr; desc = d->raw_desc(); gpu_base = d->gpu_base(); return d->attached_device(); } VkImage vulkan_image(ID3D12Resource* resource) { const Resource* r = Resource::from(resource); return r ? const_cast(r)->bound_image() : VK_NULL_HANDLE; } VkMemoryPropertyFlags vulkan_memory_flags(ID3D12Resource* resource) { const Resource* r = Resource::from(resource); return r ? r->memory_flags() : 0; } bool title_shadow_buffer(ID3D12Resource* resource) { const Resource* r = Resource::from(resource); return r && r->is_shadow(); } VkBuffer vulkan_buffer(ID3D12Resource* resource) { const Resource* r = Resource::from(resource); return r ? r->buffer() : VK_NULL_HANDLE; } leonida::PipelineWorkers::Stats pipeline_worker_stats(ID3D12Device* device) { if (!device) return {}; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (auto* d = Device::from(real ? real : device)) return d->context().pipeline_worker_stats(); return {}; } const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device) { if (!device) return nullptr; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (auto* d = Device::from(real ? real : device)) return &d->state().info; return nullptr; } leonida::VramBudget vulkan_vram_budget(ID3D12Device* device) { const VulkanDeviceInfo* info = vulkan_device_info(device); return info ? read_vram_budget(*info) : leonida::VramBudget{}; } std::uint64_t title_shadow_refresh_queries(ID3D12Device* device) { auto* d = Device::from(device); if (!d) return 0; auto& state = d->state(); std::lock_guard lock(state.shadow_mutex); std::uint64_t queries = 0; for (const auto& shadow : state.shadows) queries += shadow->refresh_queries(); return queries; } std::uint64_t title_host_imports(ID3D12Device* device) { auto* d = Device::from(device); return d ? d->state().host_imports.load(std::memory_order_relaxed) : 0; } TitleWindows title_windows(ID3D12Device* device) { TitleWindows windows; auto* d = Device::from(device); if (!d) return windows; auto& state = d->state(); std::lock_guard lock(state.title_window_mutex); windows.count = state.title_windows.size(); windows.bytes = state.title_window_bytes; windows.retired = state.title_windows_retired; std::lock_guard retired(state.retired_window_mutex); windows.waiting = state.retired_windows.size(); return windows; } std::uint64_t title_shadow_trackers(ID3D12Device* device) { auto* d = Device::from(device); if (!d) return 0; auto& state = d->state(); std::lock_guard lock(state.shadow_mutex); return state.shadows.size(); } TitleShadowWatch title_shadow_watch(ID3D12Device* device) { TitleShadowWatch watch; auto* d = Device::from(device); if (!d) return watch; auto& state = d->state(); std::lock_guard lock(state.shadow_mutex); for (const auto& shadow : state.shadows) { watch.asks += shadow->refresh_asks(); watch.written += shadow->refresh_written(); watch.faults += shadow->faults(); watch.watched_bytes += shadow->watched_bytes(); watch.hot_bytes += shadow->hot_bytes(); } return watch; } HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, void** out, const D3D12_CLEAR_VALUE* clear) { if (out) *out = nullptr; if (!device || !out) return E_POINTER; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); auto* d = Device::from(real ? real : device); if (!d) return E_NOTIMPL; return d->create_at_host_address(address, desc, layout, riid, out, clear); } bool device_supports_ray_tracing(ID3D12Device* device) { if (!device) return false; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (auto* d = Device::from(real ? real : device)) return d->context().ray_tracing_supported(); return false; } VkAccelerationStructureKHR vulkan_acceleration_structure(ID3D12Device* device, D3D12_GPU_VIRTUAL_ADDRESS va) { if (!device || !va) return VK_NULL_HANDLE; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (auto* d = Device::from(real ? real : device)) return d->context().resolve_acceleration_structure(va); return VK_NULL_HANDLE; } bool color_resolve_format_is_integer(DXGI_FORMAT format) { return DeviceState::numeric_class(vulkan_format(format, false).format) != 0; } bool color_resolve_format_matches(DXGI_FORMAT format, ID3D12Resource* dst, ID3D12Resource* src) { if (!dst || !src) return false; const Format requested = vulkan_format(format, false); if (requested.typeless || requested.rgb96 || requested.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return false; if (DeviceState::numeric_class(requested.format) != 0) return false; // D3D12 resolves no integer format const auto matches = [&](ID3D12Resource* resource) { const D3D12_RESOURCE_DESC desc = resource->GetDesc(); return vulkan_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL).format == requested.format; }; return matches(dst) && matches(src); } bool depth_stencil_resolve_supported(DXGI_FORMAT format, ID3D12Resource* dst, UINT dst_subresource, UINT x, UINT y, ID3D12Resource* src, UINT src_subresource, const D3D12_RECT* rect, D3D12_RESOLVE_MODE mode) { const Resource* d = Resource::from(dst); const Resource* s = Resource::from(src); if (!d || !s) return false; // The format names the depth format, or one plane by its shader-resource format. Measured on the PC runtime // (RTX 5070 and WARP): Close fails for AVERAGE with the depth format or a stencil plane; the depth plane's // own format (R32_FLOAT, R24_UNORM_X8_TYPELESS) takes AVERAGE as well as MIN and MAX. DXGI_FORMAT family = format; int named_plane = -1; // -1: any plane of the depth format switch (format) { case DXGI_FORMAT_R32_FLOAT: family = DXGI_FORMAT_D32_FLOAT, named_plane = 0; break; case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: family = DXGI_FORMAT_D24_UNORM_S8_UINT, named_plane = 0; break; case DXGI_FORMAT_X24_TYPELESS_G8_UINT: family = DXGI_FORMAT_D24_UNORM_S8_UINT, named_plane = 1; break; case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: family = DXGI_FORMAT_D32_FLOAT_S8X24_UINT, named_plane = 0; break; case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: family = DXGI_FORMAT_D32_FLOAT_S8X24_UINT, named_plane = 1; break; default: break; } const Format requested = vulkan_format(family, true); if (requested.typeless || !(requested.aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) return false; // The plane a subresource index names (0 depth, 1 stencil), or -1. const auto plane = [&](const Resource* r, UINT subresource) { const D3D12_RESOURCE_DESC& desc = r->desc(); if (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) || vulkan_format(desc.Format, true).format != requested.format) return -1; const UINT planes = (requested.aspects & VK_IMAGE_ASPECT_STENCIL_BIT) ? 2 : 1; const UINT per_plane = UINT(desc.MipLevels) * desc.DepthOrArraySize; return per_plane && subresource / per_plane < planes ? int(subresource / per_plane) : -1; }; const int resolved = plane(d, dst_subresource); if (resolved < 0 || resolved != plane(s, src_subresource) || (named_plane >= 0 && resolved != named_plane) || s->desc().SampleDesc.Count <= 1 || d->desc().SampleDesc.Count != 1) return false; VkResolveModeFlagBits wanted = VK_RESOLVE_MODE_MIN_BIT; if (mode == D3D12_RESOLVE_MODE_MAX) wanted = VK_RESOLVE_MODE_MAX_BIT; else if (mode == D3D12_RESOLVE_MODE_AVERAGE && named_plane == 0) wanted = VK_RESOLVE_MODE_AVERAGE_BIT; else if (mode != D3D12_RESOLVE_MODE_MIN) return false; // The rendering scope that replays it resolves pixels in place (vulkan_replay.h). if (rect ? (LONG(x) != rect->left || LONG(y) != rect->top) : (x || y)) return false; const DeviceState& state = d->device_state(); return (resolved ? state.stencil_resolve_modes : state.depth_resolve_modes) & wanted; } std::uint32_t device_max_push_constants_size(ID3D12Device* device) { if (!device) return 0; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; if (auto* d = Device::from(real)) return d->info().max_push_constants_size; return 0; } bool device_push_constants_need_fallback(ID3D12Device* device) { if (!device) return false; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; if (auto* d = Device::from(real)) return d->info().push_constants_need_fallback; return false; } bool device_upload_in_vram(ID3D12Device* device) { if (!device) return false; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; if (auto* d = Device::from(real)) return d->upload_in_vram(); return false; } bool device_sparse_buffer_tiles(ID3D12Device* device) { const Device* d = Device::from(device); return d && d->state().sparse_buffer_memory_types != 0; } std::uint64_t device_arena_size(ID3D12Device* device) { if (!device) return 0; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; const Device* d = Device::from(real); return d ? d->state().arena.size : 0; } PageMirrorState page_mirror_state(ID3D12Device* device) { if (!device) return {}; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; const Device* d = Device::from(real); if (!d) return {}; auto& state = const_cast(d->state()); std::lock_guard lock(state.page_mirror.mutex); PageMirrorState out; if (!state.page_mirror.mirror) return out; const auto c = state.page_mirror.mirror->counters(); out.on = true; out.heap_base = state.arena.address; out.pages = c.pages; out.homes = c.homes; out.chunks = c.chunks; out.uploads = c.uploads; out.binds = c.binds; return out; } namespace { // `bytes` of `buffer` at `offset` into `out`, copied by the GPU after the page mirror's bind `wait`. For tests. bool gpu_buffer_read(DeviceState& state, VkBuffer chunk, VkDeviceSize offset, std::uint64_t wait, void* out, std::size_t bytes) { auto& vk = state.context->vk; const VkDevice dev = state.info.device; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = bytes; info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; VkBuffer readback = VK_NULL_HANDLE; if (vk.vkCreateBuffer(dev, &info, nullptr, &readback) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; vk.vkGetBufferMemoryRequirements(dev, readback, &requirements); VkDeviceMemory memory = state.allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 0); VkCommandPool pool = VK_NULL_HANDLE; VkCommandBuffer commands = VK_NULL_HANDLE; bool ok = memory && vk.vkBindBufferMemory(dev, readback, memory, 0) == VK_SUCCESS; VkCommandPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; pool_info.queueFamilyIndex = state.info.queue_family; ok = ok && vk.vkCreateCommandPool(dev, &pool_info, nullptr, &pool) == VK_SUCCESS; VkCommandBufferAllocateInfo allocate{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; allocate.commandPool = pool; allocate.commandBufferCount = 1; ok = ok && vk.vkAllocateCommandBuffers(dev, &allocate, &commands) == VK_SUCCESS; if (ok) { VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; vk.vkBeginCommandBuffer(commands, &begin); const VkBufferCopy region{offset, 0, bytes}; vk.vkCmdCopyBuffer(commands, chunk, readback, 1, ®ion); vk.vkEndCommandBuffer(commands); VkTimelineSemaphoreSubmitInfo values{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; const VkPipelineStageFlags stage = VK_PIPELINE_STAGE_TRANSFER_BIT; VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO}; if (state.page_mirror.timeline != VK_NULL_HANDLE) { values.waitSemaphoreValueCount = 1; values.pWaitSemaphoreValues = &wait; submit.pNext = &values; submit.waitSemaphoreCount = 1; submit.pWaitSemaphores = &state.page_mirror.timeline; submit.pWaitDstStageMask = &stage; } submit.commandBufferCount = 1; submit.pCommandBuffers = &commands; std::lock_guard lock(state.context->submit_mutex()); ok = vk.vkQueueSubmit(state.info.queue, 1, &submit, VK_NULL_HANDLE) == VK_SUCCESS && vk.vkQueueWaitIdle(state.info.queue) == VK_SUCCESS; } void* mapped = nullptr; if (ok && vk.vkMapMemory(dev, memory, 0, VK_WHOLE_SIZE, 0, &mapped) == VK_SUCCESS) { std::memcpy(out, mapped, bytes); vk.vkUnmapMemory(dev, memory); } else { ok = false; } if (pool) vk.vkDestroyCommandPool(dev, pool, nullptr); vk.vkDestroyBuffer(dev, readback, nullptr); if (memory) vk.vkFreeMemory(dev, memory, nullptr); return ok; } DeviceState* device_state_for_test(ID3D12Device* device) { if (!device) return nullptr; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; const Device* d = Device::from(real); if (!d) return nullptr; auto& state = const_cast(d->state()); return state.context ? &state : nullptr; } DeviceState* mirror_state(ID3D12Device* device) { DeviceState* state = device_state_for_test(device); return state && state->page_mirror.mirror ? state : nullptr; } } // namespace bool page_mirror_gpu_read(ID3D12Device* device, std::uint64_t title_va, void* out, std::size_t bytes) { DeviceState* state = mirror_state(device); if (!state || !out || !bytes) return false; state->refresh_page_mirror(); state->flush_page_mirror(); VkBuffer chunk = VK_NULL_HANDLE; VkDeviceSize offset = 0; std::uint64_t wait = 0; { std::lock_guard lock(state->page_mirror.mutex); if (!state->page_mirror.mirror->chunk_at(title_va, chunk, offset)) return false; wait = state->page_mirror.value; } return gpu_buffer_read(*state, chunk, offset, wait, out, bytes); } bool arena_gpu_read(ID3D12Device* device, std::uint64_t va, void* out, std::size_t bytes) { DeviceState* state = device_state_for_test(device); if (!state || !state->arena.buffer || !out || !bytes || va > state->arena.size || bytes > state->arena.size - va) return false; // As a submission does: the mirror (heaps read in place filtered as their pages fill), the heaps (what the filter // left), then the binds. if (state->page_mirror.mirror) state->refresh_page_mirror(); state->refresh_console_heaps(); if (state->page_mirror.mirror) state->flush_page_mirror(); std::uint64_t wait = 0; if (state->page_mirror.mirror) { std::lock_guard lock(state->page_mirror.mutex); wait = state->page_mirror.value; } return gpu_buffer_read(*state, state->arena.buffer, va, wait, out, bytes); } bool set_tsharp_index_words_for_test(ID3D12Device* device, bool on) { DeviceState* state = device_state_for_test(device); if (!state) return false; const bool was = state->tsharp_index_words; state->tsharp_index_words = on; return was; } bool page_mirror_buffer_at(ID3D12Device* device, std::uint64_t va, std::uint64_t& size) { ID3D12Device* real = device ? rt::d3d12_xs::device_proxy_real_device(device) : nullptr; if (!real) real = device; const Device* d = real ? Device::from(real) : nullptr; if (!d) return false; VkBuffer buffer = VK_NULL_HANDLE; VkDeviceSize offset = 0; return const_cast(d->state()).page_mirror_buffer(va, size, buffer, offset); } bool page_mirror_gpu_write(ID3D12Device* device, std::uint64_t title_va, const void* data, std::size_t bytes) { ID3D12Device* real = device ? rt::d3d12_xs::device_proxy_real_device(device) : nullptr; if (!real) real = device; const Device* d = real ? Device::from(real) : nullptr; if (!d || !data || !bytes || bytes > 65536 || (bytes & 3) || (title_va & 3)) return false; auto& state = const_cast(d->state()); if (!state.page_mirror.mirror || !state.context) return false; state.refresh_page_mirror(); state.flush_page_mirror(); VkBuffer chunk = VK_NULL_HANDLE; VkDeviceSize offset = 0; std::uint64_t wait = 0; { std::lock_guard lock(state.page_mirror.mutex); if (!state.page_mirror.mirror->chunk_at(title_va, chunk, offset)) return false; wait = state.page_mirror.value; } auto& vk = state.context->vk; const VkDevice dev = state.info.device; VkCommandPool pool = VK_NULL_HANDLE; VkCommandBuffer commands = VK_NULL_HANDLE; VkCommandPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; pool_info.queueFamilyIndex = state.info.queue_family; bool ok = vk.vkCreateCommandPool(dev, &pool_info, nullptr, &pool) == VK_SUCCESS; VkCommandBufferAllocateInfo allocate{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; allocate.commandPool = pool; allocate.commandBufferCount = 1; ok = ok && vk.vkAllocateCommandBuffers(dev, &allocate, &commands) == VK_SUCCESS; if (ok) { VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; vk.vkBeginCommandBuffer(commands, &begin); vk.vkCmdUpdateBuffer(commands, chunk, offset, bytes, data); vk.vkEndCommandBuffer(commands); VkTimelineSemaphoreSubmitInfo values{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; values.waitSemaphoreValueCount = 1; values.pWaitSemaphoreValues = &wait; const VkPipelineStageFlags stage = VK_PIPELINE_STAGE_TRANSFER_BIT; VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &values}; submit.waitSemaphoreCount = 1; submit.pWaitSemaphores = &state.page_mirror.timeline; submit.pWaitDstStageMask = &stage; submit.commandBufferCount = 1; submit.pCommandBuffers = &commands; std::lock_guard lock(state.context->submit_mutex()); ok = vk.vkQueueSubmit(state.info.queue, 1, &submit, VK_NULL_HANDLE) == VK_SUCCESS && vk.vkQueueWaitIdle(state.info.queue) == VK_SUCCESS; } if (pool) vk.vkDestroyCommandPool(dev, pool, nullptr); return ok; } std::uint64_t page_mirror_write_back(ID3D12Device* device, std::uint64_t va, std::uint64_t bytes) { ID3D12Device* real = device ? rt::d3d12_xs::device_proxy_real_device(device) : nullptr; if (!real) real = device; const Device* d = real ? Device::from(real) : nullptr; return d ? const_cast(d->state()).page_mirror_write_back(va, va + bytes) : 0; } bool page_mirror_name(ID3D12Device* device, std::uint64_t va, std::uint64_t bytes) { ID3D12Device* real = device ? rt::d3d12_xs::device_proxy_real_device(device) : nullptr; if (!real) real = device; const Device* d = real ? Device::from(real) : nullptr; return d && const_cast(d->state()).page_mirror_resolve(va, bytes); } ArenaMemoryState device_arena_memory(ID3D12Device* device) { if (!device) return {}; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; const Device* d = Device::from(real); if (!d) return {}; auto& state = const_cast(d->state()); // the arena's mutex ArenaMemoryState out; std::lock_guard lock(state.arena.mutex); out.size = state.arena.size; out.address = state.arena.address; out.bound = state.arena.backing.stats().bound; out.sparse = state.arena.backing.sparse(); out.sparse_capable = state.arena_sparse_capable; out.signed_offsets = state.vsharp_offsets_signed(); return out; } ImageMemoryStats image_memory_stats(ID3D12Device* device) { if (!device) return {}; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; const Device* d = Device::from(real); if (!d || !d->state().image_memory) return {}; const auto stats = d->state().image_memory->stats(); return {stats.blocks, stats.block_bytes, stats.ranges}; } bool read_arena(ID3D12Device* device, std::uint64_t va, void* out, std::size_t bytes) { if (!device || !out) return false; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); if (!real) real = device; Device* d = Device::from(real); // Any arena address (a diagnostic's): read under the backing's shared lock, refused where no memory is. if (!d || !d->state().arena_ready()) return false; if (d->state().arena.staged && bytes) d->state().sync_arena_to_host(va, bytes); return d->state().arena.backing.with_host(va, bytes, [&](const std::uint8_t* host) { std::memcpy(out, host, bytes); }); } namespace { const leonida::BindlessSet* bindless_of(ID3D12Device* device) { if (!device) return nullptr; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); const Device* d = Device::from(real ? real : device); return d ? d->bindless() : nullptr; } } // namespace VkDescriptorSet bindless_set(ID3D12Device* device) { const leonida::BindlessSet* set = bindless_of(device); return set ? set->set() : VK_NULL_HANDLE; } BindlessStats bindless_stats(ID3D12Device* device) { BindlessStats stats; if (!device) return stats; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); const Device* d = Device::from(real ? real : device); if (!d || !d->bindless()) return stats; stats.generations_made = d->bindless()->generations_made(); stats.retired_pending = d->bindless()->retired_count(); stats.device_idle_waits = d->state().bindless_idle_waits.load(std::memory_order_relaxed); return stats; } VkDescriptorSetLayout bindless_set_layout(ID3D12Device* device) { const leonida::BindlessSet* set = bindless_of(device); return set ? set->layout() : VK_NULL_HANDLE; } std::uint32_t bindless_hash_lookup(ID3D12Device* device, const std::uint32_t (&key)[8]) { const leonida::BindlessSet* set = bindless_of(device); if (!set) return 0; // A T# read back from one of the layer's heaps carries its index in dword 6 (tsharp_index_word): its key is the // descriptor without it, and the word must name the index the table holds, which is what a shader reads. namespace g = leonida::gfx10; g::ImageWords words; std::memcpy(words.data(), key, sizeof(words)); if (!g::is_image(words) || !g::has_tsharp_index(words)) return set->table().lookup(key); const g::ImageWords stripped = g::tsharp_key(words); const std::uint32_t index = set->table().lookup(stripped.data()); return index == g::tsharp_index_of(words) ? index : 0; } BindlessRoom bindless_room(ID3D12Device* device) { const leonida::BindlessSet* set = bindless_of(device); if (!set) return {}; return {set->free_images(leonida::ImageDimension::dim_2d), set->free_samplers()}; } WindowPresenter::WindowPresenter(IUnknown* device, std::unique_ptr presenter) : device_(device), presenter_(std::move(presenter)) { if (device_) device_->AddRef(); } WindowPresenter::~WindowPresenter() { presenter_.reset(); // before the device it runs on if (device_) device_->Release(); } namespace { HRESULT present_result(VkResult result) { if (result == VK_SUCCESS) return S_OK; std::fprintf(stderr, "[rt] d3d12: present failed (VkResult %d)\n", int(result)); if (result == VK_ERROR_DEVICE_LOST) return DXGI_ERROR_DEVICE_REMOVED; if (result == VK_ERROR_FORMAT_NOT_SUPPORTED) return DXGI_ERROR_UNSUPPORTED; return E_FAIL; } } // namespace HRESULT WindowPresenter::present(ID3D12Resource* back_buffer, UINT sync_interval, const D3D12_RECT* src_rect, bool tear) { if (!back_buffer) return E_INVALIDARG; const leonida::PresentRect rect = src_rect ? leonida::PresentRect{src_rect->left, src_rect->top, src_rect->right, src_rect->bottom} : leonida::PresentRect{}; return present_result(presenter_->present(resource_id(back_buffer), sync_interval > 0, src_rect ? &rect : nullptr, tear)); } bool WindowPresenter::present_splash(ID3D12Resource* image) { if (!image) return false; image->AddRef(); std::shared_ptr owner(image, [](ID3D12Resource* p) { p->Release(); }); return presenter_->present_splash(resource_id(image), std::move(owner)); } bool WindowPresenter::tear_supported() const { return presenter_->tear_supported(); } bool WindowPresenter::last_present_tore() const { return presenter_->last_present_tore(); } std::uint64_t WindowPresenter::tear_presents() const { return presenter_->tear_presents(); } HRESULT WindowPresenter::present_blank(UINT sync_interval) { return present_result(presenter_->present_blank(sync_interval > 0)); } HRESULT WindowPresenter::present_planes(const leonida::PresentPlanes& planes, UINT sync_interval, bool tear) { return present_result(presenter_->present_planes(planes, sync_interval > 0, tear)); } bool WindowPresenter::hdr_active() const { return presenter_->hdr_active(); } void WindowPresenter::force_hdr_encoding(bool on) { presenter_->force_hdr_encoding(on); } std::uint64_t WindowPresenter::composed_presents() const { return presenter_->composed_presents(); } // DISPLAYCONFIG_SDR_WHITE_LEVEL.SDRWhiteLevel is the white level in units of 80/1000 nits: 1000 is 80 nits (the scRGB 1.0), // 2500 is 200 nits (MS Learn, DISPLAYCONFIG_SDR_WHITE_LEVEL). Zero is not a level. float sdr_white_nits_from_level(unsigned long level) { return float(level) / 1000.0f * 80.0f; } float WindowPresenter::display_sdr_white_nits() const { if (!window_) return 0.0f; // The GDI name of the monitor the window is on, matched to a display path's source, whose target has the setting. MONITORINFOEXW monitor{}; monitor.cbSize = sizeof(monitor); if (!GetMonitorInfoW(MonitorFromWindow(window_, MONITOR_DEFAULTTONEAREST), &monitor)) return 0.0f; // The active configuration can change between the size query and the read (a hot-plug): ERROR_INSUFFICIENT_BUFFER asks // for the sizes again (the pattern Microsoft documents for QueryDisplayConfig). UINT32 path_count = 0, mode_count = 0; std::vector paths; std::vector modes; LONG status = ERROR_INSUFFICIENT_BUFFER; for (int attempt = 0; attempt < 8 && status == ERROR_INSUFFICIENT_BUFFER; ++attempt) { if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &path_count, &mode_count) != ERROR_SUCCESS) return 0.0f; paths.assign(path_count, {}); modes.assign(mode_count, {}); status = QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &path_count, paths.data(), &mode_count, modes.data(), nullptr); } if (status != ERROR_SUCCESS) return 0.0f; // the caller keeps the last good value for (UINT32 i = 0; i < path_count; ++i) { DISPLAYCONFIG_SOURCE_DEVICE_NAME source{}; source.header = {DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, sizeof(source), paths[i].sourceInfo.adapterId, paths[i].sourceInfo.id}; if (DisplayConfigGetDeviceInfo(&source.header) != ERROR_SUCCESS || std::wcscmp(source.viewGdiDeviceName, monitor.szDevice) != 0) continue; DISPLAYCONFIG_SDR_WHITE_LEVEL level{}; level.header = {DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL, sizeof(level), paths[i].targetInfo.adapterId, paths[i].targetInfo.id}; if (DisplayConfigGetDeviceInfo(&level.header) != ERROR_SUCCESS || level.SDRWhiteLevel == 0) return 0.0f; return sdr_white_nits_from_level(level.SDRWhiteLevel); } return 0.0f; } bool WindowPresenter::enable_capture() { return presenter_->enable_capture(); } void WindowPresenter::set_abort(std::function abort) { presenter_->set_abort(std::move(abort)); } bool WindowPresenter::read_back(std::vector& pixels, VkExtent2D* extent, VkFormat* format) { return presenter_->read_back(pixels, extent, format); } VkExtent2D WindowPresenter::extent() const { return presenter_->extent(); } std::uint64_t WindowPresenter::presented() const { return presenter_->presented(); } bool device_has_swapchain_colorspace(ID3D12Device* device) { ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); Device* d = Device::from(real ? real : device); return d && d->state().info.swapchain_colorspace; } std::unique_ptr create_window_presenter(ID3D12Device* device, HWND window, bool hold_device) { // A title holds the Xbox-ABI proxy, not the layer's device: look behind it, as the helpers above do. ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); Device* d = Device::from(real ? real : device); if (device && !d) std::fprintf(stderr, "[rt] d3d12: create_window_presenter: %p is neither the Xbox device proxy nor a device of " "this layer; no presenter\n", static_cast(device)); if (!d || !window) return nullptr; const VulkanDeviceInfo& info = d->state().info; if (!info.presentation) { std::fprintf(stderr, "[rt] d3d12: the Vulkan device was created without presentation support\n"); return nullptr; } const auto create_surface = reinterpret_cast( info.get_instance_proc(info.instance, "vkCreateWin32SurfaceKHR")); if (!create_surface) return nullptr; VkWin32SurfaceCreateInfoKHR surface_info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; surface_info.hinstance = GetModuleHandleW(nullptr); surface_info.hwnd = window; VkSurfaceKHR surface = VK_NULL_HANDLE; if (create_surface(info.instance, &surface_info, nullptr, &surface) != VK_SUCCESS) return nullptr; // LEONIDA_PRESENT_NO_TEAR=1 keeps the swapchain FIFO-only (ImmediateThresholdPercent then does nothing). // Any non-empty value other than "0" turns it off. bool tear_allowed = true; { char* value = nullptr; std::size_t length = 0; if (_dupenv_s(&value, &length, "LEONIDA_PRESENT_NO_TEAR") == 0 && value) { tear_allowed = value[0] == '\0' || std::strcmp(value, "0") == 0; std::free(value); } } auto presenter = std::make_unique(*d->state().context, info.get_instance_proc, info.instance, info.physical, info.queue, info.queue_family, surface, // owns the surface info.swapchain_maintenance1 && tear_allowed, [window]() -> VkExtent2D { RECT r{}; if (GetClientRect(window, &r)) { return {static_cast(r.right - r.left), static_cast(r.bottom - r.top)}; } return {0, 0}; }, [create_surface, hinstance = GetModuleHandleW(nullptr), hwnd = window, instance = info.instance]() -> VkSurfaceKHR { // A lost surface (display gone) is remade for the // same window; VulkanSwapchain never retained the // hwnd, this callback does. VkWin32SurfaceCreateInfoKHR surface_info{ VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; surface_info.hinstance = hinstance; surface_info.hwnd = hwnd; VkSurfaceKHR made = VK_NULL_HANDLE; if (create_surface(instance, &surface_info, nullptr, &made) != VK_SUCCESS) return VK_NULL_HANDLE; return made; }); if (!presenter->ok()) { std::fprintf(stderr, "[rt] d3d12: cannot present to this window from the device's queue family\n"); return nullptr; } auto window_presenter = std::make_unique(hold_device ? d->holder() : nullptr, std::move(presenter)); window_presenter->set_window(window); return window_presenter; } HRESULT register_samplers(ID3D12Device* device, std::span samplers) { if (!device) return E_INVALIDARG; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); Device* d = Device::from(real ? real : device); if (!d) return E_INVALIDARG; bool all = true; for (const leonida::gfx10::SamplerWords& words : samplers) all = d->bind_sampler(words) && all; return all ? S_OK : E_FAIL; } HRESULT create_dxgi_factory(ID3D12Device* device, REFIID riid, void** out) { if (!out) return E_POINTER; *out = nullptr; if (!device) return E_INVALIDARG; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); Device* d = Device::from(real ? real : device); if (!d) return E_INVALIDARG; const auto& i = d->info(); const auto gdpa = reinterpret_cast(i.get_instance_proc(i.instance, "vkGetDeviceProcAddr")); if (!gdpa) return E_FAIL; return rt::dxgi::create_factory(d->context(), i.get_instance_proc, i.instance, i.physical, gdpa, i.queue, i.queue_family, riid, out); } // Creates its own Vulkan instance and a Vulkan 1.3 device, or a 1.2 device with VK_KHR_dynamic_rendering and // VK_KHR_synchronization2 (vulkan13_features.h). LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation. HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettings queue_test_settings) { if (!out) return E_POINTER; *out = nullptr; // LEONIDA_AFTERMATH=1: GPU crash dumps on before the Vulkan instance and device exist (src/vulkan_aftermath.h). leonida::aftermath::enable(); static const HMODULE library = LoadLibraryA("vulkan-1.dll"); const auto get = library ? reinterpret_cast( reinterpret_cast(GetProcAddress(library, "vkGetInstanceProcAddr"))) : nullptr; if (!get) { std::fprintf(stderr, "[rt] d3d12: vulkan-1.dll not found\n"); return E_FAIL; } const auto create_instance = reinterpret_cast(get(nullptr, "vkCreateInstance")); const auto enum_inst_exts = reinterpret_cast( get(nullptr, "vkEnumerateInstanceExtensionProperties")); std::vector inst_exts; bool surface_maintenance1_khr = false, surface_maintenance1_ext = false; // enabled on the instance bool swapchain_colorspace_enabled = false; // VK_EXT_swapchain_colorspace on the instance if (enum_inst_exts) { std::uint32_t ext_cnt = 0; enum_inst_exts(nullptr, &ext_cnt, nullptr); std::vector available(ext_cnt); enum_inst_exts(nullptr, &ext_cnt, available.data()); bool has_surface = false, has_win32 = false, has_caps2 = false; for (const auto& e : available) { if (!std::strcmp(e.extensionName, VK_KHR_SURFACE_EXTENSION_NAME)) has_surface = true; if (!std::strcmp(e.extensionName, VK_KHR_WIN32_SURFACE_EXTENSION_NAME)) has_win32 = true; if (!std::strcmp(e.extensionName, VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME)) has_caps2 = true; if (!std::strcmp(e.extensionName, "VK_KHR_surface_maintenance1")) surface_maintenance1_khr = true; if (!std::strcmp(e.extensionName, "VK_EXT_surface_maintenance1")) surface_maintenance1_ext = true; } if (has_surface && has_win32) { inst_exts.push_back(VK_KHR_SURFACE_EXTENSION_NAME); inst_exts.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); // Lists the HDR10 (ST.2084) surface formats, which a PresentX plane in HDR10 can use (xbox_present.h); without it // the surface only offers sRGB-nonlinear ones. for (const auto& e : available) if (!std::strcmp(e.extensionName, VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME)) { inst_exts.push_back(VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME); swapchain_colorspace_enabled = true; break; } // The surface half of VK_*_swapchain_maintenance1 (the present modes a swapchain can switch between). if (has_caps2 && (surface_maintenance1_khr || surface_maintenance1_ext)) { inst_exts.push_back(VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME); if (surface_maintenance1_khr) inst_exts.push_back("VK_KHR_surface_maintenance1"); if (surface_maintenance1_ext) inst_exts.push_back("VK_EXT_surface_maintenance1"); } else { surface_maintenance1_khr = surface_maintenance1_ext = false; } } else { surface_maintenance1_khr = surface_maintenance1_ext = false; } } VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; app.pApplicationName = "gta6rt"; app.apiVersion = VK_API_VERSION_1_3; VkInstanceCreateInfo instance_info{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; instance_info.pApplicationInfo = &app; const char* layer = "VK_LAYER_KHRONOS_validation"; const VkValidationFeatureEnableEXT sync_validation = VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT; VkValidationFeaturesEXT validation_features{VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT}; validation_features.enabledValidationFeatureCount = 1; validation_features.pEnabledValidationFeatures = &sync_validation; char validation[8] = {}; size_t length = 0; if (getenv_s(&length, validation, "LEONIDA_VK_VALIDATION") == 0 && length > 1 && validation[0] != '0') { // Ask for the layer only when the loader lists it, and say so when it does not: an instance that cannot be // made because of a missing layer left the caller with "Vulkan unavailable" and no hint that validation was // the cause. Wine does not list the Linux loader's layers to the program and refuses an explicit request for // one, so there only VK_INSTANCE_LAYERS (which Wine keeps out of the program's environment) loads it. bool layer_listed = false; if (const auto enumerate_layers = reinterpret_cast( get(nullptr, "vkEnumerateInstanceLayerProperties"))) { std::uint32_t layer_count = 0; enumerate_layers(&layer_count, nullptr); std::vector layers(layer_count); if (layer_count && enumerate_layers(&layer_count, layers.data()) >= VK_SUCCESS) for (std::uint32_t i = 0; i < layer_count; ++i) layer_listed = layer_listed || std::strcmp(layers[i].layerName, layer) == 0; } if (layer_listed) { instance_info.pNext = &validation_features; instance_info.enabledLayerCount = 1; instance_info.ppEnabledLayerNames = &layer; } else { std::fprintf(stderr, "[rt] d3d12: LEONIDA_VK_VALIDATION is set but %s is not listed by the Vulkan loader " "(install the Vulkan SDK; under Wine set VK_INSTANCE_LAYERS=%s instead)\n", layer, layer); return E_FAIL; } } // VK_EXT_debug_utils when the loader has it, for the game's debug markers (PIX events) in RenderDoc and the like. const char* debug_utils = VK_EXT_DEBUG_UTILS_EXTENSION_NAME; bool has_debug_utils = false; if (const auto enumerate = reinterpret_cast( get(nullptr, "vkEnumerateInstanceExtensionProperties"))) { std::uint32_t extension_count = 0; enumerate(nullptr, &extension_count, nullptr); std::vector extensions(extension_count); enumerate(nullptr, &extension_count, extensions.data()); for (const auto& e : extensions) has_debug_utils = has_debug_utils || std::strcmp(e.extensionName, debug_utils) == 0; } // One list: the surface extensions above (for DXGI presentation) and debug utils both go on the instance. const bool instance_has_surface = !inst_exts.empty(); if (has_debug_utils) inst_exts.push_back(debug_utils); instance_info.enabledExtensionCount = static_cast(inst_exts.size()); instance_info.ppEnabledExtensionNames = inst_exts.empty() ? nullptr : inst_exts.data(); OwnedRuntime owned{}; if (create_instance(&instance_info, nullptr, &owned.instance) != VK_SUCCESS) { std::fprintf(stderr, "[rt] d3d12: vkCreateInstance (Vulkan 1.3) failed\n"); return E_FAIL; } owned.destroy_instance = reinterpret_cast(get(owned.instance, "vkDestroyInstance")); // LEONIDA_ADDRESS_BINDINGS: the device's bindings reach this messenger from vkCreateDevice on (address_binding.h). if (has_debug_utils) leonida::address_binding::install_messenger(owned.instance, get); const auto fail = [&](const char* why) { std::fprintf(stderr, "[rt] d3d12: %s\n", why); leonida::address_binding::uninstall_messenger(owned.instance); owned.destroy_instance(owned.instance, nullptr); return E_FAIL; }; #define LEONIDA_INSTANCE(name) const auto name = reinterpret_cast(get(owned.instance, #name)) LEONIDA_INSTANCE(vkEnumeratePhysicalDevices); LEONIDA_INSTANCE(vkGetPhysicalDeviceProperties); LEONIDA_INSTANCE(vkGetPhysicalDeviceQueueFamilyProperties); LEONIDA_INSTANCE(vkGetPhysicalDeviceFeatures2); LEONIDA_INSTANCE(vkGetPhysicalDeviceFormatProperties); LEONIDA_INSTANCE(vkGetPhysicalDeviceProperties2); LEONIDA_INSTANCE(vkEnumerateDeviceExtensionProperties); LEONIDA_INSTANCE(vkCreateDevice); LEONIDA_INSTANCE(vkGetDeviceProcAddr); #undef LEONIDA_INSTANCE std::uint32_t count = 0; vkEnumeratePhysicalDevices(owned.instance, &count, nullptr); std::vector physicals(count); vkEnumeratePhysicalDevices(owned.instance, &count, physicals.data()); VulkanDeviceInfo info{}; info.get_instance_proc = get; info.instance = owned.instance; info.separate_depth_stencil_layouts = true; info.debug_utils = has_debug_utils; VkPhysicalDeviceProperties chosen{}; bool chosen_bc = false; VkPhysicalDeviceFeatures chosen_features{}; VkPhysicalDeviceVulkan12Features chosen12{}; bool chosen_draw_params = false; leonida::Vulkan13Features v13, candidate13; // The first usable device of the highest vulkan_device_rank: a native driver over Microsoft's Dozen (which says // it is a discrete GPU, #915), then discrete over integrated; the test harnesses (vk_device_pick.h) pick the same. int chosen_rank = -1; for (VkPhysicalDevice candidate : physicals) { VkPhysicalDeviceProperties props{}; vkGetPhysicalDeviceProperties(candidate, &props); if (!leonida::vulkan_device_wanted(props.deviceName)) continue; candidate13.query(candidate, props.apiVersion, vkGetPhysicalDeviceFeatures2, vkEnumerateDeviceExtensionProperties); if (!candidate13.usable()) continue; VkPhysicalDeviceVulkan11Features f11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &f11}; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f12}; vkGetPhysicalDeviceFeatures2(candidate, &features); const bool bc = features.features.textureCompressionBC; const bool draw_params = f11.shaderDrawParameters; if (!f12.timelineSemaphore || !f12.separateDepthStencilLayouts || !f12.bufferDeviceAddress) continue; std::uint32_t family_count = 0; vkGetPhysicalDeviceQueueFamilyProperties(candidate, &family_count, nullptr); std::vector families(family_count); vkGetPhysicalDeviceQueueFamilyProperties(candidate, &family_count, families.data()); for (std::uint32_t i = 0; i < family_count; ++i) { if (!(families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) continue; if (const int rank = leonida::vulkan_device_rank(static_cast(props.deviceType), props.vendorID); rank > chosen_rank) { chosen_rank = rank; info.physical = candidate; info.queue_family = i; chosen = props; chosen_bc = bc; chosen_features = features.features; chosen12 = f12; chosen_draw_params = draw_params; v13.choose(candidate13); } break; } } if (!info.physical) return fail(leonida::vulkan_device_filter().empty() ? "no Vulkan 1.3 GPU (or 1.2 with VK_KHR_dynamic_rendering and VK_KHR_synchronization2) with " "dynamicRendering, synchronization2, timelineSemaphore and separateDepthStencilLayouts" : "no GPU named by LEONIDA_VK_DEVICE has Vulkan 1.3 (or 1.2 with VK_KHR_dynamic_rendering and " "VK_KHR_synchronization2) with dynamicRendering, synchronization2, timelineSemaphore and " "separateDepthStencilLayouts"); if (!v13.core) std::fprintf(stderr, "[rt] d3d12: Vulkan 1.2 device: dynamicRendering and synchronization2 through their KHR " "extensions; %s\n", v13.extended_dynamic_state ? "extended dynamic state through VK_EXT_extended_dynamic_state(2)" : "no extended dynamic state, so no graphics pipelines"); // VK_EXT_conditional_rendering for SetPredication, VK_KHR_swapchain for DXGI presentation, and optional // VK_KHR_acceleration_structure + VK_KHR_ray_query for hardware BVH builds (BLAS + TLAS). VkPhysicalDeviceConditionalRenderingFeaturesEXT conditional{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT}; bool has_swapchain = false; VkPhysicalDeviceAccelerationStructureFeaturesKHR as_features{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; VkPhysicalDeviceRayQueryFeaturesKHR rq_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR}; VkPhysicalDeviceMeshShaderFeaturesEXT mesh_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; VkPhysicalDeviceTransformFeedbackFeaturesEXT transform_feedback_features{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT}; VkPhysicalDeviceTransformFeedbackPropertiesEXT transform_feedback_properties{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT}; { std::uint32_t extension_count = 0; vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr); std::vector extensions(extension_count); vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, extensions.data()); bool has_as = false, has_dho = false, has_rq = false; for (const auto& e : extensions) { if (!std::strcmp(e.extensionName, VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &conditional}; vkGetPhysicalDeviceFeatures2(info.physical, &features); info.conditional_rendering = conditional.conditionalRendering == VK_TRUE; } else if (!std::strcmp(e.extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME)) { has_swapchain = true; } else if (!std::strcmp(e.extensionName, VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME)) { has_as = true; } else if (!std::strcmp(e.extensionName, VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME)) { has_dho = true; } else if (!std::strcmp(e.extensionName, VK_KHR_RAY_QUERY_EXTENSION_NAME)) { has_rq = true; } else if (!std::strcmp(e.extensionName, VK_EXT_MESH_SHADER_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; vkGetPhysicalDeviceFeatures2(info.physical, &features); info.mesh_shader = mesh_features.meshShader == VK_TRUE; info.mesh_shader_queries = mesh_features.meshShaderQueries == VK_TRUE; } else if (!std::strcmp(e.extensionName, VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &transform_feedback_features}; vkGetPhysicalDeviceFeatures2(info.physical, &features); info.transform_feedback = transform_feedback_features.transformFeedback == VK_TRUE; info.transform_feedback_geometry_streams = transform_feedback_features.geometryStreams == VK_TRUE; // D3D-302: the queries and the stream count are properties, not features. VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &transform_feedback_properties}; vkGetPhysicalDeviceProperties2(info.physical, &properties); info.transform_feedback_queries = transform_feedback_properties.transformFeedbackQueries == VK_TRUE; info.max_transform_feedback_streams = transform_feedback_properties.maxTransformFeedbackStreams; } } if (!info.mesh_shader) std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_mesh_shader: mesh-shader PSOs are unsupported\n"); if (!info.transform_feedback) std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_transform_feedback: SO_STATISTICS query pools read zero\n"); else if (!info.transform_feedback_queries || !info.max_transform_feedback_streams) std::fprintf(stderr, "[rt] d3d12: the GPU has no transform-feedback queries (transformFeedbackQueries, " "maxTransformFeedbackStreams): SO_STATISTICS query pools read zero\n"); if (has_as && has_dho && has_rq && chosen12.bufferDeviceAddress) { as_features.pNext = &rq_features; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &as_features}; vkGetPhysicalDeviceFeatures2(info.physical, &features); info.ray_tracing = as_features.accelerationStructure == VK_TRUE && rq_features.rayQuery == VK_TRUE; } // The game's translated RT shaders read XDXR BVH4 records, which a VkAccelerationStructureKHR is not // (docs/d3d12_vulkan.md 4.8): build those, unless LEONIDA_RT_AS=khr asks for #743's KHR builds instead. char rt_as[8] = {}; std::size_t rt_as_length = 0; const bool khr = getenv_s(&rt_as_length, rt_as, "LEONIDA_RT_AS") == 0 && rt_as_length > 1 && std::strcmp(rt_as, "khr") == 0; if (!khr && chosen12.bufferDeviceAddress) { info.xdxr_acceleration_structures = true; info.ray_tracing = false; // no KHR extensions: AS resources keep their console VAs } if (!info.conditional_rendering) std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_conditional_rendering: SetPredication is unsupported\n"); } VkPhysicalDeviceConditionalRenderingFeaturesEXT enable_conditional{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT}; enable_conditional.conditionalRendering = VK_TRUE; VkPhysicalDeviceRayQueryFeaturesKHR enable_rq{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR}; enable_rq.rayQuery = VK_TRUE; VkPhysicalDeviceAccelerationStructureFeaturesKHR enable_as{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; enable_as.accelerationStructure = VK_TRUE; // Only meshShader: the game has no amplification (task) shaders, and multiview and shading-rate mesh features // are not used. VkPhysicalDeviceMeshShaderFeaturesEXT enable_mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; enable_mesh.meshShader = VK_TRUE; // The mesh-primitives query, which counts the primitives a mesh shader emits (D3D-MESH-CLIPPING-COUNTER). enable_mesh.meshShaderQueries = info.mesh_shader_queries ? VK_TRUE : VK_FALSE; // D3D-302: real SO_STATISTICS queries need transformFeedback; geometryStreams is only requested when the device // already offers it, so the enable chain matches vk_pipeline_check's (a driver keys the pipeline cache on it). VkPhysicalDeviceTransformFeedbackFeaturesEXT enable_transform_feedback{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT}; enable_transform_feedback.transformFeedback = VK_TRUE; enable_transform_feedback.geometryStreams = info.transform_feedback_geometry_streams ? VK_TRUE : VK_FALSE; void* ext_chain = nullptr; if (info.mesh_shader) { enable_mesh.pNext = ext_chain; ext_chain = &enable_mesh; } if (info.transform_feedback) { enable_transform_feedback.pNext = ext_chain; ext_chain = &enable_transform_feedback; } if (info.ray_tracing) { enable_rq.pNext = ext_chain; enable_as.pNext = &enable_rq; ext_chain = &enable_as; } if (info.conditional_rendering) { enable_conditional.pNext = ext_chain; ext_chain = &enable_conditional; } // Subgroup size control: a pipeline stage asks for the size its shader was translated for (src/subgroup_size.h). leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, info.physical, v13.subgroup_size_control, v13.compute_full_subgroups, info.subgroup); const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); const auto mode = compile_mode ? std::string_view(compile_mode) : std::string_view{}; // pipelineCreationCacheControl: for LEONIDA_PIPELINE_COMPILE=cache-only, and for the heavy pipeline cache unless // LEONIDA_HEAVY_PIPELINE_CACHE_MS=0 turns it off. v13.enable_pipeline_cache_control = (mode == "cache-only" || heavy_pipeline_cache_ms()) && v13.core && v13.pipeline_cache_control; info.cold_graphics_compile = mode == "cache-only" && v13.enable_pipeline_cache_control; info.heavy_pipeline_cache = heavy_pipeline_cache_ms() && v13.enable_pipeline_cache_control; info.prepare_on_bind = mode == "on-demand"; void* v13_chain = v13.enable(ext_chain); if (!v13.integer_dot_product) std::fprintf(stderr, "[rt] d3d12: the GPU has no shaderIntegerDotProduct; shaders that use the 4x8-bit dot " "products need make_game.py's --integer-dot-fallback\n"); // D3D-78 uses the core robustness and format-feature flags. Leave the Vulkan 1.2 extension path unchanged. if (v13.core) { VkPhysicalDeviceVulkan13Features supported{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &supported}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.robust_image_access = supported.robustImageAccess == VK_TRUE; static_cast(v13_chain)->robustImageAccess = supported.robustImageAccess; } // Translated vertex shaders read BaseVertex / BaseInstance (SPIR-V DrawParameters) to give v0 / v3 the // hardware's zero-based vertex and instance ids (docs/design.md, Inputs and outputs). VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, v13_chain}; enable11.shaderDrawParameters = chosen_draw_params ? VK_TRUE : VK_FALSE; if (!chosen_draw_params) std::fprintf(stderr, "[rt] d3d12: the GPU has no shaderDrawParameters\n"); VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; enable12.timelineSemaphore = VK_TRUE; enable12.drawIndirectCount = chosen12.drawIndirectCount; info.draw_indirect_count_enabled = enable12.drawIndirectCount == VK_TRUE; enable12.separateDepthStencilLayouts = VK_TRUE; info.buffer_device_address = chosen12.bufferDeviceAddress == VK_TRUE; enable12.bufferDeviceAddress = info.buffer_device_address ? VK_TRUE : VK_FALSE; info.storage_buffer_8bit = chosen12.storageBuffer8BitAccess == VK_TRUE; enable12.storageBuffer8BitAccess = info.storage_buffer_8bit; // Where the GPU has them: what the bindless set 0 needs (VulkanDeviceInfo::bindless), and the sampler features // D3D12 samplers can ask for. info.bindless = chosen12.runtimeDescriptorArray && chosen_features.shaderSampledImageArrayDynamicIndexing && chosen_features.shaderStorageImageArrayDynamicIndexing && chosen12.descriptorBindingSampledImageUpdateAfterBind && chosen12.descriptorBindingStorageImageUpdateAfterBind && chosen12.descriptorBindingStorageBufferUpdateAfterBind; info.bindless_partially_bound = info.bindless && chosen12.descriptorBindingPartiallyBound; info.sampler_anisotropy = chosen_features.samplerAnisotropy; info.sampler_mirror_clamp_to_edge = chosen12.samplerMirrorClampToEdge; info.sampler_filter_minmax = chosen12.samplerFilterMinmax; if (info.sampler_filter_minmax) { VkPhysicalDeviceSamplerFilterMinmaxProperties minmax{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES}; VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &minmax}; vkGetPhysicalDeviceProperties2(info.physical, &properties); info.sampler_filter_minmax_component_mapping = minmax.filterMinmaxImageComponentMapping == VK_TRUE; } enable12.runtimeDescriptorArray = info.bindless; enable12.descriptorBindingSampledImageUpdateAfterBind = info.bindless; enable12.descriptorBindingStorageImageUpdateAfterBind = info.bindless; enable12.descriptorBindingStorageBufferUpdateAfterBind = info.bindless; enable12.descriptorBindingPartiallyBound = info.bindless_partially_bound; enable12.samplerMirrorClampToEdge = info.sampler_mirror_clamp_to_edge; enable12.samplerFilterMinmax = info.sampler_filter_minmax; info.shader_output_layer = chosen12.shaderOutputLayer == VK_TRUE; info.shader_output_viewport_index = chosen12.shaderOutputViewportIndex == VK_TRUE; enable12.shaderOutputLayer = info.shader_output_layer; enable12.shaderOutputViewportIndex = info.shader_output_viewport_index; info.vulkan_memory_model = chosen12.vulkanMemoryModel == VK_TRUE; info.vulkan_memory_model_device_scope = info.vulkan_memory_model && chosen12.vulkanMemoryModelDeviceScope == VK_TRUE; enable12.vulkanMemoryModel = info.vulkan_memory_model ? VK_TRUE : VK_FALSE; enable12.vulkanMemoryModelDeviceScope = info.vulkan_memory_model_device_scope ? VK_TRUE : VK_FALSE; if (!info.bindless) std::fprintf(stderr, "[rt] d3d12: the GPU lacks a descriptor-indexing feature the bindless set needs\n"); enable12.bufferDeviceAddress = VK_TRUE; info.buffer_device_address = true; info.buffer_device_address_capture_replay = chosen12.bufferDeviceAddressCaptureReplay == VK_TRUE; enable12.bufferDeviceAddressCaptureReplay = info.buffer_device_address_capture_replay ? VK_TRUE : VK_FALSE; std::uint32_t family_count = 0; vkGetPhysicalDeviceQueueFamilyProperties(info.physical, &family_count, nullptr); std::vector families(family_count); vkGetPhysicalDeviceQueueFamilyProperties(info.physical, &family_count, families.data()); const std::uint32_t queue_cap = max_queues_per_family(queue_test_settings); const std::uint32_t command_queue_count = std::min(queue_cap, families[info.queue_family].queueCount); std::vector priorities(16, 1.0f); std::vector queue_infos; { VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; q.queueFamilyIndex = info.queue_family; q.queueCount = command_queue_count; q.pQueuePriorities = priorities.data(); queue_infos.push_back(q); } const auto preferred = leonida::pick_queue_families(families, info.queue_family); auto picked = leonida::sparse_capable_queue_families(families, preferred, chosen_features, chosen.sparseProperties); if (graphics_family_only(queue_test_settings)) picked = {info.queue_family, info.queue_family, info.queue_family}; std::uint32_t compute_count = 0, copy_count = 0; if (picked.compute != info.queue_family) { info.compute_family = picked.compute; compute_count = std::min(queue_cap, families[picked.compute].queueCount); VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; q.queueFamilyIndex = picked.compute; q.queueCount = compute_count; q.pQueuePriorities = priorities.data(); queue_infos.push_back(q); } if (picked.copy != info.queue_family) { info.copy_family = picked.copy; if (picked.copy != picked.compute) { copy_count = std::min(queue_cap, families[picked.copy].queueCount); VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; q.queueFamilyIndex = picked.copy; q.queueCount = copy_count; q.pQueuePriorities = priorities.data(); queue_infos.push_back(q); } } // The GPU address arena binds its memory blocks on a queue nothing else submits to (src/arena_backing.h): a bind // then never waits behind a submission that waits for a fence the CPU signals later. A family with the sparse // binding bit and a queue to spare, a sparse-only family first (RADV has one). None: the arena stays one // allocation. std::uint32_t arena_bind_family = UINT32_MAX, arena_bind_index = 0; if (chosen_features.sparseBinding && chosen_features.sparseResidencyBuffer && chosen12.bufferDeviceAddress) { std::vector used(family_count, 0); for (const auto& q : queue_infos) used[q.queueFamilyIndex] = q.queueCount; const auto picked_bind = leonida::pick_arena_bind_queue(families.data(), family_count, used.data(), std::uint32_t(priorities.size())); arena_bind_family = picked_bind.family; arena_bind_index = picked_bind.index; if (arena_bind_family != UINT32_MAX) { bool listed = false; for (auto& q : queue_infos) if (q.queueFamilyIndex == arena_bind_family) { ++q.queueCount; listed = true; } if (!listed) { VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; q.queueFamilyIndex = arena_bind_family; q.queueCount = 1; q.pQueuePriorities = priorities.data(); queue_infos.push_back(q); } } } info.sparse_address_space = chosen.limits.sparseAddressSpaceSize; info.residency_non_resident_strict = chosen.sparseProperties.residencyNonResidentStrict == VK_TRUE; VkPhysicalDeviceFeatures enable{}; enable.sparseBinding = chosen_features.sparseBinding; enable.sparseResidencyBuffer = chosen_features.sparseResidencyBuffer; enable.sparseResidencyImage2D = chosen_features.sparseResidencyImage2D; enable.sparseResidencyAliased = chosen_features.sparseResidencyAliased; info.texture_compression_bc = chosen_bc; enable.textureCompressionBC = chosen_bc ? VK_TRUE : VK_FALSE; // the game's textures are BC1-7 enable.shaderSampledImageArrayDynamicIndexing = info.bindless; enable.shaderStorageImageArrayDynamicIndexing = info.bindless; if (!chosen_features.shaderInt64) std::fprintf(stderr, "[rt] d3d12: the GPU has no shaderInt64; translated shaders (all declare Int64) will not load\n"); enable.samplerAnisotropy = info.sampler_anisotropy; enable.occlusionQueryPrecise = chosen_features.occlusionQueryPrecise; // exact D3D12 occlusion counts enable.pipelineStatisticsQuery = chosen_features.pipelineStatisticsQuery; enable.drawIndirectFirstInstance = chosen_features.drawIndirectFirstInstance; enable.multiDrawIndirect = chosen_features.multiDrawIndirect; info.draw_indirect_first_instance = enable.drawIndirectFirstInstance == VK_TRUE; info.multi_draw_indirect = enable.multiDrawIndirect == VK_TRUE; info.max_draw_indirect_count = chosen.limits.maxDrawIndirectCount; info.occlusion_query_precise = chosen_features.occlusionQueryPrecise == VK_TRUE; info.pipeline_statistics_query = chosen_features.pipelineStatisticsQuery == VK_TRUE; if (!chosen_bc) std::fprintf(stderr, "[rt] d3d12: the GPU has no BC texture support\n"); const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; // Optional: VK_EXT_host_image_copy lets WriteToSubresource/ReadFromSubresource copy on the CPU. std::uint32_t extension_count = 0; vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr); std::vector extensions(extension_count); vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, extensions.data()); info.conservative_rasterization = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0; }); info.sample_locations = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME) == 0; }); const bool has_host_image_copy = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME) == 0; }); VkPhysicalDeviceImageViewMinLodFeaturesEXT min_lod{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_MIN_LOD_FEATURES_EXT}; if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME) == 0; })) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &min_lod}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.image_view_min_lod = min_lod.minLod == VK_TRUE; if (info.image_view_min_lod) { min_lod.pNext = *v13.next(); *v13.next() = &min_lod; } } const char* divisor_extension = nullptr; for (const char* name : {VK_KHR_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME, VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME}) { if (std::any_of(extensions.begin(), extensions.end(), [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; })) { divisor_extension = name; break; } } VkPhysicalDeviceVertexAttributeDivisorFeaturesKHR divisor_khr{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_KHR}; VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT divisor_ext{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT}; if (divisor_extension) { const bool is_khr = std::strcmp(divisor_extension, VK_KHR_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME) == 0; VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, is_khr ? static_cast(&divisor_khr) : static_cast(&divisor_ext)}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.vertex_attribute_divisor = (is_khr ? divisor_khr.vertexAttributeInstanceRateDivisor : divisor_ext.vertexAttributeInstanceRateDivisor) == VK_TRUE; if (info.vertex_attribute_divisor) { if (is_khr) { divisor_khr.pNext = *v13.next(); *v13.next() = &divisor_khr; } else { divisor_ext.pNext = *v13.next(); *v13.next() = &divisor_ext; } } } VkPhysicalDeviceHostImageCopyFeaturesEXT host_copy{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_FEATURES_EXT}; if (has_host_image_copy) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &host_copy}; vkGetPhysicalDeviceFeatures2(info.physical, &query); } const char* host_image_copy_name = VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME; // LEONIDA_HOST_IMAGE_COPY (src/host_image_copy_policy.h). Off, the extension is neither enabled nor chained, so no // image gets host-transfer usage and every CPU texture copy takes the staging submit, as on a device without it. const leonida::HostImageCopyChoice host_copy_choice = leonida::host_image_copy_choice( std::getenv("LEONIDA_HOST_IMAGE_COPY"), has_host_image_copy && host_copy.hostImageCopy, chosen.vendorID); info.host_image_copy = host_copy_choice.use; if (info.host_image_copy) { host_copy.pNext = *v13.next(); // after the conditional rendering features, if any *v13.next() = &host_copy; } std::fprintf(stderr, "[rt] d3d12: host image copy: %s (%s)%s\n", info.host_image_copy ? "on" : "off", host_copy_choice.reason, info.host_image_copy ? "" : "; CPU texture copies use a staging submit"); const auto has_device_extension = [&](const char* name) { return std::any_of(extensions.begin(), extensions.end(), [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); }; info.depth_range_unrestricted = has_device_extension(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME); info.store_op_none = v13.store_op_none; const char* sliced_name = VK_EXT_IMAGE_SLICED_VIEW_OF_3D_EXTENSION_NAME; VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT sliced{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_SLICED_VIEW_OF_3D_FEATURES_EXT}; if (info.robust_image_access && has_device_extension(sliced_name)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &sliced}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.sliced_3d_uav = sliced.imageSlicedViewOf3D == VK_TRUE; if (info.sliced_3d_uav) { sliced.pNext = *v13.next(); *v13.next() = &sliced; } } // The pixel-shader extensions translated shaders can declare (VulkanDeviceInfo::fragment_shader_barycentric and // the two after it). Each is queried, and enabled with its feature where the GPU has it. VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR barycentric{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; if (has_device_extension(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &barycentric}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.fragment_shader_barycentric = barycentric.fragmentShaderBarycentric == VK_TRUE; if (info.fragment_shader_barycentric) { barycentric.pNext = *v13.next(); *v13.next() = &barycentric; } } VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT interlock{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT}; if (has_device_extension(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &interlock}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.fragment_shader_interlock = interlock.fragmentShaderPixelInterlock == VK_TRUE; if (info.fragment_shader_interlock) { interlock.fragmentShaderSampleInterlock = VK_FALSE; // the translator only declares the pixel interlock interlock.fragmentShaderShadingRateInterlock = VK_FALSE; interlock.pNext = *v13.next(); *v13.next() = &interlock; } } #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME VkPhysicalDeviceMaintenance8FeaturesKHR maintenance8{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_8_FEATURES_KHR}; if (has_device_extension(VK_KHR_MAINTENANCE_8_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance8}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.maintenance8 = maintenance8.maintenance8 == VK_TRUE; if (info.maintenance8) { maintenance8.pNext = *v13.next(); *v13.next() = &maintenance8; } } #endif #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME // VK_KHR_maintenance5 also supplies vkCmdBindIndexBuffer2KHR. A8 support is checked separately: only where // that format can be sampled, copied (every texture is a transfer source and destination) and is a colour // attachment the GPU can blend do we also use that format for A8 render targets. VkPhysicalDeviceMaintenance5FeaturesKHR maintenance5{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR}; if (has_device_extension(VK_KHR_MAINTENANCE_5_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance5}; vkGetPhysicalDeviceFeatures2(info.physical, &query); VkFormatProperties a8{}; if (vkGetPhysicalDeviceFormatProperties) vkGetPhysicalDeviceFormatProperties(info.physical, VK_FORMAT_A8_UNORM_KHR, &a8); const VkFormatFeatureFlags needed = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT | VK_FORMAT_FEATURE_TRANSFER_SRC_BIT | VK_FORMAT_FEATURE_TRANSFER_DST_BIT; info.a8_render_target = maintenance5.maintenance5 == VK_TRUE && (a8.optimalTilingFeatures & needed) == needed; } #endif #ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME VkPhysicalDeviceMaintenance10FeaturesKHR maintenance10{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_10_FEATURES_KHR}; // Vulkan 1.3 makes the 64-bit optimal tiling format features used by this path core. if (v13.core && has_device_extension(VK_KHR_MAINTENANCE_10_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance10}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.maintenance10 = maintenance10.maintenance10 == VK_TRUE; if (info.maintenance10) { maintenance10.pNext = *v13.next(); *v13.next() = &maintenance10; } } #endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME // VK_KHR_shader_fma: OpFmaKHR is a single-rounding multiply-add in SPIR-V (GLSL.std.450 Fma may round twice). // Translated shaders built with `rdna2spirv.py --fma khr` need it (index capability FMAKHR, feature // shaderFmaFloat32); when it is missing they must not be created, so use `--fma glsl` there. VkPhysicalDeviceShaderFmaFeaturesKHR shader_fma{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR}; if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_KHR_SHADER_FMA_EXTENSION_NAME) == 0; })) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &shader_fma}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.shader_fma = shader_fma.shaderFmaFloat32 == VK_TRUE; if (info.shader_fma) { shader_fma.pNext = *v13.next(); *v13.next() = &shader_fma; } } #endif VkPhysicalDeviceShaderClockFeaturesKHR shader_clock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR}; if (has_device_extension(VK_KHR_SHADER_CLOCK_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &shader_clock}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.shader_subgroup_clock = shader_clock.shaderSubgroupClock == VK_TRUE; info.shader_device_clock = shader_clock.shaderDeviceClock == VK_TRUE; if (info.shader_subgroup_clock || info.shader_device_clock) { shader_clock.pNext = *v13.next(); *v13.next() = &shader_clock; } } // What graphics PSOs may ask for: different blend state per render target, wireframe, a depth-bias clamp and // SRC1 blend factors. Enabled where the GPU has them; a PSO that needs a missing one is refused. enable.independentBlend = chosen_features.independentBlend; enable.fillModeNonSolid = chosen_features.fillModeNonSolid; enable.depthBiasClamp = chosen_features.depthBiasClamp; enable.dualSrcBlend = chosen_features.dualSrcBlend; enable.logicOp = chosen_features.logicOp; enable.depthClamp = chosen_features.depthClamp; enable.multiViewport = chosen_features.multiViewport; enable.depthBounds = chosen_features.depthBounds; // DEPTH_STENCIL1/2 DepthBoundsTestEnable, OMSetDepthBounds enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus) // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, formatless image // reads and writes, gather offsets (ImageGatherExtended), LOD-clamped samples (MinLod), and the layer or viewport // a vertex shader writes (above, in Vulkan 1.2). Enabled where the GPU has them; without one, vkCreateShaderModule // reports the capability (VUID-...-pCode-08740). enable.shaderInt64 = chosen_features.shaderInt64; enable.shaderFloat64 = chosen_features.shaderFloat64; enable.shaderInt16 = chosen_features.shaderInt16; enable.shaderClipDistance = chosen_features.shaderClipDistance; enable.shaderCullDistance = chosen_features.shaderCullDistance; enable.shaderStorageImageWriteWithoutFormat = chosen_features.shaderStorageImageWriteWithoutFormat; enable.shaderStorageImageExtendedFormats = chosen_features.shaderStorageImageExtendedFormats; enable.shaderStorageImageReadWithoutFormat = chosen_features.shaderStorageImageReadWithoutFormat; enable.shaderImageGatherExtended = chosen_features.shaderImageGatherExtended; enable.shaderResourceMinLod = chosen_features.shaderResourceMinLod; // A translated pixel shader that stores to an image or does an image atomic declares that storage image without // NonWritable (1,018 of the corpus's 1,038 image-atomic shaders are pixel shaders), and Vulkan allows that outside // a compute shader only with these two features: fragmentStoresAndAtomics for the pixel stage, // vertexPipelineStoresAndAtomics for vertex and geometry shaders. Enabled where the GPU has them; a graphics PSO // whose shader needs a missing one is refused (PipelineState::create_graphics). enable.fragmentStoresAndAtomics = chosen_features.fragmentStoresAndAtomics; enable.vertexPipelineStoresAndAtomics = chosen_features.vertexPipelineStoresAndAtomics; // GetClockCalibration reads both clocks at once with calibrated timestamps (KHR, or the older EXT). const char* calibrated = nullptr; for (const char* name : {VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME, VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME}) { for (const auto& extension : extensions) if (std::strcmp(extension.extensionName, name) == 0) calibrated = name; if (calibrated) break; } info.calibrated_timestamps = calibrated != nullptr; // Switching a vsync swapchain to IMMEDIATE or FIFO_RELAXED per present (PresentX's ImmediateThresholdPercent): // the KHR extension (promoted from the EXT one, same structures) with the surface extension of the same name // on the instance, else the EXT one. Only enabled where the instance has the surface half and the GPU the feature. const char* swapchain_m1_name = nullptr; #ifdef LEONIDA_SWAPCHAIN_MAINTENANCE1 VkPhysicalDeviceSwapchainMaintenance1FeaturesEXT swapchain_m1{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_EXT}; if (has_swapchain && instance_has_surface) { const auto device_has = [&](const char* name) { return std::any_of(extensions.begin(), extensions.end(), [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); }; if (surface_maintenance1_khr && device_has("VK_KHR_swapchain_maintenance1")) swapchain_m1_name = "VK_KHR_swapchain_maintenance1"; else if (surface_maintenance1_ext && device_has("VK_EXT_swapchain_maintenance1")) swapchain_m1_name = "VK_EXT_swapchain_maintenance1"; if (swapchain_m1_name) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &swapchain_m1}; vkGetPhysicalDeviceFeatures2(info.physical, &query); if (swapchain_m1.swapchainMaintenance1 == VK_TRUE) { swapchain_m1.pNext = *v13.next(); *v13.next() = &swapchain_m1; } else { swapchain_m1_name = nullptr; } } } #endif info.swapchain_maintenance1 = swapchain_m1_name != nullptr; // Optional: VK_EXT_custom_border_color lets samplers use custom float and integer border colours. const bool has_custom_border = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_CUSTOM_BORDER_COLOR_EXTENSION_NAME) == 0; }); VkPhysicalDeviceCustomBorderColorFeaturesEXT custom_border{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_FEATURES_EXT}; if (has_custom_border) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &custom_border}; vkGetPhysicalDeviceFeatures2(info.physical, &query); } const char* custom_border_name = VK_EXT_CUSTOM_BORDER_COLOR_EXTENSION_NAME; info.custom_border_color = has_custom_border && custom_border.customBorderColors; info.custom_border_color_without_format = has_custom_border && custom_border.customBorderColorWithoutFormat; if (info.custom_border_color) { custom_border.pNext = *v13.next(); // where later feature structs go since #1706 *v13.next() = &custom_border; } else { std::fprintf(stderr, "[rt] d3d12: no VK_EXT_custom_border_color; custom sampler border colours fall back to transparent black\n"); } // Optional: VK_EXT_robustness2's nullDescriptor makes set 0's storage fallbacks null descriptors, so a store or // atomic through a null UAV (a zero T#, or one the layer refused) is dropped and a load reads zero, as on the // console (vulkan_bindless.h). Robust buffer access is selected independently for bounded indexed indirect draws. VkPhysicalDeviceRobustness2FeaturesEXT robustness2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT}; if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_ROBUSTNESS_2_EXTENSION_NAME) == 0; })) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &robustness2}; vkGetPhysicalDeviceFeatures2(info.physical, &query); info.null_descriptor = robustness2.nullDescriptor == VK_TRUE; #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME info.robust_index_view = leonida::can_enable_robust_index_view( info.physical, vkGetPhysicalDeviceProperties2, info.draw_indirect_first_instance && maintenance5.maintenance5, chosen_features.robustBufferAccess && robustness2.robustBufferAccess2, info.bindless); #endif if (info.null_descriptor || info.robust_index_view) { robustness2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT}; robustness2.nullDescriptor = info.null_descriptor; robustness2.robustBufferAccess2 = info.robust_index_view; enable.robustBufferAccess = info.robust_index_view; robustness2.pNext = *v13.next(); *v13.next() = &robustness2; } } #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME if (info.a8_render_target || info.robust_index_view) { maintenance5.pNext = *v13.next(); *v13.next() = &maintenance5; } #endif if (!info.null_descriptor) std::fprintf(stderr, "[rt] d3d12: no VK_EXT_robustness2 nullDescriptor; stores through null UAVs land in " "storage fallback images instead of being dropped\n"); // Optional: VK_EXT_shader_image_atomic_int64 enables 64-bit image atomics on 2D R64_UINT storage views // (bindless set 0 binding 29, backed by 2D R32G32_* UAV images). VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT image_atomic_int64{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_IMAGE_ATOMIC_INT64_FEATURES_EXT}; if (enable.shaderInt64 && vkGetPhysicalDeviceFormatProperties && has_device_extension(VK_EXT_SHADER_IMAGE_ATOMIC_INT64_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &image_atomic_int64}; vkGetPhysicalDeviceFeatures2(info.physical, &query); VkFormatProperties r64{}; vkGetPhysicalDeviceFormatProperties(info.physical, VK_FORMAT_R64_UINT, &r64); constexpr VkFormatFeatureFlags kR64AtomicFeatures = VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT | VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT; const bool r64_transfer_ok = info.null_descriptor || (r64.optimalTilingFeatures & VK_FORMAT_FEATURE_TRANSFER_DST_BIT) != 0; info.shader_image_int64_atomics = image_atomic_int64.shaderImageInt64Atomics == VK_TRUE && (r64.optimalTilingFeatures & kR64AtomicFeatures) == kR64AtomicFeatures && r64_transfer_ok; if (info.shader_image_int64_atomics) { image_atomic_int64 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_IMAGE_ATOMIC_INT64_FEATURES_EXT}; image_atomic_int64.shaderImageInt64Atomics = VK_TRUE; image_atomic_int64.pNext = *v13.next(); *v13.next() = &image_atomic_int64; } } // Optional: VK_EXT_external_memory_host lets OpenExistingHeapFromAddress import the caller's committed memory as // the heap's backing, so the GPU reads what the CPU writes there without a copy. if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { return std::strcmp(e.extensionName, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) == 0; })) { VkPhysicalDeviceExternalMemoryHostPropertiesEXT host_memory{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT}; VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host_memory}; vkGetPhysicalDeviceProperties2(info.physical, &properties); info.host_pointer_alignment = host_memory.minImportedHostPointerAlignment; } VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12}; device_info.queueCreateInfoCount = std::uint32_t(queue_infos.size()); device_info.pQueueCreateInfos = queue_infos.data(); device_info.pEnabledFeatures = &enable; info.features = enable; std::vector device_extensions; v13.add_extensions(device_extensions); if (info.depth_range_unrestricted) device_extensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME); info.pipeline_creation_feedback = v13.core || has_device_extension(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); info.pipeline_cache_control = v13.core && v13.pipeline_creation_cache_control; if (trace_pipeline_compile() && !v13.core && info.pipeline_creation_feedback) device_extensions.push_back(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); if (info.sample_locations) device_extensions.push_back(VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME); if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension); if (info.conditional_rendering) device_extensions.push_back(conditional_extension); if (info.host_image_copy) device_extensions.push_back(host_image_copy_name); if (info.sliced_3d_uav) device_extensions.push_back(sliced_name); if (info.fragment_shader_barycentric) device_extensions.push_back(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME); if (info.fragment_shader_interlock) device_extensions.push_back(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME); #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME if (info.maintenance8) device_extensions.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME); #endif // Under its own guard only: headers or a driver without VK_KHR_maintenance8 still have the A8 path, and // a8_render_target is never set without this extension being enabled. #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME if (info.a8_render_target || info.robust_index_view) device_extensions.push_back(VK_KHR_MAINTENANCE_5_EXTENSION_NAME); #endif #ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME if (info.maintenance10) device_extensions.push_back(VK_KHR_MAINTENANCE_10_EXTENSION_NAME); #endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME if (info.shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME); #endif if (info.shader_subgroup_clock || info.shader_device_clock) device_extensions.push_back(VK_KHR_SHADER_CLOCK_EXTENSION_NAME); if (calibrated) device_extensions.push_back(calibrated); // VK_KHR_swapchain requires VK_KHR_surface on the instance (VUID-vkCreateDevice-ppEnabledExtensionNames-01387). if (has_swapchain && instance_has_surface) device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); if (swapchain_m1_name) device_extensions.push_back(swapchain_m1_name); if (info.mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); if (info.transform_feedback) device_extensions.push_back(VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME); if (info.ray_tracing) { device_extensions.push_back(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME); device_extensions.push_back(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); device_extensions.push_back(VK_KHR_RAY_QUERY_EXTENSION_NAME); } info.presentation = has_swapchain && instance_has_surface; info.swapchain_colorspace = info.presentation && swapchain_colorspace_enabled; if (info.custom_border_color) device_extensions.push_back(custom_border_name); if (info.null_descriptor || info.robust_index_view) device_extensions.push_back(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME); if (info.shader_image_int64_atomics) device_extensions.push_back(VK_EXT_SHADER_IMAGE_ATOMIC_INT64_EXTENSION_NAME); if (info.host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); // Optional: VK_EXT_memory_budget gives the GPU memory in use and the budget (vulkan_vram_budget, the title HUD). info.memory_budget = has_device_extension(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME); if (info.memory_budget) device_extensions.push_back(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME); leonida::DeviceFaultFeatures fault_features; const bool aftermath = leonida::aftermath::enable(); // already on, before the instance: see above char device_fault[2]{}; // LEONIDA_DEVICE_FAULT=1: fault info, checkpoints and NVIDIA's diagnostics config. =2: fault info and checkpoints // only — the diagnostics config compiles pipelines with debug info under other cache keys, so =2 keeps the warmed // pipeline journal usable for a boot that only wants the fault report. if (GetEnvironmentVariableA("LEONIDA_DEVICE_FAULT", device_fault, sizeof(device_fault)) == 1 && (device_fault[0] == '1' || device_fault[0] == '2')) { info.device_fault_diagnostics = true; const bool with_config = device_fault[0] == '1'; // LEONIDA_DEVICE_MARKERS=1: also VK_AMD_buffer_marker, for the AMD breadcrumbs (vulkan_device_markers.h). const auto fault = fault_features.enable(info.physical, vkGetPhysicalDeviceFeatures2, extensions, device_extensions, device_info, {true, with_config, leonida::aftermath::extra_config_flags(), leonida::device_markers_requested()}); info.device_fault_info = fault.fault; info.device_checkpoints = fault.checkpoints; info.device_diagnostics_config = fault.diagnostics_config; info.device_markers = fault.markers; } else if (aftermath) { // The diagnostics config alone: shader debug info, resource tracking and automatic checkpoints in the dump. const auto fault = fault_features.enable(info.physical, vkGetPhysicalDeviceFeatures2, extensions, device_extensions, device_info, {false, true, leonida::aftermath::extra_config_flags()}); info.device_diagnostics_config = fault.diagnostics_config; } if (leonida::device_markers_requested() && !info.device_fault_diagnostics) std::fprintf(stderr, "[rt] device-markers: unavailable: LEONIDA_DEVICE_MARKERS=1 needs LEONIDA_DEVICE_FAULT=1 " "or 2\n"); if (aftermath && !info.device_diagnostics_config) std::fprintf(stderr, "[rt] aftermath: VK_NV_device_diagnostics_config unavailable; the dump has no shader " "debug info, resource tracking or checkpoints\n"); leonida::address_binding::enable_device(owned.instance, info.physical, vkGetPhysicalDeviceFeatures2, extensions, device_extensions, device_info); device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); device_info.ppEnabledExtensionNames = device_extensions.empty() ? nullptr : device_extensions.data(); if (vkCreateDevice(info.physical, &device_info, nullptr, &owned.device) != VK_SUCCESS) return fail("vkCreateDevice failed"); info.device = owned.device; owned.destroy_device = reinterpret_cast(vkGetDeviceProcAddr(owned.device, "vkDestroyDevice")); info.command_queues.resize(command_queue_count); const auto get_queue = reinterpret_cast(vkGetDeviceProcAddr(owned.device, "vkGetDeviceQueue")); for (std::uint32_t i = 0; i < command_queue_count; ++i) get_queue(owned.device, info.queue_family, i, &info.command_queues[i]); if (compute_count) { // Copies on the async-compute family split its queues with the compute queues: one VkQueue per live queue. const bool split = info.copy_family == info.compute_family && compute_count > 1; const std::uint32_t for_compute = split ? compute_count / 2 : compute_count; for (std::uint32_t i = 0; i < compute_count; ++i) { VkQueue q = VK_NULL_HANDLE; get_queue(owned.device, info.compute_family, i, &q); (i < for_compute ? info.compute_queues : info.copy_queues).push_back(q); } if (info.copy_family == info.compute_family && !split) info.copy_family = UINT32_MAX; } for (std::uint32_t i = 0; i < copy_count; ++i) { VkQueue q = VK_NULL_HANDLE; get_queue(owned.device, info.copy_family, i, &q); info.copy_queues.push_back(q); } info.queue = info.command_queues[0]; if (arena_bind_family != UINT32_MAX) get_queue(owned.device, arena_bind_family, arena_bind_index, &info.arena_bind_queue); info.max_push_constants_size = chosen.limits.maxPushConstantsSize; info.push_constants_need_fallback = (info.max_push_constants_size < 144); std::fprintf(stderr, "[rt] d3d12: Vulkan device: %s (maxPushConstantsSize: %u bytes)\n", chosen.deviceName, chosen.limits.maxPushConstantsSize); std::fprintf(stderr, "[rt] d3d12: subgroup sizes %u..%u (default %u), requirable in stages 0x%x, subgroupSizeControl %s, " "computeFullSubgroups %s\n", info.subgroup.min_size, info.subgroup.max_size, info.subgroup.default_size, unsigned(info.subgroup.required_stages), info.subgroup.subgroup_size_control ? "on" : "off", info.subgroup.compute_full_subgroups ? "on" : "off"); if (info.push_constants_need_fallback) { std::fprintf(stderr, "[rt] d3d12: WARNING: GPU maxPushConstantsSize (%u bytes) is below the 144 bytes required by " "the shader contract; uniform-buffer fallback required for the 16-byte tail\n", chosen.limits.maxPushConstantsSize); } auto* device = new Device(info); device->own(owned); // destroyed with the device from here on, even on failure if (!device->ok()) { device->Release(); return E_FAIL; } return hand_out(device, riid, out); } // A Vulkan device made as `gta6rt --run` makes it, for building the library's compute pipelines with no title // (--precompile-pipelines, --compile-server), with the two layouts create_compute makes. class BuildHost { public: explicit BuildHost(const char* tag) : tag_(tag) {} BuildHost(const BuildHost&) = delete; BuildHost& operator=(const BuildHost&) = delete; ~BuildHost() { if (!d3d_) return; if (device_) { auto& vk = device_->context->vk; if (plain_) vk.vkDestroyPipelineLayout(device_->info.device, plain_, nullptr); if (with_set0_) vk.vkDestroyPipelineLayout(device_->info.device, with_set0_, nullptr); } d3d_->Release(); } bool open() { // The GPU address arena holds nothing here and does not change a pipeline: 64 MB, not a title's 2 GB. _putenv_s("LEONIDA_ARENA_MB", "64"); compile_helper::build_host = true; if (FAILED(create_vulkan_device_standalone(__uuidof(ID3D12Device), reinterpret_cast(&d3d_), QueueTestSettings::ignore)) || !d3d_) { d3d_ = nullptr; std::fprintf(stderr, "%s the Vulkan device could not be created\n", tag_); return false; } Device* device = Device::from(d3d_); if (!device) return false; device_ = &device->build_state(); DeviceState& state = *device_; library_ = state.library(); if (!library_) { std::fprintf(stderr, "%s no translated shader library (LEONIDA_SHADERS)\n", tag_); return false; } if (pipeline_journal_dir().empty()) std::fprintf(stderr, "%s the pipeline journal is off (LEONIDA_PIPELINE_JOURNAL=0 or " "LEONIDA_PIPELINE_CACHE_BYTES=0): only the driver's own cache is filled\n", tag_); state.pipeline_cache(); // the shared cache and the journal's upkeep, as at a title's first pipeline // Every pipeline goes into a journal file: one found in the shared cache would not be. state.journal_ask_shared = false; auto& vk = state.context->vk; const VkDevice dev = state.info.device; if (state.info.max_push_constants_size && state.info.max_push_constants_size < sizeof(leonida::ShaderUserData)) { std::fprintf(stderr, "%s maxPushConstantsSize %u is under the shaders' %zu bytes: the runtime builds no " "compute pipeline on this device\n", tag_, state.info.max_push_constants_size, sizeof(leonida::ShaderUserData)); return false; } const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(leonida::ShaderUserData)}; VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &plain_) != VK_SUCCESS) return false; if (state.bindless) { const VkDescriptorSetLayout set0 = state.bindless->layout(); layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set0; if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &with_set0_) != VK_SUCCESS) with_set0_ = VK_NULL_HANDLE; } if (const auto get_props = reinterpret_cast( state.info.get_instance_proc ? state.info.get_instance_proc(state.info.instance, "vkGetPhysicalDeviceProperties") : nullptr)) { VkPhysicalDeviceProperties props{}; get_props(state.info.physical, &props); max_shared_ = props.limits.maxComputeSharedMemorySize; } return true; } DeviceState& state() { return *device_; } const leonida::ShaderLibrary* library() const { return library_; } // Why create_compute could not build the entry on this device, or null. LEONIDA_SKIP_COMPUTE is not a reason here: // it drops a program's dispatches at play, and each caller decides whether it also keeps the program unbuilt. const char* unbuildable(const leonida::ShaderEntry& entry, std::size_t bytes) const { if (!bytes) return "no .spv"; if (entry.binding_count && !with_set0_) return "set-0 bindings and no bindless set"; if (entry.uses_image_int64_atomics && !device_->info.shader_image_int64_atomics) return "requires shaderImageInt64Atomics"; if (entry.lds_bytes && max_shared_ && entry.lds_bytes > max_shared_) return "workgroup memory over the limit"; return nullptr; } ComputeBuild build(const leonida::ShaderEntry& entry, const ComputeBuildOptions& options) { const leonida::SubgroupRequest subgroup = leonida::decide_subgroup_size(entry, device_->info.subgroup); return build_compute_pipeline(*device_, entry, entry.binding_count ? with_set0_ : plain_, subgroup, options); } void destroy(VkPipeline pipeline) { if (pipeline) device_->context->vk.vkDestroyPipeline(device_->info.device, pipeline, nullptr); } private: const char* tag_; ID3D12Device* d3d_ = nullptr; DeviceState* device_ = nullptr; const leonida::ShaderLibrary* library_ = nullptr; VkPipelineLayout plain_ = VK_NULL_HANDLE, with_set0_ = VK_NULL_HANDLE; std::uint32_t max_shared_ = 0; }; // gta6rt --precompile-pipelines (d3d12_precompile.h). int precompile_compute_pipelines(const PrecompileOptions& options) { using Clock = std::chrono::steady_clock; const auto began = Clock::now(); BuildHost host("[precompile]"); if (!host.open()) return 1; const leonida::ShaderLibrary* library = host.library(); // What to build: every compute entry the runtime could create a pipeline for. LEONIDA_SKIP_COMPUTE is a setting // for play (the game drops the listed programs' dispatches); the journal is kept for every program unless // --skip-listed asks to leave them out too, so a later run without the list finds them built. struct Job { const leonida::ShaderEntry* entry; std::size_t bytes; }; std::vector jobs; std::size_t not_buildable = 0, filtered = 0, listed = 0, listed_left_out = 0; for (const leonida::ShaderEntry* entry : library->stage_entries("cs")) { if (!options.filters.empty() && std::none_of(options.filters.begin(), options.filters.end(), [&](const std::string& part) { return entry->name.find(part) != std::string::npos; })) { ++filtered; continue; } const std::size_t bytes = library->spirv_bytes(*entry); if ((options.min_bytes && bytes < options.min_bytes) || (options.max_bytes && bytes > options.max_bytes)) { ++filtered; continue; } if (skip_compute(entry->name)) { ++listed; if (options.skip_listed) { ++listed_left_out; std::fprintf(stderr, "[precompile] %s: not built (LEONIDA_SKIP_COMPUTE, --skip-listed)\n", entry->name.c_str()); continue; } } if (const char* why = host.unbuildable(*entry, bytes)) { ++not_buildable; std::fprintf(stderr, "[precompile] %s: not built (%s)\n", entry->name.c_str(), why); continue; } jobs.push_back({entry, bytes}); } std::stable_sort(jobs.begin(), jobs.end(), [&](const Job& a, const Job& b) { return options.smallest_first ? a.bytes < b.bytes : a.bytes > b.bytes; }); if (options.limit && jobs.size() > options.limit) { filtered += jobs.size() - options.limit; jobs.resize(options.limit); } std::uint64_t total_bytes = 0; for (const Job& job : jobs) total_bytes += job.bytes; const unsigned threads = (std::max)(1u, options.threads); const unsigned big_threads = options.big_threads ? (std::min)(options.big_threads, threads) : threads; if (listed && !options.skip_listed) std::fprintf(stderr, "[precompile] LEONIDA_SKIP_COMPUTE names %zu of the entries: built anyway, since the list " "drops their dispatches at play only (--skip-listed leaves them out of this run)\n", listed); std::fprintf(stderr, "[precompile] %zu compute entries to build (%.1f MB of SPIR-V; %zu filtered out, %zu left " "out by --skip-listed, %zu not buildable), %s first, %u thread(s), at most %u on modules over " "%zu bytes; journal %ls\n", jobs.size(), double(total_bytes) / 1e6, filtered, listed_left_out, not_buildable, options.smallest_first ? "smallest" : "largest", threads, big_threads, options.big_bytes, pipeline_journal_dir().c_str()); if (options.dry_run) { for (const Job& job : jobs) std::printf("%zu %s\n", job.bytes, job.entry->name.c_str()); return 0; } std::atomic next{0}; std::mutex progress_mutex; std::size_t done = 0, compiled = 0, skipped = 0, hits = 0, failed = 0, journaled = 0, elsewhere = 0; std::uint64_t done_bytes = 0; std::mutex big_mutex; std::condition_variable big_free; unsigned big_running = 0; auto worker = [&] { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); for (;;) { const std::size_t i = next.fetch_add(1); if (i >= jobs.size()) return; const Job& job = jobs[i]; const bool big = job.bytes > options.big_bytes; if (big) { std::unique_lock lock(big_mutex); big_free.wait(lock, [&] { return big_running < big_threads; }); ++big_running; } ComputeBuildOptions build_options; build_options.trigger = "precompile"; build_options.serialize_big = false; // nothing else is building; big_threads bounds them instead build_options.skip_journaled = !options.rebuild; build_options.use_helper = options.via_helper; build_options.mark_building = !options.via_helper; // an entry another process is compiling is left to it ComputeBuild build; try { build = host.build(*job.entry, build_options); } catch (const std::exception& e) { std::fprintf(stderr, "[precompile] %s: %s\n", job.entry->name.c_str(), e.what()); } host.destroy(build.pipeline); if (big) { std::lock_guard lock(big_mutex); --big_running; big_free.notify_one(); } std::lock_guard lock(progress_mutex); ++done; done_bytes += job.bytes; const char* what = "failed"; if (build.skipped) ++skipped, ++journaled, what = "journaled already"; else if (build.busy) ++skipped, ++elsewhere, what = "being built by another process"; else if (build.result != VK_SUCCESS || (!build.pipeline && !build.skipped)) ++failed; else if (build.journal_hit || build.from_shared) ++hits, what = "found in a cache"; else ++compiled, what = build.journaled ? "compiled and journaled" : "compiled (not journaled)"; const double elapsed = std::chrono::duration(Clock::now() - began).count(); const double eta = done_bytes ? elapsed / double(done_bytes) * double(total_bytes - done_bytes) : 0.0; // Skips are not logged one by one (a resumed run skips thousands); every 100th is, with the counts. if (!build.skipped || done % 100 == 0 || done == jobs.size()) std::fprintf(stderr, "[precompile] %zu/%zu %s (%zu B): %s in %.1f s (VkResult %d) | %zu compiled, %zu " "from a cache, %zu skipped, %zu failed; %.0f s elapsed, ~%.0f s left by size\n", done, jobs.size(), job.entry->name.c_str(), job.bytes, what, double(build.ms) / 1000.0, int(build.result), compiled, hits, skipped, failed, elapsed, eta); } }; std::vector pool; for (unsigned t = 0; t < threads; ++t) pool.emplace_back(worker); for (std::thread& t : pool) t.join(); // One line for the whole run: what was built, what was there already, and what was left out and why. std::fprintf(stderr, "[precompile] done: %zu built (%zu compiled, %zu from a cache), %zu journaled already, %zu " "being built by another process, %zu failed; left out: %zu of %zu listed in " "LEONIDA_SKIP_COMPUTE%s, %zu not buildable, %zu filtered out; in %.0f s\n", compiled + hits, compiled, hits, journaled, elsewhere, failed, listed_left_out, listed, options.skip_listed ? " (--skip-listed)" : "", not_buildable, filtered, std::chrono::duration(Clock::now() - began).count()); return failed ? 2 : 0; } // What a compute pipeline's journal name depends on besides its module: a name remembered for a module is good for // another run while this is unchanged (compile_server's index). std::uint64_t journal_name_context(DeviceState& state) { leonida::pipeline_journal::Hasher hash; hash.text("journal-name-context"); hash.value(std::uint32_t(sizeof(leonida::ShaderUserData))); const leonida::SubgroupSizeCaps& sub = state.info.subgroup; hash.value(std::uint32_t(sub.subgroup_size_control)); hash.value(std::uint32_t(sub.compute_full_subgroups)); hash.value(sub.min_size); hash.value(sub.max_size); hash.value(sub.default_size); hash.value(std::uint32_t(sub.required_stages)); hash.value(std::uint32_t(state.info.device_diagnostics_config)); if (state.info.device_diagnostics_config) hash.value(std::uint32_t(leonida::aftermath::extra_config_flags())); if (state.bindless) hash_bindless_layout(hash, state.bindless->features()); return hash.digest(); } // gta6rt --compile-server (d3d12_compile_helper.h): builds what the games using this journal ask for, most urgent // first, and with nothing asked fills the rest of the library, smallest module first, at idle priority. int compile_server(const CompileServerOptions& options) { namespace helper = compile_helper; namespace journal = leonida::pipeline_journal; const std::filesystem::path& dir = pipeline_journal_dir(); if (dir.empty()) { std::fprintf(stderr, "[compile-server] the pipeline journal is off: nothing to serve\n"); return 1; } const auto requests = helper::requests_dir(dir); std::error_code ec; std::filesystem::create_directories(requests, ec); // One helper per journal: a second (two games, or one started by hand) leaves the requests to the first. journal::Hasher dir_hash; dir_hash.text(dir.string().c_str()); const std::wstring mutex_name = L"Local\\leonida-compile-server-" + std::to_wstring(dir_hash.digest()); const HANDLE single = CreateMutexW(nullptr, TRUE, mutex_name.c_str()); if (!single || GetLastError() == ERROR_ALREADY_EXISTS) { std::fprintf(stderr, "[compile-server] another helper serves %ls\n", dir.c_str()); return 0; } // It ends with the game that started it, at once: whatever it was building is in no file yet, and a file is // written whole or not at all. A .building marker it leaves names a dead process and is taken over. if (options.parent_pid) { const HANDLE parent = OpenProcess(SYNCHRONIZE, FALSE, options.parent_pid); if (!parent) { std::fprintf(stderr, "[compile-server] process %lu is gone\n", options.parent_pid); return 0; } std::thread([parent] { WaitForSingleObject(parent, INFINITE); TerminateProcess(GetCurrentProcess(), 0); }).detach(); } BuildHost host("[compile-server]"); if (!host.open()) return 1; const leonida::ShaderLibrary* library = host.library(); const std::vector entries = library->stage_entries("cs"); std::map by_name; for (const leonida::ShaderEntry* entry : entries) by_name.emplace(entry->name, entry); const unsigned threads = (std::max)(1u, options.threads); const unsigned idle_threads = (std::min)(options.idle_threads, threads - 1); // one is always free for a request std::fprintf(stderr, "[compile-server] serving %ls: %u thread(s) for requests, %u of them filling the library " "when nothing is asked, %zu compute entries\n", requests.c_str(), threads, idle_threads, entries.size()); std::mutex mutex; std::condition_variable wake; std::vector pending; // the last listing, most urgent first std::set busy; // stems being built here std::map elsewhere; // stems another process is building bool stop = false; std::atomic requests_done{0}, filled{0}; // A request this helper can take: listed, not being built here, not one another process was building a moment ago. auto take_locked = [&](helper::Request& out) { const auto now = std::chrono::steady_clock::now(); for (const helper::Request& request : pending) { if (busy.count(request.stem)) continue; if (const auto it = elsewhere.find(request.stem); it != elsewhere.end() && now - it->second < std::chrono::seconds(5)) continue; busy.insert(request.stem); out = request; return true; } return false; }; auto build_entry = [&](const leonida::ShaderEntry& entry, const char* trigger) { ComputeBuildOptions build_options; build_options.trigger = trigger; build_options.serialize_big = false; build_options.skip_journaled = true; build_options.use_helper = false; build_options.mark_building = true; ComputeBuild build = host.build(entry, build_options); host.destroy(build.pipeline); build.pipeline = VK_NULL_HANDLE; return build; }; auto serve = [&] { // normal priority: a title waits for these for (;;) { helper::Request request; { std::unique_lock lock(mutex); wake.wait_for(lock, std::chrono::milliseconds(100), [&] { return stop || take_locked(request); }); if (stop) return; if (request.stem.empty()) continue; } std::string failure; bool leave = false; // another process is building it: its file answers the request const auto it = by_name.find(request.name); const leonida::ShaderEntry* entry = it == by_name.end() ? nullptr : it->second; const std::size_t bytes = entry ? library->spirv_bytes(*entry) : 0; if (!entry) failure = "no compute entry of that name in this library"; else if (skip_compute(entry->name)) failure = "LEONIDA_SKIP_COMPUTE"; // the game drops its dispatches else if (const char* why = host.unbuildable(*entry, bytes)) failure = why; // LOCAL FIX (compile helper: the journal name was checked after the build): the name is hashed from the // module and this device's environment, which costs no driver call. A request from a game whose environment // differs is answered before a compile is spent on a file that game never reads; the build below would only // have found the same mismatch. if (failure.empty()) { ComputeBuildOptions key_options; key_options.trigger = "compile-server"; key_options.key_only = true; key_options.use_helper = false; const std::filesystem::path key_path = host.build(*entry, key_options).journal_path; if (!key_path.empty() && key_path.stem().string() != request.stem) failure = "its journal name here is " + key_path.stem().string() + ": the helper's environment differs from the game's"; } if (failure.empty()) { ComputeBuild build; try { build = build_entry(*entry, "compile-server"); } catch (const std::exception& e) { failure = e.what(); } if (failure.empty()) { if (build.busy) leave = true; else if (!build.skipped && (build.result != VK_SUCCESS || !(build.journaled || build.journal_hit))) failure = "not built or not journaled (VkResult " + std::to_string(int(build.result)) + ")"; else if (!leonida::pipeline_journal::entry_usable(build.journal_path, host.state().pso_identity)) failure = "requested writable journal file is missing or incompatible"; else std::fprintf(stderr, "[compile-server] %s (%zu B, priority %llu): %s in %.1f s\n", request.name.c_str(), bytes, static_cast(request.priority), build.skipped ? "journaled already" : "built and journaled", double(build.ms) / 1000.0); } } std::error_code ignored; // LOCAL FIX (compile helper: a .failed left with its .request listed): the .req goes first. A request with // no .req and no .failed is one the game reads as answered, so it builds the pipeline itself instead of // waiting for a file that is not coming (Client::state). if (!leave) std::filesystem::remove(requests / (request.stem + ".req"), ignored); if (!failure.empty()) { helper::write_line(requests / (request.stem + ".failed"), failure); std::fprintf(stderr, "[compile-server] %s: %s\n", request.name.c_str(), failure.c_str()); } if (!leave) ++requests_done; std::lock_guard lock(mutex); busy.erase(request.stem); if (leave) elsewhere[request.stem] = std::chrono::steady_clock::now(); } }; // The rest of the library, smallest module first, while nothing is asked. The journal names of modules looked at // before are kept in requests/names.idx (with each module's size and time, and what the names depend on), so a // later helper finds what is missing without reading every module again. struct Indexed { std::uint64_t size = 0; long long mtime = 0; std::string stem; }; std::map index; std::mutex index_mutex; const auto index_file = requests / "names.idx"; const std::string signature = "v1 " + std::to_string(journal_name_context(host.state())); { std::ifstream in(index_file, std::ios::binary); std::string line; if (std::getline(in, line) && line == signature) { while (std::getline(in, line)) { const auto t1 = line.find('\t'), t2 = line.find('\t', t1 + 1), t3 = line.find('\t', t2 + 1); if (t3 == std::string::npos) continue; index[line.substr(0, t1)] = {std::strtoull(line.c_str() + t1 + 1, nullptr, 10), std::strtoll(line.c_str() + t2 + 1, nullptr, 10), line.substr(t3 + 1)}; } } } auto save_index = [&] { std::string text = signature + "\n"; std::lock_guard lock(index_mutex); for (const auto& [name, item] : index) text += name + "\t" + std::to_string(item.size) + "\t" + std::to_string(item.mtime) + "\t" + item.stem + "\n"; journal::write_entry(index_file, text.data(), text.size()); }; std::vector fill_order = entries; std::vector fill_bytes(fill_order.size()); { std::vector> sized; for (const leonida::ShaderEntry* entry : entries) sized.emplace_back(library->spirv_bytes(*entry), entry); std::stable_sort(sized.begin(), sized.end(), [](const auto& x, const auto& y) { return x.first < y.first; }); for (std::size_t i = 0; i < sized.size(); ++i) { fill_order[i] = sized[i].second; fill_bytes[i] = sized[i].first; } } std::atomic fill_next{0}; std::atomic fill_unsaved{0}; auto fill = [&] { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_IDLE); for (;;) { { // Requests first: wait while one is listed that this helper could take. std::unique_lock lock(mutex); wake.wait_for(lock, std::chrono::milliseconds(200), [&] { if (stop) return true; for (const helper::Request& request : pending) if (!busy.count(request.stem)) return false; return true; }); if (stop) return; bool asked = false; for (const helper::Request& request : pending) if (!busy.count(request.stem)) asked = true; if (asked) continue; } const std::size_t i = fill_next.fetch_add(1); if (i >= fill_order.size()) { if (i == fill_order.size()) { save_index(); std::fprintf(stderr, "[compile-server] the library is in the journal (%u built while idle)\n", filled.load()); } return; } const leonida::ShaderEntry& entry = *fill_order[i]; if (skip_compute(entry.name) || host.unbuildable(entry, fill_bytes[i])) continue; std::error_code stat; const auto spv = library->spirv_file(entry); const long long mtime = static_cast(std::filesystem::last_write_time(spv, stat).time_since_epoch().count()); std::filesystem::path path; { std::lock_guard lock(index_mutex); const auto it = index.find(entry.name); if (it != index.end() && it->second.size == fill_bytes[i] && it->second.mtime == mtime) path = dir / (it->second.stem + ".bin"); } if (path.empty()) { ComputeBuildOptions key_options; key_options.key_only = true; key_options.use_helper = false; path = host.build(entry, key_options).journal_path; if (path.empty()) continue; { std::lock_guard lock(index_mutex); index[entry.name] = {fill_bytes[i], mtime, path.stem().string()}; } if (++fill_unsaved % 200 == 0) save_index(); } if (journal::entry_usable(path, host.state().pso_identity)) continue; ComputeBuild build; try { build = build_entry(entry, "idle-fill"); } catch (const std::exception& e) { std::fprintf(stderr, "[compile-server] %s: %s\n", entry.name.c_str(), e.what()); continue; } if (!build.skipped && !build.busy && build.result == VK_SUCCESS && build.journaled) { ++filled; std::fprintf(stderr, "[compile-server] idle: %s (%zu B) built and journaled in %.1f s (%zu/%zu)\n", entry.name.c_str(), fill_bytes[i], double(build.ms) / 1000.0, i + 1, fill_order.size()); } } }; std::vector pool; for (unsigned t = 0; t < threads - idle_threads; ++t) pool.emplace_back(serve); for (unsigned t = 0; t < idle_threads; ++t) pool.emplace_back(fill); auto quiet_since = std::chrono::steady_clock::now(); for (;;) { auto listing = helper::list_requests(requests); { std::lock_guard lock(mutex); pending = std::move(listing); if (!pending.empty() || !busy.empty()) quiet_since = std::chrono::steady_clock::now(); } wake.notify_all(); if (options.idle_exit_s && std::chrono::steady_clock::now() - quiet_since > std::chrono::seconds(options.idle_exit_s)) break; std::this_thread::sleep_for(std::chrono::milliseconds(50)); } { std::lock_guard lock(mutex); stop = true; } wake.notify_all(); for (std::thread& t : pool) t.join(); save_index(); std::fprintf(stderr, "[compile-server] nothing asked for %u s: done (%u requests, %u built while idle)\n", options.idle_exit_s, requests_done.load(), filled.load()); return 0; } bool has_global_realtime_privilege() { const int override_state = g_global_realtime_privilege_override.load(std::memory_order_relaxed); if (override_state >= 0) return override_state != 0; HANDLE token = nullptr; if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token)) { // Fall back to the process token only when the thread is not impersonating (ERROR_NO_TOKEN); fail closed on // ERROR_CANT_OPEN_ANONYMOUS or any other thread-token error so an impersonated caller cannot inherit the // process token's privilege. if (GetLastError() != ERROR_NO_TOKEN || !OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return false; } LUID luid{}; BOOL enabled = FALSE; if (LookupPrivilegeValueW(nullptr, L"SeIncreaseBasePriorityPrivilege", &luid)) { PRIVILEGE_SET set{}; set.PrivilegeCount = 1; set.Control = PRIVILEGE_SET_ALL_NECESSARY; set.Privilege[0].Luid = luid; set.Privilege[0].Attributes = SE_PRIVILEGE_ENABLED; if (!PrivilegeCheck(token, &set, &enabled)) enabled = FALSE; } CloseHandle(token); return enabled != FALSE; } void set_global_realtime_privilege_override_for_test(int state) { g_global_realtime_privilege_override.store(state, std::memory_order_relaxed); } HRESULT create_console_descriptor_heap(ID3D12Device* device, const D3D12_DESCRIPTOR_HEAP_DESC* desc, D3D12_GPU_VIRTUAL_ADDRESS console_address, std::uint64_t console_size, REFIID riid, void** out) { if (out) *out = nullptr; if (!device || !desc) return E_INVALIDARG; // No output: a capability check, as CreateDescriptorHeap does. if (!out) return S_FALSE; if ((desc->Flags & ~D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) || desc->NodeMask > 1 || ((desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && (desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_RTV || desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_DSV))) { return E_INVALIDARG; } ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); auto* d = Device::from(real ? real : device); if (!d) return E_INVALIDARG; return d->create_console_descriptor_heap(desc, console_address, console_size, riid, out); } UnboundTsharpStats unbound_tsharp_stats() { return unbound_tsharp_tracker().stats(); } void reset_unbound_tsharp_stats() { unbound_tsharp_tracker().reset(); } void note_refused_tsharp_for_test(std::uint64_t heap_va, std::size_t offset, const std::array& words, const char* why) { leonida::gfx10::ImageWords w; std::memcpy(w.data(), words.data(), sizeof(w)); unbound_tsharp_tracker().note(heap_va, offset, w, why); } TitleImage test_bind_title_image(ID3D12Device* device, const std::array& words, const char** why) { if (!device) return TitleImage::not_tsharp; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); Device* d = Device::from(real ? real : device); if (!d) return TitleImage::not_tsharp; leonida::gfx10::ImageWords w; std::memcpy(w.data(), words.data(), sizeof(w)); return bind_title_image(d->state(), w, why); } std::uint64_t resource_image_address(ID3D12Resource* resource) { if (!resource) return 0; const Resource* r = Resource::from(resource); return r ? r->image_address() : 0; } std::filesystem::path configured_shader_directory(std::string* error, const std::filesystem::path& config) { return leonida::shader_paths::configured(error, config); } } // namespace rt::d3d12