Compare commits

...
15 Commits
Author SHA1 Message Date
Ateş 414e2812de Merge pull request #815 from 1Bartosz/track-f/veh-clwb-xmem-transfer
[Picture] test_veh_clwb: call XMemTransferMemory with the GDK's arguments
2026-12-03 01:04:10 +03:00
ates 0a492476b3 Merge main into track-f/veh-clwb-xmem-transfer
Conflict in CHANGELOG.md only: both this branch and #813 added an entry at
the top of the Fixed list. Both entries are kept; no code is changed.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-03 00:55:50 +03:00
Ateş 83f0290171 Merge pull request #813 from 1Bartosz/track-c/xbox-subobject-types
[Picture] d3d12_xs: Xbox pipeline stream subobject types read with PC numbers (mesh shader seen as AS)
2026-12-03 00:54:05 +03:00
Ateş 4a41f1707b Merge pull request #818 from 1Bartosz/track-c/gate-decision-cache
[Picture] d3d12_xs: every pipeline creation re-inspects its shaders and logs each decision
2026-12-03 00:43:15 +03:00
Ateş c08c99b692 Merge pull request #816 from 1Bartosz/track-c/title-copy-counters
[Picture] d3d12_xs: bytes copied from title memory to host resources are not counted
2026-12-03 00:42:45 +03:00
Bartosz Szczepański a0358c6db2 docs: record gate decision reuse in ADR 0008 and CHANGELOG (#818)
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-12-02 22:04:22 +01:00
Bartosz Szczepański b835b78f3f d3d12_xs: remember the shader gate's decision per shader (#818)
Every pipeline creation ran each stage through the shader bridge
(inspect, a chunk scan and, for DXIL, a prepared copy) and wrote one
log line per decision, synchronously under the log lock. The target
build creates pipelines with the same shaders tens of thousands of
times in two minutes.

The decision now is made and logged once per shader, PSO kind and
stage, keyed by the length and two independent 64-bit hashes of the
bytes. Later creations reuse it without calling the bridge; a passed
DXIL copy is kept for the process so the host gets the same bytes.
Reuses are counted in a sampled shader_gate_reused record. Failures
that are not a decision (prepare_failed, copy_limit) are not kept.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-12-02 20:54:45 +01:00
Bartosz Szczepański a4d689f50d conformance: the shader gate decides once per shader (#818)
test_shader_gate_reuse creates the same SM 6.6 DXIL compute pipeline,
the same ACCC-only compute pipeline and a stream pipeline with the same
DXIL 300 times each through D3D12XboxCreateDevice. Every creation must
give the same result as the first, the last DXIL pipeline must still
write all 256 expected words, and the log must hold exactly one
shader_gate record for each of the three. On main it holds 300 each.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-12-02 20:54:45 +01:00
Bartosz Szczepański c253b4a0b2 d3d12_xs: claim: shader gate decisions remembered per shader
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-12-02 20:50:26 +01:00
Bartosz Szczepański 718c4d5fd0 docs: unified memory: what d3d12_xs copies today and a copy-free path
Measured title_copy_bytes on the menus and recorded, with #473's
D3DMetal findings, a phased design for handing the title D3D12-owned
shared memory so bound and mapped buffers need no copy.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-12-02 19:42:27 +01:00
Bartosz Szczepański 88b819872d [Picture] d3d12_xs: count bytes copied from title memory to host resources
D3DMetal cannot wrap title memory (#473), so every byte the GPU reads
from it is copied by d3d12_xs along one of eight paths, and nothing said
how much. Each path now adds to a running total (bx_title_copy_count in
title_memory.cpp), and every ExecuteCommandLists logs the totals as
title_copy_bytes at submissions 1, 2, 4 ... 1024 and every 1024th after.
Behaviour is unchanged.

Test: test_d3d12_title_copy_counters.
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-12-02 19:39:12 +01:00
Bartosz Szczepański c618af2402 d3d12_xs: claim: count bytes copied between title memory and host resources
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-12-02 19:33:16 +01:00
Bartosz Szczepański ab8a0652cd test_veh_clwb: call XMemTransferMemory with the GDK's arguments
#768 gave XMemTransferMemory the GDK's (TransferType, TransferSize)
signature and updated test_integration_boot and test_xmem, but
test_veh_clwb still declared the old (dst, src, bytes, flags) form. The
shim read the destination pointer as a transfer type and refused it, so
the test failed with "XMemTransferMemory mismatch" on every machine.

The test now declares the GDK form and checks that
XMemTransferMemory(XMemTransferTitleToSystem, 0) succeeds, as
test_integration_boot does.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-12-02 18:38:39 +01:00
Bartosz Szczepański 32b484ffc7 [Picture] d3d12_xs: read pipeline state streams with the GDK's subobject numbers
The stream walker used the PC SDK's subobject numbers. They match the
GDK's up to VIEW_INSTANCING (22); the GDK then has AS = 23, MS = 24 and
five Xbox-only subobjects at 25..29, where the PC SDK has AS = 24 and
MS = 25. A mesh shader was read as an amplification shader, an AS was
refused as unknown, and an Xbox-only subobject failed the whole stream.

copy_stream now reads the GDK's numbers and writes the host's, leaves the
Xbox-only subobjects out (logged once per type), and callers hand the
host the copy's own size. bx_stream_payload walks the host copy.

Test: test_d3d12_xbox_stream_subobjects.
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-12-02 18:29:51 +01:00
Bartosz Szczepański cd5bcda171 d3d12_xs: claim: Xbox pipeline stream subobject types read with PC numbers
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-12-02 18:23:13 +01:00
22 changed files with 1479 additions and 42 deletions

No files matched your search

+13
View File
@@ -10,6 +10,12 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- **`d3d12_xs` counts the bytes it copies from title memory into host resources** (`title_copy_bytes`).
- One running total per path: buffer shadows made (`shadow_create`), bound VB/IB/root ranges refreshed at submit (`bound_refresh`), persistently mapped buffers synced at submit (`mapped_sync`), Map reads and Unmap writes, texture contents, constant copies and rect-list vertices.
- Logged at submissions 1, 2, 4, ... 1024 and every 1024th after that. Nothing else changes.
- It measures what a copy-free path over unified memory would save. D3DMetal cannot wrap title memory (#473), so every byte the GPU reads from it goes through one of these paths.
- Test: `test_d3d12_title_copy_counters`.
- `docs/research/unified-memory.md` records the measured totals for the menus and a phased design for a copy-free path over unified memory.
- **Ghidra first: unimplemented calls name their callers, and `bx-cli ghidra` finds the function.**
- `runtime_veh` logs a `stub_caller` event once for each unimplemented call (signature, stub, direct caller): the stub, its caller and one more frame, as `module+offset`. The stub's own event is unchanged, so report signatures don't change.
- `bx-cli report` lists those caller chains under each unimplemented call.
@@ -18,6 +24,12 @@ remains unsupported.
- Tests: `test_stub_caller`, plus unit tests for the report and the lookup.
### Fixed
- **`test_veh_clwb` calls `XMemTransferMemory` with the GDK's arguments.** #768 gave the export the GDK's `(TransferType, TransferSize)` signature, but this test still declared the old `(dst, src, bytes, flags)` form. Its first argument, a pointer, was read as a transfer type and refused, so the test failed on every machine. It now checks that `XMemTransferMemory(XMemTransferTitleToSystem, 0)` succeeds, as `test_integration_boot` does.
- **`d3d12_xs`: pipeline state streams are read with the GDK's subobject numbers.**
- **Before:** the stream walker used the PC SDK's numbers, which match the GDK's only up to `VIEW_INSTANCING` (22). The GDK numbers AS 23 and MS 24, and has five Xbox-only subobjects at 25..29. A mesh shader (24) was therefore read as an amplification shader, an AS (23) was refused as unknown, and any Xbox-only subobject made the whole stream fail with `E_INVALIDARG`.
- **Now:** AS and MS reach the gate and D3DMetal under their own names and the host's numbers. `PIXEL_SHADER_OPTIONS`, `DEPTH_STENCIL_OPTIONS`, `GRAPHICS_SHADER_LIMITS`, `TESSELLATION_PARAMETERS` and `COMPUTE_SHADER_LIMITS` have no D3D12 counterpart: they are left out of the host stream, and a `pso_stream_xbox_subobject` warning is logged once per type. The host gets the renumbered copy and its size.
- **Not covered:** the GDK's `DEPTH_STENCIL2`, `RASTERIZER1` and `RASTERIZER2` (100..102) have no payload layout in the GDK headers and are still refused. Console mesh shaders are still not translated, so mesh pipelines are still refused, now as `MS`.
- Test: `test_d3d12_xbox_stream_subobjects`.
- **`DispatchX` and `CopyResourceX` are implemented.** Both Xbox command-list slots (80 and 86) were logging stubs. `DispatchX` forwards to `Dispatch`; with `USE_THREAD_DIMENSIONS` the counts are threads, so they are divided (rounding up) by the bound compute shader's `[numthreads]`, read from its `PSV0` part when the pipeline is created. A thread-count dispatch on a pipeline whose `[numthreads]` is unknown is logged and skipped rather than run with wrong counts; unknown flags are logged. `CopyResourceX` forwards to `CopyResource`. New `test_d3d12_dispatch_copy_x` (the `[numthreads]` conversion is not covered by it).
- **`AllocateFromCommandAllocatorX` returns memory instead of null (#806).** The Xbox command-list slot 148 was a logging stub. The GDK's ray-tracing BVH builder takes its upload buffer from it, and on null it throws an exception the target build does not catch, which ended the run through the title's crash reporter (exit status 99). The slot now returns aligned memory carved from 1 MiB chunks owned by the list's command allocator: the chunks are reused when the allocator is reset and freed when it is released, and a non-power-of-two alignment is refused and logged. New `test_d3d12_allocate_from_allocator`.
- **`d3d12_xs`: host memory for read-only placed textures is mapped at first use** (#782).
@@ -76,6 +88,7 @@ remains unsupported.
- **`gfx10-translate`: scan all `XBCH` candidates and support version 2/3 payloads** (#721). `container_code` previously stopped at the first `b"XBCH"` byte sequence in a container, so incidental `b"XBCH"` bytes earlier in the blob (for example in `STAT` or `DXIL` bitcode) caused it to read garbage sizes and fail with `XBCH record: compressed size past the end`. It now scans all `b"XBCH"` occurrences, validates the 24-byte header, bounds, version (`2` uncompressed `FSSM`, `1` and `3` zlib-compressed `FSSM`), and `FSSM` magic, and skips non-matching candidates. Covered by synthetic unit tests in `gfx10_translate::container::tests`.
### Changed
- **`d3d12_xs` makes the shader-gate decision once per shader instead of at every pipeline creation (#818).** The decision depends only on the bytecode, but titles create the same pipelines again and again: the target build made 60,753 gate decisions in 120 s, each calling `bx_shader_bridge.dll` and logging a `shader_gate` record. Decisions are now kept by PSO kind, stage, length and two 64-bit hashes of the bytes; a repeat reuses the decision and its prepared DXIL and is only counted in a sampled `shader_gate_reused` record, so `shader_gate` records now count distinct shaders (about 5,850 in the same run). What D3DMetal receives is unchanged. `tests/conformance/test_shader_gate_reuse` covers it.
- **`d3d12_xs` looks up title-memory host resources through indexes instead of scanning them all (#782).** A title can keep 100,000+ of them alive, and every view creation, root-buffer bind, texture-contents check, `Map` and submit-time sync scanned the whole table under one lock. Lookups by host pointer now use a hash map, lookups by address an ordered map (plus a short list of resources of 1 MiB or more), and the submit-time sync visits only mapped buffers. Behaviour is unchanged; the existing placed-memory and console tests cover every replaced lookup. On the target build's post-loading phase this roughly doubled the rate of view creation; creating the host resources themselves remains the larger cost there.
- **Open-source DXC (`dxcompiler.dll`) replaces the GDK's shader compiler as the primary source** (#757, ADR 0010).
- `.github/workflows/dxc-build.yml` builds x64 Release `dxcompiler.dll` from `microsoft/DirectXShaderCompiler` at pinned tag `v1.9.2609` on a Windows runner and uploads it as a workflow artifact.
+1
View File
@@ -30,6 +30,7 @@
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
- [gfx10-translate](../shader-transpiler/crates/gfx10-translate/README.md) — BetterXen's GFX10.3 console shader translator: container reader, decoder with an LLVM-generated opcode table, HLSL translation ported from the Python prototype, coverage over local shaders, and how to add an instruction.
- [Shader Corpus](../shader-transpiler/corpus/README.md) — Phase 0 of the console shader translator: BetterXen-authored kernels built locally into console containers, Microsoft ISA listings and PC DXIL, with the derived `FSPX` code-section layout (#649).
- [Unified Memory: Copies and a Copy-Free Path](research/unified-memory.md) — What `d3d12_xs` copies from title memory to D3DMetal (`title_copy_bytes`, measured on the menus), why D3DMetal requires it (#473), and a phased design for D3D12-owned shared memory handed to the title.
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
- [Console Compute Shader Entry ABI](research/console-shader-abi.md) — Wave size, root-argument registers, descriptor forms and binding metadata observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler on project-authored probes (class U: an authorized, not yet independently reproduced observation; inferred register roles).
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
+1
View File
@@ -65,6 +65,7 @@ Revisit this ADR in any of these cases:
- **Pipeline creation:** `CreateComputePipelineState` and `CreateGraphicsPipelineState` now depend on `bx_shader_bridge.dll` for classification. Without it, they still work, refuse ACCC-only containers, and say so in the log.
- **Stream PSOs (#576):** `ID3D12Device2::CreatePipelineState` stream descriptions are gated too. The stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Both the payload offset and the record size come from the compiler: `alignas(void*)` aligns the record, not the payload, so 4-byte-aligned payloads sit at offset 4, and `static_assert`s pin the measured values. Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, `AS`, `MS`) go through `BxShaderGate::admit`; every other payload is copied verbatim. A subobject type at or above `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID` from the toolchain header (mingw-w64 `d3d12.h`: `0x1a`, immediately after `MS`), a duplicated subobject type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim edits its own copy of the stream, so prepared DXIL can be substituted without writing to the caller's memory. `pso_stream` now reports `shaders_not_parsed=0` when it parsed, and each stream stage logs its own `shader_gate` record with `pso=stream`. The `--no-bridge` path also refuses ACCC-only through the stream. `test_shader_gate.exe` covers the stream form but was cross-compiled only, not run under CrossOver on the authoring host.
- **Decisions reused (#818):** the decision depends only on the bytecode, so `BxShaderGate::admit` makes it once per shader, PSO kind and stage, keyed by the length and two independent 64-bit hashes of the bytes, and logs that one `shader_gate` record. A later creation with the same bytes reuses the decision without calling the bridge, gets the same prepared DXIL (kept for the process), and is only counted in a sampled `shader_gate_reused` record. So the number of `shader_gate` records counts distinct shaders, not creations. `prepare_failed` and `copy_limit` are not kept and are tried again. Two threads creating the same new shader at the same moment may both decide it and both log it; the first stored decision wins.
- **Packaging:** `scripts/build-shims.sh` builds the bridge, links it with `abi/defs/bx_shader_bridge.def`, and stages it in `build-shims/bin` beside `d3d12_xs.dll` (#484).
- **Not covered by the gate yet:**
- **Raw-buffer 64-bit atomics:** these cannot be flagged from `SFI0`; the DXIL bitcode would have to be read.
+135
View File
@@ -0,0 +1,135 @@
# Unified memory: what d3d12_xs copies today, and a copy-free path
Apple Silicon, like the console, gives the CPU and GPU one pool of memory. A title therefore
expects the GPU to read the memory it writes, at the address it wrote it, with no copy. Under
D3DMetal this note covers four things:
- why `d3d12_xs` copies today;
- how much it copies, measured with the `title_copy_bytes` counters;
- what a copy-free path would look like;
- what that path would and would not save.
It is a design note for the Playable stage, which owns performance
([roadmap](../roadmap.md): "memory copies removed where the host allows"). Nothing here
changes behaviour.
## What D3DMetal allows (#473)
Three independent probes on M4 and M5 Macs, all CrossOver 26.3 with D3DMetal 3.0, found:
- **Title memory cannot be wrapped.** `OpenExistingHeapFromAddress` and
`OpenExistingHeapFromFileMapping` return `E_NOTIMPL`. The adapter reports
`UMA=0` and `CacheCoherentUMA=0`, even though the hardware is unified.
- **D3DMetal's own memory is shared.** CUSTOM heaps with `WRITE_BACK` or `WRITE_COMBINE` at
`L0` are created. A persistent `Map` of them is coherent both ways after a fence.
A 1 GiB heap grows the process footprint by 1 GiB once, and the GPU reading all of it
makes no second copy.
- **Dirty pages cost nothing at submit.** Dirtying 0 or all 65,536 pages of a 256 MiB heap
adds no measurable time to submit and fence (0.2–0.5 ms either way).
- **Textures stay opaque.** A texture with `UNKNOWN` layout has no CPU pointer.
So the only copy-free direction is **inverted ownership**: D3D12 allocates the memory, and the
title is handed a pointer into it. Copying from the title's own allocations cannot be avoided
for anything the title allocated before such a pool existed, nor for textures.
## Where d3d12_xs copies
Every path below goes through `shims/d3d12_xs`, and the `title_copy_bytes` counter named in
backticks counts it:
| Path | When | Counter |
|---|---|---|
| Placed or bound buffer gets a host copy (`make_shadow`) | once per resource or bound range | `shadow_create` |
| VB/IB/root ranges bound from title memory (`bx_xbox_refresh_bound_memory`) | every submit, whole range, no dirty check | `bound_refresh` |
| Persistently mapped buffers (`bx_xbox_sync_mapped_buffers`) | every submit, whole allocation, up to 16 MB | `mapped_sync` |
| `Map` read range, host to title | per `Map` | `map_read` |
| `Unmap` written range, title to host | per `Unmap` | `unmap_write` |
| Texture contents for translated draws (`bx_xbox_texture_contents`) | first use, then when a sampled hash changes | `texture_upload` |
| Constant buffers into the upload ring (`constant_copy`) | every submit, per descriptor entry | `constant_copy` |
| Rect-list vertices into the upload ring | every rect-list draw | `rect_list` |
Two related facts:
- **Committed resources are allocated twice.** Each one is a host resource plus an
`XMemAlloc` the size of its console allocation. A mapped 4 KiB upload buffer is synced as
its whole allocation: 64 KiB in `test_d3d12_title_copy_counters`.
- **Placed textures get one host texture each.** Lazy reserved textures
(`BX_LAZY_TEXTURES`) already map memory only on first use.
## Measured on the target build
Apple M5, 32 GB, macOS 27.2.1, CrossOver 26.3, D3DMetal. `main` f0a45544 plus the
counters. Offline run protocol, Series X profile, `BX_CONSOLE_SHADERS=1`, no input, 120 s,
one run. The menu sets a 33.3 ms frame interval and holds 29–30 fps.
| Counter | Total at 112 s | Steady state (78–112 s) |
|---|---|---|
| `shadow_create` | 1,119.5 MB, all within the first 27 s | 0 |
| `bound_refresh` | 4,634.7 MB | 47.4 MB/s, about 1.6 MB per frame, 0.79 MB per submit |
| `unmap_write` | 200.9 MB | 2.0 MB/s |
| `map_read` | 60.3 MB | 0.6 MB/s |
| `constant_copy` | 61.0 MB | 0.6 MB/s |
| `rect_list` | 0.6 MB | under 0.1 MB/s |
| `mapped_sync` | 0 | 0 |
| `texture_upload` | 0 | 0 (the textures these draws read are render targets, which are not copied) |
**What this says:**
- **Bandwidth is not the menu's problem.** Steady-state copying is about 50 MB/s, a tiny
fraction of what an M-series memory system moves, and the menu already runs at the rate it
asks for.
- **Memory footprint is the larger cost.** 1.12 GB of host copies duplicate title memory that
stays allocated. Committed resources are doubled too. The World stage's memory gate
(16 GB tier) is where this matters first.
- **The work runs on the submitting thread.** `bound_refresh` copies whole ranges at every
submit, so its cost grows with what a scene binds, not with what it changes.
These numbers are for one run of the menus only. Gameplay may bind far more.
## Copy-free path, in phases
Each phase is its own pull request with a conformance test, and is measured with these
counters before and after.
1. **Shared pool in d3d12_xs.**
- `d3d12_xs` keeps a pool of CUSTOM `WRITE_BACK` `L0` heaps, each with one persistently
mapped buffer; `vmem.cpp` already does this for its backing heap (#464).
- It exports `bx_d3d12_alloc_shared` and `bx_d3d12_free_shared` through an `[ABI]` pull
request.
- xmem serves GPU-visible title allocations from that pool when it exists, selected by
their `XALLOC` attributes. Before the device exists, or when the pool is exhausted, it
falls back to today's path.
2. **No refresh for pool memory.**
- `make_shadow` and `bx_xbox_bind_title_memory` recognise an address inside the pool and
use its buffer and offset directly. No host copy is made.
- `bx_xbox_refresh_bound_memory` and `bx_xbox_sync_mapped_buffers` skip such ranges. The
title's writes are already in the memory the GPU reads.
- Committed buffers on UPLOAD and READBACK heaps can take their console allocation from the
pool instead of a second `XMemAlloc`.
3. **Dirty tracking for the rest** (ADR 0009). Ranges outside the pool are copied only when
write-watch reports a written page. Write-watch sees CPU writes at 4 KiB, but not GPU
writes, since `IsolatedMMU=0`.
**Constraints to carry into phase 1:**
- **Alignment.** The CPU address of a mapped heap may miss 64 KiB alignment, while console
allocations assume it, so the pool has to sub-allocate at aligned offsets.
- **Retained memory.** D3DMetal keeps a 256 MiB internal pool and holds freed memory after
`Release`, so the pool should grow in large heaps and reuse them, not free them back.
- **Physical page aliasing stays on today's path.** xmem's physical pages
(`XMemMapPhysicalPages`, one file-mapping section per call, mapped at several addresses)
cannot come from a D3D12 heap.
- **Textures keep their copies.** Only linear (`layout 0x100`) placed textures could in
principle read from a buffer, and that is out of scope here.
**What it would not change:** frame rate in today's menus, texture uploads, and anything the
title allocates before the device is created.
## Open questions for a maintainer
- Whether xmem may depend on `d3d12_xs` at all. Today it does not, and the pool would need a
late-bound hook rather than an import.
- Which `XALLOC` memory types should come from the pool: all GPU-visible ones, or only those
the title marks for CPU write and GPU read.
- Whether phase 1 should wait for gameplay measurements, where binding volume may be very
different from the menus.
+1
View File
@@ -138,6 +138,7 @@ bool constant_copy(ID3D12Device* device, uint64_t title_va, uint64_t size, D3D12
if (cursor + aligned > kRing) cursor = 0;
std::memset(mapped + cursor, 0, aligned);
std::memcpy(mapped + cursor, reinterpret_cast<const void*>(title_va), size);
bx_title_copy_count(BxTitleCopy::ConstantCopy, size);
out->BufferLocation = ring->GetGPUVirtualAddress() + cursor;
out->SizeInBytes = static_cast<UINT>(aligned);
cursor += aligned;
+1
View File
@@ -262,6 +262,7 @@ void execute(void* self, UINT count, ID3D12CommandList* const* lists) {
bx_xbox_sync_mapped_buffers();
bx_xbox_refresh_bound_memory(host.data(), count);
bx_console_submit(queue, host.data(), count);
bx_title_copy_note_submission();
QueueState* s = any ? state_for(queue) : nullptr;
if (!s) {
if (any) bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_writes", "no fences for this queue; writes and waits dropped");
+2 -2
View File
@@ -361,8 +361,8 @@ HRESULT create_stream(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
type = host_topology_type(type);
std::memcpy(&stream[topology_at], &type, sizeof(type));
}
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
admitted.pPipelineStateSubobjectStream = stream.data();
// copy_stream renumbered the stream for the host and may have dropped Xbox-only records.
const D3D12_PIPELINE_STATE_STREAM_DESC admitted{stream.size(), stream.data()};
// The shader gate refused a stage: console code. The pair is kept for its first draw.
if (FAILED(hr)) return refused(device, hr, "stream", riid, ppv, bx_console_pipeline_create(device, stream, offsets, names, root_offset));
hr = device->CreatePipelineState(&admitted, riid, ppv);
+9 -5
View File
@@ -178,7 +178,7 @@ void release_texture_memory(const void* host) {
}
// Copies between a buffer's title memory and its host resource, when the host is CPU-mappable.
bool copy_buffer(const Shadow& s, bool to_host, uint64_t begin, uint64_t end) {
bool copy_buffer(const Shadow& s, bool to_host, uint64_t begin, uint64_t end, BxTitleCopy path) {
if (!s.buffer || end <= begin || end > s.size) return false;
void* mapped = nullptr;
const D3D12_RANGE none{0, 0};
@@ -187,6 +187,7 @@ bool copy_buffer(const Shadow& s, bool to_host, uint64_t begin, uint64_t end) {
auto* title = reinterpret_cast<uint8_t*>(s.title_va) + begin;
if (to_host) std::memcpy(host, title, static_cast<size_t>(end - begin));
else std::memcpy(title, host, static_cast<size_t>(end - begin));
bx_title_copy_count(path, end - begin);
const D3D12_RANGE written{static_cast<SIZE_T>(begin), static_cast<SIZE_T>(end)};
s.host->Unmap(0, to_host ? &written : &none);
return true;
@@ -385,6 +386,7 @@ HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURC
if (SUCCEEDED(resource->Map(0, nullptr, &mapped)) && mapped) {
if (readable(title, desc.Width)) {
std::memcpy(mapped, title, static_cast<size_t>(desc.Width));
bx_title_copy_count(BxTitleCopy::ShadowCreate, desc.Width);
} else {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "placed_x_shadow", "title memory not readable; shadow left zeroed");
}
@@ -977,7 +979,7 @@ void bx_xbox_refresh_bound_memory(ID3D12CommandList* const* host_lists, UINT cou
const size_t i = buffer_holding_locked(r.va, r.size);
if (i == SIZE_MAX) continue;
const uint64_t begin = r.va - g_shadows[i].title_va;
copy_buffer(g_shadows[i], true, begin, begin + r.size);
copy_buffer(g_shadows[i], true, begin, begin + r.size, BxTitleCopy::BoundRefresh);
}
}
@@ -1124,9 +1126,11 @@ ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads*
}
subresources = 1;
hr = S_OK;
bx_title_copy_count(BxTitleCopy::TextureUpload, static_cast<uint64_t>(row) * shadow.desc.Height);
} else {
hr = bx_gdk_xg_detile(shadow.desc, reinterpret_cast<const void*>(shadow.title_va), known.mapped, known.footprints.data(),
known.rows.data(), static_cast<UINT>(known.footprints.size()), &subresources);
if (hr == S_OK) bx_title_copy_count(BxTitleCopy::TextureUpload, bytes);
}
}
if (hr == S_OK && shadow.reserved) {
@@ -1323,7 +1327,7 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_resource_map(void* self, UINT subre
title_va = s.title_va;
// Make GPU results visible: refresh the read range of title memory from the host.
const uint64_t begin = read ? read->Begin : 0, end = read ? read->End : s.size;
if (s.buffer && end > begin) copy_buffer(s, false, begin, end < s.size ? end : s.size);
if (s.buffer && end > begin) copy_buffer(s, false, begin, end < s.size ? end : s.size, BxTitleCopy::MapRead);
++s.mapped;
g_mapped_hosts.insert(s.host);
}
@@ -1354,7 +1358,7 @@ extern "C" void STDMETHODCALLTYPE bx_xbox_resource_unmap(void* self, UINT subres
Shadow& s = g_shadows[i];
// Hand the CPU's writes to the host resource (a null range means all of it).
const uint64_t begin = written ? written->Begin : 0, end = written ? written->End : s.size;
if (s.buffer && end > begin) copy_buffer(s, true, begin, end < s.size ? end : s.size);
if (s.buffer && end > begin) copy_buffer(s, true, begin, end < s.size ? end : s.size, BxTitleCopy::UnmapWrite);
if (s.mapped > 0) --s.mapped;
if (!s.mapped) g_mapped_hosts.erase(s.host);
return;
@@ -1385,6 +1389,6 @@ void bx_xbox_sync_mapped_buffers() {
}
continue;
}
copy_buffer(s, true, 0, s.size);
copy_buffer(s, true, 0, s.size, BxTitleCopy::MappedSync);
}
}
+102 -28
View File
@@ -1,6 +1,7 @@
#include "proxy.h"
#include "vmem.h"
#include <atomic>
#include <cstdio>
#include <cstring>
#include <new>
@@ -454,15 +455,49 @@ constexpr size_t record_size() {
return (offsetof(StreamRecord<Payload>, payload) + sizeof(Payload) + 7) & ~static_cast<size_t>(7);
}
/* The title's stream uses the GDK's subobject numbering (d3d12_xs.h). It matches the PC SDK's
* up to VIEW_INSTANCING (22) and then differs: the GDK has AS = 23 and MS = 24, then five
* Xbox-only subobjects at 25..29, where the PC SDK has AS = 24 and MS = 25. A stream is read
* with the GDK's numbers and handed to D3DMetal with the host's. */
enum : uint32_t {
kXboxSubobjectAS = 23,
kXboxSubobjectMS = 24,
kXboxSubobjectPixelShaderOptions = 25,
kXboxSubobjectDepthStencilOptions = 26,
kXboxSubobjectGraphicsShaderLimits = 27,
kXboxSubobjectTessellationParameters = 28,
kXboxSubobjectComputeShaderLimits = 29,
kXboxSubobjectLimit = 30,
/* A host type for an Xbox-only subobject: it has no D3D12 counterpart and is left out of
* the host stream. */
kNoHostSubobject = UINT32_MAX,
};
/* Payload layouts of the Xbox-only subobjects, as d3d12_xs.h declares them. Only their size and
* alignment matter here: the walker steps over them. */
struct XboxPixelShaderOptionsDesc { UINT options[8]; };
struct XboxDepthStencilOptionsDesc { BOOL flags[4]; UINT8 masks_and_refs[6]; };
struct XboxGraphicsShaderLimitsDesc { UINT values[15]; };
struct XboxTessellationParametersDesc { UINT patches; FLOAT factor_threshold; UINT ds_wave_threshold; };
struct XboxComputeShaderLimitsDesc { UINT values[6]; };
static_assert(sizeof(XboxPixelShaderOptionsDesc) == 32, "8 four-byte options");
static_assert(sizeof(XboxDepthStencilOptionsDesc) == 24, "4 BOOLs and 6 bytes, padded to 4");
static_assert(sizeof(XboxGraphicsShaderLimitsDesc) == 60, "15 four-byte values");
static_assert(sizeof(XboxTessellationParametersDesc) == 12, "3 four-byte values");
static_assert(sizeof(XboxComputeShaderLimitsDesc) == 24, "6 four-byte values");
struct StreamSubobject {
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
uint32_t type; /* the GDK's number, as the title writes it */
uint32_t host_type; /* the host SDK's number, or kNoHostSubobject */
size_t payload_offset;
size_t record_size;
const char* stage; /* non-null only for a shader subobject */
};
#define BX_SUBOBJECT(tag, type, stage) \
{tag, payload_at<type>(), record_size<type>(), stage}
{static_cast<uint32_t>(tag), static_cast<uint32_t>(tag), payload_at<type>(), record_size<type>(), stage}
#define BX_XBOX_SUBOBJECT(xbox, host, type, stage) \
{xbox, static_cast<uint32_t>(host), payload_at<type>(), record_size<type>(), stage}
constexpr StreamSubobject kStreamSubobjects[] = {
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, void*, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, D3D12_SHADER_BYTECODE, "VS"),
@@ -487,9 +522,15 @@ constexpr StreamSubobject kStreamSubobjects[] = {
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, UINT, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, D3D12_DEPTH_STENCIL_DESC1, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING, D3D12_VIEW_INSTANCING_DESC, nullptr),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, D3D12_SHADER_BYTECODE, "AS"),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, D3D12_SHADER_BYTECODE, "MS"),
BX_XBOX_SUBOBJECT(kXboxSubobjectAS, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, D3D12_SHADER_BYTECODE, "AS"),
BX_XBOX_SUBOBJECT(kXboxSubobjectMS, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, D3D12_SHADER_BYTECODE, "MS"),
BX_XBOX_SUBOBJECT(kXboxSubobjectPixelShaderOptions, kNoHostSubobject, XboxPixelShaderOptionsDesc, nullptr),
BX_XBOX_SUBOBJECT(kXboxSubobjectDepthStencilOptions, kNoHostSubobject, XboxDepthStencilOptionsDesc, nullptr),
BX_XBOX_SUBOBJECT(kXboxSubobjectGraphicsShaderLimits, kNoHostSubobject, XboxGraphicsShaderLimitsDesc, nullptr),
BX_XBOX_SUBOBJECT(kXboxSubobjectTessellationParameters, kNoHostSubobject, XboxTessellationParametersDesc, nullptr),
BX_XBOX_SUBOBJECT(kXboxSubobjectComputeShaderLimits, kNoHostSubobject, XboxComputeShaderLimitsDesc, nullptr),
};
#undef BX_XBOX_SUBOBJECT
#undef BX_SUBOBJECT
/* Pin the layout facts the walker depends on, measured with this toolchain. A header change
@@ -504,48 +545,81 @@ static_assert(payload_at<D3D12_RT_FORMAT_ARRAY>() == 4, "RT_FORMAT_ARRAY payload
static_assert(payload_at<D3D12_DEPTH_STENCIL_DESC1>() == 4, "DEPTH_STENCIL1 payload sits at offset 4");
static_assert(payload_at<void*>() == 8 && record_size<void*>() == 16, "root signature record");
static_assert(payload_at<D3D12_INPUT_LAYOUT_DESC>() == 8, "INPUT_LAYOUT payload sits at offset 8");
static_assert(record_size<XboxPixelShaderOptionsDesc>() == 40, "PIXEL_SHADER_OPTIONS record");
static_assert(record_size<XboxDepthStencilOptionsDesc>() == 32, "DEPTH_STENCIL_OPTIONS record");
static_assert(record_size<XboxGraphicsShaderLimitsDesc>() == 64, "GRAPHICS_SHADER_LIMITS record");
static_assert(record_size<XboxTessellationParametersDesc>() == 16, "TESSELLATION_PARAMETERS record");
static_assert(record_size<XboxComputeShaderLimitsDesc>() == 32, "COMPUTE_SHADER_LIMITS record");
static_assert(static_cast<uint32_t>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING) == 22,
"the GDK and the host SDK agree on 0..22");
/* `type` in the GDK's numbering (a title's stream). */
const StreamSubobject* find_subobject(uint32_t type) {
for (const StreamSubobject& entry : kStreamSubobjects) {
if (static_cast<uint32_t>(entry.type) == type) return &entry;
if (entry.type == type) return &entry;
}
return nullptr;
}
/* Copies the caller's stream into `copy` so the gate can substitute prepared bytecode without
* touching memory it does not own, and records where each shader payload sits (and, when
* `root_offset` is given, the root-signature payload, or SIZE_MAX without one). An unknown tag,
* or a payload that overruns SizeInBytes, is rejected. */
/* `type` in the host SDK's numbering (a stream copy_stream produced). */
static const StreamSubobject* find_host_subobject(uint32_t type) {
for (const StreamSubobject& entry : kStreamSubobjects) {
if (entry.host_type == type) return &entry;
}
return nullptr;
}
static void note_xbox_only_subobject(uint32_t type) {
static std::atomic<uint32_t> seen{0};
const uint32_t bit = 1u << type;
if (seen.fetch_or(bit) & bit) return;
char detail[128];
std::snprintf(detail, sizeof(detail), "Xbox-only pipeline subobject %u not applied: D3D12 has no counterpart",
type);
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pso_stream_xbox_subobject", detail);
}
/* Reads the title's stream (GDK numbering) and writes `copy` in the host's numbering, so the gate
* can substitute prepared bytecode without touching memory it does not own. Xbox-only subobjects
* are left out of `copy`, which can therefore be shorter than SizeInBytes: pass copy.size() on.
* Records where each shader payload sits in `copy` (and, when `root_offset` is given, the
* root-signature payload, or SIZE_MAX without one). An unknown tag, a duplicated one, or a payload
* that overruns SizeInBytes, is rejected. */
HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<uint8_t>& copy,
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names,
size_t* root_offset) {
if (root_offset) *root_offset = SIZE_MAX;
copy.clear();
if (desc.SizeInBytes == 0 || !desc.pPipelineStateSubobjectStream) return E_INVALIDARG;
const auto* source = static_cast<const uint8_t*>(desc.pPipelineStateSubobjectStream);
copy.assign(source, source + desc.SizeInBytes);
const size_t size = desc.SizeInBytes;
copy.reserve(size);
uint32_t seen = 0;
size_t offset = 0;
while (offset < copy.size()) {
if (copy.size() - offset < sizeof(SIZE_T)) return E_INVALIDARG;
while (offset < size) {
if (size - offset < sizeof(SIZE_T)) return E_INVALIDARG;
/* The tag is a 4-byte enum at the start of an 8-byte-aligned record; the rest of
* those 8 bytes is padding a caller may leave uninitialized, so read only the enum
* and step to the payload at offset sizeof(SIZE_T). */
uint32_t raw = 0;
std::memcpy(&raw, &copy[offset], sizeof(raw));
if (raw >= static_cast<uint32_t>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID)) return E_INVALIDARG;
std::memcpy(&raw, source + offset, sizeof(raw));
if (raw >= kXboxSubobjectLimit) return E_INVALIDARG;
const StreamSubobject* entry = find_subobject(raw);
if (!entry) return E_INVALIDARG;
/* Microsoft's ID3D12Device2 rules reject a duplicated subobject type. */
for (size_t seen = 0; seen < offset; ) {
uint32_t prior = 0;
std::memcpy(&prior, &copy[seen], sizeof(prior));
if (prior == raw) return E_INVALIDARG;
const StreamSubobject* prior_entry = find_subobject(prior);
if (!prior_entry) return E_INVALIDARG;
seen += prior_entry->record_size;
}
const size_t payload = offset + entry->payload_offset;
if (seen & (1u << raw)) return E_INVALIDARG;
seen |= 1u << raw;
const size_t record = entry->record_size;
if (copy.size() - offset < record) return E_INVALIDARG;
if (size - offset < record) return E_INVALIDARG;
if (entry->host_type == kNoHostSubobject) {
note_xbox_only_subobject(raw);
offset += record;
continue;
}
const size_t at = copy.size();
copy.insert(copy.end(), source + offset, source + offset + record);
std::memcpy(&copy[at], &entry->host_type, sizeof(entry->host_type));
const size_t payload = at + entry->payload_offset;
if (root_offset && entry->type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE) *root_offset = payload;
if (entry->stage) {
D3D12_SHADER_BYTECODE code{};
@@ -564,7 +638,7 @@ size_t bx_stream_payload(const std::vector<uint8_t>& stream, uint32_t type) {
while (offset + sizeof(SIZE_T) <= stream.size()) {
uint32_t raw = 0;
std::memcpy(&raw, &stream[offset], sizeof(raw));
const StreamSubobject* entry = find_subobject(raw);
const StreamSubobject* entry = find_host_subobject(raw);
if (!entry) return SIZE_MAX;
if (raw == type) return offset + entry->payload_offset;
offset += entry->record_size;
@@ -599,8 +673,10 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELIN
static_cast<unsigned long long>(desc->SizeInBytes), offsets.empty() ? 1 : 0);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_stream", detail);
}
/* The host gets the renumbered copy, never the title's stream (GDK numbering). */
D3D12_PIPELINE_STATE_STREAM_DESC admitted{stream.size(), stream.data()};
if (FAILED(copied) || offsets.empty()) {
const HRESULT hr = FAILED(copied) ? copied : h_ID3D12Device2->CreatePipelineState(desc, riid, ppv);
const HRESULT hr = FAILED(copied) ? copied : h_ID3D12Device2->CreatePipelineState(&admitted, riid, ppv);
log_created("stream pipeline state", hr);
return hr;
}
@@ -620,8 +696,6 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELIN
log_created("stream pipeline state", gated);
return gated;
}
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
admitted.pPipelineStateSubobjectStream = stream.data();
const HRESULT hr = h_ID3D12Device2->CreatePipelineState(&admitted, riid, ppv);
log_created("stream pipeline state", hr);
return hr;
+5 -3
View File
@@ -119,10 +119,12 @@ using BxCommandListProxy = BxChildProxy<BxCommandListProxyGen>;
#endif /* BETTERXEN_D3D12_XS_PROXY_H */
/* Validates and copies a pipeline-state stream (proxy.cpp, #576): shader payload offsets and
* stage names, and the root-signature payload offset when `root_offset` is given. */
/* Validates and copies a title's pipeline-state stream (proxy.cpp, #576), read with the GDK's
* subobject numbers and written with the host's; Xbox-only subobjects are left out, so pass
* copy.size() on, not SizeInBytes. Reports shader payload offsets and stage names, and the
* root-signature payload offset when `root_offset` is given. */
HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<uint8_t>& copy,
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names,
size_t* root_offset);
/* The payload offset of the subobject of `type` in a stream copy_stream accepted, or SIZE_MAX. */
/* The payload offset of the subobject of host `type` in a stream copy_stream produced, or SIZE_MAX. */
size_t bx_stream_payload(const std::vector<uint8_t>& stream, uint32_t type);
+1
View File
@@ -94,6 +94,7 @@ bool ring_place(ID3D12Device* device, const uint8_t* data, size_t size, D3D12_GP
const uint64_t aligned = (size + 15) & ~15ull;
if (cursor + aligned > kRing) cursor = 0;
std::memcpy(mapped + cursor, data, size);
bx_title_copy_count(BxTitleCopy::RectList, size);
*address = ring->GetGPUVirtualAddress() + cursor;
cursor += aligned;
return true;
+115
View File
@@ -1,9 +1,12 @@
#include "shader_gate.h"
#include <atomic>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <iterator>
#include <mutex>
#include <unordered_map>
#include "bx_log.h"
#include "bx_shader_bridge.h"
@@ -203,6 +206,82 @@ void log_gate(const char* pso_kind, const char* stage, size_t len, const bx_shad
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "shader_gate", detail);
}
/*
* Decisions remembered per shader (#818). A title recreates the same pipelines many times (the
* target build tens of thousands of times in two minutes), and the decision depends only on the
* bytecode, so it is made and logged once per shader, PSO kind and stage. Later calls with the
* same bytes take the remembered result without calling the bridge, and are only counted
* (`shader_gate_reused`). A shader passed as prepared DXIL keeps that copy for the process, so
* the host gets the same bytes it got the first time. Failures that are not a decision
* (prepare_failed, copy_limit) are not remembered.
*
* The key is the length plus two independent 64-bit hashes of the bytes (FNV-1a, and a
* multiply-rotate over 8-byte words), and a hash of the PSO kind and stage names.
*/
struct GateKey {
uint64_t fnv;
uint64_t mix;
uint64_t where;
size_t len;
bool operator==(const GateKey& o) const {
return fnv == o.fnv && mix == o.mix && where == o.where && len == o.len;
}
};
struct GateKeyHash {
size_t operator()(const GateKey& k) const { return static_cast<size_t>(k.fnv ^ (k.where * 0x9e3779b97f4a7c15ull)); }
};
struct Remembered {
HRESULT hr;
const uint8_t* copy; // the prepared DXIL handed to the host, or null when it got the input
size_t copy_len;
};
std::mutex g_remembered_lock;
std::unordered_map<GateKey, Remembered, GateKeyHash> g_remembered;
std::atomic<uint64_t> g_reused{0};
uint64_t fnv1a(const void* data, size_t size, uint64_t h = 14695981039346656037ull) {
for (size_t i = 0; i < size; ++i) h = (h ^ static_cast<const uint8_t*>(data)[i]) * 1099511628211ull;
return h;
}
uint64_t word_mix(const uint8_t* bytes, size_t len) {
uint64_t h = 0x243f6a8885a308d3ull ^ len;
size_t i = 0;
for (; i + 8 <= len; i += 8) {
uint64_t word;
std::memcpy(&word, bytes + i, sizeof(word));
h = (h ^ word) * 0xff51afd7ed558ccdull;
h = (h << 29) | (h >> 35);
}
uint64_t tail = 0;
std::memcpy(&tail, bytes + i, len - i);
h = (h ^ tail) * 0xc4ceb9fe1a85ec53ull;
return h ^ (h >> 33);
}
GateKey gate_key(const char* pso_kind, const char* stage, const uint8_t* bytes, size_t len) {
const uint64_t where = fnv1a(stage, std::strlen(stage), fnv1a(pso_kind, std::strlen(pso_kind) + 1));
return {fnv1a(bytes, len), word_mix(bytes, len), where, len};
}
void note_reused() {
const uint64_t total = ++g_reused;
if (total & (total - 1)) return; // the 1st, 2nd, 4th, ... reuse
size_t remembered = 0;
{
std::lock_guard<std::mutex> guard(g_remembered_lock);
remembered = g_remembered.size();
}
char detail[200];
std::snprintf(detail, sizeof(detail),
"gate decisions reused=%llu remembered=%llu: a shader seen before is not inspected or logged again",
static_cast<unsigned long long>(total), static_cast<unsigned long long>(remembered));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "shader_gate_reused", detail);
}
} // namespace
BxShaderGate::~BxShaderGate() {
@@ -216,6 +295,42 @@ HRESULT BxShaderGate::admit(const char* pso_kind, const char* stage, const D3D12
D3D12_SHADER_BYTECODE& out) {
out = in;
if (!in.pShaderBytecode || in.BytecodeLength == 0) return S_OK;
const GateKey key = gate_key(pso_kind, stage, static_cast<const uint8_t*>(in.pShaderBytecode), in.BytecodeLength);
bool seen = false;
Remembered r{};
{
std::lock_guard<std::mutex> guard(g_remembered_lock);
const auto found = g_remembered.find(key);
if (found != g_remembered.end()) {
seen = true;
r = found->second;
}
}
if (seen) {
if (SUCCEEDED(r.hr) && r.copy) {
out.pShaderBytecode = r.copy;
out.BytecodeLength = r.copy_len;
}
note_reused();
return r.hr;
}
const size_t copies_before = copy_count_;
const HRESULT hr = decide(pso_kind, stage, in, out);
if (hr != S_OK && hr != E_NOTIMPL) return hr; // not a decision: try again next time
// A passed copy moves from this object to the table, which keeps it for the process.
const bool passed_copy = hr == S_OK && copy_count_ > copies_before && out.pShaderBytecode == copies_[copy_count_ - 1];
r = {hr, passed_copy ? copies_[copy_count_ - 1] : nullptr, passed_copy ? copy_sizes_[copy_count_ - 1] : 0};
{
std::lock_guard<std::mutex> guard(g_remembered_lock);
// Another thread may have decided the same shader meanwhile; then this copy stays ours.
if (g_remembered.emplace(key, r).second && passed_copy) --copy_count_;
}
return hr;
}
HRESULT BxShaderGate::decide(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTECODE& in,
D3D12_SHADER_BYTECODE& out) {
const auto* bytes = static_cast<const uint8_t*>(in.pShaderBytecode);
const size_t len = in.BytecodeLength;
+8
View File
@@ -27,11 +27,19 @@ public:
* DXIL for D3DMetal until M3 Branch D2, with or without the bridge, and for a container whose
* DXIL part the bridge cannot classify (a header-only program). Copies live until this
* object is destroyed.
*
* The decision is remembered per shader, PSO kind and stage (#818): a later call with the
* same bytes returns it without calling the bridge or logging it again, and a passed DXIL
* copy is then kept for the process instead of until this object is destroyed.
*/
HRESULT admit(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTECODE& in,
D3D12_SHADER_BYTECODE& out);
private:
/* The first decision for a shader: classifies, logs and (for DXIL) prepares the copy. */
HRESULT decide(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTECODE& in,
D3D12_SHADER_BYTECODE& out);
static constexpr size_t kMaxCopies = 5; /* VS, PS, DS, HS, GS */
uint8_t* copies_[kMaxCopies] = {};
size_t copy_sizes_[kMaxCopies] = {};
+33
View File
@@ -2,6 +2,11 @@
#include <windows.h>
#include <atomic>
#include <cstdio>
#include "bx_log.h"
#include "bx_xmem_internal.h"
namespace {
@@ -50,3 +55,31 @@ uint64_t bx_title_memory_readable_extent(uint64_t address, uint64_t limit) {
if (end <= address) return 0;
return end - address < limit ? end - address : limit;
}
namespace {
std::atomic<uint64_t> g_copy_bytes[static_cast<unsigned>(BxTitleCopy::Count)];
std::atomic<uint64_t> g_copy_submissions{0};
} // namespace
void bx_title_copy_count(BxTitleCopy path, uint64_t bytes) {
if (bytes) g_copy_bytes[static_cast<unsigned>(path)].fetch_add(bytes, std::memory_order_relaxed);
}
void bx_title_copy_note_submission() {
const uint64_t n = g_copy_submissions.fetch_add(1, std::memory_order_relaxed) + 1;
const bool power_of_two = (n & (n - 1)) == 0;
if (!(power_of_two && n <= 1024) && n % 1024 != 0) return;
auto at = [](BxTitleCopy path) {
return static_cast<unsigned long long>(g_copy_bytes[static_cast<unsigned>(path)].load(std::memory_order_relaxed));
};
char detail[384];
std::snprintf(detail, sizeof(detail),
"submissions=%llu shadow_create=%llu bound_refresh=%llu mapped_sync=%llu map_read=%llu "
"unmap_write=%llu texture_upload=%llu constant_copy=%llu rect_list=%llu",
static_cast<unsigned long long>(n), at(BxTitleCopy::ShadowCreate), at(BxTitleCopy::BoundRefresh),
at(BxTitleCopy::MappedSync), at(BxTitleCopy::MapRead), at(BxTitleCopy::UnmapWrite),
at(BxTitleCopy::TextureUpload), at(BxTitleCopy::ConstantCopy), at(BxTitleCopy::RectList));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "title_copy_bytes", detail);
}
+21
View File
@@ -17,3 +17,24 @@ bool bx_title_memory_present(uint64_t address, uint64_t size, bool write = false
// How many bytes from `address` are present and readable, up to `limit`, within the one region
// (or xmem page) that holds `address`.
uint64_t bx_title_memory_readable_extent(uint64_t address, uint64_t limit);
// Bytes d3d12_xs moves between title memory and host resources, one counter per path. They show
// what a copy-free path would save (#473 found D3DMetal cannot wrap title memory, so every byte the
// GPU reads from it goes through one of these).
enum class BxTitleCopy : unsigned {
ShadowCreate, // a placed or bound buffer's host copy, filled once when it is made
BoundRefresh, // VB/IB/root ranges bound from title memory, copied again at every submit
MappedSync, // buffers the title keeps mapped, copied whole at every submit
MapRead, // host to title, for the read range of a Map
UnmapWrite, // title to host, for the written range of an Unmap
TextureUpload, // texture contents read from title memory for a translated draw
ConstantCopy, // constant buffers copied into the upload ring at submit
RectList, // rect-list vertices expanded into the upload ring, per draw
Count,
};
void bx_title_copy_count(BxTitleCopy path, uint64_t bytes);
// Called once per ExecuteCommandLists. Logs `title_copy_bytes` (running totals) at submissions
// 1, 2, 4, ... 1024 and every 1024th after that.
void bx_title_copy_note_submission();
@@ -0,0 +1,3 @@
add_executable(test_d3d12_title_copy_counters main.cpp)
target_compile_definitions(test_d3d12_title_copy_counters PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_title_copy_counters PRIVATE d3d12_xs kernel32 uuid)
@@ -0,0 +1,225 @@
/*
* Conformance test: d3d12_xs counts the bytes it copies from title memory into host resources.
*
* Contract (this layer's own, #816): every ExecuteCommandLists counts as one submission, and
* `title_copy_bytes` logs running byte totals per copy path at submissions 1, 2, 4, ... 1024 and
* every 1024th after that. Two paths are exercised here, with sizes the test chooses:
* - bound_refresh: a vertex buffer bound from plain title memory (VirtualAlloc, no Direct3D
* resource) is copied to its host buffer at every submission of the list that binds it, so
* after N submissions of a 64 KiB binding the total is N x 64 KiB;
* - mapped_sync: a committed UPLOAD buffer the title keeps mapped is copied whole at every
* submission: each submission while a 4 KiB buffer stays mapped adds the same amount, at least
* 4 KiB (the shim copies the console allocation behind it); after Unmap the total stops growing.
* Expected values come from these sizes and submission counts, not from the shim.
*
* Slots (Xbox-layout tables, ADR 0009): as in test_d3d12_title_memory_geometry.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr int kRelease = 2;
constexpr int kDevCreateCommandAllocator = 9, kDevCreateCommittedResource = 27, kDevCreateFence = 36;
constexpr int kDevCreateCommandQueueX = 48, kDevCreateCommandListX = 73;
constexpr int kResMap = 8, kResUnmap = 9;
constexpr int kListClose = 9, kListIASetVertexBuffers = 48;
constexpr int kQueueExecuteCommandLists = 10, kQueueSignal = 16, kFenceSetEventOnCompletion = 9;
constexpr uint64_t kVertexBytes = 64 * 1024;
constexpr uint64_t kUploadBytes = 4096;
int g_checks = 0;
int g_failed = 0;
#define CHECK(cond, ...) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_title_copy_counters:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
struct QueueDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, EngineOrPipeIndex, QueueIndex;
};
struct ListDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, NodeMask, ResourceBarrierBatchSize;
};
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
const D3D12_CLEAR_VALUE*, REFIID, void**);
using CreateFenceFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, D3D12_FENCE_FLAGS, REFIID, void**);
using MapFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RANGE*, void**);
using UnmapFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RANGE*);
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
using SetVbFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_VERTEX_BUFFER_VIEW*);
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
using QueueSignalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64);
using FenceEventFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, HANDLE);
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* f = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
std::fclose(f);
}
return text;
}
// The value of `key=` in the title_copy_bytes record for `submissions`, or -1 when there is none.
long long counter(const std::string& log, unsigned submissions, const char* key) {
char needle[64];
std::snprintf(needle, sizeof(needle), "submissions=%u ", submissions);
size_t start = 0;
while (start < log.size()) {
size_t end = log.find('\n', start);
if (end == std::string::npos) end = log.size();
const std::string line = log.substr(start, end - start);
if (line.find("\"event\":\"title_copy_bytes\"") != std::string::npos && line.find(needle) != std::string::npos) {
const std::string k = std::string(" ") + key + "=";
const size_t at = line.find(k);
if (at == std::string::npos) return -1;
return std::strtoll(line.c_str() + at + k.size(), nullptr, 10);
}
start = end + 1;
}
return -1;
}
} // namespace
int main() {
if (GetEnvironmentVariableA("BX_LOG_FILE", nullptr, 0) == 0) {
std::fprintf(stderr, "FAIL: test_d3d12_title_copy_counters: BX_LOG_FILE is not set; run through bx-cli run --log\n");
return 1;
}
alignas(8) unsigned char title_params[80] = {};
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
std::memcpy(title_params, &version, sizeof(version));
void* dev = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
if (hr == E_NOINTERFACE) {
std::printf("SKIP: test_d3d12_title_copy_counters: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
return 77;
}
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
if (!dev) return 1;
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
void* queue = nullptr;
void* allocator = nullptr;
void* list = nullptr;
void* fence = nullptr;
void* upload = nullptr;
slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue);
slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT,
__uuidof(ID3D12CommandAllocator), &allocator);
slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr, __uuidof(ID3D12GraphicsCommandList), &list);
slot<CreateFenceFn>(dev, kDevCreateFence)(dev, 0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &fence);
D3D12_HEAP_PROPERTIES upload_heap{};
upload_heap.Type = D3D12_HEAP_TYPE_UPLOAD;
D3D12_RESOURCE_DESC buffer{};
buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buffer.Width = kUploadBytes;
buffer.Height = 1;
buffer.DepthOrArraySize = 1;
buffer.MipLevels = 1;
buffer.SampleDesc.Count = 1;
buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &upload_heap, D3D12_HEAP_FLAG_NONE, &buffer,
D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
__uuidof(ID3D12Resource), &upload);
CHECK(hr == S_OK && upload, "committed UPLOAD buffer hr=0x%08lx", static_cast<unsigned long>(hr));
auto* vertex_memory = static_cast<uint8_t*>(VirtualAlloc(nullptr, kVertexBytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
if (!queue || !allocator || !list || !fence || !upload || !vertex_memory) {
std::fprintf(stderr, "FAIL: test_d3d12_title_copy_counters: setup\n");
return 1;
}
// One list that binds 64 KiB of plain title memory as a vertex buffer. It records nothing
// else, so each submission refreshes exactly that range.
const D3D12_VERTEX_BUFFER_VIEW view{reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(vertex_memory),
static_cast<UINT>(kVertexBytes), 16};
slot<SetVbFn>(list, kListIASetVertexBuffers)(list, 0, 1, &view);
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close");
UINT64 fence_value = 0;
auto submit = [&]() {
void* one[] = {list};
slot<ExecuteFn>(queue, kQueueExecuteCommandLists)(queue, 1, one);
++fence_value;
CHECK(slot<QueueSignalFn>(queue, kQueueSignal)(queue, fence, fence_value) == S_OK, "queue Signal");
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
CHECK(slot<FenceEventFn>(fence, kFenceSetEventOnCompletion)(fence, fence_value, done) == S_OK, "fence event");
CHECK(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0, "GPU work completes");
CloseHandle(done);
};
// Submissions 1 and 2: the upload buffer is mapped (a persistent map, as titles keep them).
void* mapped = nullptr;
const D3D12_RANGE nothing_read{0, 0};
hr = slot<MapFn>(upload, kResMap)(upload, 0, &nothing_read, &mapped);
CHECK(hr == S_OK && mapped, "upload Map hr=0x%08lx", static_cast<unsigned long>(hr));
submit();
submit();
// Submissions 3 and 4: unmapped, with nothing written.
const D3D12_RANGE nothing_written{0, 0};
slot<UnmapFn>(upload, kResUnmap)(upload, 0, &nothing_written);
submit();
submit();
const std::string log = read_log();
for (unsigned n : {1u, 2u, 4u}) {
const long long bound = counter(log, n, "bound_refresh");
CHECK(bound == static_cast<long long>(n * kVertexBytes),
"after %u submissions bound_refresh=%lld, want %llu (%u x the 64 KiB binding)", n, bound,
static_cast<unsigned long long>(n * kVertexBytes), n);
}
const long long sync1 = counter(log, 1, "mapped_sync"), sync2 = counter(log, 2, "mapped_sync");
const long long sync4 = counter(log, 4, "mapped_sync");
// The whole buffer is copied each time: at least its 4 KiB width (the shim copies its console
// allocation, which may be larger), and the same amount at each submission while it is mapped.
CHECK(sync1 >= static_cast<long long>(kUploadBytes) && sync2 - sync1 == sync1,
"each submission while the buffer is mapped adds the same amount, at least 4096, to mapped_sync (%lld, %lld)",
sync1, sync2);
CHECK(sync4 == sync2, "unmapped, the buffer is no longer copied at submit (%lld -> %lld)", sync2, sync4);
CHECK(counter(log, 3, "bound_refresh") == -1, "no record at submission 3 (logged at powers of two)");
VirtualFree(vertex_memory, 0, MEM_RELEASE);
for (void* object : {upload, fence, list, allocator, queue, dev}) slot<ReleaseFn>(object, kRelease)(object);
std::printf("%s: test_d3d12_title_copy_counters (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS",
g_checks - g_failed, g_checks);
return g_failed ? 1 : 0;
}
@@ -0,0 +1,8 @@
# Pipeline state streams written with the GDK's subobject numbering (AS 23, MS 24, Xbox-only 25..29)
# through d3d12_xs.dll. Needs bx_shader_bridge.dll beside the shims and BX_LOG_FILE (bx-cli run --log).
add_executable(test_d3d12_xbox_stream_subobjects main.cpp)
target_include_directories(test_d3d12_xbox_stream_subobjects PRIVATE
"${BX_ABI_INCLUDE_DIR}"
"${BX_ROOT_DIR}/shader-transpiler/crates/d3dmetal-harness/probe/shaders"
)
target_link_libraries(test_d3d12_xbox_stream_subobjects PRIVATE d3d12_xs kernel32)
@@ -0,0 +1,385 @@
/* test_d3d12_xbox_stream_subobjects: a title's pipeline state stream uses the GDK's subobject
* numbering, not the PC SDK's.
*
* The GDK's d3d12_xs.h numbers subobjects 0..22 as the PC SDK does, then AS = 23, MS = 24 and
* five Xbox-only subobjects at 25..29 (PIXEL_SHADER_OPTIONS, DEPTH_STENCIL_OPTIONS,
* GRAPHICS_SHADER_LIMITS, TESSELLATION_PARAMETERS, COMPUTE_SHADER_LIMITS). The PC SDK has AS = 24
* and MS = 25. Through D3D12XboxCreateDevice + ID3D12Device2::CreatePipelineState it checks:
* 1. a compute stream carrying COMPUTE_SHADER_LIMITS (29) is accepted and its kernel runs;
* 2. a compute stream carrying all five Xbox-only subobjects, followed by NODE_MASK, is accepted
* (their record sizes come from the GDK layouts, so the walk stays in step);
* 3. a duplicated Xbox-only subobject is rejected with E_INVALIDARG;
* 4. a shader under tag 24 is gated as stage MS and one under tag 23 as stage AS.
* Record sizes are taken from this test's own copies of the GDK payload layouts with the
* CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT record shape (alignas(void*) on the record), not from
* the shim. Needs bx_shader_bridge.dll beside the shims and BX_LOG_FILE (bx-cli run --log).
*/
#ifndef WIDL_EXPLICIT_AGGREGATE_RETURNS
#define WIDL_EXPLICIT_AGGREGATE_RETURNS
#endif
#include <windows.h>
#include <unknwn.h>
#include <d3d12.h>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <initializer_list>
#include <string>
#include <vector>
#include "fill_cs66.h" // g_fill_cs66, d3dmetal-harness
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12SerializeVersionedRootSignature(
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc, ID3DBlob** blob, ID3DBlob** error);
/* A zeroed D3D12XBOX_CREATE_DEVICE_PARAMETERS block asks for defaults. */
alignas(8) static const unsigned char kCreateParams[80] = {};
namespace {
/* GDK d3d12_xs.h, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE. */
constexpr uint32_t kXboxAS = 23;
constexpr uint32_t kXboxMS = 24;
constexpr uint32_t kXboxPixelShaderOptions = 25;
constexpr uint32_t kXboxDepthStencilOptions = 26;
constexpr uint32_t kXboxGraphicsShaderLimits = 27;
constexpr uint32_t kXboxTessellationParameters = 28;
constexpr uint32_t kXboxComputeShaderLimits = 29;
/* GDK payload layouts (d3d12_xs.h), all 4-byte fields. */
struct PixelShaderOptions { UINT per_sample, zorder, texkill, hier_fail, noop, depth_before, conservative_z, ooo; };
struct DepthStencilOptions {
BOOL back_face_disable, depth_bounds_disable, color_writes_on_fail, color_writes_on_pass_disable;
UINT8 read_mask_back, write_mask_back, ref_front, ref_back, op_ref_front, op_ref_back;
};
struct GraphicsShaderLimits { UINT late_alloc, vs_disable, reserved0, gs_disable, ps_disable, waves[10]; };
struct TessellationParameters { UINT patches; FLOAT factor_threshold; UINT ds_wave_threshold; };
struct ComputeShaderLimits { UINT disable_flags, max_waves_per_se, max_tg_per_cu, max_waves_cu_lock, tg_walked, simd_walk; };
int g_checks = 0;
int g_failures = 0;
__attribute__((format(gnu_printf, 2, 3)))
bool check(bool ok, const char* fmt, ...) {
++g_checks;
if (!ok) {
++g_failures;
char msg[320];
va_list ap;
va_start(ap, fmt);
std::vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
std::fprintf(stderr, "FAIL: %s\n", msg);
std::fflush(stderr);
}
return ok;
}
unsigned long ul(HRESULT hr) { return static_cast<unsigned long>(hr); }
int finish() {
if (g_failures) {
std::fprintf(stderr, "FAIL: test_d3d12_xbox_stream_subobjects (%d of %d checks failed)\n", g_failures, g_checks);
return 1;
}
std::printf("PASS: test_d3d12_xbox_stream_subobjects (%d checks)\n", g_checks);
return 0;
}
/* The kernel in fill_cs66.hlsl: Out[i] = hash(i) for 4 groups of 64 threads. */
constexpr uint32_t kWords = 256;
uint32_t expected_word(uint32_t i) {
uint32_t v = i * 0x9E3779B1u;
v ^= v >> 15;
return v + 0x01234567u;
}
template<class Payload>
struct alignas(void*) Record {
uint32_t type;
Payload payload;
};
struct StreamBuilder {
std::vector<uint8_t> bytes;
template<class Payload>
void add(uint32_t type, const Payload& payload) {
using R = Record<Payload>;
const size_t at = bytes.size();
bytes.resize(at + sizeof(R), 0);
std::memcpy(bytes.data() + at + offsetof(R, type), &type, sizeof(type));
std::memcpy(bytes.data() + at + offsetof(R, payload), &payload, sizeof(payload));
}
D3D12_PIPELINE_STATE_STREAM_DESC desc() const {
D3D12_PIPELINE_STATE_STREAM_DESC d = {};
d.SizeInBytes = bytes.size();
d.pPipelineStateSubobjectStream = const_cast<uint8_t*>(bytes.data());
return d;
}
};
/* Record sizes of the Xbox-only subobjects, as CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT lays them out. */
static_assert(sizeof(Record<PixelShaderOptions>) == 40, "PIXEL_SHADER_OPTIONS record");
static_assert(sizeof(Record<DepthStencilOptions>) == 32, "DEPTH_STENCIL_OPTIONS record");
static_assert(sizeof(Record<GraphicsShaderLimits>) == 64, "GRAPHICS_SHADER_LIMITS record");
static_assert(sizeof(Record<TessellationParameters>) == 16, "TESSELLATION_PARAMETERS record");
static_assert(sizeof(Record<ComputeShaderLimits>) == 32, "COMPUTE_SHADER_LIMITS record");
void put32(std::vector<uint8_t>& out, size_t at, uint32_t value) { std::memcpy(out.data() + at, &value, 4); }
/* A DXBC container holding one ACCC chunk (FSPX v1, stage configuration only) and no DXIL: the
* gate refuses it before the host sees it, so the stage name it logs is the shim's reading. */
std::vector<uint8_t> accc_only_container() {
std::vector<uint8_t> fspx(40, 0);
std::memcpy(fspx.data(), "FSPX", 4);
put32(fspx, 4, 1);
put32(fspx, 8, 1);
put32(fspx, 16, 1);
put32(fspx, 20, 28);
put32(fspx, 24, 12);
put32(fspx, 28, 6);
put32(fspx, 32, 6);
const uint32_t total = 32 + 4 + 8 + static_cast<uint32_t>(fspx.size());
std::vector<uint8_t> out(total, 0);
std::memcpy(out.data(), "DXBC", 4);
put32(out, 20, 1);
put32(out, 24, total);
put32(out, 28, 1);
put32(out, 32, 36);
std::memcpy(out.data() + 36, "ACCC", 4);
put32(out, 40, static_cast<uint32_t>(fspx.size()));
std::memcpy(out.data() + 44, fspx.data(), fspx.size());
return out;
}
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* file = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), file)) > 0) text.append(buffer, got);
std::fclose(file);
}
return text;
}
bool log_has(const std::string& log, std::initializer_list<const char*> needles) {
size_t start = 0;
while (start < log.size()) {
size_t end = log.find('\n', start);
if (end == std::string::npos) end = log.size();
const std::string line = log.substr(start, end - start);
bool all = true;
for (const char* needle : needles) all = all && line.find(needle) != std::string::npos;
if (all) return true;
start = end + 1;
}
return false;
}
ID3D12RootSignature* make_root(ID3D12Device* device) {
D3D12_ROOT_PARAMETER uav = {};
uav.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
uav.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc = {};
desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
desc.Desc_1_0.NumParameters = 1;
desc.Desc_1_0.pParameters = &uav;
ID3DBlob* blob = nullptr;
ID3DBlob* error = nullptr;
HRESULT hr = D3D12SerializeVersionedRootSignature(&desc, &blob, &error);
if (error) error->Release();
if (!check(SUCCEEDED(hr) && blob, "D3D12SerializeVersionedRootSignature hr=0x%08lx", ul(hr))) return nullptr;
ID3D12RootSignature* root = nullptr;
hr = device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), __uuidof(ID3D12RootSignature),
reinterpret_cast<void**>(&root));
blob->Release();
check(SUCCEEDED(hr) && root, "CreateRootSignature hr=0x%08lx", ul(hr));
return root;
}
ID3D12Resource* make_buffer(ID3D12Device* device, D3D12_HEAP_TYPE heap, D3D12_RESOURCE_FLAGS flags,
D3D12_RESOURCE_STATES state) {
D3D12_HEAP_PROPERTIES props = {};
props.Type = heap;
D3D12_RESOURCE_DESC desc = {};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = kWords * 4;
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.SampleDesc.Count = 1;
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
desc.Flags = flags;
ID3D12Resource* buffer = nullptr;
const HRESULT hr = device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&buffer));
check(SUCCEEDED(hr) && buffer, "CreateCommittedResource heap=%d hr=0x%08lx", static_cast<int>(heap), ul(hr));
return buffer;
}
HRESULT create_stream(ID3D12Device* device, const StreamBuilder& stream, ID3D12PipelineState** pso) {
*pso = nullptr;
const D3D12_PIPELINE_STATE_STREAM_DESC desc = stream.desc();
return static_cast<ID3D12Device2*>(device)->CreatePipelineState(&desc, __uuidof(ID3D12PipelineState),
reinterpret_cast<void**>(pso));
}
/* Runs fill_cs66 and checks every output word. */
void run_kernel(ID3D12Device* device, ID3D12RootSignature* root, ID3D12PipelineState* pso) {
D3D12_COMMAND_QUEUE_DESC queue_desc = {};
queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
ID3D12CommandQueue* queue = nullptr;
ID3D12CommandAllocator* allocator = nullptr;
ID3D12GraphicsCommandList* list = nullptr;
ID3D12Fence* fence = nullptr;
HRESULT hr = device->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&queue));
if (!check(SUCCEEDED(hr), "CreateCommandQueue hr=0x%08lx", ul(hr))) return;
hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
reinterpret_cast<void**>(&allocator));
if (check(SUCCEEDED(hr), "CreateCommandAllocator hr=0x%08lx", ul(hr))) {
hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator, pso,
__uuidof(ID3D12GraphicsCommandList), reinterpret_cast<void**>(&list));
check(SUCCEEDED(hr), "CreateCommandList hr=0x%08lx", ul(hr));
}
hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence));
check(SUCCEEDED(hr), "CreateFence hr=0x%08lx", ul(hr));
ID3D12Resource* out = make_buffer(device, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
ID3D12Resource* readback =
make_buffer(device, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST);
if (list && fence && out && readback) {
list->SetComputeRootSignature(root);
list->SetComputeRootUnorderedAccessView(0, out->GetGPUVirtualAddress());
list->Dispatch(kWords / 64, 1, 1);
D3D12_RESOURCE_BARRIER barrier = {};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Transition.pResource = out;
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
list->ResourceBarrier(1, &barrier);
list->CopyResource(readback, out);
hr = list->Close();
check(SUCCEEDED(hr), "Close hr=0x%08lx", ul(hr));
ID3D12CommandList* lists[] = {list};
queue->ExecuteCommandLists(1, lists);
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
check(SUCCEEDED(queue->Signal(fence, 1)), "Signal");
if (fence->GetCompletedValue() < 1) {
check(SUCCEEDED(fence->SetEventOnCompletion(1, done)), "SetEventOnCompletion");
check(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0, "fence did not complete within 10 s");
}
CloseHandle(done);
void* mapped = nullptr;
D3D12_RANGE range = {0, kWords * 4};
hr = readback->Map(0, &range, &mapped);
if (check(SUCCEEDED(hr) && mapped, "Map hr=0x%08lx", ul(hr))) {
const auto* words = static_cast<const uint32_t*>(mapped);
uint32_t mismatched = 0;
for (uint32_t i = 0; i < kWords; ++i) mismatched += words[i] != expected_word(i);
check(mismatched == 0, "kernel readback: %u of %u words wrong", mismatched, kWords);
D3D12_RANGE none = {0, 0};
readback->Unmap(0, &none);
}
}
if (readback) readback->Release();
if (out) out->Release();
if (fence) fence->Release();
if (list) list->Release();
if (allocator) allocator->Release();
if (queue) queue->Release();
}
StreamBuilder compute_stream(ID3D12RootSignature* root) {
StreamBuilder stream;
stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root);
stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, D3D12_SHADER_BYTECODE{g_fill_cs66, sizeof(g_fill_cs66)});
return stream;
}
} // namespace
int main() {
check(expected_word(0) == 0x01234567u && expected_word(255) == 0x9a664b32u, "expected_word reference values");
if (!check(GetEnvironmentVariableA("BX_LOG_FILE", nullptr, 0) > 0, "BX_LOG_FILE is not set; run through bx-cli run --log")) {
return finish();
}
ID3D12Device* device = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (!check(SUCCEEDED(hr) && device, "D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) return finish();
ID3D12RootSignature* root = make_root(device);
if (!root) return finish();
ID3D12PipelineState* pso = nullptr;
// 1. COMPUTE_SHADER_LIMITS (29) is a valid Xbox subobject: the stream is accepted and runs.
{
StreamBuilder stream = compute_stream(root);
stream.add(kXboxComputeShaderLimits, ComputeShaderLimits{0, 0, 0, 0, 0, 0});
hr = create_stream(device, stream, &pso);
check(SUCCEEDED(hr) && pso, "compute stream with COMPUTE_SHADER_LIMITS (29): hr=0x%08lx", ul(hr));
if (pso) {
run_kernel(device, root, pso);
pso->Release();
}
}
// 2. All five Xbox-only subobjects, then NODE_MASK: each record is stepped over at its GDK size.
{
StreamBuilder stream;
stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root);
stream.add(kXboxPixelShaderOptions, PixelShaderOptions{});
stream.add(kXboxDepthStencilOptions, DepthStencilOptions{});
stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, D3D12_SHADER_BYTECODE{g_fill_cs66, sizeof(g_fill_cs66)});
stream.add(kXboxGraphicsShaderLimits, GraphicsShaderLimits{});
stream.add(kXboxTessellationParameters, TessellationParameters{});
stream.add(kXboxComputeShaderLimits, ComputeShaderLimits{});
stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, UINT{0});
hr = create_stream(device, stream, &pso);
check(SUCCEEDED(hr) && pso, "compute stream with Xbox subobjects 25..29 and NODE_MASK: hr=0x%08lx", ul(hr));
if (pso) {
run_kernel(device, root, pso);
pso->Release();
}
}
// 3. A duplicated Xbox-only subobject breaks ID3D12Device2's one-of-each rule.
{
StreamBuilder stream = compute_stream(root);
stream.add(kXboxComputeShaderLimits, ComputeShaderLimits{});
stream.add(kXboxComputeShaderLimits, ComputeShaderLimits{});
hr = create_stream(device, stream, &pso);
check(hr == E_INVALIDARG && !pso, "duplicated COMPUTE_SHADER_LIMITS: hr=0x%08lx (want E_INVALIDARG)", ul(hr));
if (pso) pso->Release();
}
// 4. Tag 24 carries a mesh shader and tag 23 an amplification shader. A console-only container
// is refused by the gate, which logs the stage it was given.
const std::vector<uint8_t> accc = accc_only_container();
for (uint32_t tag : {kXboxMS, kXboxAS}) {
StreamBuilder stream;
stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root);
stream.add(tag, D3D12_SHADER_BYTECODE{accc.data(), accc.size()});
hr = create_stream(device, stream, &pso);
std::printf("tag %u console-only stream: hr=0x%08lx\n", tag, ul(hr));
if (pso) pso->Release();
}
const std::string log = read_log();
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=stream", "stage=MS", "decision=reject_accc_only"}),
"the shader under tag 24 was gated as stage MS");
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=stream", "stage=AS", "decision=reject_accc_only"}),
"the shader under tag 23 was gated as stage AS");
check(log_has(log, {"\"event\":\"pso_stream_xbox_subobject\"", "subobject 29 "}),
"the Xbox-only COMPUTE_SHADER_LIMITS subobject was logged as not applied");
root->Release();
device->Release();
return finish();
}
@@ -0,0 +1,8 @@
# The shader gate decides once per shader, PSO kind and stage (#818): recreating the same pipeline
# does not inspect or log the shader again. Needs bx_shader_bridge.dll next to the shims at run time.
add_executable(test_shader_gate_reuse main.cpp)
target_include_directories(test_shader_gate_reuse PRIVATE
"${BX_ABI_INCLUDE_DIR}"
"${BX_ROOT_DIR}/shader-transpiler/crates/d3dmetal-harness/probe/shaders"
)
target_link_libraries(test_shader_gate_reuse PRIVATE d3d12_xs kernel32)
@@ -0,0 +1,397 @@
/*
* The shader gate decides once per shader, PSO kind and stage (#818).
*
* A title may create the same pipeline many times: the target build creates pipelines with the
* same shaders tens of thousands of times in two minutes. The gate's decision depends only on
* the shader's bytes, so d3d12_xs makes it, and logs its `shader_gate` record, the first time a
* shader is seen for a PSO kind and stage, and reuses it afterwards.
*
* Through D3D12XboxCreateDevice the test creates, 300 times each:
* - a compute PSO from a real DXC 1.9.2609 SM 6.6 DXIL blob (fill_cs66, from d3dmetal-harness);
* every creation must succeed, and the last pipeline must still run and write all 256
* expected words (the reused, prepared DXIL is what the host got);
* - a compute PSO from a synthetic ACCC-only container: every creation must return E_NOTIMPL
* with no object, as the first one does;
* - a stream PSO with the same DXIL as its CS stage.
* It then requires exactly one `shader_gate` record for each of the three, and one or more
* `shader_gate_reused` records. Expected outputs come from the D3D12 contract and the documented
* kernel, not from the shim. Needs bx_shader_bridge.dll next to the shims and BX_LOG_FILE.
*/
#ifndef WIDL_EXPLICIT_AGGREGATE_RETURNS
#define WIDL_EXPLICIT_AGGREGATE_RETURNS
#endif
#include <windows.h>
#include <unknwn.h>
#include <d3d12.h>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include "fill_cs66.h" // g_fill_cs66, d3dmetal-harness
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
/* A zeroed D3D12XBOX_CREATE_DEVICE_PARAMETERS block asks for defaults (as in test_shader_gate). */
alignas(8) static const unsigned char kCreateParams[80] = {};
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12SerializeVersionedRootSignature(
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc, ID3DBlob** blob, ID3DBlob** error);
namespace {
int g_checks = 0;
int g_failures = 0;
__attribute__((format(gnu_printf, 2, 3)))
bool check(bool ok, const char* fmt, ...) {
++g_checks;
if (!ok) {
++g_failures;
char msg[320];
va_list ap;
va_start(ap, fmt);
std::vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
std::fprintf(stderr, "FAIL: %s\n", msg);
std::fflush(stderr);
}
return ok;
}
unsigned long ul(HRESULT hr) { return static_cast<unsigned long>(hr); }
/* The kernel in fill_cs66.hlsl: Out[i] = hash(i) for 4 groups of 64 threads. */
constexpr uint32_t kWords = 256;
uint32_t expected_word(uint32_t i) {
uint32_t v = i * 0x9E3779B1u;
v ^= v >> 15;
return v + 0x01234567u;
}
void put32(std::vector<uint8_t>& out, size_t at, uint32_t value) { std::memcpy(out.data() + at, &value, 4); }
/* A DXBC container (version 1) holding one ACCC chunk with a BetterXen FSPX v1 table whose only
* section is the stage configuration: compute, shader model 6.0. No DXIL. */
std::vector<uint8_t> accc_only_container() {
std::vector<uint8_t> fspx(40, 0);
std::memcpy(fspx.data(), "FSPX", 4);
put32(fspx, 4, 1); // version
put32(fspx, 8, 1); // section count
put32(fspx, 16, 1); // section id 1: stage configuration
put32(fspx, 20, 28); // offset
put32(fspx, 24, 12); // size
put32(fspx, 28, 6); // stage: compute
put32(fspx, 32, 6); // shader model 6.0
put32(fspx, 36, 0);
const uint32_t total = 32 + 4 + 8 + static_cast<uint32_t>(fspx.size());
std::vector<uint8_t> out(total, 0);
std::memcpy(out.data(), "DXBC", 4);
put32(out, 20, 1);
put32(out, 24, total);
put32(out, 28, 1);
put32(out, 32, 36);
std::memcpy(out.data() + 36, "ACCC", 4);
put32(out, 40, static_cast<uint32_t>(fspx.size()));
std::memcpy(out.data() + 44, fspx.data(), fspx.size());
return out;
}
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* file = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), file)) > 0) text.append(buffer, got);
std::fclose(file);
}
return text;
}
/* Every JSONL line whose text holds `needle`, so shape checks can loop over
* the records the shim actually wrote rather than the lines typed by hand in
* the trace-summary fixtures. */
std::vector<std::string> log_lines_with(const std::string& log, const char* needle) {
std::vector<std::string> lines;
size_t start = 0;
while (start < log.size()) {
size_t end = log.find('\n', start);
if (end == std::string::npos) end = log.size();
const std::string line = log.substr(start, end - start);
if (line.find(needle) != std::string::npos) lines.push_back(line);
start = end + 1;
}
return lines;
}
ID3D12RootSignature* make_root(ID3D12Device* device, const D3D12_ROOT_PARAMETER& param) {
D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc = {};
desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
desc.Desc_1_0.NumParameters = 1;
desc.Desc_1_0.pParameters = &param;
ID3DBlob* blob = nullptr;
ID3DBlob* error = nullptr;
HRESULT hr = D3D12SerializeVersionedRootSignature(&desc, &blob, &error);
if (error) error->Release();
if (!check(SUCCEEDED(hr) && blob, "D3D12SerializeVersionedRootSignature hr=0x%08lx", ul(hr))) return nullptr;
ID3D12RootSignature* root = nullptr;
hr = device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), __uuidof(ID3D12RootSignature),
reinterpret_cast<void**>(&root));
blob->Release();
check(SUCCEEDED(hr) && root, "CreateRootSignature hr=0x%08lx", ul(hr));
return root;
}
ID3D12Resource* make_buffer(ID3D12Device* device, D3D12_HEAP_TYPE heap, D3D12_RESOURCE_FLAGS flags,
D3D12_RESOURCE_STATES state) {
D3D12_HEAP_PROPERTIES props = {};
props.Type = heap;
D3D12_RESOURCE_DESC desc = {};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = kWords * 4;
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.SampleDesc.Count = 1;
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
desc.Flags = flags;
ID3D12Resource* buffer = nullptr;
const HRESULT hr = device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&buffer));
check(SUCCEEDED(hr) && buffer, "CreateCommittedResource heap=%d hr=0x%08lx", static_cast<int>(heap), ul(hr));
return buffer;
}
HRESULT create_compute(ID3D12Device* device, ID3D12RootSignature* root, const void* code, size_t size,
ID3D12PipelineState** pso) {
D3D12_COMPUTE_PIPELINE_STATE_DESC desc = {};
desc.pRootSignature = root;
desc.CS.pShaderBytecode = code;
desc.CS.BytecodeLength = size;
*pso = nullptr;
return device->CreateComputePipelineState(&desc, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(pso));
}
/* Builds a stream PSO using the REAL subobject layout: alignas(void*) on the class, so a
* 4-byte-aligned payload sits at offset 4, not 8. Encoding the layout from the compiler,
* rather than from the shim's own assumption, is what lets these tests catch a desync in the
* shim's walker (#576 review). */
template<class Payload>
struct alignas(void*) TestSubobject {
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
Payload payload;
};
struct StreamBuilder {
std::vector<uint8_t> bytes;
template<class Payload>
void add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type, const Payload& payload) {
using Record = TestSubobject<Payload>;
const size_t at = bytes.size();
bytes.resize(at + sizeof(Record), 0);
std::memcpy(bytes.data() + at + offsetof(Record, type), &type, sizeof(type));
std::memcpy(bytes.data() + at + offsetof(Record, payload), &payload, sizeof(payload));
}
D3D12_PIPELINE_STATE_STREAM_DESC desc() const {
D3D12_PIPELINE_STATE_STREAM_DESC d = {};
d.SizeInBytes = bytes.size();
d.pPipelineStateSubobjectStream = const_cast<uint8_t*>(bytes.data());
return d;
}
};
StreamBuilder compute_stream(const void* code, size_t size, ID3D12RootSignature* root) {
StreamBuilder stream;
D3D12_SHADER_BYTECODE cs = {code, size};
stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, cs);
stream.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root);
return stream;
}
HRESULT create_stream(ID3D12Device* device, const D3D12_PIPELINE_STATE_STREAM_DESC& desc,
ID3D12PipelineState** pso) {
*pso = nullptr;
auto* device2 = static_cast<ID3D12Device2*>(device);
return device2->CreatePipelineState(&desc, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(pso));
}
/* Runs fill_cs66 and checks every output word. */
void run_dxil(ID3D12Device* device, ID3D12RootSignature* root, ID3D12PipelineState* pso) {
D3D12_COMMAND_QUEUE_DESC queue_desc = {};
queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
ID3D12CommandQueue* queue = nullptr;
ID3D12CommandAllocator* allocator = nullptr;
ID3D12GraphicsCommandList* list = nullptr;
ID3D12Fence* fence = nullptr;
HRESULT hr = device->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&queue));
if (!check(SUCCEEDED(hr), "CreateCommandQueue hr=0x%08lx", ul(hr))) return;
hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
reinterpret_cast<void**>(&allocator));
if (check(SUCCEEDED(hr), "CreateCommandAllocator hr=0x%08lx", ul(hr))) {
hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator, pso,
__uuidof(ID3D12GraphicsCommandList), reinterpret_cast<void**>(&list));
check(SUCCEEDED(hr), "CreateCommandList hr=0x%08lx", ul(hr));
}
hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence));
check(SUCCEEDED(hr), "CreateFence hr=0x%08lx", ul(hr));
ID3D12Resource* out = make_buffer(device, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
ID3D12Resource* readback =
make_buffer(device, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST);
if (list && fence && out && readback) {
list->SetComputeRootSignature(root);
list->SetComputeRootUnorderedAccessView(0, out->GetGPUVirtualAddress());
list->Dispatch(kWords / 64, 1, 1);
D3D12_RESOURCE_BARRIER barrier = {};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Transition.pResource = out;
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
list->ResourceBarrier(1, &barrier);
list->CopyResource(readback, out);
hr = list->Close();
check(SUCCEEDED(hr), "Close hr=0x%08lx", ul(hr));
ID3D12CommandList* lists[] = {list};
queue->ExecuteCommandLists(1, lists);
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
check(SUCCEEDED(queue->Signal(fence, 1)), "Signal");
if (fence->GetCompletedValue() < 1) {
check(SUCCEEDED(fence->SetEventOnCompletion(1, done)), "SetEventOnCompletion");
check(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0, "fence did not complete within 10 s");
}
CloseHandle(done);
check(fence->GetCompletedValue() != UINT64_MAX, "device removed (fence value UINT64_MAX)");
void* mapped = nullptr;
D3D12_RANGE range = {0, kWords * 4};
hr = readback->Map(0, &range, &mapped);
if (check(SUCCEEDED(hr) && mapped, "Map hr=0x%08lx", ul(hr))) {
const auto* words = static_cast<const uint32_t*>(mapped);
uint32_t mismatched = 0, first = kWords;
for (uint32_t i = 0; i < kWords; ++i) {
if (words[i] != expected_word(i)) {
if (!mismatched) first = i;
++mismatched;
}
}
check(mismatched == 0, "DXIL readback: %u of %u words wrong (first %u: got 0x%08x want 0x%08x)",
mismatched, kWords, first, first < kWords ? words[first] : 0u,
first < kWords ? expected_word(first) : 0u);
D3D12_RANGE none = {0, 0};
readback->Unmap(0, &none);
if (!mismatched) std::printf("dxil: %u/%u words verified\n", kWords, kWords);
}
}
if (readback) readback->Release();
if (out) out->Release();
if (fence) fence->Release();
if (list) list->Release();
if (allocator) allocator->Release();
if (queue) queue->Release();
}
int finish() {
if (g_failures) {
std::fprintf(stderr, "FAIL: test_shader_gate_reuse (%d of %d checks failed)\n", g_failures, g_checks);
return 1;
}
std::printf("PASS: test_shader_gate_reuse (%d checks)\n", g_checks);
return 0;
}
/* Lines that hold every needle. */
size_t count_lines(const std::string& log, std::initializer_list<const char*> needles) {
size_t count = 0;
for (const std::string& line : log_lines_with(log, needles.begin()[0])) {
bool all = true;
for (const char* needle : needles) all = all && line.find(needle) != std::string::npos;
count += all;
}
return count;
}
constexpr int kRepeats = 300;
} // namespace
int main() {
if (!check(GetEnvironmentVariableA("BX_LOG_FILE", nullptr, 0) > 0,
"BX_LOG_FILE is not set; run through bx-cli run --log")) {
return finish();
}
ID3D12Device* device = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (!check(SUCCEEDED(hr) && device, "D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) return finish();
D3D12_ROOT_PARAMETER uav = {};
uav.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
uav.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
ID3D12RootSignature* root = make_root(device, uav);
if (!root) return finish();
const std::string before = read_log();
const char* kDxilCompute[] = {"\"event\":\"shader_gate\"", "pso=compute", "stage=CS", "decision=pass_dxil", "sm=6.6"};
const char* kAcccCompute[] = {"\"event\":\"shader_gate\"", "pso=compute", "stage=CS", "decision=reject_accc_only"};
const char* kDxilStream[] = {"\"event\":\"shader_gate\"", "pso=stream", "stage=CS", "decision=pass_dxil"};
// 1. The same DXIL compute pipeline, created again and again.
ID3D12PipelineState* last = nullptr;
int dxil_ok = 0;
for (int i = 0; i < kRepeats; ++i) {
ID3D12PipelineState* pso = nullptr;
hr = create_compute(device, root, g_fill_cs66, sizeof(g_fill_cs66), &pso);
if (SUCCEEDED(hr) && pso) ++dxil_ok;
if (last) last->Release();
last = pso;
}
check(dxil_ok == kRepeats, "DXIL compute PSO: %d of %d creations succeeded", dxil_ok, kRepeats);
if (last) {
run_dxil(device, root, last); // the reused prepared DXIL must still run correctly
last->Release();
}
// 2. The same ACCC-only container, refused every time.
const std::vector<uint8_t> accc = accc_only_container();
int refused = 0;
for (int i = 0; i < kRepeats; ++i) {
ID3D12PipelineState* pso = nullptr;
hr = create_compute(device, root, accc.data(), accc.size(), &pso);
if (hr == E_NOTIMPL && !pso) ++refused;
if (pso) pso->Release();
}
check(refused == kRepeats, "ACCC-only compute PSO: %d of %d creations returned E_NOTIMPL with no object", refused,
kRepeats);
// 3. The same DXIL as the CS stage of a stream PSO: another PSO kind, so its own first record.
const StreamBuilder stream = compute_stream(g_fill_cs66, sizeof(g_fill_cs66), root);
int stream_ok = 0;
for (int i = 0; i < kRepeats; ++i) {
ID3D12PipelineState* pso = nullptr;
hr = create_stream(device, stream.desc(), &pso);
if (SUCCEEDED(hr) && pso) ++stream_ok;
if (pso) pso->Release();
}
check(stream_ok == kRepeats, "DXIL stream PSO: %d of %d creations succeeded", stream_ok, kRepeats);
const std::string all = read_log();
const std::string log = all.size() >= before.size() ? all.substr(before.size()) : all;
const size_t dxil_records = count_lines(log, {kDxilCompute[0], kDxilCompute[1], kDxilCompute[2], kDxilCompute[3], kDxilCompute[4]});
const size_t accc_records = count_lines(log, {kAcccCompute[0], kAcccCompute[1], kAcccCompute[2], kAcccCompute[3]});
const size_t stream_records = count_lines(log, {kDxilStream[0], kDxilStream[1], kDxilStream[2], kDxilStream[3]});
std::printf("shader_gate records over %d creations each: dxil compute=%zu accc compute=%zu dxil stream=%zu\n",
kRepeats, dxil_records, accc_records, stream_records);
check(dxil_records == 1, "DXIL compute: %zu shader_gate records, want 1", dxil_records);
check(accc_records == 1, "ACCC-only compute: %zu shader_gate records, want 1", accc_records);
check(stream_records == 1, "DXIL stream CS: %zu shader_gate records, want 1", stream_records);
check(count_lines(log, {"\"event\":\"shader_gate_reused\""}) >= 1, "no shader_gate_reused record");
root->Release();
device->Release();
return finish();
}
+5 -4
View File
@@ -15,7 +15,7 @@ extern "C" {
uint64_t bx_veh_get_clwb_trap_count(void);
PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes);
VOID WINAPI XMemFree(PVOID address, uint64_t attributes);
BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t flags);
BOOL WINAPI XMemTransferMemory(DWORD transfer_type, SIZE_T transfer_size); // GDK xmem.h (#768)
}
// ---------------------------------------------------------------------------
@@ -280,9 +280,10 @@ int main() {
std::fprintf(stderr, "FAIL: XMemAlloc returned null\n");
return 2;
}
std::memset(src, 0x5A, 4096);
if (!XMemTransferMemory(dst, src, 4096, 0) || std::memcmp(src, dst, 4096) != 0) {
std::fprintf(stderr, "FAIL: XMemTransferMemory mismatch\n");
/* XMemTransferMemory(XMemTransferTitleToSystem, 0) transfers nothing and succeeds (GDK xmem.h).
* It moves budget between title and system, not bytes between buffers. */
if (!XMemTransferMemory(0, 0)) {
std::fprintf(stderr, "FAIL: XMemTransferMemory(TitleToSystem, 0) failed: %lu\n", GetLastError());
return 3;
}
bx_xmem_stats_t stats = {};