diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 80807b58db..1728ce5f8d 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -838,8 +838,9 @@ The compute path, end to end: - Shader programs (FSSM blobs) are copied in as the code base. - **`CreateRootSignature`** parses the blob with `parse_rts0` and keeps each parameter's place in two layouts: `pack()` for the graphics bind point and `pack_stage(Stage::Compute)` for the compute one (from s4, one dword per - table; section 3.5, D3D-448). A signature neither can place (more than 32 user dwords: the spill layout is open; the - translated shaders have no below-base spill-pointer candidates) is refused with both reasons; one only a single layout places is created with a log line, and binding it at the other bind point + table; section 3.5, D3D-448). Compute parameters that do not fit inline and every later parameter are packed into + the measured spill array. Graphics still has no spill layout; a signature neither layout can place is refused, and + one only a single layout places is created with a log line. Binding it at the other bind point invalidates the list. Before that it answers as the host runtime does (`compare_invalid_arguments`, "root signature:", RTX 5070 / 621.14): `S_FALSE` for a null output whatever the blob, then `E_INVALIDARG` for a node other than node 0 or a DXBC @@ -1868,7 +1869,11 @@ Taken together this disagrees with the packing above (from s0, two dwords per ta in root order from the stage base, each while it fits whole, a constant taking one dword per value, a root CBV/SRV/UAV two (its 64-bit VA), a descriptor table **one** (the 32-bit VA of its first descriptor; the heaps live below 4 GiB). A parameter that does not fit goes, with every later one, to the spill array behind `s[0:1]` -(section 7), which is not modelled, so such a signature is refused. How each part is known: +(section 7), packed in root order with no padding: constants take 4 bytes per value, root views 8 bytes and tables +4 bytes. At recording time the runtime snapshots those bytes into a host-visible upload-heap buffer placed in the GPU +address arena and writes its arena-relative console GPU VA to `s[0:1]` for that dispatch; the command list keeps the +resource and heap alive until reset or release. Other stages +still reject spills because their per-stage base and spill ABI are not measured. How each part is known: - **Compute, base s4: measured three ways.** - The console compiler's output (section 7). - The package's FidelityFX DLL, whose 29 compute containers carry their `RTS0` next to the console-compiled @@ -1883,14 +1888,14 @@ below 4 GiB). A parameter that does not fit goes, with every later one, to the s - **Vertex/pixel/geometry s8 and mesh s16: a hypothesis.** It rests on the census above only; no signature confirms these bases, and visibility is not modelled (every parameter takes its place in every stage). -The runtime uses the console layout for the **compute** bind point only. Graphics keeps `pack()`: every stage of a +The runtime uses the console layout and spill array for the **compute** bind point only. Graphics keeps `pack()`: every stage of a pipeline reads `s0..s31` from one push-constant block at offset 0 (`tools/rdna2spirv.py`, `ShaderUserData` in `runtime/src/vulkan_replay.h`), so a mesh shader (base s16) and a pixel shader (base s8) in one pipeline would need the same root argument at two offsets. That needs per-stage user-data windows in the translator's push-constant contract (D3D-448 follow-up). A root signature carries both layouts; one that only one of them can place is created, and binding it at the other bind point invalidates the command list (`Close` returns `E_INVALIDARG`). -`s0..s3` of a compute dispatch are the driver's block; the layer leaves them zero (109 CS read `s1` as a constant, -42 `s3`; their meaning is open). +For compute dispatches without spills, the layer leaves `s0..s3` zero (109 CS read `s1` as a constant, 42 `s3`; their +meaning is open). With a spill, `s0:s1` carry the measured spill-array pointer; `s2:s3` remain zero. **Measured: a real signature beside the count it produced.** `tools/fspx_unpack.py` decodes `COMPUTE_PGM_RSRC2` of each of the 29 compute programs in `amd_fidelityfx_upscaler_xbox.dll`, and its `USER_SGPR` field is the count the @@ -1929,9 +1934,11 @@ Still open: which CBV index lands in which pair. The four pairs do appear in dec package proves that order, and every parameter in these 29 is `D3D12_SHADER_VISIBILITY_ALL`, so they say nothing about the visibility question below. -Spill policy: a signature needing more than 32 user SGPRs, or more than the 64-dword D3D12 cost limit, is -refused loudly (`pack` returns the offending parameter) instead of being truncated. The console spills through -`__XB_GetRootSignatureSpillPointer`; until that layout is measured, refusing is the only correct behaviour. +Spill policy: signatures over the 64-dword D3D12 cost limit are refused. The graphics `pack()` layout still refuses +parameters beyond its 32-dword window. Compute uses the measured spill policy described in section 3.5: parameters +from the first one that does not fit are copied in root order into a host-visible upload-heap buffer placed in the GPU +address arena, whose arena-relative console GPU VA is put in `s[0:1]` for each dispatch. This path is implemented, but remains to be validated against the executable's +actual spilled shaders. Measured (D3D-315): zero below-base spill-pointer candidates in the translated shaders. `python -I tools/root_spill_census.py --carve --expect-no-spill` exits 0 on @@ -1958,7 +1965,8 @@ What this does not settle: - **A spill behind a pointer at or above the base.** It reads the same as a table pointer, so the census can't tell the two apart. -The spill layout stays unimplemented: no shader in the translated set reads a candidate a spill could sit behind. +The census only describes the translated shader corpus at the time it was generated; its lack of below-base reads does +not rule out runtime-created signatures that spill. The runtime now implements the measured compute spill convention. Reconciliation: `tools/root_sig_contract.py` checks a candidate root signature against every shader's `user_sgpr_reads` from `spirv/index.json` (const32 vs constant dwords, 64-bit VAs vs view/table pairs) and fails @@ -2028,10 +2036,9 @@ Things that can invalidate this simple model, all **Open**: so the executable's pipeline table would settle it; `tests/test_user_sgpr_census.py` shows that the two models give different counts. Mesh shaders (base s16) and the compute signatures are not covered here. - **Root signature larger than 32 dwords.** D3D12 allows up to 64 dwords. The console has 32 user SGPRs, so a - driver must spill the rest to memory, probably behind a pointer in the user data. The current shader contract has - no representation for that. The likely answer is that this game keeps its root signatures small (bindless - descriptors, a few constants), but it must be measured. If a large root signature appears, the spill layout has - to be reverse-engineered from the shader's loads. Measured on the shader side (D3D-315, spill policy above): + driver spills the remaining compute parameters through the pointer in user data. The runtime implements the + measured compute layout; validation against a game dispatch that actually spills is still needed. Measured on the + shader side (D3D-315, spill policy above): zero below-base spill-pointer candidates in the translated shaders. The root signatures themselves, and how many exceed the budget, are still to be dumped from the executable. - **Direct heap indexing.** The bound heap base and stride are not root parameters. Measured (D3D-329, section diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index f84465564d..e15d11846b 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -194,6 +194,7 @@ class GraphicsCommandList final explicit GraphicsCommandList(D3D12_COMMAND_LIST_TYPE type) : type_(type) {} ~GraphicsCommandList() override { stop_recording(); + spill_chunks_.clear(); release_held(); } @@ -244,6 +245,7 @@ class GraphicsCommandList final invalid_ = false; calls_.clear(); tables_.clear(); + spill_chunks_.clear(); // borrowed pointers below are owned by held_ release_held(); // what the old recording used: it was replayed at ExecuteCommandLists reset_state(state); // Reset returns every list state to its default if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) set_initial_pipeline(state); // reset_state holds it @@ -957,7 +959,9 @@ class GraphicsCommandList final if (kind == leonida::IndirectKind::dispatch && max_command_count) { // the pipeline and root arguments a Dispatch would record if (!compute_pipeline_ || !compute_.layout) return check(false); cmd.pipeline = compute_pipeline_; - cmd.user_data = compute_user_data(); + + if (!snapshot_compute_user_data(cmd.user_data)) return; + } check(list_.execute_indirect(cmd)); } @@ -1282,6 +1286,16 @@ class GraphicsCommandList final struct RootState { const RootArgumentLayout* layout = nullptr; std::array data{}; + std::vector spill_data; + }; + + struct SpillChunk { + ID3D12Resource* resource = nullptr; // borrowed from held_ + ID3D12Heap* heap = nullptr; // borrowed from held_ + std::uint8_t* mapped = nullptr; + D3D12_GPU_VIRTUAL_ADDRESS gpu_va = 0; + std::uint64_t capacity = 0; + std::uint64_t used = 0; }; // D3D12 leaves root arguments undefined after a root-signature change; they start at zero here. Setting the @@ -1302,6 +1316,10 @@ class GraphicsCommandList final hold(signature); // state.layout points into it state.layout = layout; state.data = {}; + state.spill_data.clear(); + if (layout && is_compute(state) && layout->compute_ok && layout->compute_spill_bytes) + state.spill_data.resize((layout->compute_spill_bytes + sizeof(std::uint32_t) - 1) / + sizeof(std::uint32_t)); // CreateRootSignature accepted it for the other bind point only (its log line says why). if (layout && !(is_compute(state) ? layout->compute_ok : layout->graphics_ok)) { stub(is_compute(state) ? "SetComputeRootSignature(signature that does not fit the compute layout)" @@ -1312,11 +1330,6 @@ class GraphicsCommandList final bool is_compute(const RootState& state) const { return &state == &compute_; } - // The parameter's first user-data dword at this bind point (RootArgumentLayout). - std::uint32_t first_dword(const RootState& state, const RootArgumentLayout::Parameter& p) const { - return is_compute(state) ? p.compute_offset : p.user_offset; - } - // The parameter, if it exists and has the expected type; null after recording an invalid call. const RootArgumentLayout::Parameter* parameter(RootState& state, UINT index, rt::rootsig::ParamType type) { if (!state.layout || index >= state.layout->parameters.size() || @@ -1327,12 +1340,21 @@ class GraphicsCommandList final return &state.layout->parameters[index]; } - // Dwords beyond the 32 user registers are what the console spills to memory; that layout is still open. - void write(RootState& state, std::uint32_t dword, std::uint32_t value) { - if (dword < rt::rootsig::kMaxUserSgprs) - state.data[dword] = value; - else - stub("root arguments beyond 32 user-data dwords (spill not modelled)"); + // Compute arguments after the first one that does not fit in s4..s31 use the measured packed spill array. + void write(RootState& state, const RootArgumentLayout::Parameter& p, std::uint32_t relative_dword, + std::uint32_t value) { + if (is_compute(state) && p.compute_spill_offset != rt::rootsig::kNoSpill) { + const std::uint64_t byte_offset = std::uint64_t(p.compute_spill_offset) + + std::uint64_t(relative_dword) * sizeof(std::uint32_t); + const std::uint64_t dword = byte_offset / sizeof(std::uint32_t); + if (byte_offset % sizeof(std::uint32_t) || dword >= state.spill_data.size()) return check(false); + state.spill_data[static_cast(dword)] = value; + return; + } + const std::uint32_t first = is_compute(state) ? p.compute_offset : p.user_offset; + const std::uint64_t dword = std::uint64_t(first) + relative_dword; + if (first == rt::rootsig::kNoSgpr || dword >= rt::rootsig::kMaxUserSgprs) return check(false); + state.data[static_cast(dword)] = value; } void constants(RootState& state, UINT index, UINT count, const void* data, UINT offset) { @@ -1354,8 +1376,7 @@ class GraphicsCommandList final if (!p) return; if ((count && !data) || std::uint64_t(offset) + count > p->constant_count) return check(false); const auto* values = static_cast(data); - const std::uint32_t first = first_dword(state, *p); - for (UINT i = 0; i < count; ++i) write(state, first + offset + i, values[i]); + for (UINT i = 0; i < count; ++i) write(state, *p, offset + i, values[i]); } void address(RootState& state, UINT index, std::uint64_t va, rt::rootsig::ParamType type) { @@ -1366,10 +1387,7 @@ class GraphicsCommandList final return; const RootArgumentLayout::Parameter* p = parameter(state, index, type); if (!p) return; - // A root view into the title's own memory (a slot-133 buffer, a constant ring) gets the console VA of a GPU - // copy of it, so the shader's heap_base + VA reaches it (src/title_va_alias.h). A descriptor table is in one - // of the layer's heaps: kept, and its buffer V#s are rewritten the same way before each submission. - // A table in a console descriptor heap is read from the heap's arena copy (console_descriptor_table_va). + // Route title buffers and descriptor tables through their console GPU address aliases before recording. if (type == rt::rootsig::ParamType::Descriptor) va = leonida::title_va_aliases().resolve(va, kRootViewBytes, leonida::TitleVaAliases::root_view); else @@ -1377,12 +1395,10 @@ class GraphicsCommandList final if (type != rt::rootsig::ParamType::Descriptor && va && p->table_descriptors && (tables_.empty() || tables_.back().first != va)) tables_.push_back({va, p->table_descriptors}); - const std::uint32_t first = first_dword(state, *p); - write(state, first, std::uint32_t(va)); - // In the console layouts a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps - // live below 4 GiB); a root view keeps both halves. pack()'s graphics layout gives every address two dwords. + write(state, *p, 0, std::uint32_t(va)); + // Console descriptor tables occupy one dword; root views retain both address halves. const bool console = is_compute(state) || state.layout->graphics_console; - if (!(console && type == rt::rootsig::ParamType::Table)) write(state, first + 1, std::uint32_t(va >> 32)); + if (!(console && type == rt::rootsig::ParamType::Table)) write(state, *p, 1, std::uint32_t(va >> 32)); } D3D12_COMMAND_LIST_TYPE type_; @@ -1393,6 +1409,7 @@ class GraphicsCommandList final UINT back_stencil_ref_ = 0; RootState compute_; RootState graphics_; + std::vector spill_chunks_; std::uintptr_t compute_pipeline_ = 0; bool unregistered_pipeline_ = false; // the bound PSO has no pipeline here (a stub): see set_pipeline std::uintptr_t graphics_pipeline_ = 0; @@ -1644,7 +1661,97 @@ class GraphicsCommandList final } } note_direct_heap_indexing(compute_.layout); - check(list_.dispatch({compute_pipeline_, compute_user_data(), x, y, z})); + + std::array user_data{}; + if (!snapshot_compute_user_data(user_data)) return; + check(list_.dispatch({compute_pipeline_, user_data, x, y, z})); + } + + bool snapshot_compute_user_data(std::array& user_data) { + user_data = compute_user_data(); + if (compute_.spill_data.empty()) return true; + + const std::uint64_t bytes = std::uint64_t(compute_.spill_data.size()) * sizeof(std::uint32_t); + SpillChunk* chunk = spill_chunks_.empty() ? nullptr : &spill_chunks_.back(); + std::uint64_t offset = chunk ? (chunk->used + sizeof(std::uint32_t) - 1) & + ~(std::uint64_t(sizeof(std::uint32_t)) - 1) + : 0; + if (chunk && (offset > chunk->capacity || bytes > chunk->capacity - offset)) { + chunk = nullptr; + } + if (!chunk) { + IUnknown* const owner = attached_device(); + ID3D12Device* device = nullptr; + if (!owner || FAILED(owner->QueryInterface(__uuidof(ID3D12Device), reinterpret_cast(&device))) || + !device) { + std::fprintf(stderr, "[rt] d3d12: compute root spill could not resolve its D3D12 device\n"); + check(false); + return false; + } + + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + const std::uint64_t previous_capacity = spill_chunks_.empty() ? 0 : spill_chunks_.back().capacity; + const std::uint64_t geometric_capacity = previous_capacity > UINT64_MAX / 2 + ? UINT64_MAX + : previous_capacity * 2; + desc.Width = std::max({std::uint64_t(64 * 1024), bytes, geometric_capacity}); + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + D3D12_HEAP_DESC heap_desc{}; + heap_desc.SizeInBytes = desc.Width; + heap_desc.Properties.Type = D3D12_HEAP_TYPE_UPLOAD; + heap_desc.Properties.CreationNodeMask = 1; + heap_desc.Properties.VisibleNodeMask = 1; + heap_desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + ID3D12Heap* heap = nullptr; + HRESULT created = device->CreateHeap(&heap_desc, __uuidof(ID3D12Heap), + reinterpret_cast(&heap)); + ID3D12Resource* resource = nullptr; + if (SUCCEEDED(created) && heap) + created = device->CreatePlacedResource(heap, 0, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + __uuidof(ID3D12Resource), + reinterpret_cast(&resource)); + device->Release(); + if (FAILED(created) || !resource) { + if (resource) resource->Release(); + if (heap) heap->Release(); + std::fprintf(stderr, "[rt] d3d12: compute root spill buffer creation failed with 0x%08lx\n", + static_cast(created)); + check(false); + return false; + } + + void* mapped = nullptr; + const D3D12_RANGE no_read{0, 0}; + const HRESULT map_result = resource->Map(0, &no_read, &mapped); + const D3D12_GPU_VIRTUAL_ADDRESS gpu_va = resource->GetGPUVirtualAddress(); + if (FAILED(map_result) || !mapped || !gpu_va) { + resource->Release(); + if (heap) heap->Release(); + std::fprintf(stderr, "[rt] d3d12: compute root spill buffer mapping/address failed\n"); + check(false); + return false; + } + hold(resource); + hold(heap); // release the placed resource before its backing heap + heap->Release(); + resource->Release(); + spill_chunks_.push_back({resource, heap, static_cast(mapped), gpu_va, desc.Width, 0}); + chunk = &spill_chunks_.back(); + offset = 0; + } + + std::memcpy(chunk->mapped + offset, compute_.spill_data.data(), static_cast(bytes)); + chunk->used = offset + bytes; + const std::uint64_t spill_va = chunk->gpu_va + offset; + user_data[0] = static_cast(spill_va); + user_data[1] = static_cast(spill_va >> 32); + return true; + } // The views block a draw records. Rebuilt only when the render targets or the bound vertex buffers change. diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 093582415d..dc7ddb9174 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -438,11 +438,15 @@ struct RootArgumentLayout { std::uint32_t user_offset; // graphics: first dword; unused for a parameter with no dwords std::uint32_t constant_count; // constants only std::uint32_t compute_offset = rt::rootsig::kNoSgpr; // compute: first user SGPR + // A table: the CBV/SRV/UAV slots its ranges declare (an unbounded range counts as 1024), for the scan of // title-written V#s before a submission (src/title_va_alias.h). 0: a sampler table, or not a table. std::uint32_t table_descriptors = 0; + std::uint32_t compute_spill_offset = rt::rootsig::kNoSpill; // compute: packed byte offset after first spill + }; std::vector parameters; + std::uint32_t compute_spill_bytes = 0; std::uint32_t flags = 0; // D3D12_ROOT_SIGNATURE_FLAGS from the serialized blob // The graphics layout is the console's (pack_stage(Stage::Pixel)): a table takes one dword. False: pack()'s, two. bool graphics_console = false; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index a1ddc9b0ed..81332c34a5 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -10792,6 +10792,7 @@ class Device final layout.graphics_console = pixel.ok; layout.graphics_ok = graphics_ok; layout.compute_ok = compute.ok; + layout.compute_spill_bytes = compute.ok ? compute.spill_dwords * sizeof(std::uint32_t) : 0; 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). @@ -10809,7 +10810,10 @@ class Device final } 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_view_descriptors(parsed.sig.params[i])}); + table_view_descriptors(parsed.sig.params[i]), + compute.ok && compute.spill_dword[i] != rt::rootsig::kNoSpill + ? compute.spill_dword[i] * sizeof(std::uint32_t) + : rt::rootsig::kNoSpill}); } register_static_samplers(parsed.sig); auto* signature = new RootSignature( diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 23b0e05a05..83fef20b3b 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -3128,6 +3128,9 @@ void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D1 HRESULT proxy_create_compute_pipeline_state(DeviceProxy* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, std::uint64_t w2, std::uint64_t w3, const IID* riid, void** out) { note_slot(62); + static std::atomic logged_calls{0}; + const unsigned call = logged_calls.fetch_add(1, std::memory_order_relaxed); + const bool trace_call = call < 512; if (w2 || w3) { static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) @@ -3137,7 +3140,16 @@ HRESULT proxy_create_compute_pipeline_state(DeviceProxy* self, const D3D12_COMPU if (!out) return E_POINTER; *out = nullptr; if (!riid) return E_POINTER; - return self->real->CreateComputePipelineState(desc, *riid, out); + if (trace_call) + std::fprintf(stderr, "[rt] d3d12_xs: slot 62 compute PSO #%u desc=%p root=%p shader=%p bytes=%zu\n", + call + 1, static_cast(desc), + desc ? static_cast(desc->pRootSignature) : nullptr, + desc ? desc->CS.pShaderBytecode : nullptr, desc ? desc->CS.BytecodeLength : std::size_t(0)); + const HRESULT hr = self->real->CreateComputePipelineState(desc, *riid, out); + if (trace_call) + std::fprintf(stderr, "[rt] d3d12_xs: slot 62 compute PSO #%u returned 0x%08lx object=%p\n", call + 1, + static_cast(hr), *out); + return hr; } // The Xbox slot 41 is CreateCommandSignature at its PC position, (desc, root signature, riid, out), but a console diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 82d8142d0f..22ba55b901 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -581,6 +581,13 @@ void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULON } if (new_placeholder || window) { void* const result = reserve_placeholder(address, size, base_granularity); + if (size >= (1ULL << 30)) + std::fprintf(stderr, + "[rt] xmem: XMemVirtualAlloc large window size=%zu allocType=0x%08lx attrs=0x%llx " + "protect=0x%08lx -> %p (error=%lu)\n", + size, static_cast(allocation_type), + static_cast(attributes), static_cast(protect), result, + static_cast(result ? ERROR_SUCCESS : GetLastError())); if (result && window) { const std::lock_guard lock(g_phys_mutex); record_window(result, size, host_prot); @@ -820,16 +827,25 @@ BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, } const uint64_t count = *page_count; if (count == 0) return TRUE; + const bool trace_large = count >= (1u << 14); + if (trace_large) + std::fprintf(stderr, "[rt] xmem: XMemAllocatePhysicalPages begin attrs=0x%llx pages=%llu bytes=%llu\n", + static_cast(attributes), static_cast(count), + static_cast(count * kPhysicalPageSize)); const std::lock_guard lock(g_phys_mutex); if (count > g_free_slots.size() + (kPageSlotLimit - g_next_slot)) { *page_count = 0; SetLastError(ERROR_NOT_ENOUGH_MEMORY); + if (trace_large) + std::fprintf(stderr, "[rt] xmem: XMemAllocatePhysicalPages failed: page-number slots exhausted\n"); return FALSE; } if (!install_physical_page_fault_handler()) { *page_count = 0; SetLastError(ERROR_NOT_SUPPORTED); + if (trace_large) + std::fprintf(stderr, "[rt] xmem: XMemAllocatePhysicalPages failed: page-fault handler unavailable\n"); return FALSE; } const uint64_t bytes = count * kPhysicalPageSize; // below 2^37: count is below 2^21 @@ -837,12 +853,20 @@ BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, static_cast(bytes >> 32), static_cast(bytes), nullptr); if (!handle) { *page_count = 0; + const DWORD error = GetLastError(); + if (trace_large) + std::fprintf(stderr, "[rt] xmem: XMemAllocatePhysicalPages CreateFileMapping failed error=%lu\n", + static_cast(error)); return FALSE; } // From host_heap: the unmap that drops the last reference frees it under g_fault_lock. const auto section = std::allocate_shared
(leonida::host_heap::Allocator
{}, handle); if (!section->scratch) { *page_count = 0; + const DWORD error = GetLastError(); + if (trace_large) + std::fprintf(stderr, "[rt] xmem: XMemAllocatePhysicalPages section map failed error=%lu\n", + static_cast(error)); return FALSE; } for (uint64_t i = 0; i < count; ++i) { @@ -857,6 +881,10 @@ BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, g_pages[page] = PhysicalPage{section, i * kPhysicalPageSize}; page_array[i] = page; } + if (trace_large) + std::fprintf(stderr, "[rt] xmem: XMemAllocatePhysicalPages succeeded pages=%llu first=0x%llx last=0x%llx\n", + static_cast(count), static_cast(page_array[0]), + static_cast(page_array[count - 1])); return TRUE; } @@ -894,6 +922,10 @@ BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_arra // page number that is not a live page fails with the pages before it mapped and the rest of the range unmapped. void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) { const uintptr_t start = reinterpret_cast(address); + const bool trace_large = page_count >= (1u << 14); + if (trace_large) + std::fprintf(stderr, "[rt] xmem: XMemMapPhysicalPages begin base=%p pages=%llu pageArray=%p\n", address, + static_cast(page_count), static_cast(page_array)); if (!aligned_page_address(start) || page_count > (std::numeric_limits::max)() / kPhysicalPageSize || start > (std::numeric_limits::max)() - page_count * kPhysicalPageSize) { SetLastError(ERROR_INVALID_PARAMETER); @@ -909,9 +941,13 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint const Window* const window = find_window(start, page_count * kPhysicalPageSize); if (!window) { SetLastError(ERROR_INVALID_ADDRESS); + if (trace_large) + std::fprintf(stderr, "[rt] xmem: XMemMapPhysicalPages failed: no reserved window error=%lu\n", + static_cast(GetLastError())); return nullptr; } const DWORD protect = view_protect(*window); + if (!unmap_range(start, end)) return nullptr; for (uint64_t i = 0; i < page_count;) { if (page_array[i] == 0) { @@ -921,6 +957,10 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint const auto it = g_pages.find(page_array[i]); if (it == g_pages.end()) { SetLastError(ERROR_INVALID_PARAMETER); + if (trace_large) + std::fprintf(stderr, "[rt] xmem: XMemMapPhysicalPages invalid page at index %llu id=0x%llx\n", + static_cast(i), + static_cast(page_array[i])); return nullptr; } View view{1, it->second.section, it->second.offset, protect}; @@ -934,7 +974,14 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint } { const FaultLockExclusive view_lock; - if (!map_view(start + i * kPhysicalPageSize, view)) return nullptr; + if (!map_view(start + i * kPhysicalPageSize, view)) { + const DWORD error = GetLastError(); + if (trace_large) + std::fprintf(stderr, "[rt] xmem: XMemMapPhysicalPages map failed at page %llu count=%llu error=%lu\n", + static_cast(i), static_cast(view.count), + static_cast(error)); + return nullptr; + } } // After the fault lock: page_array is the title's memory, and a read of it that faults would wait for the // lock on this thread. g_mapped and the aliases are g_phys_mutex's; the fault handler reads neither. @@ -944,7 +991,12 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint note_mapping(page_array[i + k], at, true); } i += view.count; + } + if (trace_large) + std::fprintf(stderr, "[rt] xmem: XMemMapPhysicalPages succeeded base=%p pages=%llu end=%p\n", address, + static_cast(page_count), + reinterpret_cast(start + page_count * kPhysicalPageSize)); return address; }