Compare commits

..
2 Commits
Author SHA1 Message Date
ates f16abbf4eb Add memory diagnostics to the d3d12_xs, XCRDAPI and xmem shims
Counters only: host buffer and texture totals, which GPU-written textures are ever used, title pages under buffer copies, DirectStorage delivery by destination and codec, and first touches of pool pages. Not for merge as is.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-02 23:58:03 +03:00
ates 2fac6c3560 Add unified-memory probes and their results
Synthetic probes under tools/probes/unified-memory (native helper page overlay, heap behaviour, tile mapping, unused and reserved texture cost, heap import) and the write-up of their results on D3DMetal 3.0 and on Mullion v0.5-alpha.4.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-02 23:58:03 +03:00
40 changed files with 2372 additions and 1482 deletions

No files matched your search

+1 -13
View File
@@ -10,12 +10,7 @@ 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.
- **Unified memory probes (research only, no shim change).** `tools/probes/unified-memory/` holds three synthetic D3D12 programs and a Wine builtin helper pair (`bx_host.dll` and an x86_64 Mach-O `bx_host.so`, built by its `build.sh`, not by `scripts/build-shims.sh`). Results for one host are in `docs/research/unified-memory-probes.md`: a heap page mapped over a section view with `mach_vm_remap` is shared by the CPU and the GPU in both directions, D3DMetal accounts heaps in 256 MiB pools, a small committed buffer costs about 1.7 KiB, and BC1 tiles of reserved textures can be taken from, and shared on, a CPU-visible heap.
- **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.
@@ -24,12 +19,6 @@ 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).
@@ -88,7 +77,6 @@ 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 -1
View File
@@ -30,8 +30,8 @@
- [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).
- [Unified Memory Probes](research/unified-memory-probes.md) — Synthetic probes on one host: a D3D12 heap page mapped behind a title-style address is shared by CPU and GPU, D3DMetal's 256 MiB heap pools, and texture tiles taken from a CPU-visible heap (`tools/probes/unified-memory/`).
- [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,7 +65,6 @@ 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.
+239
View File
@@ -0,0 +1,239 @@
# Unified memory probes (Milestone 0)
Can title memory and GPU memory be the same pages under CrossOver and D3DMetal? These are the
results of six synthetic probes, which use no title and no GDK material, and of one measured run of
the target build (P4).
- **Host:** one Apple Silicon Mac with 16 GB, macOS 27.2, CrossOver 26.3 with D3DMetal 3.0,
Rosetta 2, run on 2026-12-02 in a bottle with the `d3dmetal` backend.
- **Evidence class:** local implementer runs, not independently reproduced. They describe this
host and these versions, not D3DMetal or macOS in general.
- **Sources:** `tools/probes/unified-memory/` (`build.sh`, `p1_alias.cpp`, `p2_heap.cpp`,
`p3_tiles.cpp`, and the helper pair `bx_host.c` / `bx_host_unix.c`).
- **Target build:** P4 is one run of the target build; its figures are for that run only.
## How the probes run
`build.sh` builds a Wine builtin pair: `x86_64-windows/bx_host.dll` (mingw, stamped
`Wine builtin DLL` after the DOS header) and `x86_64-unix/bx_host.so` (x86_64 Mach-O exporting
`__wine_unix_call_funcs`). Two things are needed for Wine to load the native half:
- the directory holding both subdirectories is on `WINEDLLPATH` (CrossOver's `bin/wine` applies
`--env` after it sets its own value, so the default entries must be repeated);
- a copy of the stamped DLL lies where the Windows search finds it (beside the program). Without
a file there the loader never looks for a builtin: the first attempt failed with error 126.
```sh
tools/probes/unified-memory/build.sh
OUT=$PWD/target/unified-memory-probes; cp $OUT/x86_64-windows/bx_host.dll $OUT/
CX=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver
$CX/bin/wine --bottle <bottle> --env "CX_GRAPHICS_BACKEND=d3dmetal \
WINEDLLPATH=$OUT:$CX/lib/wine/x86_64-windows:$CX/lib/wine/i386-windows:$CX/lib/wine" $OUT/p1_alias.exe
```
## P1: one page, seen by the CPU at a title-style address and by the GPU
A 64 MiB heap (`CUSTOM`, `L0`, `WRITE_BACK`) with one placed buffer over it, mapped. A 64 KiB
section view is made the way `xmem` makes them (placeholder, `MapViewOfFile3`, commit), then the
native half maps a heap page over it with `mach_vm_remap` (shared, fixed, overwrite). 20 of 20
checks passed:
| Check | Result |
| --- | --- |
| Native half reached from a mingw DLL through Wine's unix call | yes |
| Process page size / host page size | 4 KiB / 16 KiB |
| Heap base alignment | 16 KiB (not 64 KiB) |
| `mach_vm_remap` over the view | success, read-write |
| CPU write through the view, then GPU copy out | same bytes, 8 of 8 rounds, no `Map`/`Unmap` |
| GPU copy in, then CPU read through the view | same bytes, 8 of 8 rounds |
| `ReadFile` into the view | succeeds; bytes are in the heap page |
| `VirtualProtect` to no access and back | honoured; bytes intact |
| `VirtualQuery` on the view | still a committed mapped view |
| A second view of the same heap page | shows the first view's writes |
| Cost of one overlay | 1.4 microseconds (10,000 overlays) |
| `UnmapViewOfFile2` preserving the placeholder | slot inaccessible again; heap page keeps its bytes |
| Mapping the section there again | shows the section's own bytes |
## P2: how heaps behave and what they cost
- **Placement granularity is 256 bytes.** A buffer placed at a heap offset that is a multiple of
256 (tested 64 KiB, 4 KiB and 256 bytes past a 64 KiB boundary) reads the heap's bytes at that
offset. Offsets of 16 and 4 bytes are accepted but the buffer does not start at those bytes.
- **Heaps come out of 256 MiB pools that are counted whole and not given back.** Ten 64 MiB heaps
made in turn, each touched in full and used once by the GPU, moved the process footprint by
+28, +28, +28, +285, +285, +285, +541, +541, +541, +797 MiB. Touching or using a heap changed
nothing by itself. After releasing all ten the footprint was still +769 MiB.
- **A small committed buffer costs about 1.7 KiB.** 50,000 committed 240-byte buffers, each mapped
and written, added 85 MiB. Releasing them left 26 MiB.
Not tested: shader views (`FirstElement`) on a heap-wide buffer, which need a shader.
## P3: texture tiles on a CPU-visible heap
The device reports `TiledResourcesTier` 2 and `ResourceHeapTier` 2.
| Check | Result |
| --- | --- |
| `UpdateTileMappings` of a reserved texture onto scattered, descending tiles of the CPU-visible heap | texels land in exactly the 16 named heap tiles, visible through the heap-wide buffer |
| Reserved buffer, 16 tiles mapped to scattered heap tiles | reads the bytes the CPU wrote into those tiles |
| A tile unmapped again | reads zero |
| **BC1**: how blocks lie in a 64 KiB tile | plain 8-byte blocks; each tile holds only its own 512x256 texels; order (0,0) (1,0) (0,1) (1,1) (2,0) ... (Morton, x in the low bit) |
| **BC1**: second reserved texture on the same heap tiles | reads the same blocks |
| **BC1**: one block written into the heap tile by the CPU | is what the texture reads there |
| **RGBA8**: how texels lie in a tile | not plain texels (no tile held only its own texels) |
| **RGBA8**: second reserved texture on the same heap tiles | does **not** read the same texels (all differ) |
| **RGBA8**: CPU overwrite of one heap tile | changes that tile of the texture and no other |
| 1024x1024 BC7, 11 mips | 256x256 tiles; mips 0 to 2 standard (16, 4, 1 tiles); 8 packed mips in 1 tile |
| 1024x1024 BC1, 11 mips | 512x256 tiles; mips 0 to 1 standard (8, 2 tiles); 9 packed mips in 1 tile |
Reading of the RGBA8 rows (an inference, not tested further): this host stores such textures in an
encoded form whose description is kept per texture, so their tiles cannot be shared or written as
plain texels. Block-compressed textures do not have that property.
## P5 and P6: what unused textures cost
A first version of this probe (`p5_small_textures.cpp`) created textures and read the footprint
without submitting any GPU work, and found a few KiB per texture. That was misleading: D3DMetal
makes the pools behind its allocations resident at the next GPU submission. `p6_targets.cpp` adds
one unrelated submission (a 16-byte buffer copy) and runs each case in a process of its own, since
pools are kept and reused. Textures are committed, created and never used:
| Never-used textures | Host-reported total | Footprint at creation | After one unrelated GPU submission |
| --- | --- | --- | --- |
| 30 x 3840x2160 render-target BGRA8 | 971 MiB | +0 MiB | +1,291 MiB |
| 30 x 3840x2160 unordered-access RGBA8 | 956 MiB | +0 MiB | +1,044 MiB |
| 30 x 3840x2160 depth D32 | 971 MiB | +0 MiB | +1,300 MiB |
| 30 x 3840x2160 plain RGBA8 | 971 MiB | +0 MiB | +1,281 MiB |
| 10,000 x 16x4 RGBA16F | 625 MiB | +25 MiB | +282 MiB |
| 10,000 x 128x128 BC1 | 625 MiB | +25 MiB | +281 MiB |
| 10,000 x 64x64 BC7 | 625 MiB | +25 MiB | +281 MiB |
A texture that is never used still costs its size once the GPU runs anything, rounded up to whole
256 MiB pools. Ten thousand small textures fit one pool, about 28 KiB each, less than the 64 KiB
the host reports for each. Releasing them returned nothing in the same process.
## P7: GPU-written textures as reserved resources
`p7_reserved_targets.cpp`, one case per process:
| Check | Render target BGRA8 | Depth D32 | Unordered access RGBA8 |
| --- | --- | --- | --- |
| 30 reserved, unmapped 3840x2160 textures after an unrelated GPU submission | -13 MiB | -12 MiB | -27 MiB |
| Reserved 1024x1024 texture created and all tiles mapped to a heap | yes | yes | yes |
| Written and read back, 1,048,576 texels | cleared as a target: all correct | cleared as depth: all correct | copied in and out: all correct |
Not tested: shader writes into a reserved unordered-access texture (the probe has no compute
shader), and drawing into the reserved render target with a pipeline.
## P4: measurements on the target build
One supervised run of the target build (Series S profile, `main` plus diagnostic counters, compute
pipelines not translated), sampled 180 s after its intro began. The counters are in
`shims/d3d12_xs/placed_x.cpp` (`host_memory_buffers`, `host_memory_textures`),
`shims/xcrdapi/xcrdapi.cpp` (`dstorage_delivered`) and `shims/xmem/physical_pages.cpp`
(`page_touches`). They are diagnostics on a local branch, not merged.
**Process footprint 8.6 GB:**
| Part | Size | What the map says |
| --- | --- | --- |
| Graphics, not CPU-mapped | 2.67 GB | 97 objects: textures in GPU-only storage |
| Graphics, CPU-mapped | 2.47 GB | 1,104 regions: buffers |
| Wine's anonymous memory | 2.67 GB dirty | 2.3 GB of it already compressed or swapped |
| Rosetta, allocator heaps, other | about 0.8 GB | |
**Host resources the shim made (its own count, sizes as asked for or as the host reports):**
| Kind | Count | Size | Note |
| --- | --- | --- | --- |
| Buffers for views of placed memory | 173,566 | 873 MiB | grew from 40 MiB to 725 MiB in 120 s |
| Buffers for placed resources | 4,203 | 761 MiB | flat after loading |
| Buffers, all: under 16 KiB / to 1 MiB / larger | 169,060 / 8,608 / 121 | 158 / 671 / 827 MiB | |
| GPU-written placed textures (render target, depth, unordered access) | 1,174 | 2,069 MiB | present from the menus on |
| GPU-written committed textures | 10 | 128 MiB | |
| Read-only textures under 64 KiB, committed | 19,077 | 1,217 MiB as reported | by P6, about 28 KiB each in whole pools: roughly 0.5 GB |
| Reserved read-only textures: live / memory mapped | 4,105 / 31 MiB | | 33 mappings made |
**Page pool and DirectStorage:**
- The pool is one 4.17 GB Wine section file (`tmpmap-*`), with three smaller ones (311, 231 and
194 MB). The game process had 204 MB of those mappings resident.
- During the 205 s run the system counted 302,875 page-outs (about 4.6 GB at 16 KiB) and 45,948
swap-outs. The run cannot say which file they went to.
- DirectStorage delivered 2,644 MiB zlib and 297 MiB BCPack into physical pages, and 5,870 MiB to
memory addresses (cumulative, destinations are reused).
- First touches of 64 KiB pages: 34,429 written through DirectStorage spans; 2,638 first touched by
the title's own code, **none of them span-written**; 60,228 first touched from other modules
(the shims and the libraries they call), 5,665 of them span-written. Counts are cumulative over
allocations, not live pages.
**Which GPU-written textures the title used** (second run, 4 minutes, `host_memory_written_use`).
A texture counts as used once the title binds it as a target, names it in a barrier, copies or
resolves to or from it, or a translated draw reads or writes it through a view:
| | Count | Size |
| --- | --- | --- |
| Used | 222 | 559 MiB |
| Never used | 962 | 1,655 MiB |
| First used in the last 30 s of the run | 10 | 6 MiB |
The largest never-used ones are 3840x2160 (32 to 41 MiB each). Not seen by this count: clears, and
all but the first view of a single-range target bind; compute pipelines are not translated on this
branch, so their views are not seen either. The never-used figure is therefore an upper bound.
**Pages under the buffers** (`host_memory_buffer_pages`, same run): the buffers placed in title
memory held 1,757 MiB of copies and covered 28,752 distinct 64 KiB pages of title addresses
(1,797 MiB); the ones made for views alone 988 MiB over 17,927 pages (1,120 MiB). Title addresses,
not physical pages, so the page figures are upper bounds.
Reading (inference): the two graphics rows of the footprint match the kinds below them: GPU-only
storage is mostly the 2.2 GB of GPU-written textures, and the CPU-mapped part is the buffer copies
(1.66 GB of data, about 0.3 GB of per-buffer overhead at P2's 1.7 KiB, and pool rounding).
## What this decides
- The native helper and the page overlay work on this host: a page of a D3D12 heap can be the
memory behind a title address, for the CPU, Windows calls and the GPU alike.
- Heap memory should be asked for in few, large steps: D3DMetal accounts 256 MiB at a time and
keeps it.
- Packing small buffers saves about 1.7 KiB per buffer, not a memory page per buffer.
- For block-compressed textures, tiles can be taken from chosen pages of a CPU-visible heap and
shared between textures. For plain RGBA8 they cannot be shared.
- On the target build, host copies of streamed textures are not where the memory is (31 MiB mapped):
it is in GPU-written textures (about 2.2 GB) and in buffer copies (about 2.4 GB, and growing
through buffers made for views).
- The title's own code did not touch any page DirectStorage had written into, in this run.
- About 1.65 GB of GPU-written textures were never used in four minutes, an unused texture costs
its full size (P6), and reserved render-target and depth textures cost nothing until mapped and
work once mapped (P7). Giving GPU-written textures their memory at first use, as read-only
textures already get it, is the largest saving measured here.
- Sharing pages for buffers saves little footprint by itself: the buffers' own pages (up to
1.8 GB) are about as large as the copies (1.76 GB plus overhead). Its value is that the title-side
pages stop being a second copy, the copies stop growing, and GPU writes reach the title.
## The same probes on Mullion (evaluation, 2026-12-02)
Mullion (`dttdrv/mullion`, LGPL-2.1, release `v0.5-alpha.4`) is an open-source Direct3D 12 to Metal
layer built on DXMT. Its release was installed into a fresh bottle only, by its own installer, which
gives the bottle a CrossOver root of its own and leaves CrossOver and other bottles unchanged. No
licence or provenance review has been recorded yet and nothing in BetterXen depends on it. Run the
probes with `CX_ROOT=<that root> BX_PROBE_BACKEND=dxmt`.
| Probe | D3DMetal 3.0 | Mullion v0.5-alpha.4 |
| --- | --- | --- |
| P1 page overlay with the native helper | 20 of 20 | 20 of 20 |
| P2 heap memory | 256 MiB pools, kept after release | counted as used; a touched 64 MiB heap and ten more all returned on release |
| P2 placed buffer offsets | any multiple of 256 bytes | multiples of 64 KiB only (`E_INVALIDARG` otherwise) |
| P2 50,000 small committed buffers | 1.7 KiB each | 3.5 KiB each |
| P3 tiled resources | tier 2; RGBA8 tiles cannot be shared | tier 3; RGBA8 and BC1 tiles shared, 0 failed |
| P6 30 never-used 3840x2160 textures | +1,044 to +1,300 MiB, kept | +956 to +972 MiB, returned on release |
| P6 10,000 never-used 128x128 BC1 | +281 MiB | +187 MiB |
| P7 reserved GPU-written textures | cost nothing unmapped; work mapped | the same |
| P8 `OpenExistingHeapFromFileMapping`, committed section of 1 GiB | not implemented (`E_NOTIMPL`, #473) | succeeds; +0 MiB; +1 MiB after one page is used |
| P8 a buffer placed on that heap, against two views of the section | | GPU writes show in the views, view writes are read by the GPU with no `Map`, `ReadFile` into the view works, a page first written by the GPU shows in a view mapped later |
| P8 the same with a reserved section (`SEC_RESERVE`) | | refused, `E_INVALIDARG` |
| P8 `OpenExistingHeapFromAddress` on `VirtualAlloc` memory | not implemented | succeeds, both directions coherent |
| P8 tiles of a reserved texture mapped to the imported heap | | `UpdateTileMappings` never returns (process idle) |
`p8_import.cpp` holds the import checks. Not run on Mullion: the conformance suite, the shims and
the target build.
-135
View File
@@ -1,135 +0,0 @@
# 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 -1
View File
@@ -138,7 +138,6 @@ 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;
@@ -170,6 +169,7 @@ void resolve(ID3D12Device* device, const char* key, const BxConsoleUse& use, uin
// Held for this resolve: bx_console_forget_resource may drop the registry's reference.
if (ok && view.resource) view.resource->AddRef();
}
if (ok && view.resource) bx_xbox_note_resource_use(view.resource, 4); // diagnostic; outside g_view_lock
const D3D12_CPU_DESCRIPTOR_HANDLE host = bx_xbox_host_cpu_handle({static_cast<SIZE_T>(entry)});
uint64_t total = 0;
// A view whose resource the shim has released (an implicit shadow the title replaced) resolves
+2
View File
@@ -248,6 +248,7 @@ void STDMETHODCALLTYPE bx_xbox_device_create_render_target_view(void* self, ID3D
ID3D12Resource* host_resource = bx_xbox_unwrap_as<ID3D12Resource>(resource);
const D3D12_RENDER_TARGET_VIEW_DESC* host_desc = host.of(desc, "CreateRenderTargetView");
bx_xbox_host<ID3D12Device>(self)->CreateRenderTargetView(host_resource, host_desc, bx_xbox_host_cpu_handle(dest));
bx_xbox_note_target_view(bx_xbox_host_cpu_handle(dest).ptr, host_resource);
bx_console_rtv_created(bx_xbox_host_cpu_handle(dest).ptr, view_format(host_resource, host_desc ? host_desc->Format : DXGI_FORMAT_UNKNOWN));
}
@@ -259,6 +260,7 @@ void STDMETHODCALLTYPE bx_xbox_device_create_depth_stencil_view(void* self, ID3D
ID3D12Resource* host_resource = bx_xbox_unwrap_as<ID3D12Resource>(resource);
const D3D12_DEPTH_STENCIL_VIEW_DESC* host_desc = host.of(desc, "CreateDepthStencilView");
bx_xbox_host<ID3D12Device>(self)->CreateDepthStencilView(host_resource, host_desc, bx_xbox_host_cpu_handle(dest));
bx_xbox_note_target_view(bx_xbox_host_cpu_handle(dest).ptr, host_resource);
bx_console_dsv_created(bx_xbox_host_cpu_handle(dest).ptr, view_format(host_resource, host_desc ? host_desc->Format : DXGI_FORMAT_UNKNOWN));
}
+3
View File
@@ -242,6 +242,9 @@ void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count
const UINT n = count > 8 ? 8 : count;
for (UINT i = 0; rtvs && i < (single_range ? 1u : n); ++i) host_rtvs[i] = bx_xbox_host_cpu_handle(rtvs[i]);
const D3D12_CPU_DESCRIPTOR_HANDLE host_dsv = dsv ? bx_xbox_host_cpu_handle(*dsv) : D3D12_CPU_DESCRIPTOR_HANDLE{};
// Diagnostic: with a single range only the first view is known here; the others are not marked.
for (UINT i = 0; rtvs && i < (single_range ? 1u : n); ++i) bx_xbox_note_target_bound(host_rtvs[i].ptr);
if (dsv) bx_xbox_note_target_bound(host_dsv.ptr);
bx_xbox_host<ID3D12GraphicsCommandList>(self)->OMSetRenderTargets(n, rtvs ? host_rtvs : nullptr, single_range,
dsv ? &host_dsv : nullptr);
bx_console_list_targets(bx_xbox_host<ID3D12GraphicsCommandList>(self), n, rtvs ? host_rtvs : nullptr, single_range,
-1
View File
@@ -262,7 +262,6 @@ 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));
}
// 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()};
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
admitted.pPipelineStateSubobjectStream = 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);
+189 -12
View File
@@ -25,6 +25,7 @@
#include "bx_log.h"
#include <algorithm>
#include <atomic>
#include <cstdio>
#include <cstdlib>
@@ -51,6 +52,9 @@ struct Shadow {
bool simultaneous = false; // texture made with D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS
uint64_t span = 0; // implicit: the bytes of title memory the resource covers
bool reserved = false; // texture made as a reserved resource: memory mapped at first use
uint64_t host_bytes = 0; // diagnostic: what the host says the resource takes (0 for a reserved texture)
unsigned char used = 0; // diagnostic: how the title has used it (bx_xbox_note_resource_use)
uint64_t made_ms = 0, first_use_ms = 0; // diagnostic: GetTickCount64 at creation and at first use
};
/*
@@ -178,7 +182,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, BxTitleCopy path) {
bool copy_buffer(const Shadow& s, bool to_host, uint64_t begin, uint64_t end) {
if (!s.buffer || end <= begin || end > s.size) return false;
void* mapped = nullptr;
const D3D12_RANGE none{0, 0};
@@ -187,7 +191,6 @@ bool copy_buffer(const Shadow& s, bool to_host, uint64_t begin, uint64_t end, Bx
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;
@@ -275,7 +278,9 @@ void for_candidates_locked(uint64_t lo, uint64_t hi, F f) {
}
}
bool remember(const Shadow& shadow) {
bool remember(const Shadow& new_shadow) {
Shadow shadow = new_shadow;
shadow.made_ms = GetTickCount64();
std::lock_guard<std::mutex> guard(g_lock);
if (g_count == g_capacity) {
const size_t capacity = g_capacity ? g_capacity * 2 : 64;
@@ -386,7 +391,6 @@ 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");
}
@@ -399,6 +403,11 @@ HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURC
Shadow record{resource, title_va, desc.Width, buffer, desc, 0};
record.simultaneous = made_simultaneous;
record.reserved = reserved;
if (buffer) {
record.host_bytes = desc.Width;
} else if (!reserved) {
record.host_bytes = device->GetResourceAllocationInfo(0, 1, &host_desc).SizeInBytes;
}
if (reserved) {
std::lock_guard<std::mutex> guard(g_memory_lock);
g_texture_memory[resource] = TextureMemory{};
@@ -979,7 +988,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, BxTitleCopy::BoundRefresh);
copy_buffer(g_shadows[i], true, begin, begin + r.size);
}
}
@@ -1000,8 +1009,14 @@ D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title) {
}
bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64_t size, ULONGLONG attributes) {
return remember({host, title_va, size, host->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER, host->GetDesc(),
attributes});
Shadow record{host, title_va, size, host->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER, host->GetDesc(), attributes};
record.host_bytes = record.desc.Width;
ID3D12Device* device = nullptr;
if (!record.buffer && SUCCEEDED(host->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) && device) {
record.host_bytes = device->GetResourceAllocationInfo(0, 1, &record.desc).SizeInBytes;
device->Release();
}
return remember(record);
}
void bx_xbox_texture_memory_for_write(ID3D12Resource* host) {
@@ -1126,11 +1141,9 @@ 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) {
@@ -1205,9 +1218,173 @@ ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads*
return host;
}
namespace {
/*
* Diagnostic (unified-memory measurements): every 10 s of submissions, what the host resources
* this file made take, by kind. Buffers are counted at the size asked for, committed textures at
* the size the host reports for them, reserved textures at the heap mapped behind them.
* "committed" resources are the ones a title creates without placing them; "view" buffers are made
* for a view of placed memory that has no resource; "bound" ones for memory bound by address.
*/
void report_host_memory() {
static std::atomic<uint64_t> next{0};
const uint64_t now = GetTickCount64();
uint64_t due = next.load();
if (now < due || !next.compare_exchange_strong(due, now + 10000)) return;
struct Kind {
uint64_t count = 0, bytes = 0;
};
Kind buf_placed, buf_committed, buf_view, buf_small, buf_medium, buf_large;
Kind written_used, written_unused, used_target, used_barrier_only, used_draw, used_copy, first_use_recent;
struct Unused {
uint64_t bytes, width;
UINT height;
int format;
UINT flags;
};
std::vector<Unused> unused;
std::vector<uint64_t> buffer_pages, view_pages;
Kind tex_reserved, tex_readonly, tex_written, tex_committed_written, tex_committed_other;
constexpr UINT kWritten = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL |
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
auto add = [](Kind& k, uint64_t bytes) {
++k.count;
k.bytes += bytes;
};
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
const Shadow& s = g_shadows[i];
if (s.buffer) {
add(s.title_attributes ? buf_committed : s.implicit ? buf_view : buf_placed, s.host_bytes);
add(s.host_bytes < 16384 ? buf_small : s.host_bytes < (1u << 20) ? buf_medium : buf_large, s.host_bytes);
if (!s.title_attributes && s.size) { // placed in title memory: the 64 KiB pages it covers
for (uint64_t page = s.title_va >> 16; page <= (s.title_va + s.size - 1) >> 16; ++page) {
buffer_pages.push_back(page);
if (s.implicit) view_pages.push_back(page);
}
}
} else if (s.reserved) {
add(tex_reserved, 0);
} else {
const bool written = (static_cast<UINT>(s.desc.Flags) & kWritten) != 0;
if (written) {
if (s.used) {
add(written_used, s.host_bytes);
if (s.used & 1) add(used_target, s.host_bytes);
if (s.used == 2) add(used_barrier_only, s.host_bytes);
if (s.used & 4) add(used_draw, s.host_bytes);
if (s.used & 8) add(used_copy, s.host_bytes);
if (now - s.first_use_ms < 30000) add(first_use_recent, s.host_bytes);
} else {
add(written_unused, s.host_bytes);
unused.push_back({s.host_bytes, s.desc.Width, s.desc.Height, static_cast<int>(s.desc.Format), static_cast<UINT>(s.desc.Flags)});
}
}
add(s.title_attributes ? (written ? tex_committed_written : tex_committed_other) : (written ? tex_written : tex_readonly),
s.host_bytes);
}
}
}
uint64_t upload_bytes = 0, uploads = 0, retired = 0;
{
std::lock_guard<std::mutex> guard(g_texture_lock);
for (const auto& entry : g_texture_uploads) {
if (entry.second.upload) {
++uploads;
upload_bytes += entry.second.upload_bytes;
}
}
retired = g_retired.size();
}
constexpr double kMiB = 1024.0 * 1024.0;
char detail[400];
std::snprintf(detail, sizeof(detail),
"host buffers MiB (count): placed %.0f (%llu), committed %.0f (%llu), for views %.0f (%llu); "
"by size: under 16 KiB %.0f (%llu), to 1 MiB %.0f (%llu), larger %.0f (%llu)",
buf_placed.bytes / kMiB, static_cast<unsigned long long>(buf_placed.count), buf_committed.bytes / kMiB,
static_cast<unsigned long long>(buf_committed.count), buf_view.bytes / kMiB,
static_cast<unsigned long long>(buf_view.count), buf_small.bytes / kMiB, static_cast<unsigned long long>(buf_small.count),
buf_medium.bytes / kMiB, static_cast<unsigned long long>(buf_medium.count), buf_large.bytes / kMiB,
static_cast<unsigned long long>(buf_large.count));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "host_memory_buffers", detail);
std::snprintf(detail, sizeof(detail),
"host textures MiB (count): reserved, mapped now %.0f (%llu mappings made so far, %llu reserved live); placed read-only committed %.0f (%llu); "
"placed GPU-written %.0f (%llu); title-committed GPU-written %.0f (%llu), other %.0f (%llu); "
"upload buffers %.0f (%llu live, %llu retiring)",
g_mapped_bytes.load() / kMiB, static_cast<unsigned long long>(g_mapped_count.load()),
static_cast<unsigned long long>(tex_reserved.count), tex_readonly.bytes / kMiB,
static_cast<unsigned long long>(tex_readonly.count), tex_written.bytes / kMiB,
static_cast<unsigned long long>(tex_written.count), tex_committed_written.bytes / kMiB,
static_cast<unsigned long long>(tex_committed_written.count), tex_committed_other.bytes / kMiB,
static_cast<unsigned long long>(tex_committed_other.count), upload_bytes / kMiB,
static_cast<unsigned long long>(uploads), static_cast<unsigned long long>(retired));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "host_memory_textures", detail);
std::snprintf(detail, sizeof(detail),
"GPU-written textures MiB (count): used %.0f (%llu), never used %.0f (%llu); of the used: bound as a target %.0f (%llu), "
"in a translated draw's view %.0f (%llu), copied %.0f (%llu), named in a barrier only %.0f (%llu); first used in the last 30 s %.0f (%llu)",
written_used.bytes / kMiB, static_cast<unsigned long long>(written_used.count), written_unused.bytes / kMiB,
static_cast<unsigned long long>(written_unused.count), used_target.bytes / kMiB,
static_cast<unsigned long long>(used_target.count), used_draw.bytes / kMiB, static_cast<unsigned long long>(used_draw.count),
used_copy.bytes / kMiB, static_cast<unsigned long long>(used_copy.count), used_barrier_only.bytes / kMiB,
static_cast<unsigned long long>(used_barrier_only.count), first_use_recent.bytes / kMiB,
static_cast<unsigned long long>(first_use_recent.count));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "host_memory_written_use", detail);
std::sort(unused.begin(), unused.end(), [](const Unused& a, const Unused& b) { return a.bytes > b.bytes; });
int at = std::snprintf(detail, sizeof(detail), "largest never-used GPU-written textures (MiB WxH format flags):");
for (size_t i = 0; i < unused.size() && i < 10 && at > 0 && at < static_cast<int>(sizeof(detail)) - 40; ++i) {
at += std::snprintf(detail + at, sizeof(detail) - at, " %.0f %llux%u f%d 0x%x;", unused[i].bytes / kMiB,
static_cast<unsigned long long>(unused[i].width), unused[i].height, unused[i].format, unused[i].flags);
}
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "host_memory_written_unused", detail);
auto distinct = [](std::vector<uint64_t>& pages) {
std::sort(pages.begin(), pages.end());
return static_cast<unsigned long long>(std::unique(pages.begin(), pages.end()) - pages.begin());
};
const unsigned long long all_pages = distinct(buffer_pages), of_views = distinct(view_pages);
std::snprintf(detail, sizeof(detail),
"buffers placed in title memory cover %llu distinct 64 KiB pages of title addresses (%.0f MiB); the ones made for views alone %llu (%.0f MiB)",
all_pages, all_pages * 65536.0 / kMiB, of_views, of_views * 65536.0 / kMiB);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "host_memory_buffer_pages", detail);
}
} // namespace
void bx_xbox_note_resource_use(ID3D12Resource* host, unsigned how) {
if (!host) return;
std::lock_guard<std::mutex> guard(g_lock);
const size_t i = find_host_locked(host);
if (i == SIZE_MAX) return;
if (!g_shadows[i].used) g_shadows[i].first_use_ms = GetTickCount64();
g_shadows[i].used |= static_cast<unsigned char>(how);
}
namespace {
std::mutex g_target_lock;
std::unordered_map<uint64_t, ID3D12Resource*> g_target_views; // host descriptor -> the resource its view shows (not referenced)
} // namespace
void bx_xbox_note_target_view(uint64_t handle, ID3D12Resource* host) {
std::lock_guard<std::mutex> guard(g_target_lock);
g_target_views[handle] = host;
}
void bx_xbox_note_target_bound(uint64_t handle) {
ID3D12Resource* host = nullptr;
{
std::lock_guard<std::mutex> guard(g_target_lock);
auto it = g_target_views.find(handle);
if (it != g_target_views.end()) host = it->second;
}
// The pointer is only looked up, never dereferenced: a released resource is no longer in the table.
bx_xbox_note_resource_use(host, 1);
}
void bx_xbox_placed_note_submission() {
++g_submissions;
sweep_implicit();
report_host_memory();
}
void bx_xbox_placed_forget(IUnknown* host) {
@@ -1327,7 +1504,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, BxTitleCopy::MapRead);
if (s.buffer && end > begin) copy_buffer(s, false, begin, end < s.size ? end : s.size);
++s.mapped;
g_mapped_hosts.insert(s.host);
}
@@ -1358,7 +1535,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, BxTitleCopy::UnmapWrite);
if (s.buffer && end > begin) copy_buffer(s, true, begin, end < s.size ? end : s.size);
if (s.mapped > 0) --s.mapped;
if (!s.mapped) g_mapped_hosts.erase(s.host);
return;
@@ -1389,6 +1566,6 @@ void bx_xbox_sync_mapped_buffers() {
}
continue;
}
copy_buffer(s, true, 0, s.size, BxTitleCopy::MappedSync);
copy_buffer(s, true, 0, s.size);
}
}
+28 -102
View File
@@ -1,7 +1,6 @@
#include "proxy.h"
#include "vmem.h"
#include <atomic>
#include <cstdio>
#include <cstring>
#include <new>
@@ -455,49 +454,15 @@ 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 {
uint32_t type; /* the GDK's number, as the title writes it */
uint32_t host_type; /* the host SDK's number, or kNoHostSubobject */
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
size_t payload_offset;
size_t record_size;
const char* stage; /* non-null only for a shader subobject */
};
#define BX_SUBOBJECT(tag, 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}
{tag, 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"),
@@ -522,15 +487,9 @@ 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_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),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, D3D12_SHADER_BYTECODE, "AS"),
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, D3D12_SHADER_BYTECODE, "MS"),
};
#undef BX_XBOX_SUBOBJECT
#undef BX_SUBOBJECT
/* Pin the layout facts the walker depends on, measured with this toolchain. A header change
@@ -545,81 +504,48 @@ 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 (entry.type == type) return &entry;
if (static_cast<uint32_t>(entry.type) == type) return &entry;
}
return nullptr;
}
/* `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. */
/* 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. */
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);
const size_t size = desc.SizeInBytes;
copy.reserve(size);
uint32_t seen = 0;
copy.assign(source, source + desc.SizeInBytes);
size_t offset = 0;
while (offset < size) {
if (size - offset < sizeof(SIZE_T)) return E_INVALIDARG;
while (offset < copy.size()) {
if (copy.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, source + offset, sizeof(raw));
if (raw >= kXboxSubobjectLimit) return E_INVALIDARG;
std::memcpy(&raw, &copy[offset], sizeof(raw));
if (raw >= static_cast<uint32_t>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID)) return E_INVALIDARG;
const StreamSubobject* entry = find_subobject(raw);
if (!entry) return E_INVALIDARG;
/* Microsoft's ID3D12Device2 rules reject a duplicated subobject type. */
if (seen & (1u << raw)) return E_INVALIDARG;
seen |= 1u << raw;
const size_t record = entry->record_size;
if (size - offset < record) return E_INVALIDARG;
if (entry->host_type == kNoHostSubobject) {
note_xbox_only_subobject(raw);
offset += record;
continue;
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 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;
const size_t payload = offset + entry->payload_offset;
const size_t record = entry->record_size;
if (copy.size() - offset < record) return E_INVALIDARG;
if (root_offset && entry->type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE) *root_offset = payload;
if (entry->stage) {
D3D12_SHADER_BYTECODE code{};
@@ -638,7 +564,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_host_subobject(raw);
const StreamSubobject* entry = find_subobject(raw);
if (!entry) return SIZE_MAX;
if (raw == type) return offset + entry->payload_offset;
offset += entry->record_size;
@@ -673,10 +599,8 @@ 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(&admitted, riid, ppv);
const HRESULT hr = FAILED(copied) ? copied : h_ID3D12Device2->CreatePipelineState(desc, riid, ppv);
log_created("stream pipeline state", hr);
return hr;
}
@@ -696,6 +620,8 @@ 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;
+3 -5
View File
@@ -119,12 +119,10 @@ using BxCommandListProxy = BxChildProxy<BxCommandListProxyGen>;
#endif /* BETTERXEN_D3D12_XS_PROXY_H */
/* 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. */
/* 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. */
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 host `type` in a stream copy_stream produced, or SIZE_MAX. */
/* The payload offset of the subobject of `type` in a stream copy_stream accepted, or SIZE_MAX. */
size_t bx_stream_payload(const std::vector<uint8_t>& stream, uint32_t type);
-1
View File
@@ -94,7 +94,6 @@ 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,12 +1,9 @@
#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"
@@ -206,82 +203,6 @@ 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() {
@@ -295,42 +216,6 @@ 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,19 +27,11 @@ 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,11 +2,6 @@
#include <windows.h>
#include <atomic>
#include <cstdio>
#include "bx_log.h"
#include "bx_xmem_internal.h"
namespace {
@@ -55,31 +50,3 @@ 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,24 +17,3 @@ 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();
+8
View File
@@ -309,6 +309,7 @@ UINT STDMETHODCALLTYPE bx_xbox_list_resource_barrier(void* self, UINT count, con
switch (copy[i].Type) {
case D3D12_RESOURCE_BARRIER_TYPE_TRANSITION:
copy[i].Transition.pResource = bx_xbox_unwrap_as(copy[i].Transition.pResource);
bx_xbox_note_resource_use(copy[i].Transition.pResource, 2);
break;
case D3D12_RESOURCE_BARRIER_TYPE_ALIASING:
copy[i].Aliasing.pResourceBefore = bx_xbox_unwrap_as(copy[i].Aliasing.pResourceBefore);
@@ -316,6 +317,7 @@ UINT STDMETHODCALLTYPE bx_xbox_list_resource_barrier(void* self, UINT count, con
break;
case D3D12_RESOURCE_BARRIER_TYPE_UAV:
copy[i].UAV.pResource = bx_xbox_unwrap_as(copy[i].UAV.pResource);
bx_xbox_note_resource_use(copy[i].UAV.pResource, 2);
break;
default:
break;
@@ -335,10 +337,12 @@ void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_
d = *dst;
d.pResource = bx_xbox_unwrap_as(d.pResource);
bx_xbox_texture_memory_for_write(d.pResource);
bx_xbox_note_resource_use(d.pResource, 8);
}
if (src) {
s = *src;
s.pResource = bx_xbox_unwrap_as(s.pResource);
bx_xbox_note_resource_use(s.pResource, 8);
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyTextureRegion(dst ? &d : nullptr, x, y, z, src ? &s : nullptr, box);
}
@@ -347,6 +351,8 @@ void STDMETHODCALLTYPE bx_xbox_list_copy_resource(void* self, ID3D12Resource* ds
BX_D3D_TRACE("XboxGraphicsCommandList", "CopyResource");
ID3D12Resource* d = bx_xbox_unwrap_as<ID3D12Resource>(dst);
bx_xbox_texture_memory_for_write(d);
bx_xbox_note_resource_use(d, 8);
bx_xbox_note_resource_use(bx_xbox_unwrap_as<ID3D12Resource>(src), 8);
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyResource(d, bx_xbox_unwrap_as<ID3D12Resource>(src));
}
@@ -355,6 +361,8 @@ void STDMETHODCALLTYPE bx_xbox_list_resolve_subresource(void* self, ID3D12Resour
BX_D3D_TRACE("XboxGraphicsCommandList", "ResolveSubresource");
ID3D12Resource* d = bx_xbox_unwrap_as<ID3D12Resource>(dst);
bx_xbox_texture_memory_for_write(d);
bx_xbox_note_resource_use(d, 8);
bx_xbox_note_resource_use(bx_xbox_unwrap_as<ID3D12Resource>(src), 8);
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResolveSubresource(d, dst_sub, bx_xbox_unwrap_as<ID3D12Resource>(src), src_sub,
format);
}
+8
View File
@@ -256,6 +256,14 @@ ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads*
/* Before a title's GPU copy or resolve writes `host` (a host resource): a texture whose memory is
mapped at first use (placed_x.cpp, #782) gets it now, so the write is kept. */
void bx_xbox_texture_memory_for_write(ID3D12Resource* host);
/* Diagnostic (unified-memory measurements): the title used host resource `host`. `how`: 1 bound as a
render target or depth buffer, 2 named in a barrier, 4 read or written by a translated draw's view,
8 source or destination of a copy or resolve. */
void bx_xbox_note_resource_use(ID3D12Resource* host, unsigned how);
/* Diagnostic: a render-target or depth view at host descriptor `handle` shows `host`; and that view
was bound. */
void bx_xbox_note_target_view(uint64_t handle, ID3D12Resource* host);
void bx_xbox_note_target_bound(uint64_t handle);
/* Logs a host call that failed (`host_call_failed`), so a refusal is never silent. */
void bx_xbox_log_host_failure(const char* iface, const char* method, HRESULT hr);
+27
View File
@@ -590,8 +590,35 @@ bool dstorage_trace_enabled() {
return on;
}
// Diagnostic (unified-memory measurements): bytes delivered, by destination and codec, logged at
// most every 10 s.
void count_delivery(const Request& request, HRESULT hr) {
static std::atomic<uint64_t> pages_bcpack{0}, pages_zlib{0}, pages_plain{0}, memory_bytes{0}, resource_bytes{0}, requests{0}, next{0};
if (FAILED(hr)) return;
const bool packed = request.compression == compression_zlib || request.compression == compression_bcpack;
const uint64_t out = packed ? request.output_size : request.size;
++requests;
if (request.resource) resource_bytes += out;
else if (!request.page_array) memory_bytes += out;
else if (request.compression == compression_bcpack) pages_bcpack += out;
else if (request.compression == compression_zlib) pages_zlib += out;
else pages_plain += out;
const uint64_t now = GetTickCount64();
uint64_t due = next.load();
if (now < due || !next.compare_exchange_strong(due, now + 10000)) return;
constexpr double kMiB = 1024.0 * 1024.0;
char detail[240];
std::snprintf(detail, sizeof(detail),
"delivered MiB so far: to physical pages BCPack %.0f, zlib %.0f, uncompressed %.0f; to memory addresses %.0f; "
"to resources %.0f; requests %llu",
pages_bcpack.load() / kMiB, pages_zlib.load() / kMiB, pages_plain.load() / kMiB, memory_bytes.load() / kMiB,
resource_bytes.load() / kMiB, static_cast<unsigned long long>(requests.load()));
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_delivered", detail);
}
CopyResult fulfill(HANDLE file, const Request& request) {
const CopyResult result = fulfill_request(file, request);
count_delivery(request, result.hr);
if (!dstorage_trace_enabled() || request.resource) return result;
static std::atomic<UINT> traced{0};
if (traced.fetch_add(1) >= 20000) return result;
+67
View File
@@ -23,6 +23,10 @@ struct Page {
PageBlock* block;
bool allocated;
bool releasing;
// Diagnostic (unified-memory measurements): who has touched the page since it was allocated.
// 1: written through a span of its own (DirectStorage); 2: first touch by the title;
// 4: by d3d12_xs; 8: by another module.
unsigned char touched = 0;
};
// One XMemAllocatePhysicalPages call: a single pagefile-backed section holding all its pages,
@@ -388,6 +392,57 @@ View* view_at(uintptr_t address) {
LONG lazy_mapped = 0; // slots mapped on first touch, logged every 4096
// Diagnostic (unified-memory measurements): pages by who touched them. Counted under memory_lock.
enum : unsigned char { kBySpan = 1, kByTitle = 2, kByD3D = 4, kByOther = 8 };
struct TouchCounts {
LONG span = 0, title = 0, d3d = 0, other = 0; // pages first touched this way
LONG span_then_title = 0, span_then_d3d = 0, span_then_other = 0;
} touch_counts;
struct ModuleRange {
uintptr_t begin = 0, end = 0;
bool holds(uintptr_t at) const { return at >= begin && at < end; }
};
ModuleRange module_range(const wchar_t* name) {
const HMODULE module = GetModuleHandleW(name);
if (!module) return {};
const auto base = reinterpret_cast<uintptr_t>(module);
const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(base);
const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS*>(base + dos->e_lfanew);
return {base, base + nt->OptionalHeader.SizeOfImage};
}
// Which module the faulting instruction lies in. Resolved before memory_lock is taken.
unsigned char toucher_of(uintptr_t rip) {
static ModuleRange title = module_range(nullptr);
static ModuleRange d3d{};
if (!d3d.end) d3d = module_range(L"d3d12_xs.dll");
return title.holds(rip) ? kByTitle : d3d.holds(rip) ? kByD3D : kByOther;
}
// Records a first touch of `page` by `who`. Called with memory_lock held.
void note_touch(Page* page, unsigned char who) {
if (page->touched & who) return;
const bool by_span = (page->touched & kBySpan) != 0;
const bool first = (page->touched & ~kBySpan) == 0;
page->touched |= who;
if (who == kBySpan) {
++touch_counts.span;
return;
}
if (!first) return; // counted for its first toucher only
if (who == kByTitle) {
++touch_counts.title;
if (by_span) ++touch_counts.span_then_title;
} else if (who == kByD3D) {
++touch_counts.d3d;
if (by_span) ++touch_counts.span_then_d3d;
} else {
++touch_counts.other;
if (by_span) ++touch_counts.span_then_other;
}
}
// First touch of a recorded slot: map it and run the instruction again. Any instruction in the
// process takes this path, the title's or a shim's. A system call writing into the slot does not
// fault but fails, so those writers map the slot first: ReadFile through import_hooks.cpp, and
@@ -403,6 +458,8 @@ LONG CALLBACK lazy_fault(PEXCEPTION_POINTERS ep) {
LONG verdict = EXCEPTION_CONTINUE_SEARCH;
LONG touched = 0;
size_t recorded = 0;
const unsigned char who = toucher_of(static_cast<uintptr_t>(ep->ContextRecord->Rip));
TouchCounts counts{};
{
Lock lock;
recorded = views.size();
@@ -417,13 +474,22 @@ LONG CALLBACK lazy_fault(PEXCEPTION_POINTERS ep) {
} else if (map_view(view)) {
verdict = EXCEPTION_CONTINUE_EXECUTION;
touched = InterlockedIncrement(&lazy_mapped);
note_touch(view->page, who);
}
}
counts = touch_counts;
}
if (touched % 4096 == 0 && touched) {
char detail[96];
std::snprintf(detail, sizeof(detail), "%ld slots mapped on first touch (%zu recorded)", touched, recorded);
bx_log_emit(BX_LOG_INFO, "xmem", "lazy_map", detail);
char who_detail[256];
std::snprintf(who_detail, sizeof(who_detail),
"64 KiB pages: written through spans %ld; first touched by the title %ld (%ld of them span-written), "
"by d3d12_xs %ld (%ld span-written), by other modules %ld (%ld span-written)",
counts.span, counts.title, counts.span_then_title, counts.d3d, counts.span_then_d3d, counts.other,
counts.span_then_other);
bx_log_emit(BX_LOG_INFO, "xmem", "page_touches", who_detail);
}
SetLastError(saved_error);
return verdict;
@@ -588,6 +654,7 @@ PVOID map_unreserved(SIZE_T count, const ULONG_PTR* tags) {
SetLastError(error);
return nullptr;
}
for (View* v = pending; v; v = v->next) note_touch(v->page, kBySpan);
publish(pending);
return base;
}
@@ -1,3 +0,0 @@
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)
@@ -1,225 +0,0 @@
/*
* 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;
}
@@ -1,8 +0,0 @@
# 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)
@@ -1,385 +0,0 @@
/* 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();
}
@@ -1,8 +0,0 @@
# 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)
@@ -1,397 +0,0 @@
/*
* 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();
}
+4 -5
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(DWORD transfer_type, SIZE_T transfer_size); // GDK xmem.h (#768)
BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t flags);
}
// ---------------------------------------------------------------------------
@@ -280,10 +280,9 @@ int main() {
std::fprintf(stderr, "FAIL: XMemAlloc returned null\n");
return 2;
}
/* 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());
std::memset(src, 0x5A, 4096);
if (!XMemTransferMemory(dst, src, 4096, 0) || std::memcmp(src, dst, 4096) != 0) {
std::fprintf(stderr, "FAIL: XMemTransferMemory mismatch\n");
return 3;
}
bx_xmem_stats_t stats = {};
+31
View File
@@ -0,0 +1,31 @@
#!/bin/bash
# Builds the Milestone 0 probes into $OUT (default: target/unified-memory-probes).
# Layout: $OUT/x86_64-windows/bx_host.dll + $OUT/x86_64-unix/bx_host.so (a Wine builtin pair), and
# the probe programs in $OUT.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
OUT="${OUT:-$HERE/../../../target/unified-memory-probes}"
mkdir -p "$OUT/x86_64-windows" "$OUT/x86_64-unix"
# Native half: x86_64 Mach-O (the Wine process runs under Rosetta 2).
clang -target x86_64-apple-macos13 -O2 -Wall -Wextra -dynamiclib -fvisibility=hidden \
-o "$OUT/x86_64-unix/bx_host.so" "$HERE/bx_host_unix.c"
# Windows half, then the 16-byte marker Wine's server looks for right after the DOS header.
x86_64-w64-mingw32-gcc -O2 -Wall -Wextra -shared -static-libgcc -o "$OUT/x86_64-windows/bx_host.dll" "$HERE/bx_host.c" -lntdll
python3 - "$OUT/x86_64-windows/bx_host.dll" <<'EOF'
import struct, sys
path = sys.argv[1]
data = bytearray(open(path, "rb").read())
lfanew = struct.unpack_from("<I", data, 0x3C)[0]
assert lfanew >= 0x40 + 32, "no room for the builtin marker before the PE header"
data[0x40:0x60] = b"Wine builtin DLL".ljust(32, b"\0")
open(path, "wb").write(data)
EOF
for probe in "$HERE"/p*.cpp; do
name="$(basename "$probe" .cpp)"
x86_64-w64-mingw32-g++ -std=c++20 -O2 -Wall -Wextra -static -o "$OUT/$name.exe" "$probe"
done
file "$OUT/x86_64-unix/bx_host.so" | sed 's/.*: //'
ls "$OUT"
+50
View File
@@ -0,0 +1,50 @@
/* Probe only (Milestone 0): the Windows half of bx_host. Built with mingw and stamped as a Wine
* builtin so Wine loads bx_host.so beside it. */
#include <windows.h>
#include <winternl.h>
#include <stdint.h>
typedef NTSTATUS (WINAPI *dispatcher_t)(UINT64 handle, unsigned int code, void *args);
NTSYSAPI void *NTAPI RtlFindExportedRoutineByName(void *module, const char *name);
NTSYSAPI NTSTATUS NTAPI NtQueryVirtualMemory(HANDLE process, const void *address, int info_class, void *buffer, SIZE_T size, SIZE_T *returned);
static UINT64 g_handle;
static dispatcher_t g_dispatch;
static NTSTATUS g_init = (NTSTATUS)0xC0000001;
struct alias_args { uint64_t dst, src, size; int32_t kr; int32_t cur, max; };
struct stats_args { uint64_t phys_footprint, resident, wired_pages, page_size, host_page_size; };
__declspec(dllexport) NTSTATUS bx_host_init(void)
{
HMODULE self = NULL;
GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)(void *)bx_host_init, &self);
HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
dispatcher_t *slot = (dispatcher_t *)RtlFindExportedRoutineByName(ntdll, "__wine_unix_call_dispatcher");
if (!slot || !*slot) return g_init = (NTSTATUS)0xC0000139; /* entry point not found */
g_dispatch = *slot;
/* 1000: Wine's MemoryWineUnixFuncs / MemoryWineLoadUnixLib. */
g_init = NtQueryVirtualMemory(GetCurrentProcess(), self, 1000,&g_handle, sizeof(g_handle), NULL);
return g_init;
}
__declspec(dllexport) int bx_host_alias(void *dst, void *src, uint64_t size, int *cur, int *max)
{
struct alias_args a = { (uint64_t)(uintptr_t)dst, (uint64_t)(uintptr_t)src, size, -1, 0, 0 };
if (g_init) return -2;
if (g_dispatch(g_handle, 0, &a)) return -3;
if (cur) *cur = a.cur;
if (max) *max = a.max;
return a.kr;
}
__declspec(dllexport) int bx_host_stats(uint64_t *out5)
{
struct stats_args s = {0};
if (g_init) return -2;
if (g_dispatch(g_handle, 1, &s)) return -3;
out5[0] = s.phys_footprint; out5[1] = s.resident; out5[2] = s.wired_pages; out5[3] = s.page_size; out5[4] = s.host_page_size;
return 0;
}
BOOL WINAPI DllMain(HINSTANCE inst, DWORD reason, LPVOID reserved) { (void)inst; (void)reason; (void)reserved; return TRUE; }
@@ -0,0 +1,48 @@
/* Probe only (Milestone 0): the native half of bx_host. x86_64 Mach-O, loaded by Wine as the
* unix library of bx_host.dll. Uses public macOS interfaces on the process's own memory. */
#include <mach/mach.h>
#include <mach/mach_vm.h>
#include <stdint.h>
#include <unistd.h>
typedef int NTSTATUS;
typedef NTSTATUS (*unixlib_entry_t)(void *args);
struct alias_args { uint64_t dst, src, size; int32_t kr; int32_t cur, max; };
struct stats_args { uint64_t phys_footprint, resident, wired_pages, page_size, host_page_size; };
/* Maps the pages at `src` a second time at `dst` (replacing what is mapped there), shared. */
static NTSTATUS bx_alias(void *p)
{
struct alias_args *a = p;
mach_vm_address_t target = a->dst;
vm_prot_t cur = 0, max = 0;
a->kr = mach_vm_remap(mach_task_self(), &target, a->size, 0, VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
mach_task_self(), a->src, FALSE, &cur, &max, VM_INHERIT_NONE);
a->cur = cur;
a->max = max;
return 0;
}
static NTSTATUS bx_stats(void *p)
{
struct stats_args *s = p;
task_vm_info_data_t info;
mach_msg_type_number_t count = TASK_VM_INFO_COUNT;
s->phys_footprint = s->resident = 0;
if (task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&info, &count) == KERN_SUCCESS) {
s->phys_footprint = info.phys_footprint;
s->resident = info.resident_size;
}
vm_statistics64_data_t vm;
mach_msg_type_number_t n = HOST_VM_INFO64_COUNT;
s->wired_pages = 0;
if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t)&vm, &n) == KERN_SUCCESS) s->wired_pages = vm.wire_count;
s->page_size = (uint64_t)getpagesize();
vm_size_t hp = 0;
host_page_size(mach_host_self(), &hp);
s->host_page_size = hp;
return 0;
}
__attribute__((visibility("default"))) const unixlib_entry_t __wine_unix_call_funcs[] = { bx_alias, bx_stats };
+237
View File
@@ -0,0 +1,237 @@
// Probe P1 (Milestone 0): can pages of a D3D12 heap be mapped a second time at an address inside a
// Wine section view, so that CPU code using that address and the GPU share one memory?
// Standalone and synthetic: no title, no GDK material. Prints one line per check.
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
static int g_fail = 0;
#define CHECK(ok, ...) \
do { \
std::printf("%s: ", (ok) ? "PASS" : "FAIL"); \
std::printf(__VA_ARGS__); \
std::printf("\n"); \
if (!(ok)) ++g_fail; \
std::fflush(stdout); \
} while (0)
using InitFn = LONG (*)(void);
using AliasFn = int (*)(void*, void*, uint64_t, int*, int*);
using StatsFn = int (*)(uint64_t*);
using VirtualAlloc2Fn = PVOID(WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG);
using MapViewOfFile3Fn = PVOID(WINAPI*)(HANDLE, HANDLE, PVOID, ULONG64, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG);
using UnmapViewOfFile2Fn = BOOL(WINAPI*)(HANDLE, PVOID, ULONG);
static ID3D12Device* g_dev;
static ID3D12CommandQueue* g_queue;
static ID3D12CommandAllocator* g_alloc;
static ID3D12GraphicsCommandList* g_list;
static ID3D12Fence* g_fence;
static UINT64 g_value;
static HANDLE g_event;
static bool submit() {
g_list->Close();
ID3D12CommandList* lists[] = {g_list};
g_queue->ExecuteCommandLists(1, lists);
g_queue->Signal(g_fence, ++g_value);
g_fence->SetEventOnCompletion(g_value, g_event);
const bool done = WaitForSingleObject(g_event, 20000) == WAIT_OBJECT_0;
g_alloc->Reset();
g_list->Reset(g_alloc, nullptr);
return done;
}
static D3D12_RESOURCE_DESC buffer_desc(UINT64 size) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
d.Width = size;
d.Height = 1;
d.DepthOrArraySize = 1;
d.MipLevels = 1;
d.SampleDesc.Count = 1;
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
return d;
}
static ID3D12Resource* committed(D3D12_HEAP_TYPE type, UINT64 size, D3D12_RESOURCE_STATES state) {
D3D12_HEAP_PROPERTIES hp{};
hp.Type = type;
const D3D12_RESOURCE_DESC d = buffer_desc(size);
ID3D12Resource* r = nullptr;
g_dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, state, nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&r));
return r;
}
static bool readable(const void* p) {
uint8_t byte = 0;
SIZE_T got = 0;
return ReadProcessMemory(GetCurrentProcess(), p, &byte, 1, &got) && got == 1;
}
int main() {
constexpr UINT64 kHeap = 64ull << 20, kPage = 64 * 1024;
// --- the native helper ---
HMODULE host = LoadLibraryA("bx_host.dll");
CHECK(host != nullptr, "bx_host.dll loaded (error %lu)", host ? 0ul : GetLastError());
if (!host) return 1;
auto init = reinterpret_cast<InitFn>(reinterpret_cast<void*>(GetProcAddress(host, "bx_host_init")));
auto alias = reinterpret_cast<AliasFn>(reinterpret_cast<void*>(GetProcAddress(host, "bx_host_alias")));
auto stats = reinterpret_cast<StatsFn>(reinterpret_cast<void*>(GetProcAddress(host, "bx_host_stats")));
const LONG st = init ? init() : -1;
CHECK(st == 0, "native half reached through Wine's unix call (status 0x%08lx)", static_cast<unsigned long>(st));
if (st != 0) return 1;
uint64_t s0[5] = {}, s1[5] = {}, s2[5] = {};
stats(s0);
std::printf("INFO: process page size %llu, host page size %llu, footprint %llu MiB\n", (unsigned long long)s0[3],
(unsigned long long)s0[4], (unsigned long long)(s0[0] >> 20));
// --- a CPU-visible D3D12 heap with one buffer over all of it ---
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
auto create = reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")));
if (!create || FAILED(create(nullptr, D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&g_dev)))) {
CHECK(false, "D3D12 device");
return 1;
}
D3D12_COMMAND_QUEUE_DESC qd{};
qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
g_dev->CreateCommandQueue(&qd, __uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&g_queue));
g_dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), reinterpret_cast<void**>(&g_alloc));
g_dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_alloc, nullptr, __uuidof(ID3D12GraphicsCommandList),
reinterpret_cast<void**>(&g_list));
g_dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&g_fence));
g_event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
D3D12_HEAP_DESC hd{};
hd.SizeInBytes = kHeap;
hd.Properties.Type = D3D12_HEAP_TYPE_CUSTOM;
hd.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
hd.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
ID3D12Heap* heap = nullptr;
HRESULT hr = g_dev->CreateHeap(&hd, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&heap));
CHECK(SUCCEEDED(hr) && heap, "CPU-visible heap of 64 MiB (hr 0x%08lx)", static_cast<unsigned long>(hr));
ID3D12Resource* whole = nullptr;
const D3D12_RESOURCE_DESC wd = buffer_desc(kHeap);
hr = heap ? g_dev->CreatePlacedResource(heap, 0, &wd, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource),
reinterpret_cast<void**>(&whole))
: E_FAIL;
uint8_t* H = nullptr;
if (whole) whole->Map(0, nullptr, reinterpret_cast<void**>(&H));
CHECK(H != nullptr, "heap-wide buffer mapped at %p (hr 0x%08lx)", static_cast<void*>(H), static_cast<unsigned long>(hr));
if (!H) return 1;
CHECK((reinterpret_cast<uintptr_t>(H) & 0x3FFF) == 0, "heap base is 16 KiB aligned (low bits 0x%llx)",
(unsigned long long)(reinterpret_cast<uintptr_t>(H) & 0xFFFF));
stats(s1);
// --- a title-style slot: placeholder, section view (reserved, then committed), as xmem makes them ---
HMODULE kb = GetModuleHandleW(L"kernelbase.dll");
auto va2 = reinterpret_cast<VirtualAlloc2Fn>(reinterpret_cast<void*>(GetProcAddress(kb, "VirtualAlloc2")));
auto mv3 = reinterpret_cast<MapViewOfFile3Fn>(reinterpret_cast<void*>(GetProcAddress(kb, "MapViewOfFile3")));
auto um2 = reinterpret_cast<UnmapViewOfFile2Fn>(reinterpret_cast<void*>(GetProcAddress(kb, "UnmapViewOfFile2")));
const HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, 0, 1 << 20, nullptr);
auto* base = static_cast<uint8_t*>(va2(GetCurrentProcess(), nullptr, 1 << 20, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0));
CHECK(section && base, "section and 1 MiB placeholder at %p", static_cast<void*>(base));
uint8_t* V0 = base;
uint8_t* V1 = base + kPage;
VirtualFree(V0, kPage, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
VirtualFree(V1, kPage, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
bool ok = mv3(section, GetCurrentProcess(), V0, 0, kPage, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0) == V0 &&
VirtualAlloc(V0, kPage, MEM_COMMIT, PAGE_READWRITE) == V0;
ok = ok && mv3(section, GetCurrentProcess(), V1, kPage, kPage, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0) == V1 &&
VirtualAlloc(V1, kPage, MEM_COMMIT, PAGE_READWRITE) == V1;
CHECK(ok, "two 64 KiB section views mapped over the placeholder");
if (!ok) return 1;
std::memcpy(V0, "SECTION0", 8);
// --- the overlay ---
uint8_t* P = H + 3 * kPage; // heap page 3
std::memcpy(P, "HEAPPAGE", 8);
int cur = 0, max = 0;
int kr = alias(V0, P, kPage, &cur, &max);
CHECK(kr == 0, "mach_vm_remap of a heap page over the view (kr %d, cur prot %d, max prot %d)", kr, cur, max);
if (kr != 0) return 1;
CHECK(std::memcmp(V0, "HEAPPAGE", 8) == 0, "the view now shows the heap page's bytes");
std::memcpy(V0 + 16, "VIAVIEW!", 8);
CHECK(std::memcmp(P + 16, "VIAVIEW!", 8) == 0, "a CPU write through the view lands in the heap page");
// --- the GPU sees CPU writes made through the view, and the view sees GPU writes ---
ID3D12Resource* readback = committed(D3D12_HEAP_TYPE_READBACK, 4096, D3D12_RESOURCE_STATE_COPY_DEST);
ID3D12Resource* upload = committed(D3D12_HEAP_TYPE_UPLOAD, 4096, D3D12_RESOURCE_STATE_GENERIC_READ);
uint32_t* rb = nullptr;
uint32_t* up = nullptr;
readback->Map(0, nullptr, reinterpret_cast<void**>(&rb));
upload->Map(0, nullptr, reinterpret_cast<void**>(&up));
bool gpu_reads = true, gpu_writes = true;
for (uint32_t round = 0; round < 8; ++round) {
const uint32_t v = 0xC0DE0000u + round;
std::memcpy(V0 + 256, &v, 4);
g_list->CopyBufferRegion(readback, 0, whole, 3 * kPage + 256, 4);
gpu_reads = submit() && rb[0] == v && gpu_reads;
up[0] = 0xFEED0000u + round;
g_list->CopyBufferRegion(whole, 3 * kPage + 512, upload, 0, 4);
uint32_t got = 0;
const bool done = submit();
std::memcpy(&got, V0 + 512, 4);
gpu_writes = done && got == 0xFEED0000u + round && gpu_writes;
}
CHECK(gpu_reads, "GPU reads what the CPU wrote through the view (8 rounds, no Map/Unmap)");
CHECK(gpu_writes, "the view shows what the GPU wrote (8 rounds)");
// --- Windows calls on the overlaid view ---
wchar_t dir[MAX_PATH], path[MAX_PATH];
GetTempPathW(MAX_PATH, dir);
GetTempFileNameW(dir, L"bxp", 0, path);
HANDLE f = CreateFileW(path, GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, nullptr);
char pattern[4096];
for (int i = 0; i < 4096; ++i) pattern[i] = static_cast<char>(i * 7 + 1);
DWORD n = 0;
WriteFile(f, pattern, sizeof(pattern), &n, nullptr);
SetFilePointer(f, 0, nullptr, FILE_BEGIN);
const BOOL rd = ReadFile(f, V0 + 8192, sizeof(pattern), &n, nullptr);
CHECK(rd && n == sizeof(pattern) && std::memcmp(P + 8192, pattern, sizeof(pattern)) == 0,
"ReadFile into the view succeeds and the bytes are in the heap page (ok %d, %lu bytes, error %lu)", rd, n, rd ? 0ul : GetLastError());
CloseHandle(f);
DWORD old = 0;
const BOOL p1 = VirtualProtect(V0, kPage, PAGE_NOACCESS, &old);
const bool blocked = !readable(V0);
const BOOL p2 = VirtualProtect(V0, kPage, PAGE_READWRITE, &old);
CHECK(p1 && blocked && p2 && std::memcmp(V0, "HEAPPAGE", 8) == 0, "VirtualProtect: no access, then read-write again with the heap bytes intact");
MEMORY_BASIC_INFORMATION mbi{};
VirtualQuery(V0, &mbi, sizeof(mbi));
CHECK(mbi.State == MEM_COMMIT && mbi.Type == MEM_MAPPED, "VirtualQuery still reports a committed mapped view (state 0x%lx type 0x%lx)", mbi.State, mbi.Type);
// --- one heap page at two addresses ---
kr = alias(V1, P, kPage, &cur, &max);
std::memcpy(V0 + 1024, "TWOVIEWS", 8);
CHECK(kr == 0 && std::memcmp(V1 + 1024, "TWOVIEWS", 8) == 0, "a second view of the same heap page shows writes made through the first");
// --- many overlays ---
LARGE_INTEGER freq, t0, t1;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&t0);
int bad = 0;
for (int i = 0; i < 10000; ++i) bad += alias(V1, H + (static_cast<UINT64>(i) % 1000) * kPage, kPage, nullptr, nullptr) != 0;
QueryPerformanceCounter(&t1);
const double us = 1e6 * static_cast<double>(t1.QuadPart - t0.QuadPart) / static_cast<double>(freq.QuadPart) / 10000.0;
CHECK(bad == 0, "10,000 overlays of one slot onto different heap pages: %.1f microseconds each", us);
// --- unmapping gives the slot back and leaves the heap alone ---
const BOOL un = um2(GetCurrentProcess(), V0, MEM_PRESERVE_PLACEHOLDER);
CHECK(un && !readable(V0) && std::memcmp(P, "HEAPPAGE", 8) == 0, "unmapping the view restores the placeholder; the heap page keeps its bytes");
ok = mv3(section, GetCurrentProcess(), V0, 0, kPage, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0) == V0 &&
VirtualAlloc(V0, kPage, MEM_COMMIT, PAGE_READWRITE) == V0;
CHECK(ok && std::memcmp(V0, "SECTION0", 8) == 0, "mapping the section there again shows the section's own bytes");
// --- what it costs ---
for (UINT64 i = 0; i < kHeap; i += 4096) H[i] = 1; // touch the whole heap
g_list->CopyBufferRegion(readback, 0, whole, 0, 4);
submit();
stats(s2);
std::printf("INFO: footprint MiB: start %llu, heap created %llu, heap touched and used %llu; system wired pages: %llu -> %llu -> %llu\n",
(unsigned long long)(s0[0] >> 20), (unsigned long long)(s1[0] >> 20), (unsigned long long)(s2[0] >> 20),
(unsigned long long)s0[2], (unsigned long long)s1[2], (unsigned long long)s2[2]);
std::printf("RESULT: %d failed\n", g_fail);
return g_fail ? 1 : 0;
}
+232
View File
@@ -0,0 +1,232 @@
// Probe P2 (Milestone 0): how D3DMetal heaps behave and what they cost.
// Standalone and synthetic. Footprint figures are the process's phys_footprint, read through bx_host.
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <vector>
static int g_fail = 0;
#define CHECK(ok, ...) \
do { \
std::printf("%s: ", (ok) ? "PASS" : "FAIL"); \
std::printf(__VA_ARGS__); \
std::printf("\n"); \
if (!(ok)) ++g_fail; \
std::fflush(stdout); \
} while (0)
using InitFn = LONG (*)(void);
using StatsFn = int (*)(uint64_t*);
static StatsFn g_stats;
static ID3D12Device* g_dev;
static ID3D12CommandQueue* g_queue;
static ID3D12CommandAllocator* g_alloc;
static ID3D12GraphicsCommandList* g_list;
static ID3D12Fence* g_fence;
static UINT64 g_value;
static HANDLE g_event;
static double footprint_mib() {
uint64_t s[5] = {};
g_stats(s);
return static_cast<double>(s[0]) / (1024.0 * 1024.0);
}
static bool submit() {
g_list->Close();
ID3D12CommandList* lists[] = {g_list};
g_queue->ExecuteCommandLists(1, lists);
g_queue->Signal(g_fence, ++g_value);
g_fence->SetEventOnCompletion(g_value, g_event);
const bool done = WaitForSingleObject(g_event, 30000) == WAIT_OBJECT_0;
g_alloc->Reset();
g_list->Reset(g_alloc, nullptr);
return done;
}
static D3D12_RESOURCE_DESC buffer_desc(UINT64 size) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
d.Width = size;
d.Height = 1;
d.DepthOrArraySize = 1;
d.MipLevels = 1;
d.SampleDesc.Count = 1;
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
return d;
}
static D3D12_HEAP_PROPERTIES cpu_visible() {
D3D12_HEAP_PROPERTIES hp{};
hp.Type = D3D12_HEAP_TYPE_CUSTOM;
hp.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
hp.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
return hp;
}
static ID3D12Heap* heap_of(UINT64 size) {
D3D12_HEAP_DESC hd{};
hd.SizeInBytes = size;
hd.Properties = cpu_visible();
ID3D12Heap* heap = nullptr;
g_dev->CreateHeap(&hd, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&heap));
return heap;
}
static ID3D12Resource* placed(ID3D12Heap* heap, UINT64 offset, UINT64 size, HRESULT* hr) {
const D3D12_RESOURCE_DESC d = buffer_desc(size);
ID3D12Resource* r = nullptr;
*hr = g_dev->CreatePlacedResource(heap, offset, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&r));
return r;
}
int main() {
HMODULE host = LoadLibraryA("bx_host.dll");
auto init = host ? reinterpret_cast<InitFn>(reinterpret_cast<void*>(GetProcAddress(host, "bx_host_init"))) : nullptr;
g_stats = host ? reinterpret_cast<StatsFn>(reinterpret_cast<void*>(GetProcAddress(host, "bx_host_stats"))) : nullptr;
if (!init || init() != 0 || !g_stats) {
CHECK(false, "bx_host");
return 1;
}
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
auto create = reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")));
if (!create || FAILED(create(nullptr, D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&g_dev)))) {
CHECK(false, "D3D12 device");
return 1;
}
D3D12_COMMAND_QUEUE_DESC qd{};
qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
g_dev->CreateCommandQueue(&qd, __uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&g_queue));
g_dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), reinterpret_cast<void**>(&g_alloc));
g_dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_alloc, nullptr, __uuidof(ID3D12GraphicsCommandList),
reinterpret_cast<void**>(&g_list));
g_dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&g_fence));
g_event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
// A readback buffer placed in a small CPU-visible heap of its own, so the cost figures below are
// not mixed with D3DMetal's pools for committed resources.
ID3D12Heap* rb_heap = heap_of(1 << 20);
HRESULT hr = S_OK;
ID3D12Resource* readback = placed(rb_heap, 0, 1 << 20, &hr);
uint8_t* rb = nullptr;
if (readback) readback->Map(0, nullptr, reinterpret_cast<void**>(&rb));
CHECK(rb != nullptr, "readback buffer placed in its own CPU-visible heap (hr 0x%08lx)", static_cast<unsigned long>(hr));
if (!rb) return 1;
g_list->CopyBufferRegion(readback, 4096, readback, 0, 16); // first GPU use of the device
submit();
const double f_base = footprint_mib();
// --- A. residency of a heap ---
constexpr UINT64 kHeap = 64ull << 20, kPage = 64 * 1024;
ID3D12Heap* heap = heap_of(kHeap);
const double f_created = footprint_mib();
ID3D12Resource* whole = heap ? placed(heap, 0, kHeap, &hr) : nullptr;
uint8_t* H = nullptr;
if (whole) whole->Map(0, nullptr, reinterpret_cast<void**>(&H));
CHECK(H != nullptr, "64 MiB heap with a heap-wide buffer");
if (!H) return 1;
const double f_mapped = footprint_mib();
std::memcpy(H + 5 * kPage, "ONEPAGE!", 8);
g_list->CopyBufferRegion(readback, 0, whole, 5 * kPage, 8);
const bool used = submit() && std::memcmp(rb, "ONEPAGE!", 8) == 0;
const double f_used = footprint_mib();
CHECK(used, "one page of the heap written and read by the GPU");
std::printf("INFO: footprint MiB: baseline %.0f; heap created %+.0f; buffer mapped %+.0f; one page used by the GPU %+.0f\n", f_base,
f_created - f_base, f_mapped - f_base, f_used - f_base);
for (UINT64 i = 0; i < kHeap; i += 4096) H[i] = 1;
g_list->CopyBufferRegion(readback, 0, whole, 7 * kPage, 8);
submit();
const double f_touched = footprint_mib();
std::printf("INFO: after touching every page of the heap: %+.0f MiB over baseline\n", f_touched - f_base);
// --- B. buffers placed at fine offsets, overlapping the heap-wide buffer ---
const UINT64 offsets[] = {kPage * 9, kPage * 9 + 4096, kPage * 9 + 256, kPage * 9 + 16, kPage * 9 + 4};
for (UINT64 off : offsets) {
char text[8];
std::snprintf(text, sizeof(text), "o%05x", static_cast<unsigned>(off & 0xFFFFF));
std::memcpy(H + off, text, 8);
ID3D12Resource* small = placed(heap, off, 4096, &hr);
bool same = false;
if (small) {
std::memset(rb, 0, 16);
g_list->CopyBufferRegion(readback, 0, small, 0, 8);
same = submit() && std::memcmp(rb, text, 8) == 0;
small->Release();
}
std::printf("%s: buffer placed at heap offset 64 KiB*9 + %llu: hr 0x%08lx, its first bytes are the heap's bytes there: %s\n",
small && same ? "PASS" : "INFO", (unsigned long long)(off - kPage * 9), static_cast<unsigned long>(hr),
small ? (same ? "yes" : "NO") : "not created");
}
std::fflush(stdout);
// --- C. releasing the heap ---
whole->Unmap(0, nullptr);
whole->Release();
heap->Release();
g_list->CopyBufferRegion(readback, 4096, readback, 0, 16);
submit();
Sleep(1500);
const double f_released = footprint_mib();
std::printf("INFO: after releasing the heap: %+.0f MiB over baseline\n", f_released - f_base);
// --- C2. how the footprint moves as more heaps are made and used ---
{
std::vector<ID3D12Heap*> heaps;
std::vector<ID3D12Resource*> buffers;
const double f0 = footprint_mib();
std::printf("INFO: footprint over this point as 64 MiB heaps are made, each touched in full and used once by the GPU:");
for (int i = 0; i < 10; ++i) {
ID3D12Heap* h = heap_of(kHeap);
ID3D12Resource* b = h ? placed(h, 0, kHeap, &hr) : nullptr;
uint8_t* p = nullptr;
if (b) b->Map(0, nullptr, reinterpret_cast<void**>(&p));
if (!p) break;
for (UINT64 k = 0; k < kHeap; k += 4096) p[k] = 1;
g_list->CopyBufferRegion(readback, 0, b, 0, 8);
submit();
heaps.push_back(h);
buffers.push_back(b);
std::printf(" %+.0f", footprint_mib() - f0);
}
std::printf(" MiB\n");
for (size_t i = 0; i < heaps.size(); ++i) {
buffers[i]->Release();
heaps[i]->Release();
}
g_list->CopyBufferRegion(readback, 4096, readback, 0, 16);
submit();
Sleep(1500);
std::printf("INFO: after releasing those heaps: %+.0f MiB\n", footprint_mib() - f0);
}
// --- D. what many small committed buffers cost ---
constexpr int kCount = 50000;
std::vector<ID3D12Resource*> small(kCount, nullptr);
const D3D12_HEAP_PROPERTIES hp = cpu_visible();
const D3D12_RESOURCE_DESC sd = buffer_desc(240);
int made = 0;
const double f_before = footprint_mib();
for (int i = 0; i < kCount; ++i) {
if (FAILED(g_dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &sd, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource),
reinterpret_cast<void**>(&small[i])))) break;
void* p = nullptr;
if (SUCCEEDED(small[i]->Map(0, nullptr, &p)) && p) std::memset(p, 0x5A, 240);
++made;
}
if (made) {
g_list->CopyBufferRegion(readback, 0, small[made - 1], 0, 16);
submit();
}
const double f_small = footprint_mib();
std::printf("INFO: %d committed 240-byte buffers (mapped and written): %+.0f MiB, %.1f KiB each\n", made, f_small - f_before,
made ? (f_small - f_before) * 1024.0 / made : 0.0);
for (int i = 0; i < made; ++i) small[i]->Release();
g_list->CopyBufferRegion(readback, 4096, readback, 0, 16);
submit();
Sleep(1500);
std::printf("INFO: after releasing them: %+.0f MiB over the figure before they were made\n", footprint_mib() - f_before);
std::printf("RESULT: %d failed\n", g_fail);
return g_fail ? 1 : 0;
}
+411
View File
@@ -0,0 +1,411 @@
// Probe P3 (Milestone 0): can a reserved texture take its tiles from chosen offsets of a
// CPU-visible heap, can two textures share those tiles, and are reserved buffers available?
// Standalone and synthetic.
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <vector>
static int g_fail = 0;
#define CHECK(ok, ...) \
do { \
std::printf("%s: ", (ok) ? "PASS" : "FAIL"); \
std::printf(__VA_ARGS__); \
std::printf("\n"); \
if (!(ok)) ++g_fail; \
std::fflush(stdout); \
} while (0)
static ID3D12Device* g_dev;
static ID3D12CommandQueue* g_queue;
static ID3D12CommandAllocator* g_alloc;
static ID3D12GraphicsCommandList* g_list;
static ID3D12Fence* g_fence;
static UINT64 g_value;
static HANDLE g_event;
static bool wait_queue() {
g_queue->Signal(g_fence, ++g_value);
g_fence->SetEventOnCompletion(g_value, g_event);
return WaitForSingleObject(g_event, 30000) == WAIT_OBJECT_0;
}
static bool submit() {
g_list->Close();
ID3D12CommandList* lists[] = {g_list};
g_queue->ExecuteCommandLists(1, lists);
const bool done = wait_queue();
g_alloc->Reset();
g_list->Reset(g_alloc, nullptr);
return done;
}
static D3D12_RESOURCE_DESC buffer_desc(UINT64 size) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
d.Width = size;
d.Height = 1;
d.DepthOrArraySize = 1;
d.MipLevels = 1;
d.SampleDesc.Count = 1;
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
return d;
}
static ID3D12Resource* committed(D3D12_HEAP_TYPE type, UINT64 size, D3D12_RESOURCE_STATES state) {
D3D12_HEAP_PROPERTIES hp{};
hp.Type = type;
const D3D12_RESOURCE_DESC d = buffer_desc(size);
ID3D12Resource* r = nullptr;
g_dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, state, nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&r));
return r;
}
constexpr UINT kSize = 512, kPitch = kSize * 4;
constexpr UINT64 kTile = 64 * 1024, kHeap = 64ull << 20;
static D3D12_RESOURCE_DESC texture_desc(DXGI_FORMAT format, UINT size, UINT16 mips) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
d.Width = size;
d.Height = size;
d.DepthOrArraySize = 1;
d.MipLevels = mips;
d.Format = format;
d.SampleDesc.Count = 1;
d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
return d;
}
static ID3D12Resource* reserved(const D3D12_RESOURCE_DESC& d, HRESULT* hr) {
ID3D12Resource* r = nullptr;
*hr = g_dev->CreateReservedResource(&d, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&r));
return r;
}
// Maps tile i of mip 0 (16 tiles of 128x128 for a 512x512 RGBA8 texture) to heap tile first + step * i.
static void map_tiles(ID3D12Resource* tex, ID3D12Heap* heap, UINT first, int step) {
for (UINT i = 0; i < 16; ++i) {
D3D12_TILED_RESOURCE_COORDINATE at{};
at.X = i % 4;
at.Y = i / 4;
D3D12_TILE_REGION_SIZE size{};
size.NumTiles = 1;
D3D12_TILE_RANGE_FLAGS flags = D3D12_TILE_RANGE_FLAG_NONE;
UINT offset = static_cast<UINT>(static_cast<int>(first) + step * static_cast<int>(i));
UINT count = 1;
g_queue->UpdateTileMappings(tex, 1, &at, &size, heap, 1, &flags, &offset, &count, D3D12_TILE_MAPPING_FLAG_NONE);
}
}
static uint32_t texel(UINT x, UINT y) { return 0xFF000000u | ((y & 0xFFF) << 12) | (x & 0xFFF); }
static void copy_out(ID3D12Resource* tex, ID3D12Resource* readback) {
D3D12_TEXTURE_COPY_LOCATION dst{};
dst.pResource = readback;
dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, kPitch};
D3D12_TEXTURE_COPY_LOCATION src{};
src.pResource = tex;
src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
g_list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
}
static unsigned wrong_texels(const uint32_t* rb) {
unsigned wrong = 0;
for (UINT y = 0; y < kSize; ++y)
for (UINT x = 0; x < kSize; ++x) wrong += rb[y * kSize + x] != texel(x, y);
return wrong;
}
int main() {
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
auto create = reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")));
if (!create || FAILED(create(nullptr, D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&g_dev)))) {
CHECK(false, "D3D12 device");
return 1;
}
D3D12_FEATURE_DATA_D3D12_OPTIONS o{};
g_dev->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &o, sizeof(o));
std::printf("INFO: the device reports TiledResourcesTier %d, ResourceHeapTier %d, StandardSwizzle64KBSupported %d\n",
static_cast<int>(o.TiledResourcesTier), static_cast<int>(o.ResourceHeapTier), o.StandardSwizzle64KBSupported);
D3D12_COMMAND_QUEUE_DESC qd{};
qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
g_dev->CreateCommandQueue(&qd, __uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&g_queue));
g_dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), reinterpret_cast<void**>(&g_alloc));
g_dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_alloc, nullptr, __uuidof(ID3D12GraphicsCommandList),
reinterpret_cast<void**>(&g_list));
g_dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&g_fence));
g_event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
// A CPU-visible heap with one buffer over all of it.
D3D12_HEAP_DESC hd{};
hd.SizeInBytes = kHeap;
hd.Properties.Type = D3D12_HEAP_TYPE_CUSTOM;
hd.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
hd.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
ID3D12Heap* heap = nullptr;
HRESULT hr = g_dev->CreateHeap(&hd, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&heap));
ID3D12Resource* whole = nullptr;
const D3D12_RESOURCE_DESC wd = buffer_desc(kHeap);
if (heap) g_dev->CreatePlacedResource(heap, 0, &wd, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&whole));
uint8_t* H = nullptr;
if (whole) whole->Map(0, nullptr, reinterpret_cast<void**>(&H));
CHECK(H != nullptr, "CPU-visible 64 MiB heap with a heap-wide buffer (hr 0x%08lx)", static_cast<unsigned long>(hr));
if (!H) return 1;
ID3D12Resource* upload = committed(D3D12_HEAP_TYPE_UPLOAD, UINT64(kPitch) * kSize, D3D12_RESOURCE_STATE_GENERIC_READ);
ID3D12Resource* readback = committed(D3D12_HEAP_TYPE_READBACK, UINT64(kPitch) * kSize, D3D12_RESOURCE_STATE_COPY_DEST);
uint32_t* up = nullptr;
uint32_t* rb = nullptr;
upload->Map(0, nullptr, reinterpret_cast<void**>(&up));
readback->Map(0, nullptr, reinterpret_cast<void**>(&rb));
for (UINT y = 0; y < kSize; ++y)
for (UINT x = 0; x < kSize; ++x) up[y * kSize + x] = texel(x, y);
// --- a reserved texture whose 16 tiles come from scattered, descending offsets of that heap ---
const D3D12_RESOURCE_DESC td = texture_desc(DXGI_FORMAT_R8G8B8A8_UNORM, kSize, 1);
ID3D12Resource* a = reserved(td, &hr);
CHECK(a != nullptr, "reserved 512x512 RGBA8 texture (hr 0x%08lx)", static_cast<unsigned long>(hr));
if (!a) return 1;
UINT total = 0, count = 1;
D3D12_PACKED_MIP_INFO packed{};
D3D12_TILE_SHAPE shape{};
D3D12_SUBRESOURCE_TILING tiling{};
g_dev->GetResourceTiling(a, &total, &packed, &shape, &count, 0, &tiling);
std::printf("INFO: tiling: %u tiles of %ux%u texels, %ux%u tiles in mip 0, %u packed mips\n", total, shape.WidthInTexels, shape.HeightInTexels,
tiling.WidthInTiles, tiling.HeightInTiles, packed.NumPackedMips);
constexpr UINT kFirst = 200; // tile i -> heap tile 200 - 3*i
map_tiles(a, heap, kFirst, -3);
wait_queue();
D3D12_TEXTURE_COPY_LOCATION dst{};
dst.pResource = a;
dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
D3D12_TEXTURE_COPY_LOCATION src{};
src.pResource = upload;
src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
src.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, kPitch};
g_list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
copy_out(a, readback);
bool ok = submit();
unsigned wrong = wrong_texels(rb);
CHECK(ok && wrong == 0, "texels uploaded into the texture read back (%u of %u wrong)", wrong, kSize * kSize);
// Did the texels land in the heap pages named in the mapping, where the CPU can see them?
unsigned named_filled = 0, others_filled = 0;
for (UINT t = 0; t < kHeap / kTile; ++t) {
bool any = false;
for (UINT64 i = 0; i < kTile && !any; i += 64) any = H[t * kTile + i] != 0;
bool named = false;
for (UINT i = 0; i < 16; ++i) named = named || t == kFirst - 3 * i;
if (any && named) ++named_filled;
if (any && !named) ++others_filled;
}
CHECK(named_filled == 16 && others_filled == 0,
"the texels are in exactly the 16 heap tiles named by the mapping, visible to the CPU (%u named tiles filled, %u others)", named_filled,
others_filled);
// Does each 64 KiB heap tile hold exactly the texels of its 128x128 tile?
unsigned tiles_self_contained = 0;
for (UINT i = 0; i < 16; ++i) {
const uint32_t* words = reinterpret_cast<const uint32_t*>(H + (kFirst - 3 * i) * kTile);
const UINT tx = i % 4, ty = i / 4;
bool inside = true;
for (UINT w = 0; w < kTile / 4 && inside; ++w) {
const UINT x = words[w] & 0xFFF, y = (words[w] >> 12) & 0xFFF;
inside = (words[w] >> 24) == 0xFF && x / 128 == tx && y / 128 == ty;
}
tiles_self_contained += inside;
}
std::printf("INFO: heap tiles holding only texels of their own 128x128 tile: %u of 16\n", tiles_self_contained);
const uint32_t* first = reinterpret_cast<const uint32_t*>(H + kFirst * kTile);
std::printf("INFO: texel order in a tile, as (x,y) of the first 12 texels in memory:");
for (int w = 0; w < 12; ++w) std::printf(" (%u,%u)", first[w] & 0xFFF, (first[w] >> 12) & 0xFFF);
std::printf("\n");
// --- a second texture mapped to the same heap tiles shows the same picture ---
ID3D12Resource* b = reserved(td, &hr);
if (b) {
map_tiles(b, heap, kFirst, -3);
wait_queue();
std::memset(rb, 0, UINT64(kPitch) * kSize);
copy_out(b, readback);
ok = submit();
wrong = wrong_texels(rb);
}
CHECK(b && ok && wrong == 0, "a second reserved texture on the same heap tiles reads the same texels (%u wrong)", b ? wrong : kSize * kSize);
// --- a CPU write into a heap tile changes what the texture reads ---
std::memset(H + kFirst * kTile, 0, kTile); // tile (0,0)
std::memset(rb, 0xAB, UINT64(kPitch) * kSize);
copy_out(a, readback);
ok = submit();
unsigned zeroed = 0, changed = 0, kept = 0;
for (UINT y = 0; y < kSize; ++y)
for (UINT x = 0; x < kSize; ++x) {
const bool in_tile = x < 128 && y < 128;
if (in_tile && rb[y * kSize + x] == 0) ++zeroed;
if (in_tile && rb[y * kSize + x] != texel(x, y)) ++changed;
if (!in_tile && rb[y * kSize + x] == texel(x, y)) ++kept;
}
// RGBA8 tiles are not stored as plain texels (see the texel-order line above), so a zeroed tile
// need not read as zero: what matters is that only that tile changes.
CHECK(ok && changed > 0 && kept == kSize * kSize - 128 * 128,
"overwriting one heap tile from the CPU changes that tile of the texture and no other (%u of %u texels changed, %u read zero, %u of %u others kept)",
changed, 128 * 128, zeroed, kept, kSize * kSize - 128 * 128);
// --- an unmapped tile reads zero ---
{
D3D12_TILED_RESOURCE_COORDINATE at{};
at.X = 3;
at.Y = 3;
D3D12_TILE_REGION_SIZE size{};
size.NumTiles = 1;
D3D12_TILE_RANGE_FLAGS flags = D3D12_TILE_RANGE_FLAG_NULL;
UINT count1 = 1;
g_queue->UpdateTileMappings(a, 1, &at, &size, nullptr, 1, &flags, nullptr, &count1, D3D12_TILE_MAPPING_FLAG_NONE);
wait_queue();
copy_out(a, readback);
ok = submit();
unsigned z = 0;
for (UINT y = 384; y < 512; ++y)
for (UINT x = 384; x < 512; ++x) z += rb[y * kSize + x] == 0;
CHECK(ok && z == 128 * 128, "a tile unmapped again reads zero (%u of %u)", z, 128 * 128);
}
// --- block-compressed textures: are the blocks stored plainly, and can two textures share them? ---
{
// 512x512 BC1: 128x128 blocks of 8 bytes = 128 KiB = two 512x256 tiles.
constexpr UINT kBlocks = 128, kBcPitch = kBlocks * 8;
const D3D12_RESOURCE_DESC bd = texture_desc(DXGI_FORMAT_BC1_UNORM, 512, 1);
ID3D12Resource* c = reserved(bd, &hr);
ID3D12Resource* d = reserved(bd, &hr);
ID3D12Resource* bc_up = committed(D3D12_HEAP_TYPE_UPLOAD, UINT64(kBcPitch) * kBlocks, D3D12_RESOURCE_STATE_GENERIC_READ);
uint64_t* blocks = nullptr;
bc_up->Map(0, nullptr, reinterpret_cast<void**>(&blocks));
auto block = [](UINT bx, UINT by) { return 0xB1C0000000000000ull | (static_cast<uint64_t>(by) << 16) | bx; };
for (UINT by = 0; by < kBlocks; ++by)
for (UINT bx = 0; bx < kBlocks; ++bx) blocks[by * kBlocks + bx] = block(bx, by);
auto map_two = [&](ID3D12Resource* tex) {
for (UINT i = 0; i < 2; ++i) {
D3D12_TILED_RESOURCE_COORDINATE at{};
at.Y = i;
D3D12_TILE_REGION_SIZE size{};
size.NumTiles = 1;
D3D12_TILE_RANGE_FLAGS flags = D3D12_TILE_RANGE_FLAG_NONE;
UINT offset = 500 + 7 * i, count1 = 1; // heap tiles 500 and 507
g_queue->UpdateTileMappings(tex, 1, &at, &size, heap, 1, &flags, &offset, &count1, D3D12_TILE_MAPPING_FLAG_NONE);
}
};
auto read_blocks = [&](ID3D12Resource* tex) {
D3D12_TEXTURE_COPY_LOCATION out{};
out.pResource = readback;
out.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
out.PlacedFootprint.Footprint = {DXGI_FORMAT_BC1_UNORM, 512, 512, 1, kBcPitch};
D3D12_TEXTURE_COPY_LOCATION in{};
in.pResource = tex;
in.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
std::memset(rb, 0xEE, UINT64(kBcPitch) * kBlocks);
g_list->CopyTextureRegion(&out, 0, 0, 0, &in, nullptr);
return submit();
};
if (c && d) {
map_two(c);
wait_queue();
D3D12_TEXTURE_COPY_LOCATION to{};
to.pResource = c;
to.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
D3D12_TEXTURE_COPY_LOCATION from{};
from.pResource = bc_up;
from.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
from.PlacedFootprint.Footprint = {DXGI_FORMAT_BC1_UNORM, 512, 512, 1, kBcPitch};
g_list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
ok = submit() && read_blocks(c);
const uint64_t* got = reinterpret_cast<const uint64_t*>(rb);
unsigned bad = 0;
for (UINT i = 0; i < kBlocks * kBlocks; ++i) bad += got[i] != block(i % kBlocks, i / kBlocks);
CHECK(ok && bad == 0, "BC1: blocks uploaded into a reserved texture read back (%u wrong)", bad);
// Are the heap tiles made of exactly those 8-byte blocks, each tile holding its own half?
const uint64_t* t0 = reinterpret_cast<const uint64_t*>(H + 500 * kTile);
const uint64_t* t1 = reinterpret_cast<const uint64_t*>(H + 507 * kTile);
unsigned plain0 = 0, plain1 = 0;
for (UINT w = 0; w < kTile / 8; ++w) {
plain0 += (t0[w] >> 48) == 0xB1C0 && ((t0[w] >> 16) & 0xFFFF) < 64;
plain1 += (t1[w] >> 48) == 0xB1C0 && ((t1[w] >> 16) & 0xFFFF) >= 64;
}
std::printf("INFO: BC1: heap tile words that are plain blocks of that tile's half: %u and %u of %llu\n", plain0, plain1,
(unsigned long long)(kTile / 8));
std::printf("INFO: BC1: block order in a tile, as (bx,by) of the first 20 blocks in memory:");
for (int w = 0; w < 20; ++w) std::printf(" (%u,%u)", static_cast<unsigned>(t0[w] & 0xFFFF), static_cast<unsigned>((t0[w] >> 16) & 0xFFFF));
std::printf("\n");
// A second texture on the same heap tiles.
map_two(d);
wait_queue();
ok = read_blocks(d);
bad = 0;
for (UINT i = 0; i < kBlocks * kBlocks; ++i) bad += got[i] != block(i % kBlocks, i / kBlocks);
CHECK(ok && bad == 0, "BC1: a second reserved texture on the same heap tiles reads the same blocks (%u wrong)", bad);
// A CPU write of one block, found by its value, is what the texture then reads there.
uint64_t* w0 = reinterpret_cast<uint64_t*>(H + 500 * kTile);
UINT at = 0;
for (UINT w = 0; w < kTile / 8; ++w)
if (w0[w] == block(5, 9)) at = w;
w0[at] = 0x1122334455667788ull;
ok = read_blocks(c);
CHECK(ok && got[9 * kBlocks + 5] == 0x1122334455667788ull, "BC1: a block written into the heap tile by the CPU is what the texture reads there");
} else {
std::printf("INFO: reserved BC1 textures not created (hr 0x%08lx)\n", static_cast<unsigned long>(hr));
}
}
// --- a mip chain: which mips are packed ---
for (DXGI_FORMAT f : {DXGI_FORMAT_BC7_UNORM, DXGI_FORMAT_BC1_UNORM}) {
const D3D12_RESOURCE_DESC md = texture_desc(f, 1024, 11);
ID3D12Resource* m = reserved(md, &hr);
if (!m) {
std::printf("INFO: reserved 1024x1024 format %d with 11 mips not created (hr 0x%08lx)\n", static_cast<int>(f), static_cast<unsigned long>(hr));
continue;
}
UINT mtotal = 0, mcount = 11;
D3D12_PACKED_MIP_INFO mp{};
D3D12_TILE_SHAPE ms{};
D3D12_SUBRESOURCE_TILING mt[11]{};
g_dev->GetResourceTiling(m, &mtotal, &mp, &ms, &mcount, 0, mt);
std::printf("INFO: 1024x1024 format %d, 11 mips: %u tiles of %ux%u texels; standard mips %u, packed mips %u in %u tiles; mip0 %ux%u tiles, mip1 %ux%u, mip2 %ux%u\n",
static_cast<int>(f), mtotal, ms.WidthInTexels, ms.HeightInTexels, mp.NumStandardMips, mp.NumPackedMips, mp.NumTilesForPackedMips,
mt[0].WidthInTiles, mt[0].HeightInTiles, mt[1].WidthInTiles, mt[1].HeightInTiles, mt[2].WidthInTiles, mt[2].HeightInTiles);
m->Release();
}
// --- a reserved buffer ---
{
D3D12_RESOURCE_DESC bd = buffer_desc(1 << 20);
bd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
ID3D12Resource* rbuf = reserved(bd, &hr);
bool same = false;
if (rbuf) {
// buffer tiles 0..15 -> heap tiles 300, 298, ... (descending by two)
for (UINT i = 0; i < 16; ++i) {
D3D12_TILED_RESOURCE_COORDINATE at{};
at.X = i;
D3D12_TILE_REGION_SIZE size{};
size.NumTiles = 1;
D3D12_TILE_RANGE_FLAGS flags = D3D12_TILE_RANGE_FLAG_NONE;
UINT offset = 300 - 2 * i, count1 = 1;
g_queue->UpdateTileMappings(rbuf, 1, &at, &size, heap, 1, &flags, &offset, &count1, D3D12_TILE_MAPPING_FLAG_NONE);
std::memcpy(H + UINT64(offset) * kTile + 8, &i, 4);
}
wait_queue();
same = true;
for (UINT i = 0; i < 16; ++i) g_list->CopyBufferRegion(readback, i * 4, rbuf, UINT64(i) * kTile + 8, 4);
same = submit();
for (UINT i = 0; i < 16; ++i) same = same && rb[i] == i;
}
std::printf("%s: reserved buffer of 1 MiB: created hr 0x%08lx; its tiles read the scattered heap tiles they were mapped to: %s\n",
rbuf && same ? "PASS" : "INFO", static_cast<unsigned long>(hr), rbuf ? (same ? "yes" : "NO") : "not created");
}
std::printf("RESULT: %d failed\n", g_fail);
return g_fail ? 1 : 0;
}
@@ -0,0 +1,101 @@
// Probe P5 (Milestone 0): what many small textures cost on D3DMetal, committed versus reserved.
// Standalone and synthetic. Footprint is the process's phys_footprint, read through bx_host.
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <vector>
using InitFn = LONG (*)(void);
using StatsFn = int (*)(uint64_t*);
static StatsFn g_stats;
static ID3D12Device* g_dev;
static ID3D12CommandQueue* g_queue;
static ID3D12Fence* g_fence;
static UINT64 g_value;
static HANDLE g_event;
static double footprint_mib() {
uint64_t s[5] = {};
g_stats(s);
return static_cast<double>(s[0]) / (1024.0 * 1024.0);
}
static void settle() {
g_queue->Signal(g_fence, ++g_value);
g_fence->SetEventOnCompletion(g_value, g_event);
WaitForSingleObject(g_event, 30000);
Sleep(1000);
}
static D3D12_RESOURCE_DESC texture(DXGI_FORMAT format, UINT w, UINT h, bool reserved) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
d.Width = w;
d.Height = h;
d.DepthOrArraySize = 1;
d.MipLevels = 1;
d.Format = format;
d.SampleDesc.Count = 1;
d.Layout = reserved ? D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE : D3D12_TEXTURE_LAYOUT_UNKNOWN;
return d;
}
static void measure(const char* name, DXGI_FORMAT format, UINT w, UINT h, bool reserved, int count) {
const D3D12_RESOURCE_DESC d = texture(format, w, h, reserved);
const D3D12_RESOURCE_ALLOCATION_INFO info = g_dev->GetResourceAllocationInfo(0, 1, &d);
D3D12_HEAP_PROPERTIES hp{};
hp.Type = D3D12_HEAP_TYPE_DEFAULT;
std::vector<ID3D12Resource*> made;
made.reserve(count);
const double before = footprint_mib();
HRESULT hr = S_OK;
for (int i = 0; i < count; ++i) {
ID3D12Resource* r = nullptr;
hr = reserved ? g_dev->CreateReservedResource(&d, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&r))
: g_dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&r));
if (FAILED(hr) || !r) break;
made.push_back(r);
}
settle();
const double after = footprint_mib();
std::printf("INFO: %d %s %ux%u %s textures (host says %llu bytes each, last hr 0x%08lx): %+.0f MiB, %.1f KiB each\n",
static_cast<int>(made.size()), reserved ? "reserved, unmapped" : "committed", w, h, name,
static_cast<unsigned long long>(info.SizeInBytes), static_cast<unsigned long>(hr), after - before,
made.empty() ? 0.0 : (after - before) * 1024.0 / static_cast<double>(made.size()));
for (ID3D12Resource* r : made) r->Release();
settle();
std::printf("INFO: after releasing them: %+.0f MiB against the figure before\n", footprint_mib() - before);
std::fflush(stdout);
}
int main() {
HMODULE host = LoadLibraryA("bx_host.dll");
auto init = host ? reinterpret_cast<InitFn>(reinterpret_cast<void*>(GetProcAddress(host, "bx_host_init"))) : nullptr;
g_stats = host ? reinterpret_cast<StatsFn>(reinterpret_cast<void*>(GetProcAddress(host, "bx_host_stats"))) : nullptr;
if (!init || init() != 0 || !g_stats) {
std::printf("FAIL: bx_host\n");
return 1;
}
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
auto create = reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")));
if (!create || FAILED(create(nullptr, D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&g_dev)))) {
std::printf("FAIL: D3D12 device\n");
return 1;
}
D3D12_COMMAND_QUEUE_DESC qd{};
qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
g_dev->CreateCommandQueue(&qd, __uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&g_queue));
g_dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&g_fence));
g_event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
settle();
constexpr int kCount = 10000;
measure("RGBA16F", DXGI_FORMAT_R16G16B16A16_FLOAT, 16, 4, false, kCount);
measure("RGBA16F", DXGI_FORMAT_R16G16B16A16_FLOAT, 16, 4, true, kCount);
measure("BC1", DXGI_FORMAT_BC1_UNORM, 128, 128, false, kCount);
measure("BC1", DXGI_FORMAT_BC1_UNORM, 128, 128, true, kCount);
measure("BC7", DXGI_FORMAT_BC7_UNORM, 64, 64, false, kCount);
std::printf("RESULT: done\n");
return 0;
}
+144
View File
@@ -0,0 +1,144 @@
// Probe P6 (Milestone 0): what GPU-written textures cost on D3DMetal while they are never used.
// Standalone and synthetic. Footprint is the process's phys_footprint, read through bx_host.
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <vector>
using InitFn = LONG (*)(void);
using StatsFn = int (*)(uint64_t*);
static StatsFn g_stats;
static ID3D12Device* g_dev;
static ID3D12CommandQueue* g_queue;
static ID3D12CommandAllocator* g_alloc;
static ID3D12GraphicsCommandList* g_list;
static ID3D12Fence* g_fence;
static UINT64 g_value;
static HANDLE g_event;
static ID3D12Resource* g_a;
static ID3D12Resource* g_b;
static double footprint_mib() {
uint64_t s[5] = {};
g_stats(s);
return static_cast<double>(s[0]) / (1024.0 * 1024.0);
}
// An unrelated GPU submission (a 16-byte buffer copy), then a pause.
static void submit_something() {
g_list->CopyBufferRegion(g_b, 0, g_a, 0, 16);
g_list->Close();
ID3D12CommandList* lists[] = {g_list};
g_queue->ExecuteCommandLists(1, lists);
g_queue->Signal(g_fence, ++g_value);
g_fence->SetEventOnCompletion(g_value, g_event);
WaitForSingleObject(g_event, 30000);
g_alloc->Reset();
g_list->Reset(g_alloc, nullptr);
Sleep(1500);
}
static ID3D12Resource* small_buffer(D3D12_HEAP_TYPE type, D3D12_RESOURCE_STATES state) {
D3D12_HEAP_PROPERTIES hp{};
hp.Type = type;
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
d.Width = 4096;
d.Height = 1;
d.DepthOrArraySize = 1;
d.MipLevels = 1;
d.SampleDesc.Count = 1;
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
ID3D12Resource* r = nullptr;
g_dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, state, nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&r));
return r;
}
static void measure(const char* name, DXGI_FORMAT format, UINT w, UINT h, D3D12_RESOURCE_FLAGS flags, int count) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
d.Width = w;
d.Height = h;
d.DepthOrArraySize = 1;
d.MipLevels = 1;
d.Format = format;
d.SampleDesc.Count = 1;
d.Flags = flags;
const UINT64 each = g_dev->GetResourceAllocationInfo(0, 1, &d).SizeInBytes;
D3D12_HEAP_PROPERTIES hp{};
hp.Type = D3D12_HEAP_TYPE_DEFAULT;
std::vector<ID3D12Resource*> made;
const double before = footprint_mib();
HRESULT hr = S_OK;
for (int i = 0; i < count; ++i) {
ID3D12Resource* r = nullptr;
hr = g_dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource),
reinterpret_cast<void**>(&r));
if (FAILED(hr) || !r) break;
made.push_back(r);
}
const double created = footprint_mib();
submit_something();
const double later = footprint_mib();
const double nominal = static_cast<double>(each) * static_cast<double>(made.size()) / (1024.0 * 1024.0);
std::printf("INFO: %d never-used %ux%u %s textures (host says %.0f MiB in all, last hr 0x%08lx): footprint %+.0f MiB at creation, "
"%+.0f MiB after an unrelated GPU submission\n",
static_cast<int>(made.size()), w, h, name, nominal, static_cast<unsigned long>(hr), created - before, later - before);
for (ID3D12Resource* r : made) r->Release();
submit_something();
std::printf("INFO: after releasing them: %+.0f MiB against the figure before\n", footprint_mib() - before);
std::fflush(stdout);
}
int main(int argc, char** argv) {
HMODULE host = LoadLibraryA("bx_host.dll");
auto init = host ? reinterpret_cast<InitFn>(reinterpret_cast<void*>(GetProcAddress(host, "bx_host_init"))) : nullptr;
g_stats = host ? reinterpret_cast<StatsFn>(reinterpret_cast<void*>(GetProcAddress(host, "bx_host_stats"))) : nullptr;
if (!init || init() != 0 || !g_stats) {
std::printf("FAIL: bx_host\n");
return 1;
}
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
auto create = reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")));
if (!create || FAILED(create(nullptr, D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&g_dev)))) {
std::printf("FAIL: D3D12 device\n");
return 1;
}
D3D12_COMMAND_QUEUE_DESC qd{};
qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
g_dev->CreateCommandQueue(&qd, __uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&g_queue));
g_dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), reinterpret_cast<void**>(&g_alloc));
g_dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_alloc, nullptr, __uuidof(ID3D12GraphicsCommandList),
reinterpret_cast<void**>(&g_list));
g_dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&g_fence));
g_event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
g_a = small_buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ);
g_b = small_buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST);
submit_something();
// One case per process (argv[1]): D3DMetal keeps and reuses its pools, so cases run in one
// process hide each other's cost.
struct Case {
const char* name;
DXGI_FORMAT format;
UINT w, h;
D3D12_RESOURCE_FLAGS flags;
int count;
};
const Case cases[] = {
{"render-target BGRA8", DXGI_FORMAT_B8G8R8A8_UNORM, 3840, 2160, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, 30},
{"unordered-access RGBA8", DXGI_FORMAT_R8G8B8A8_UNORM, 3840, 2160, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, 30},
{"depth D32", DXGI_FORMAT_D32_FLOAT, 3840, 2160, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, 30},
{"plain RGBA8", DXGI_FORMAT_R8G8B8A8_UNORM, 3840, 2160, D3D12_RESOURCE_FLAG_NONE, 30},
{"plain RGBA16F", DXGI_FORMAT_R16G16B16A16_FLOAT, 16, 4, D3D12_RESOURCE_FLAG_NONE, 10000},
{"plain BC1", DXGI_FORMAT_BC1_UNORM, 128, 128, D3D12_RESOURCE_FLAG_NONE, 10000},
{"plain BC7", DXGI_FORMAT_BC7_UNORM, 64, 64, D3D12_RESOURCE_FLAG_NONE, 10000},
};
const int only = argc > 1 ? std::atoi(argv[1]) : 0;
if (only < 0 || only >= static_cast<int>(sizeof(cases) / sizeof(cases[0]))) return 2;
const Case& c = cases[only];
measure(c.name, c.format, c.w, c.h, c.flags, c.count);
std::printf("RESULT: done\n");
return 0;
}
@@ -0,0 +1,251 @@
// Probe P7 (Milestone 0): can GPU-written textures be reserved resources on D3DMetal, cost nothing
// while unmapped, and work once tiles are mapped? One case per process: argv[1] = 0 render target,
// 1 depth, 2 unordered access. Standalone and synthetic.
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
using InitFn = LONG (*)(void);
using StatsFn = int (*)(uint64_t*);
static StatsFn g_stats;
static ID3D12Device* g_dev;
static ID3D12CommandQueue* g_queue;
static ID3D12CommandAllocator* g_alloc;
static ID3D12GraphicsCommandList* g_list;
static ID3D12Fence* g_fence;
static UINT64 g_value;
static HANDLE g_event;
static double footprint_mib() {
uint64_t s[5] = {};
g_stats(s);
return static_cast<double>(s[0]) / (1024.0 * 1024.0);
}
static bool wait_queue() {
g_queue->Signal(g_fence, ++g_value);
g_fence->SetEventOnCompletion(g_value, g_event);
return WaitForSingleObject(g_event, 30000) == WAIT_OBJECT_0;
}
static bool submit() {
g_list->Close();
ID3D12CommandList* lists[] = {g_list};
g_queue->ExecuteCommandLists(1, lists);
const bool done = wait_queue();
g_alloc->Reset();
g_list->Reset(g_alloc, nullptr);
return done;
}
static ID3D12Resource* buffer(D3D12_HEAP_TYPE type, UINT64 size, D3D12_RESOURCE_STATES state) {
D3D12_HEAP_PROPERTIES hp{};
hp.Type = type;
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
d.Width = size;
d.Height = 1;
d.DepthOrArraySize = 1;
d.MipLevels = 1;
d.SampleDesc.Count = 1;
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
ID3D12Resource* r = nullptr;
g_dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, state, nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&r));
return r;
}
static D3D12_RESOURCE_DESC texture(DXGI_FORMAT format, UINT w, UINT h, D3D12_RESOURCE_FLAGS flags) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
d.Width = w;
d.Height = h;
d.DepthOrArraySize = 1;
d.MipLevels = 1;
d.Format = format;
d.SampleDesc.Count = 1;
d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
d.Flags = flags;
return d;
}
// One heap behind every tile of `tex`.
static HRESULT map_all(ID3D12Resource* tex, ID3D12Heap** out) {
UINT total = 0, count = 1;
D3D12_PACKED_MIP_INFO packed{};
D3D12_TILE_SHAPE shape{};
D3D12_SUBRESOURCE_TILING tiling{};
g_dev->GetResourceTiling(tex, &total, &packed, &shape, &count, 0, &tiling);
if (!total) return E_FAIL;
D3D12_HEAP_DESC hd{};
hd.SizeInBytes = static_cast<UINT64>(total) * 65536;
hd.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
const HRESULT hr = g_dev->CreateHeap(&hd, __uuidof(ID3D12Heap), reinterpret_cast<void**>(out));
if (FAILED(hr) || !*out) return FAILED(hr) ? hr : E_FAIL;
D3D12_TILED_RESOURCE_COORDINATE at{};
D3D12_TILE_REGION_SIZE size{};
size.NumTiles = total;
const D3D12_TILE_RANGE_FLAGS flags = D3D12_TILE_RANGE_FLAG_NONE;
const UINT start = 0, range = total;
g_queue->UpdateTileMappings(tex, 1, &at, &size, *out, 1, &flags, &start, &range, D3D12_TILE_MAPPING_FLAG_NONE);
wait_queue();
return S_OK;
}
int main(int argc, char** argv) {
HMODULE host = LoadLibraryA("bx_host.dll");
auto init = host ? reinterpret_cast<InitFn>(reinterpret_cast<void*>(GetProcAddress(host, "bx_host_init"))) : nullptr;
g_stats = host ? reinterpret_cast<StatsFn>(reinterpret_cast<void*>(GetProcAddress(host, "bx_host_stats"))) : nullptr;
if (!init || init() != 0 || !g_stats) {
std::printf("FAIL: bx_host\n");
return 1;
}
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
auto create = reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")));
if (!create || FAILED(create(nullptr, D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&g_dev)))) {
std::printf("FAIL: D3D12 device\n");
return 1;
}
D3D12_COMMAND_QUEUE_DESC qd{};
qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
g_dev->CreateCommandQueue(&qd, __uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&g_queue));
g_dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), reinterpret_cast<void**>(&g_alloc));
g_dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_alloc, nullptr, __uuidof(ID3D12GraphicsCommandList),
reinterpret_cast<void**>(&g_list));
g_dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&g_fence));
g_event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
constexpr UINT kW = 1024, kH = 1024;
ID3D12Resource* upload = buffer(D3D12_HEAP_TYPE_UPLOAD, UINT64(kW) * kH * 4, D3D12_RESOURCE_STATE_GENERIC_READ);
ID3D12Resource* readback = buffer(D3D12_HEAP_TYPE_READBACK, UINT64(kW) * kH * 4, D3D12_RESOURCE_STATE_COPY_DEST);
uint32_t* up = nullptr;
uint32_t* rb = nullptr;
upload->Map(0, nullptr, reinterpret_cast<void**>(&up));
readback->Map(0, nullptr, reinterpret_cast<void**>(&rb));
g_list->CopyBufferRegion(readback, 0, upload, 0, 16);
submit();
const int which = argc > 1 ? std::atoi(argv[1]) : 0;
const char* name = which == 0 ? "render-target BGRA8" : which == 1 ? "depth D32" : "unordered-access RGBA8";
const DXGI_FORMAT format = which == 0 ? DXGI_FORMAT_B8G8R8A8_UNORM : which == 1 ? DXGI_FORMAT_D32_FLOAT : DXGI_FORMAT_R8G8B8A8_UNORM;
const D3D12_RESOURCE_FLAGS flags = which == 0 ? D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET
: which == 1 ? D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL
: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
// --- A. thirty 3840x2160 reserved textures, never mapped: what do they cost? ---
{
const D3D12_RESOURCE_DESC big = texture(format, 3840, 2160, flags);
std::vector<ID3D12Resource*> made;
HRESULT hr = S_OK;
const double before = footprint_mib();
for (int i = 0; i < 30; ++i) {
ID3D12Resource* r = nullptr;
hr = g_dev->CreateReservedResource(&big, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&r));
if (FAILED(hr) || !r) break;
made.push_back(r);
}
g_list->CopyBufferRegion(readback, 0, upload, 0, 16);
submit();
Sleep(1500);
std::printf("INFO: %d reserved, unmapped 3840x2160 %s textures (last hr 0x%08lx): footprint %+.0f MiB after an unrelated GPU submission\n",
static_cast<int>(made.size()), name, static_cast<unsigned long>(hr), footprint_mib() - before);
for (ID3D12Resource* r : made) r->Release();
}
// --- B. one 1024x1024 reserved texture: map it, write it the way its kind is written, read it back ---
const D3D12_RESOURCE_DESC td = texture(format, kW, kH, flags);
ID3D12Resource* tex = nullptr;
HRESULT hr = g_dev->CreateReservedResource(&td, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&tex));
std::printf("%s: reserved 1024x1024 %s texture created (hr 0x%08lx)\n", tex ? "PASS" : "FAIL", name, static_cast<unsigned long>(hr));
if (!tex) return 1;
ID3D12Heap* heap = nullptr;
hr = map_all(tex, &heap);
std::printf("%s: all its tiles mapped to a heap (hr 0x%08lx)\n", SUCCEEDED(hr) ? "PASS" : "FAIL", static_cast<unsigned long>(hr));
if (FAILED(hr)) return 1;
D3D12_RESOURCE_BARRIER b{};
b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
b.Transition.pResource = tex;
b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
D3D12_TEXTURE_COPY_LOCATION out{};
out.pResource = readback;
out.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
D3D12_TEXTURE_COPY_LOCATION in{};
in.pResource = tex;
in.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
std::memset(rb, 0xEE, UINT64(kW) * kH * 4);
unsigned wrong = 0;
bool ok = false;
if (which == 0 || which == 1) {
D3D12_DESCRIPTOR_HEAP_DESC dh{};
dh.Type = which == 0 ? D3D12_DESCRIPTOR_HEAP_TYPE_RTV : D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
dh.NumDescriptors = 1;
ID3D12DescriptorHeap* views = nullptr;
g_dev->CreateDescriptorHeap(&dh, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&views));
// The handle is returned by value; widl-style headers differ in how, so read it through the vtable-free helper.
D3D12_CPU_DESCRIPTOR_HANDLE handle{};
#if defined(__GNUC__)
views->GetCPUDescriptorHandleForHeapStart(&handle);
#else
handle = views->GetCPUDescriptorHandleForHeapStart();
#endif
b.Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON;
b.Transition.StateAfter = which == 0 ? D3D12_RESOURCE_STATE_RENDER_TARGET : D3D12_RESOURCE_STATE_DEPTH_WRITE;
g_list->ResourceBarrier(1, &b);
if (which == 0) {
g_dev->CreateRenderTargetView(tex, nullptr, handle);
const float colour[4] = {1.0f, 0.5f, 0.25f, 1.0f}; // BGRA8: B=0x40 G=0x80 R=0xFF A=0xFF
g_list->ClearRenderTargetView(handle, colour, 0, nullptr);
} else {
g_dev->CreateDepthStencilView(tex, nullptr, handle);
g_list->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_DEPTH, 0.75f, 0, 0, nullptr);
}
b.Transition.StateBefore = b.Transition.StateAfter;
b.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
g_list->ResourceBarrier(1, &b);
out.PlacedFootprint.Footprint = {which == 0 ? DXGI_FORMAT_B8G8R8A8_UNORM : DXGI_FORMAT_R32_FLOAT, kW, kH, 1, kW * 4};
g_list->CopyTextureRegion(&out, 0, 0, 0, &in, nullptr);
ok = submit();
float depth = 0.75f;
uint32_t expect = 0xFFFF8040u;
if (which == 1) std::memcpy(&expect, &depth, 4);
for (UINT i = 0; i < kW * kH; ++i) {
const uint32_t v = rb[i];
// BGRA8 clear of (1, 0.5, 0.25, 1): allow the two roundings of 0.5 and 0.25.
const bool same = which == 1 ? v == expect
: ((v >> 24) == 0xFF && ((v >> 16) & 0xFF) == 0xFF && (((v >> 8) & 0xFF) == 0x80 || ((v >> 8) & 0xFF) == 0x7F) &&
((v & 0xFF) == 0x40 || (v & 0xFF) == 0x3F));
wrong += !same;
}
std::printf("%s: cleared as a %s and read back: %u of %u texels wrong (first 0x%08x)\n", ok && wrong == 0 ? "PASS" : "FAIL",
which == 0 ? "render target" : "depth buffer", wrong, kW * kH, rb[0]);
} else {
// No compute shader here: the storage is exercised with a copy in and a copy out.
for (UINT i = 0; i < kW * kH; ++i) up[i] = 0xFF000000u | (i * 2654435761u >> 8);
D3D12_TEXTURE_COPY_LOCATION to{};
to.pResource = tex;
to.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
D3D12_TEXTURE_COPY_LOCATION from{};
from.pResource = upload;
from.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
from.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kW, kH, 1, kW * 4};
b.Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON;
b.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST;
g_list->ResourceBarrier(1, &b);
g_list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
b.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
g_list->ResourceBarrier(1, &b);
out.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kW, kH, 1, kW * 4};
g_list->CopyTextureRegion(&out, 0, 0, 0, &in, nullptr);
ok = submit();
for (UINT i = 0; i < kW * kH; ++i) wrong += rb[i] != up[i];
std::printf("%s: copied into and out of (shader writes not tested): %u of %u texels wrong\n", ok && wrong == 0 ? "PASS" : "FAIL", wrong,
kW * kH);
}
std::printf("RESULT: done\n");
return 0;
}
+267
View File
@@ -0,0 +1,267 @@
// Probe P8: can existing memory become a D3D12 heap (OpenExistingHeapFromFileMapping / FromAddress),
// so that a view of the mapping and the GPU see the same bytes? argv[1]: 0 = committed section,
// 1 = reserved section (pages committed through the view, as a page pool does). Standalone and synthetic.
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using InitFn = LONG (*)(void);
using StatsFn = int (*)(uint64_t*);
static StatsFn g_stats;
static ID3D12Device3* g_dev;
static ID3D12CommandQueue* g_queue;
static ID3D12CommandAllocator* g_alloc;
static ID3D12GraphicsCommandList* g_list;
static ID3D12Fence* g_fence;
static UINT64 g_value;
static HANDLE g_event;
static int g_failed;
static void check(bool ok, const char* what) {
std::printf("%s: %s\n", ok ? "PASS" : "FAIL", what);
g_failed += !ok;
std::fflush(stdout);
}
static double footprint_mib() {
uint64_t s[5] = {};
g_stats(s);
return static_cast<double>(s[0]) / (1024.0 * 1024.0);
}
static bool submit() {
g_list->Close();
ID3D12CommandList* lists[] = {g_list};
g_queue->ExecuteCommandLists(1, lists);
g_queue->Signal(g_fence, ++g_value);
g_fence->SetEventOnCompletion(g_value, g_event);
const bool done = WaitForSingleObject(g_event, 30000) == WAIT_OBJECT_0;
g_alloc->Reset();
g_list->Reset(g_alloc, nullptr);
return done;
}
static D3D12_RESOURCE_DESC buffer_desc(UINT64 size, D3D12_RESOURCE_FLAGS flags) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
d.Width = size;
d.Height = 1;
d.DepthOrArraySize = 1;
d.MipLevels = 1;
d.SampleDesc.Count = 1;
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
d.Flags = flags;
return d;
}
static ID3D12Resource* committed(D3D12_HEAP_TYPE type, UINT64 size, D3D12_RESOURCE_STATES state) {
D3D12_HEAP_PROPERTIES hp{};
hp.Type = type;
const D3D12_RESOURCE_DESC d = buffer_desc(size, D3D12_RESOURCE_FLAG_NONE);
ID3D12Resource* r = nullptr;
g_dev->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &d, state, nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&r));
return r;
}
// A buffer placed on `heap` at `offset`; tries without and then with the cross-adapter flag.
static ID3D12Resource* placed(ID3D12Heap* heap, UINT64 offset, UINT64 size, const char* what) {
ID3D12Resource* r = nullptr;
HRESULT hr = E_FAIL;
const D3D12_RESOURCE_FLAGS tries[] = {D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER,
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS};
for (D3D12_RESOURCE_FLAGS f : tries) {
const D3D12_RESOURCE_DESC d = buffer_desc(size, f);
hr = g_dev->CreatePlacedResource(heap, offset, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource),
reinterpret_cast<void**>(&r));
std::printf("INFO: %s: placed buffer with flags 0x%x: hr 0x%08lx\n", what, static_cast<unsigned>(f), static_cast<unsigned long>(hr));
if (f != D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS && r) break;
if (f == D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS && r) { // informational only
r->Release();
r = nullptr;
}
}
return r;
}
// GPU -> CPU and CPU -> GPU through `cpu` (the caller's own pointer to the bytes behind `res`).
static void coherence(ID3D12Resource* res, uint8_t* cpu, ID3D12Resource* upload, uint8_t* up, ID3D12Resource* readback, uint8_t* rb,
const char* what) {
constexpr UINT64 kLen = 65536;
char line[200];
bool gpu_to_cpu = true, cpu_to_gpu = true;
for (int round = 0; round < 4; ++round) {
for (UINT64 i = 0; i < kLen; ++i) up[i] = static_cast<uint8_t>(i * 7 + round * 31 + 1);
g_list->CopyBufferRegion(res, 0, upload, 0, kLen);
gpu_to_cpu &= submit();
gpu_to_cpu &= std::memcmp(cpu, up, kLen) == 0;
for (UINT64 i = 0; i < kLen; ++i) cpu[i] = static_cast<uint8_t>(i * 13 + round * 17 + 5);
std::memset(rb, 0, kLen);
g_list->CopyBufferRegion(readback, 0, res, 0, kLen);
cpu_to_gpu &= submit();
cpu_to_gpu &= std::memcmp(cpu, rb, kLen) == 0;
}
std::snprintf(line, sizeof line, "%s: the caller's memory shows what the GPU wrote (4 rounds)", what);
check(gpu_to_cpu, line);
std::snprintf(line, sizeof line, "%s: the GPU reads what the caller wrote, with no Map (4 rounds)", what);
check(cpu_to_gpu, line);
}
int main(int argc, char** argv) {
const bool reserve = argc > 1 && std::atoi(argv[1]) == 1;
HMODULE host = LoadLibraryA("bx_host.dll");
auto init = host ? reinterpret_cast<InitFn>(reinterpret_cast<void*>(GetProcAddress(host, "bx_host_init"))) : nullptr;
g_stats = host ? reinterpret_cast<StatsFn>(reinterpret_cast<void*>(GetProcAddress(host, "bx_host_stats"))) : nullptr;
if (!init || init() != 0 || !g_stats) {
std::printf("FAIL: bx_host\n");
return 1;
}
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
auto create = reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")));
if (!create || FAILED(create(nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device3), reinterpret_cast<void**>(&g_dev)))) {
std::printf("FAIL: D3D12 device (ID3D12Device3)\n");
return 1;
}
D3D12_COMMAND_QUEUE_DESC qd{};
qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
g_dev->CreateCommandQueue(&qd, __uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&g_queue));
g_dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), reinterpret_cast<void**>(&g_alloc));
g_dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_alloc, nullptr, __uuidof(ID3D12GraphicsCommandList),
reinterpret_cast<void**>(&g_list));
g_dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&g_fence));
g_event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
ID3D12Resource* upload = committed(D3D12_HEAP_TYPE_UPLOAD, 1 << 20, D3D12_RESOURCE_STATE_GENERIC_READ);
ID3D12Resource* readback = committed(D3D12_HEAP_TYPE_READBACK, 1 << 20, D3D12_RESOURCE_STATE_COPY_DEST);
uint8_t* up = nullptr;
uint8_t* rb = nullptr;
upload->Map(0, nullptr, reinterpret_cast<void**>(&up));
readback->Map(0, nullptr, reinterpret_cast<void**>(&rb));
g_list->CopyBufferRegion(readback, 0, upload, 0, 16);
submit();
// --- A. a 1 GiB section, opened as a heap ---
constexpr UINT64 kSection = 1ull << 30;
constexpr UINT64 kAt = 65536ull * 4099; // a page well inside
std::printf("INFO: section kind: %s\n", reserve ? "reserved (SEC_RESERVE), pages committed through the view" : "committed (SEC_COMMIT)");
HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | (reserve ? SEC_RESERVE : SEC_COMMIT),
static_cast<DWORD>(kSection >> 32), static_cast<DWORD>(kSection), nullptr);
check(section != nullptr, "1 GiB section created");
const double base = footprint_mib();
ID3D12Heap* heap = nullptr;
HRESULT hr = g_dev->OpenExistingHeapFromFileMapping(section, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&heap));
std::printf("INFO: OpenExistingHeapFromFileMapping: hr 0x%08lx\n", static_cast<unsigned long>(hr));
check(SUCCEEDED(hr) && heap, "the section opened as a D3D12 heap");
if (heap) {
const D3D12_HEAP_DESC hd = heap->GetDesc();
std::printf("INFO: heap: %llu MiB, type %d, CPU page property %d, flags 0x%x, alignment %llu\n",
static_cast<unsigned long long>(hd.SizeInBytes >> 20), static_cast<int>(hd.Properties.Type),
static_cast<int>(hd.Properties.CPUPageProperty), static_cast<unsigned>(hd.Flags),
static_cast<unsigned long long>(hd.Alignment));
std::printf("INFO: footprint after opening the heap: %+.0f MiB\n", footprint_mib() - base);
// Two views of the same 64 KiB page, as a page pool maps one page at several addresses.
auto* v1 = static_cast<uint8_t*>(MapViewOfFile(section, FILE_MAP_ALL_ACCESS, static_cast<DWORD>(kAt >> 32), static_cast<DWORD>(kAt), 65536));
auto* v2 = static_cast<uint8_t*>(MapViewOfFile(section, FILE_MAP_ALL_ACCESS, static_cast<DWORD>(kAt >> 32), static_cast<DWORD>(kAt), 65536));
bool mapped = v1 && v2;
if (mapped && reserve) mapped = VirtualAlloc(v1, 65536, MEM_COMMIT, PAGE_READWRITE) && VirtualAlloc(v2, 65536, MEM_COMMIT, PAGE_READWRITE);
check(mapped, "two views of one 64 KiB page of the section");
ID3D12Resource* res = mapped ? placed(heap, kAt, 65536, "section heap") : nullptr;
check(res != nullptr, "a buffer placed on the section heap at that page");
if (res) {
coherence(res, v1, upload, up, readback, rb, "section heap");
check(std::memcmp(v1, v2, 65536) == 0, "the second view shows the same bytes");
DWORD got = 0;
char self[MAX_PATH] = {};
GetModuleFileNameA(nullptr, self, MAX_PATH);
HANDLE file = CreateFileA(self, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
const bool read_ok = file != INVALID_HANDLE_VALUE && ReadFile(file, v1, 4096, &got, nullptr) && got == 4096;
std::memset(rb, 0, 4096);
g_list->CopyBufferRegion(readback, 0, res, 0, 4096);
submit();
check(read_ok && std::memcmp(rb, v1, 4096) == 0 && rb[0] == 'M' && rb[1] == 'Z', "ReadFile into the view is what the GPU then reads");
std::printf("INFO: footprint after using one page of the 1 GiB heap: %+.0f MiB\n", footprint_mib() - base);
// A page the views never touched, written only by the GPU, then seen by a later view.
constexpr UINT64 kOther = 65536ull * 9001;
ID3D12Resource* other = placed(heap, kOther, 65536, "section heap, untouched page");
if (other) {
for (UINT64 i = 0; i < 65536; ++i) up[i] = static_cast<uint8_t>(i * 3 + 9);
g_list->CopyBufferRegion(other, 0, upload, 0, 65536);
submit();
auto* v3 = static_cast<uint8_t*>(
MapViewOfFile(section, FILE_MAP_ALL_ACCESS, static_cast<DWORD>(kOther >> 32), static_cast<DWORD>(kOther), 65536));
if (v3 && reserve) VirtualAlloc(v3, 65536, MEM_COMMIT, PAGE_READWRITE);
check(v3 && std::memcmp(v3, up, 65536) == 0, "a page first written by the GPU shows those bytes in a view mapped afterwards");
} else {
check(false, "a buffer placed on an untouched page of the section heap");
}
}
// A reserved BC1 texture with its tiles on the section heap.
D3D12_RESOURCE_DESC td{};
td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
td.Width = 512;
td.Height = 512;
td.DepthOrArraySize = 1;
td.MipLevels = 1;
td.Format = DXGI_FORMAT_BC1_UNORM;
td.SampleDesc.Count = 1;
td.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
ID3D12Resource* tex = nullptr;
hr = g_dev->CreateReservedResource(&td, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&tex));
const bool tiles = !(argc > 2 && std::strcmp(argv[2], "notiles") == 0);
if (!tiles) {
std::printf("INFO: tile check skipped on request\n");
} else if (tex) {
std::printf("INFO: reserved texture created; mapping two tiles to the section heap\n");
std::fflush(stdout);
constexpr UINT64 kTile = 65536ull * 12000;
D3D12_TILED_RESOURCE_COORDINATE at{};
D3D12_TILE_REGION_SIZE size{};
size.NumTiles = 2; // 512x512 BC1 = 128 KiB = 2 tiles
const D3D12_TILE_RANGE_FLAGS flags = D3D12_TILE_RANGE_FLAG_NONE;
const UINT start = static_cast<UINT>(kTile / 65536), range = 2;
g_queue->UpdateTileMappings(tex, 1, &at, &size, heap, 1, &flags, &start, &range, D3D12_TILE_MAPPING_FLAG_NONE);
g_queue->Signal(g_fence, ++g_value);
g_fence->SetEventOnCompletion(g_value, g_event);
std::printf("INFO: tile mapping %s\n", WaitForSingleObject(g_event, 20000) == WAIT_OBJECT_0 ? "completed" : "did not complete in 20 s");
std::fflush(stdout);
uint32_t* words = reinterpret_cast<uint32_t*>(up);
for (UINT i = 0; i < 128 * 128 * 2; ++i) words[i] = 0x9E3779B9u * (i + 1);
D3D12_TEXTURE_COPY_LOCATION to{};
to.pResource = tex;
to.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
D3D12_TEXTURE_COPY_LOCATION from{};
from.pResource = upload;
from.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
from.PlacedFootprint.Footprint = {DXGI_FORMAT_BC1_UNORM, 512, 512, 1, 128 * 8};
g_list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
const bool done = submit();
auto* tv = static_cast<uint8_t*>(
MapViewOfFile(section, FILE_MAP_ALL_ACCESS, static_cast<DWORD>(kTile >> 32), static_cast<DWORD>(kTile), 131072));
if (tv && reserve) VirtualAlloc(tv, 131072, MEM_COMMIT, PAGE_READWRITE);
unsigned nonzero = 0;
if (tv)
for (UINT i = 0; i < 131072; ++i) nonzero += tv[i] != 0;
std::printf("INFO: reserved BC1 texture with tiles on the section heap: upload %s; %u of 131072 bytes of those section pages are non-zero\n",
done ? "done" : "timed out", nonzero);
check(done && nonzero > 100000, "texture tiles mapped to the section heap live in the section's pages");
} else {
std::printf("INFO: reserved texture not created (hr 0x%08lx); tile check skipped\n", static_cast<unsigned long>(hr));
}
}
// --- B. VirtualAlloc memory, opened as a heap ---
constexpr SIZE_T kMem = 64u << 20;
auto* mem = static_cast<uint8_t*>(VirtualAlloc(nullptr, kMem, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
ID3D12Heap* aheap = nullptr;
hr = g_dev->OpenExistingHeapFromAddress(mem, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&aheap));
std::printf("INFO: OpenExistingHeapFromAddress: hr 0x%08lx\n", static_cast<unsigned long>(hr));
check(SUCCEEDED(hr) && aheap, "VirtualAlloc memory opened as a D3D12 heap");
if (aheap) {
ID3D12Resource* res = placed(aheap, 65536 * 5, 65536, "address heap");
check(res != nullptr, "a buffer placed on the address heap");
if (res) coherence(res, mem + 65536 * 5, upload, up, readback, rb, "address heap");
}
std::printf("RESULT: %d failed\n", g_failed);
return g_failed ? 1 : 0;
}
+17
View File
@@ -0,0 +1,17 @@
#!/bin/bash
# Runs one built probe under CrossOver.
# usage: run.sh <bottle> <probe name without .exe> [arguments]
# BX_PROBE_BACKEND picks the graphics backend (default d3dmetal); CX_ROOT picks the CrossOver root
# (a bottle with a root of its own, such as one a third-party graphics layer installed, needs it).
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
OUT="${OUT:-$HERE/../../../target/unified-memory-probes}"
OUT="$(cd "$OUT" && pwd)"
CX="${CX_ROOT:-/Applications/CrossOver.app/Contents/SharedSupport/CrossOver}"
BACKEND="${BX_PROBE_BACKEND:-d3dmetal}"
bottle="$1"; probe="$2"; shift 2
cp "$OUT/x86_64-windows/bx_host.dll" "$OUT/bx_host.dll"
exec env -i HOME="$HOME" USER="$USER" TMPDIR="${TMPDIR:-/tmp}" PATH=/usr/bin:/bin \
"$CX/bin/wine" --bottle "$bottle" \
--env "CX_GRAPHICS_BACKEND=$BACKEND WINEDLLPATH=$OUT:$CX/lib/wine/x86_64-windows:$CX/lib/wine/i386-windows:$CX/lib/wine" \
"$OUT/$probe.exe" "$@"