Skip to content
Open
77 changes: 77 additions & 0 deletions docs/experiments/startup-view-token-guarded.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# View token written under an exception guard (opt-in)

A view call (device slots 17–22) ends in `note_view` (`d3d12_capture.inl`), which writes a 32-byte token (16 bytes
for a sampler) into the title's descriptor memory, so that descriptor copies the title makes itself can be followed.
The write is preceded by `x2w_local::writable`: `commit_lazy` (with `X2W_XMEM_LAZY_COMMIT`, `x2w_xmem_commit_range`,
which takes xmem's commit mutex) and then a `VirtualQuery`. The destination is always inside a registered descriptor
range (`title_backed`). Late in the main executable's load the title creates about 10^5 views per second, from five
recording threads at once.

## What the switch changes

- `X2W_D3D12_VIEW_TOKEN_GUARDED=1`: the token is written by `write_view_token` under `__try`, without the commit call
and the query. A page that refuses the write (no access, read-only, a guard page, an in-page error) leaves the
descriptor without a token, as `writable` returning false did; a guard page has its guard bit set again, on that
page only, as `probe_readable` does.
- Lazy commit: with `X2W_XMEM_LAZY_COMMIT`, xmem's vectored handler commits a page on the first touch, before the
`__except` filter sees the fault. Only the startup runs below exercise this; the fixture commits its memory up
front and loads no xmem.dll.
- Concurrency: between the fault that clears a guard bit and the re-arm, another thread's write to that page goes
through, where `writable` would have refused it. The runs below refused no write, so it did not occur there.
- Only a token that lies inside one 4 KiB page takes the guarded write, so a refusal comes on its first byte and
changes nothing. A descriptor heap's title backing has no alignment check, so a token can cross a page boundary;
such a token keeps the full-span `writable` check, with or without the switch.
- With the switch set, the render totals are followed every 300 frames by
`x2w-render view tokens (X2W_D3D12_VIEW_TOKEN_GUARDED): written N, refused M`.
- Unset, the check and the write are as before.
- Only the token write changes; the view record, the shadow slot and the view references are untouched.

## Fixture

```powershell
ctest --preset dev --no-tests=error -j 1 -R '^startup_view_token_' -V
```

`startup_view_token_{unset,set}_{warp,hardware}` (`tests/startup_view_token.cpp`) creates three descriptor heaps over
title memory the fixture owns and, after creation, makes the second read-only and gives the third a guard page. A
texture SRV goes into each heap, and a second one into the writable heap. In both modes the writable heap holds both
tokens, the read-only heap stays zero and the process keeps running, and the guard page keeps its guard bit and stays
zero. Two more heaps start 16 bytes before a page boundary, so their first token crosses into a read-only page or a
guard page: in both modes the 16-byte writable prefix keeps its bytes, the left page stays `PAGE_READWRITE` without
a guard bit, and the right page keeps its protection and stays zero. The fixture-only export
`x2w_d3d12_view_token_writes` reports the guarded writes: unset `0, 0`, set `2, 2` (crossing tokens are not
guarded writes). Mutants: ignoring the switch fails `the guarded path did not write 2 tokens and refuse 2`; not
setting the guard bit again fails `the guard page lost its guard bit`; setting it again over the whole region
(`info.BaseAddress`, `info.RegionSize`) fails `the page after the guard page changed its protection`; guarding
crossing tokens too fails
`a crossing heap's writable prefix changed` (read-only right page) and leaves the left page `0x104`
(`PAGE_READWRITE | PAGE_GUARD`, guard right page).

## Startup run of the main executable

Local diagnostic runs, Windows 10 22H2 (19045), i7-4790K (4 cores, 8 threads), 16 GB, RTX 3080 Ti, NVIDIA driver
32.0.16.1047. Release build of this change on `main` `36d2cbeb`, warm shader cache (revision 29), scripted input,
250 s. `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1`, `X2W_D3D12_TABLE_ALIAS=1` and `X2W_D3D12_ROOT_SRV_AT_DRAW=1` in every
run; only this switch differs. Two pairs, the second in reverse order. Aggregates only; logs stay local.

| 150–240 s | switch unset | switch set |
|---|---|---|
| mean fps, pair 1 / pair 2 | 15.5 / 15.1 | 16.6 / 15.6 |
| time in view calls (threads); µs per call | 1.19 / 1.20; 10.4 / 11.2 | 0.88 / 0.92; 7.0 / 6.7 |
| view calls per second | 114k / 107k | 126k / 136k |
| null bindings `buffer`; device removal | 0; none | 0; none |
| null bindings `token` per 1,000 translated draws | 25.7 / 23.5 | 33.6 / 30.1 |
| process commit peak | 19.3 / 18.9 GiB | 19.6 / 19.4 GiB |

- A view call costs about 3.6 µs less. In a breakdown of a view call on the same machine, the `writable` check was
about a third of its time.
- Why it shows in the frame rate: five recording threads draw the late load. A thread-state sample of them
(`NtQuerySystemInformation`, every 20 ms) found them runnable but without a free core in 14–21% of the samples,
so CPU time they save is CPU time they use for the next lists.
- A confirmation run with the switch set (the report line above) logged `written 16447410, refused 0`: the guard
refused no write. That shows no token was lost to a refusal, not that every token matches the default path.
- The `token` null bindings were higher with the switch (33.6 / 30.1 against 25.7 / 23.5 per 1,000 translated
draws). Runs without this change gave 23–34 per 1,000 on the same machine, so the difference lies within that
spread, but it is not explained.

Not established: other adapters and drivers, hosts with more cores, and Wine (where #2911 changes `writable`).
1 change: 1 addition & 0 deletions docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -1644,6 +1644,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V
| `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) |
| `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory |
| `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) |
| `X2W_D3D12_VIEW_TOKEN_GUARDED=1` | opt-in, render mode: the view token that a view call (device slots 17–22) writes into title descriptor memory is written under an exception guard instead of after `commit_lazy` and a `VirtualQuery` per view (default). A page that refuses the write (no access, read-only, a guard page, whose guard bit is set again, an in-page error) leaves the descriptor without a token, as before; a token that crosses a page boundary keeps the check (`startup_view_token_*`). See [the experiment note](experiments/startup-view-token-guarded.md) |
| `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1` | opt-in, render mode: a closed command list releases its upload ring chunks once its submit is fenced instead of holding them until Reset, and the ring grows in 16 MiB chunks up to 512 MiB (default: doubling chunks up to 256 MiB, holds until Reset). The larger ring can add up to about 1 GiB of process commit at peak (startup runs in the experiment note). A later submit of the same list before its Reset fences its unchanged chunks again; if one was reused in between, that list is refused before the execute and logged (`startup_address_console_gate_ring_keep_*`, `upload_reservation`). See [the experiment note](experiments/startup-upload-ring-release-at-submit.md) |
| `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the confirmed `BeginQuery`, `EndQuery` and `ResolveQueryData` methods (see [Occlusion queries](#occlusion-queries)). The bindings remain diagnostic because the forwarding behavior is not a console runtime oracle. Unset, the three slots stay no-ops |
| `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat |
Expand Down
55 changes: 50 additions & 5 deletions src/startup_stubs/d3d12_capture.inl
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,47 @@ void view_refs_leave_class(std::uint32_t slot, u64 resource, u64 counter, Retire

constexpr std::uint32_t view_token_magic = 0x56573258; // "X2WV"

// X2W_D3D12_VIEW_TOKEN_GUARDED=1 (opt-in): note_view writes the token into title descriptor memory under an exception
// guard instead of asking first (commit_lazy, which takes xmem's commit mutex, then a VirtualQuery). A view is created
// about 10^5 times per second late in the load, by several recording threads at once. The destination is always in a
// registered descriptor range (title_backed), so the write normally does not fault; a lazily committed page is
// committed by xmem's handler on the first touch, as for any other write.
bool view_token_guarded()
{
static const bool on = x2w_local::env_on("X2W_D3D12_VIEW_TOKEN_GUARDED");
return on;
}
LONG view_tokens_guarded_written, view_tokens_guarded_refused;
// Whether [dest, dest + bytes) lies inside one 4 KiB page. A descriptor heap's title backing has no alignment check,
// so a token can cross a page; such a token takes the full-span writable() check instead of the guarded write.
bool view_token_in_one_page(u64 dest, std::size_t bytes)
{
return bytes && ((dest ^ (dest + bytes - 1)) & ~u64{0xFFF}) == 0;
}
// The token write of view_token_guarded(), for a span inside one page (view_token_in_one_page), so a refusal happens
// on the first byte and writes nothing. A page that refuses the write (no access, read-only, a guard page, an in-page
// error) leaves the descriptor without a token, as writable() returning false did; a guard page has its guard bit set
// again, on that page only. Between the fault that clears the guard bit and the re-arm, another thread's write to that
// page goes through, where writable() would have refused it.
__declspec(noinline) bool write_view_token(void* dest, const void* token, std::size_t bytes) noexcept
{
DWORD code = 0;
__try {
std::memcpy(dest, token, bytes);
return true;
} __except (code = GetExceptionCode(),
code == EXCEPTION_ACCESS_VIOLATION || code == EXCEPTION_IN_PAGE_ERROR || code == STATUS_GUARD_PAGE_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
if (code == STATUS_GUARD_PAGE_VIOLATION) {
MEMORY_BASIC_INFORMATION info{};
DWORD old = 0;
if (VirtualQuery(dest, &info, sizeof(info)) && info.State == MEM_COMMIT)
VirtualProtect(dest, bytes, info.Protect | PAGE_GUARD, &old);
}
return false;
}
}

bool title_backed(u64 title_handle, u64 bytes)
{
bool inside = false;
Expand Down Expand Up @@ -506,12 +547,16 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_
}
ReleaseSRWLockExclusive(&note_lock);
const std::size_t token_bytes = slot == 22 ? x2w_startup::title_sampler_stride : 32u;
if (dest_title != dest_desktop && title_backed(dest_title, token_bytes) &&
x2w_local::writable(reinterpret_cast<void*>(dest_title), token_bytes)) {
std::uint32_t token[8] = {view_token_magic, record.id, static_cast<std::uint32_t>(slot), 0,
static_cast<std::uint32_t>(resource), static_cast<std::uint32_t>(resource >> 32), 0, 0};
std::memcpy(reinterpret_cast<void*>(dest_title), token, token_bytes);
const std::uint32_t token[8] = {view_token_magic, record.id, static_cast<std::uint32_t>(slot), 0,
static_cast<std::uint32_t>(resource), static_cast<std::uint32_t>(resource >> 32), 0, 0};
if (dest_title == dest_desktop || !title_backed(dest_title, token_bytes)) return;
if (view_token_guarded() && view_token_in_one_page(dest_title, token_bytes)) {
InterlockedIncrement(write_view_token(reinterpret_cast<void*>(dest_title), token, token_bytes)
? &view_tokens_guarded_written : &view_tokens_guarded_refused);
return;
}
if (x2w_local::writable(reinterpret_cast<void*>(dest_title), token_bytes))
std::memcpy(reinterpret_cast<void*>(dest_title), token, token_bytes);
}
void note_copy(u64 dest_title, u64 src_title, u64 dest_desktop, u64 src_desktop, UINT count, UINT increment)
{
Expand Down
11 changes: 11 additions & 0 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6379,6 +6379,14 @@ extern "C" __declspec(dllexport) void x2w_d3d12_fail_view_allocations(int site,
if (site >= 0 && site < view_allocation_sites) InterlockedExchange(&view_allocations_to_fail[site], count);
}

// Fixture export (startup_view_token): view token writes made through the guard since the process started; both stay 0
// without X2W_D3D12_VIEW_TOKEN_GUARDED=1.
extern "C" __declspec(dllexport) void x2w_d3d12_view_token_writes(LONG* written, LONG* refused)
{
if (written) *written = view_tokens_guarded_written;
if (refused) *refused = view_tokens_guarded_refused;
}

// Fixture probe (startup_view_alloc): the sizes of the three view containers, the id + 1 that the tracked slot of a
// title descriptor handle names (0: none), and whether a resource is still in the retire class.
struct ViewStoreProbe {
Expand Down Expand Up @@ -7422,6 +7430,9 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa
for (int c = 0; c < x2w_local::null_cause_count; ++c) null_causes[c] = null_by_cause[c];
ReleaseSRWLockExclusive(&draw_lock);
}
if (render_mode() && frame % 300 == 0 && view_token_guarded())
log("x2w-render view tokens (X2W_D3D12_VIEW_TOKEN_GUARDED): written %ld, refused %ld", view_tokens_guarded_written,
view_tokens_guarded_refused);
if (render_mode() && frame % 300 == 0 && root_srv_at_draw())
log("x2w-render root SRV copies (X2W_D3D12_ROOT_SRV_AT_DRAW): skipped %ld, copied %ld", root_srv_copies_skipped,
root_srv_copies_made);
Expand Down
17 changes: 17 additions & 0 deletions tests/cmake/startup_view_token.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# The slot 18 view token in title descriptor memory, written after a check (unset) or under an exception guard
# (opt-in X2W_D3D12_VIEW_TOKEN_GUARDED=1): the same tokens, and no write to a read-only page or through a guard page.
add_executable(startup_view_token tests/startup_view_token.cpp)
target_compile_features(startup_view_token PRIVATE cxx_std_17)
target_link_libraries(startup_view_token PRIVATE d3d12_xs_shim d3d12 dxgi)
foreach(backend IN ITEMS warp hardware)
foreach(mode IN ITEMS unset set)
set(token_test startup_view_token_${mode}_${backend})
add_test(NAME ${token_test} COMMAND startup_view_token ${backend} ${mode})
set(token_env "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0")
list(APPEND token_env "X2W_TRAP_LOG=${CMAKE_CURRENT_BINARY_DIR}/${token_test}.log")
if(mode STREQUAL "set")
list(APPEND token_env "X2W_D3D12_VIEW_TOKEN_GUARDED=1")
endif()
set_tests_properties(${token_test} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "${token_env}")
endforeach()
endforeach()
Loading
Loading