diff --git a/CMakeLists.txt b/CMakeLists.txt index 48760486c..9da5a545c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2101,6 +2101,16 @@ foreach(mutation IN ITEMS bc4 width clamp) add_test(NAME startup_tile64_plan_${mutation}_control COMMAND startup_tile64_plan_check --mutate ${mutation}) set_tests_properties(startup_tile64_plan_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() +# Console texture layouts for the non-XOR standard and display swizzle modes (src/startup_stubs/gfx10_layout.h) +# and the slot-70 descriptions that use them (src/startup_stubs/address_texture.h), without a device: address +# equations against the pattern rows of AMD addrlib (Mesa 25.1.0, src/amd/addrlib, MIT), agreement with +# bc7_4k_s.h, bc64_chain.h and tile64_plan.h, and round trips. The mutated run reads the display order as the standard one and is a negative control. +add_executable(startup_gfx10_layout_check tests/startup_gfx10_layout_check.cpp) +target_compile_features(startup_gfx10_layout_check PRIVATE cxx_std_17) +target_include_directories(startup_gfx10_layout_check PRIVATE src) +add_test(NAME startup_gfx10_layout COMMAND startup_gfx10_layout_check) +add_test(NAME startup_gfx10_layout_display_control COMMAND startup_gfx10_layout_check --mutate display) +set_tests_properties(startup_gfx10_layout_display_control PROPERTIES WILL_FAIL TRUE) add_test(NAME xg_swizzle_select COMMAND xg_swizzle_select_check) set_tests_properties(xg_swizzle_select PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77) # Mutation control: the same comparison must identify all nine mismatches. @@ -2842,6 +2852,19 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_bc_view_check.py" "$" "${backend}") set_tests_properties(startup_address_bc_view_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_address_console_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_console_check.py" + "$" "${backend}") + set_tests_properties(startup_address_console_${backend} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + # Uploads of by-address textures recorded while the queue waits on a fence keep their bytes until the + # queue has run them. The ring control fills them from the shared upload ring and must lose the first. + foreach(gate IN ITEMS gate gate-ring) + string(REPLACE "-" "_" gate_name "${gate}") + add_test(NAME startup_address_console_${gate_name}_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_console_check.py" + "$" "${backend}" "${gate}") + set_tests_properties(startup_address_console_${gate_name}_${backend} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() add_test(NAME startup_xg_bc_chain_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_xg_bc_chain_check.py" "$" "$" "${backend}") diff --git a/docs/experiments.md b/docs/experiments.md index c1152ff2e..5da389e9a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -12312,6 +12312,69 @@ cmake --build --preset release --target startup_stream_consumer startup_stub_con ctest --preset release --no-tests=error --output-on-failure -R '^(startup_address_(bc_view|srv)_(hardware|warp)|startup_xg_bc7_layout|startup_bc7_4k_s|bc7_tile_swizzle)$' ``` +### Sample by-address textures of the non-XOR console layouts + +Slot 70 took a few texture shapes without a resource object (the R8 plane of an existing resource, +the single texel, the `0x105` BC3/BC7 view above and the `0x109` BC chains below; those keep their +own paths) and refused every other description, which leaves the destination descriptor as it was. +It now also takes a two-dimensional, +single-sample, sampled-only texture with a known element size whose layout is `0x101`, `0x102`, +`0x105`, `0x106`, `0x109` or `0x10a`, and reads it in that console layout, mip tail and array slices +included. Layout `0` and the linear mode `0x100` are refused as before: `startup_address_srv` still +runs in the default configuration, and its mismatched-width and interior-address calls stay refused. +The accepted descriptions, views, limits and log lines are listed in `docs/startup-runtime.md` +("Textures published by address"). + +`startup_gfx10_layout` needs no device. It compares `src/startup_stubs/gfx10_layout.h` with the 30 +one-pipe equations of AMD addrlib's `GFX10_SW_{256,4K,64K}_{S,D}_PATINFO` rows written out in the test +(five element sizes for each of the six modes), with `bc7_4k_s.h` on five 4 KiB surfaces, with +`bc64_chain.h` on eight 64 KiB chains and with `tile64_plan.h` on ten tile plans; it tiles and +detiles nine textures back to their bytes, and lists 11 refused layouts, 15 slot 70 descriptions and +16 views on each side of the accepted set. `startup_gfx10_layout_display_control` reads the `0x10a` +order as `0x109` and must fail. The addrlib reference is the revision `tools/fetch_addrlib.py` pins +(Mesa 25.1.0, commit `5c142e46f3f6e752ed745fd48912ebb8fad67145`, `src/amd/addrlib`, MIT); the files +and their notice ("Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved.", +`SPDX-License-Identifier: MIT`) are named in the header and in both fixtures. +[AMD addrlib revision](https://gitlab.freedesktop.org/mesa/mesa/-/tree/5c142e46f3f6e752ed745fd48912ebb8fad67145/src/amd/addrlib) + +`startup_address_console_{warp,hardware}` builds the backing bytes in Python from the same addrlib +rows, independently of the header, publishes them through slot 70 with no resource object, and +compares all 65,536 RGBA pixels of a 512 by 128 target for each of seven textures: RGBA8 96 by 40 +and BC1 192 by 96 at `0x105`, BC1 256 by 128 at `0x10a`, mips 1, 2 and 3 of a four-mip RGBA8 256 by +256 chain at `0x10a` (mips 2 and 3 are in the mip tail), and RGBA8 40 by 24 at `0x101`. Each run must +also log `slot70 texture kind 1: published console layout`. Two held descriptions follow: the first +texture again over an address announced as an XG copy of rows (`console_layout_xg_rows`), and +RGBA8 257 by 257 at `0x109`, whose nine 64 KiB blocks run past the 393,216 bytes the XG stand-in +reports (`console_layout_beyond_xg_size`). Both must log their reason, publish nothing and read the +null view at every pixel. Last, the first texture is published and its address is then announced as +an XG copy of rows before the draw; the published view must read the null view at every pixel, as +a partial-tile BC view does after a later row copy. + +An upload of a console-layout texture owns its upload buffer. The buffer and the texture stay referenced +by the recording and by each submit of it until the queue has completed that submit; the shared +upload ring, which is reused without waiting for a queue, is not used. `startup_address_console_gate_{warp,hardware}` +makes the queue wait on a fence the fixture holds (queue slot 17), then records and submits eighteen +lists on one list object, resetting the allocator and the list between them. Each republishes one +2048 by 2048 RGBA8 texture at `0x109` (16 MiB) from the same address with a new payload and draws it, +payload 0 over the left half of the target and the others over the right half. No submit may complete +before the fixture signals the fence. After the last one completes, the left half must hold payload 0 +and the right half payload 17, and the log must report eighteen retained submits released. +`startup_address_console_gate_ring_{warp,hardware}` is the control: with +`X2W_TEST_ADDRESS_UPLOAD_RING=1` (fixtures only) the same uploads come from the 256 MiB ring, the +later ones pass over the bytes of payload 0 before the queue copies them, and the left half must not +hold payload 0. + +The equations are checked against addrlib and against the three existing layout headers, not against +console memory. Which layouts a given console build writes for which textures is not established by +these fixtures. The gate fixture covers one direct queue, one texture and uploads recorded by draws; +it does not cover a release of the desktop texture, which this change never does. + +```powershell +cmake --build --preset release --target startup_gfx10_layout_check startup_stream_consumer +ctest --preset release --no-tests=error --output-on-failure -R '^startup_gfx10_layout' +ctest --preset release --no-tests=error --output-on-failure -j 1 -R '^startup_address_(console|console_gate|console_gate_ring|bc_view|srv)_(hardware|warp)$' +``` + ### Six BC5/BC7 mips on a 64 KiB standard layout `startup_xg_bc_chain_{warp,hardware}` uses a source-built 1024×1024 BC5_UNORM or BC7_UNORM texture with six mip levels, one slice, one sample, explicit layout `0x109` (64 KiB standard, no XOR), default alignment and zero flags. The guest chain occupies `0x160000` bytes. The six offsets starting at mip 0 are `0x60000, 0x20000, 0x10000, 0x8000, 0x4000, 0x2000`. The three smallest mips share tile zero. These offsets and all 87,360 visible block addresses were checked with `Addr2ComputeSurfaceInfo` and `Addr2ComputeSurfaceAddrFromCoord` on the pinned Navi21 configuration. [AMD addrlib revision](https://gitlab.freedesktop.org/mesa/mesa/-/tree/5c142e46f3f6e752ed745fd48912ebb8fad67145/src/amd/addrlib) · [XCL comparison](https://github.com/ivall/xcl/blob/64b3f35599bb7102f55d640e1a791e7d6dd3b175/crates/xcl/src/gpu/tiling.rs) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index dfd07921b..194b6ae52 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2097,6 +2097,81 @@ memory-type and state rules are unchanged. The five-second `x2w-d3d12 views note that call count is its sole failure. Neither is `WILL_FAIL`, so a crash cannot pass them. A refused allocation or mapping is a capability skip (77) in the controls. +## Textures published by address (device slot 70) + +Device slot 70 gets a resource description, a view and the address of the texels. When a live +texture with that description exists at the address, its view is created as before. The shapes slot +70 already read from an address keep their own paths unchanged: the single texel, the `0x105` +BC3/BC7 surface (partial last tiles included) and the `0x109` BC chains. For any other description +with no live texture whose `Layout` is `0x101`, `0x102`, `0x105`, `0x106`, `0x109` or `0x10a` (256 B, +4 KiB and 64 KiB blocks in the standard and display orders, no XOR), the texels are read from the +address in that console layout (`src/startup_stubs/address_texture.h`, device-free). A translated +draw that samples the view copies each mip of each array slice from that layout into desktop +footprint rows (`src/startup_stubs/gfx10_layout.h`: address equations, block sizes and mip-tail rules +after AMD addrlib, Mesa 25.1.0, `src/amd/addrlib`, MIT). A 256 B layout is taken with one mip only. + +The description must be two-dimensional, at most 16384 texels a side, with 1 to 15 mips, one sample, +no target, depth or unordered-access flag, and a format with a known element size (8- to 128-bit +texels and BC1 to BC7, whose largest mip must then be whole 4x4 blocks). The view must be a 2D or +2D-array view of the same typeless family whose mip and slice ranges stay inside the texture. +Anything else is refused as before and leaves the destination descriptor unchanged: layout `0` and +the linear mode `0x100` without a live texture, three-dimensional and cube views, multisampled +textures, the XOR swizzle modes and every other layout value. The texels must be readable and span +at most 64 MiB. + +A console-layout description is held (not published, descriptor unchanged) in the two cases a +partial-tile BC view is held for. `console_layout_xg_rows`: the latest XG stand-in copy announced +for the address wrote desktop-footprint rows, so the bytes are not in the layout the description +names. As for a partial-tile view, a texture already published there samples the null view while +that is so. `console_layout_beyond_xg_size`: the layout runs past the size the XG stand-in reports +for the description (the desktop copyable footprints of a slice rounded up to 64 KiB, times the +slices), which the title may not own. + +Upload lifetime: each upload of a console-layout texture is written into an upload buffer of its own +(`x2w_upload::make_page`), not into the shared upload ring. The recording keeps a reference to the +buffer and to the texture until the list is reset, and each `ExecuteCommandLists` of the recording +takes its own references and signals a fence behind the submit; a later submit drops the references +of the submits whose fence has completed. A submit whose fence cannot be created or signalled keeps +its references. The earlier by-address shapes keep using the shared ring as before. The desktop +texture of a by-address texture is made on the first draw that samples it and is not released. The +texels are compared with the uploaded copy on each frame that binds them, as for the earlier +by-address shapes, and at once after a repeated slot 70 call for the same texture, which announces +a write: a description and address that were published before are published again rather than +taken as a live resource, so changed texels are uploaded again. + +Limits and choices that are not measured against a console: + +- The texels are taken in the layout the description names. The XG stand-in's default copy writes + rows whatever the swizzle mode; a description filled through it is held as above. A write by the + title itself is not told apart from one in the named layout. +- One upload buffer is created per upload and there is no bound on the bytes uploaded in a frame. + A policy for releasing textures that are no longer sampled and for spreading large uploads over + frames is left to a follow-up. +- Second sources for the address equations: only the 16-byte standard rows of `0x105` and `0x109` + are compared with another implementation in the tree (`bc7_4k_s.h`, `bc64_chain.h`); + `tile64_plan.h` checks the `0x10a` mip starts and tail, not the bit order. The display (`_D`) + rows in `gfx10_layout.h` that differ from the standard ones (1-, 8- and 16-byte elements; the 2- + and 4-byte display rows equal the standard rows) and the standard rows for 1-, 2-, 4- and 8-byte + elements are checked only against the addrlib pattern rows restated from the addrlib source text + in `startup_gfx10_layout_check.cpp` (all five element sizes) and in the Python oracle of + `startup_address_console_check.py` (4- and 8-byte elements), both written from the same source. + +Log lines (stderr and `X2W_TRAP_LOG`): + +- `x2w-d3d12 slot70 texture kind : ; first seen res{...} view{...} address=...`, once + for each new combination of format, layout, one or several mips, one or several slices, flags, + dimension, view format, view dimension and outcome (at most 200). The outcome is + `existing resource`, `published BC shape` (the earlier `0x105` and `0x109` BC paths), + `published console layout`, one of the two hold reasons or `texture_unavailable`. +- `x2w-draw by-address uploads: submits completed and released (...)`, for the first twelve + submits that drop retained uploads. + +Checks (reproduction in `docs/experiments.md`, "Sample by-address textures of the non-XOR console +layouts"): + +- `ctest --preset release --no-tests=error -R '^startup_gfx10_layout' -V` +- `ctest --preset release --no-tests=error -j 1 -R '^startup_address_console_' -V` + ## Buffer memory SRVs (device slot 70) Device slot 70 (`src/startup_stubs/d3d12_memory_srv.inl`, validation in diff --git a/src/startup_stubs/address_texture.h b/src/startup_stubs/address_texture.h new file mode 100644 index 000000000..6701ed8ec --- /dev/null +++ b/src/startup_stubs/address_texture.h @@ -0,0 +1,56 @@ +#pragma once + +// Textures a title publishes by address (device slot 70): a resource description, a view and the +// address of the texels, with no resource object behind them. This header decides, without a +// device, which of those descriptions the startup renderer reads from the address: a sampled-only, +// two-dimensional, single-sample texture whose Layout field holds a console swizzle mode that +// gfx10_layout.h addresses. Its texels are in that console layout. +// Everything else is refused here: the desktop's unknown layout and the console's linear mode (the +// extent of such rows is not established), other dimensions, multisampled textures, textures that +// are also targets, formats without a known element size and swizzle modes without an equation. + +#include "startup_stubs/gfx10_layout.h" + +namespace x2w_startup { +inline bool console_address_texture(const D3D12_RESOURCE_DESC& r) +{ + // Each flag is cast on its own: with MinGW-w64 headers the flag enum's operator| is not constexpr. + constexpr UINT not_sampled_only = static_cast(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) | + static_cast(D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) | + static_cast(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) | + static_cast(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE); + // A desktop block-compressed texture needs whole 4x4 blocks in its largest mip. + const UINT texels = gfx10::element_of(r.Format).texels; + return r.SampleDesc.Quality == 0 && !(static_cast(r.Flags) & not_sampled_only) && gfx10::supports(r) && + r.Width % texels == 0 && r.Height % texels == 0; +} + +// Formats with one typeless parent hold the same bytes; a view may name any of them. +inline UINT format_family(DXGI_FORMAT format) +{ + const UINT f = static_cast(format); + constexpr UINT first[] = {1, 5, 9, 15, 19, 23, 27, 33, 39, 44, 48, 53, 60, 70, 73, 76, 79, 82, 94, 97}; + constexpr UINT last[] = {4, 8, 14, 18, 22, 25, 32, 38, 43, 47, 52, 59, 64, 72, 75, 78, 81, 84, 96, 99}; + for (UINT i = 0; i < sizeof(first) / sizeof(first[0]); ++i) + if (f >= first[i] && f <= last[i]) return first[i]; + if (f == 87 || f == 90 || f == 91) return 90; // B8G8R8A8 + if (f == 88 || f == 92 || f == 93) return 92; // B8G8R8X8 + return f; +} + +// A two-dimensional or array view that stays inside the texture and reads its texels as stored. +inline bool address_view_fits(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v) +{ + if (format_family(v.Format) != format_family(r.Format)) return false; + const auto inside = [](UINT first, UINT count, UINT total) { + return first < total && (count == ~0u || (count && count <= total - first)); + }; + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D) + return inside(v.Texture2D.MostDetailedMip, v.Texture2D.MipLevels, r.MipLevels) && !v.Texture2D.PlaneSlice; + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY) + return inside(v.Texture2DArray.MostDetailedMip, v.Texture2DArray.MipLevels, r.MipLevels) && + inside(v.Texture2DArray.FirstArraySlice, v.Texture2DArray.ArraySize, r.DepthOrArraySize) && + !v.Texture2DArray.PlaneSlice; + return false; +} +} // namespace x2w_startup diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 09a896e65..16645a622 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -753,6 +753,74 @@ void retire_draw_sampler_heaps(ID3D12CommandQueue* queue, const std::vector buffer, texture; +}; +std::unordered_map> recorded_address_uploads; +struct SubmittedAddressUploads { + x2w_startup::ComPtr fence; + std::vector uploads; +}; +std::vector submitted_address_uploads; + +// X2W_TEST_ADDRESS_UPLOAD_RING=1 (fixtures only): fill by-address textures from the shared upload ring, +// without the buffers above. The control of startup_address_console_gate runs with it. +bool address_uploads_from_ring() +{ + static const bool on = GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_UPLOAD_RING", nullptr, 0) != 0; + return on; +} + +void discard_address_uploads(ID3D12CommandList* list) +{ + AcquireSRWLockExclusive(&draw_lock); + recorded_address_uploads.erase(list); + ReleaseSRWLockExclusive(&draw_lock); +} + +// draw_lock held. The lists have already been executed on this queue. Each submit takes its own +// references; they are dropped by a later call, once the fence signalled behind the submit has +// completed. A submit whose fence could not be made or signalled keeps its references. +void retire_address_uploads(ID3D12CommandQueue* queue, const std::vector& lists) +{ + static std::size_t peak, released; + const std::size_t before = submitted_address_uploads.size(); + submitted_address_uploads.erase(std::remove_if(submitted_address_uploads.begin(), + submitted_address_uploads.end(), [](const SubmittedAddressUploads& batch) { + return batch.fence && batch.fence->GetCompletedValue() != 0; + }), submitted_address_uploads.end()); + if (const std::size_t gone = before - submitted_address_uploads.size()) { + released += gone; + static LONG reports; + if (first_calls(reports, 12)) + log("x2w-draw by-address uploads: %zu submits completed and released (%zu so far, %zu still pending, at most %zu pending)", + gone, released, submitted_address_uploads.size(), peak); + } + SubmittedAddressUploads batch; + for (auto* list : lists) { + const auto it = recorded_address_uploads.find(list); + if (it == recorded_address_uploads.end()) continue; + for (const auto& upload : it->second) batch.uploads.push_back(upload); + } + if (batch.uploads.empty()) return; + x2w_startup::ComPtr device; + HRESULT hr = queue->GetDevice(IID_PPV_ARGS(&device)); + if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&batch.fence)); + if (SUCCEEDED(hr)) hr = queue->Signal(batch.fence.Get(), 1); + if (FAILED(hr)) { + batch.fence.Reset(); + log("x2w-draw by-address upload retirement fence failed 0x%08lx", static_cast(hr)); + } + submitted_address_uploads.push_back(std::move(batch)); + peak = (std::max)(peak, submitted_address_uploads.size()); +} + bool resolve_draw_sampler(const x2w_startup::SamplerWords& words, D3D12_SAMPLER_DESC& sampler) { if (words[0] != view_token_magic) { @@ -913,8 +981,13 @@ void upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) const auto* original = resource_info(resource); const bool tiled_chain = original && x2w_startup::bc64::supports(original->console); const bool tiled_address = resource->own().tiled_address_srv; + // Any other texture slot 70 publishes holds its texels in the console layout its description names + // (gfx10_layout.h, address_texture.h). + const bool console = tiled_address && !single && !tiled_chain && original && console_layout_srv(original->console); const bool tiled_bc7 = !tiled_chain && !tiled_address && written.bc7_width != 0; const bool tiled = tiled_bc7 || tiled_address || tiled_chain; + std::optional console_layout; + if (console) console_layout.emplace(original->console); const auto generation = written.generation; const x2w_startup::Bc16Surface surface(tiled_bc7 ? written.bc7_width : static_cast(desc.Width), tiled_bc7 ? written.bc7_height : desc.Height); @@ -924,9 +997,17 @@ void upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) desc.Format != DXGI_FORMAT_BC7_UNORM || desc.Width != surface.columns * surface.block_texels || desc.Height != surface.rows * surface.block_texels) return; } - if (tiled && !tiled_chain && !single && (plan.count != 1 || plan.rows[0] != surface.rows || + if (tiled && !tiled_chain && !single && !console && (plan.count != 1 || plan.rows[0] != surface.rows || plan.row_bytes[0] != u64{surface.columns} * surface.block_bytes)) return; - const u64 total = tiled_chain ? x2w_startup::bc64::Chain(original->console).bytes() : tiled && !single ? surface.size() : stride * (slices - 1) + slice_total; + if (console) { + // The desktop footprints must hold exactly the elements the console layout addresses. + if (console_layout->mips != mips || console_layout->slices != slices) return; + for (UINT i = 0; i < mips; ++i) + if (plan.rows[i] != console_layout->rows(i) || + plan.row_bytes[i] != u64{console_layout->columns(i)} * console_layout->bytes_per_element) return; + } + const u64 total = tiled_chain ? x2w_startup::bc64::Chain(original->console).bytes() : console ? console_layout->bytes() + : tiled && !single ? surface.size() : stride * (slices - 1) + slice_total; const bool announced = state.generation != generation; const UINT elapsed = static_cast(frame_number) - static_cast(state.checked_frame); // A single texel (at most 16 bytes) is rehashed on every bind, so a write between two draws is seen. @@ -945,8 +1026,47 @@ void upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) state.generation = generation; return; } + // 512: D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, the offset of each footprint in its upload buffer. + constexpr u64 placement = 512; + x2w_upload::Page owned; + if (console && !address_uploads_from_ring()) { + u64 bytes = 0; + for (UINT i = 0; i < mips; ++i) bytes += (plan.bytes(i) + placement - 1) & ~(placement - 1); + bytes *= slices; + if (!bytes || FAILED(x2w_upload::make_page(device_of(the_device), bytes, owned))) { + state.done = false; + return; + } + std::memset(owned.cpu, 0, static_cast(bytes)); + } require_state(self, texture, D3D12_RESOURCE_STATE_COPY_DEST); - if (tiled_chain) { + if (console) { + for (UINT slice = 0; slice < slices; ++slice) { + for (UINT i = 0; i < mips; ++i) { + const u64 bytes = plan.bytes(i); + u64 offset = owned.cursor; + unsigned char* rows = owned.cpu ? owned.cpu + offset : nullptr; + if (owned.cpu) { + owned.cursor += (bytes + placement - 1) & ~(placement - 1); + } else { + rows = reserve_upload_ring(static_cast(bytes), &offset); + if (!rows) { + state.done = false; + return; + } + std::memset(rows, 0, static_cast(bytes)); + } + console_layout->detile(i, slice, memory, rows, plan.placed[i].Footprint.RowPitch); + plan.upload(list, texture, owned.cpu ? owned.resource.Get() : upload_ring, mips, slices, slice, i, offset); + } + } + if (owned.cpu) { + AddressUpload upload; + upload.buffer = owned.resource.Get(); + upload.texture = texture; + recorded_address_uploads[list].push_back(std::move(upload)); + } + } else if (tiled_chain) { const x2w_startup::bc64::Chain chain(original->console); for (UINT slice = 0; slice < slices; ++slice) { for (UINT i = 0; i < mips; ++i) { diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index 12663d87e..037558c4d 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -57,7 +57,17 @@ u64 xg_reported_bytes(Wrapper* device, const D3D12_RESOURCE_DESC& desc) return plan.size == UINT64_MAX ? 0 : (plan.size + 0xFFFF) & ~u64{0xFFFF}; } +bool supports_placed_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v); +// The shapes slot 70 took before address_texture.h, or a texture in a console layout gfx10_layout.h +// addresses with a view that stays inside it. bool supports_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v) +{ + if (supports_placed_memory_srv(r, v)) return true; + return r.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && x2w_startup::console_address_texture(r) && + x2w_startup::address_view_fits(r, v); +} + +bool supports_placed_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v) { if (r.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return x2w_startup::supports_buffer_memory_srv(r, v); @@ -205,10 +215,60 @@ bool latest_texture_write_is_rows(u64 address) return rows; } +// A texture slot 70 reads in a console layout of gfx10_layout.h: not one of the shapes it read before +// (the single texel, the 0x105 BC3/BC7 surface and the 0x109 BC chains keep their own paths). +bool console_layout_srv(const D3D12_RESOURCE_DESC& desc) +{ + return x2w_startup::console_address_texture(desc) && !x2w_startup::single_element_bytes(desc) && + !tiled_bc_srv(desc) && !x2w_startup::bc64::supports(desc); +} + +// One line for each new kind of slot-70 texture call (format, layout, shape class, view and outcome), so +// a run shows every shape a title asks for without a line per texture. +void log_address_kind(const char* outcome, const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v, u64 address) +{ + static std::mutex mutex; + static std::unordered_map kinds; + const u64 words[] = {static_cast(r.Format), static_cast(r.Layout), r.MipLevels > 1 ? 2u : 1u, + r.DepthOrArraySize > 1 ? 2u : 1u, static_cast(r.Flags), static_cast(r.Dimension), + static_cast(v.Format), static_cast(v.ViewDimension), reinterpret_cast(outcome)}; + const u64 key = fnv_bytes(words, sizeof(words)); + std::lock_guard lock(mutex); + if (kinds.size() >= 200 || kinds[key]++) return; + log("x2w-d3d12 slot70 texture kind %zu: %s; first seen res{dim=%d fmt=%d size=%llux%ux%u mips=%u layout=0x%x flags=0x%x " + "align=%llu} view{dim=%d fmt=%d map=0x%x} address=0x%llx", kinds.size(), outcome, r.Dimension, r.Format, r.Width, + r.Height, r.DepthOrArraySize, r.MipLevels, static_cast(r.Layout), static_cast(r.Flags), r.Alignment, + v.ViewDimension, v.Format, v.Shader4ComponentMapping, address); +} + +// Bytes the texels of a by-address texture span at their address. +u64 address_texture_bytes(const D3D12_RESOURCE_DESC& desc) +{ + if (const UINT element = x2w_startup::single_element_bytes(desc)) return element; + if (x2w_startup::bc64::supports(desc)) return x2w_startup::bc64::Chain(desc).bytes(); + if (console_layout_srv(desc)) return x2w_startup::gfx10::Layout(desc).bytes(); + return x2w_startup::Bc16Surface(desc).size(); +} + +// Why a console-layout description is not read from an address, or null. The two cases a partial-tile +// BC view is held for: +// - the latest XG stand-in copy to the address wrote desktop-footprint rows (only the opt-in BC7 4 KiB +// copy records a tiled write; the 0x109 BC chains, which XG writes in their layout, keep their own +// path and never come through here); +// - the layout runs past the size the XG stand-in reports for the description (the desktop copyable +// footprints of a slice rounded up to 64 KiB, times the slices), which the title may not own. +const char* console_address_hold(Wrapper* device, u64 address, const D3D12_RESOURCE_DESC& desc) +{ + if (latest_texture_write_is_rows(address)) return "console_layout_xg_rows"; + const x2w_startup::SliceFootprints plan(device_of(device), sanitized(desc), desc.MipLevels); + if (plan.size == UINT64_MAX || !plan.size) return "console_layout_without_footprints"; + const u64 reported = ((plan.size + 0xFFFF) & ~u64{0xFFFF}) * desc.DepthOrArraySize; + return x2w_startup::gfx10::Layout(desc).bytes() > reported ? "console_layout_beyond_xg_size" : nullptr; +} + Wrapper* publish_tiled_texture(Wrapper* device, u64 address, const D3D12_RESOURCE_DESC& desc) { - const UINT element = x2w_startup::single_element_bytes(desc); - const auto bytes = element ? u64{element} : x2w_startup::bc64::supports(desc) ? x2w_startup::bc64::Chain(desc).bytes() : x2w_startup::Bc16Surface(desc).size(); + const auto bytes = address_texture_bytes(desc); // The transient upload ring accepts individual copies up to 64 MiB. if (bytes > (64ull << 20) || !x2w_local::readable(reinterpret_cast(address), bytes)) return nullptr; std::lock_guard lock(tiled_srv_mutex); @@ -238,7 +298,7 @@ ID3D12Resource* sampled_address_texture(Wrapper* resource) std::lock_guard lock(tiled_srv_mutex); auto& sampled = tiled_srv_textures.at(resource); // An already-published token can outlive a write in a different layout. - if (partial_tiled_bc(sampled.desc) && + if ((partial_tiled_bc(sampled.desc) || console_layout_srv(sampled.desc)) && latest_texture_write_is_rows(reinterpret_cast(resource->own().title_memory))) return nullptr; if (!sampled.desktop) { @@ -335,6 +395,18 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou : (tiled_bc_srv(*resource) || x2w_startup::bc64::supports(*resource)) ? publish_tiled_texture(self, input->address, *resource) : existing_memory_texture(input->address, *resource); if (first) log_partial_tile_view(*resource, input->address, held, texture != nullptr); + // Without a resource the title created at this address with this description, a texture in a console + // layout is read from the address. A match that is itself a texture published here is published + // again, which announces a write, so changed texels are uploaded again. + const bool console = console_layout_srv(*resource); + const char* outcome = tiled_bc_srv(*resource) || x2w_startup::bc64::supports(*resource) ? "published BC shape" : "existing resource"; + if (console && (!texture || texture->own().tiled_address_srv)) { + held = console_address_hold(self, input->address, *resource); + texture = held ? nullptr : publish_tiled_texture(self, input->address, *resource); + outcome = "published console layout"; + } + if (!texture) outcome = held ? held : "texture_unavailable (no resource there, or texels not readable or over 64 MiB)"; + log_address_kind(outcome, *resource, input->view, input->address); if (!texture) { if (first_calls(refused, 8)) log_refused_memory_srv("unavailable texture at the supplied base and layout", held ? held : "texture_unavailable", diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 6257cc2fe..56e7b1893 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -24,6 +24,9 @@ #include "startup_stubs/heap_indexed_root.h" #include "startup_stubs/bc7_4k_s.h" #include "startup_stubs/bc64_chain.h" +#include "startup_stubs/address_texture.h" +#include "startup_stubs/list_upload_pages.h" +#include #include "startup_stubs/derived_blend.h" #include "startup_stubs/placement_publish.h" #include "startup_stubs/placed_build.h" @@ -1074,6 +1077,7 @@ void release_targets(Wrapper* self); void end_open_queries(Wrapper* self, ID3D12GraphicsCommandList* list); void reset_list_dynamic_state(Wrapper* self); void discard_draw_sampler_heaps(ID3D12CommandList* list); +void discard_address_uploads(ID3D12CommandList* list); void use_as_target(Wrapper* self, ID3D12Resource* resource); bool is_container(const void* p); bool shader_dump_dir(wchar_t* out, DWORD size); @@ -1352,6 +1356,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) if (SUCCEEDED(hr)) { reset_list_dynamic_state(self); discard_draw_sampler_heaps(previous); + discard_address_uploads(previous); if (draw_dump_frame()) draw_dumps().discard(previous); } InterlockedIncrement(SUCCEEDED(hr) ? &render_resets : &render_reset_failures); @@ -1385,6 +1390,7 @@ HRESULT __stdcall list_close(Wrapper* self) InterlockedIncrement(&render_closes); if (FAILED(hr)) { discard_draw_sampler_heaps(list); + discard_address_uploads(list); if (draw_dump_frame()) draw_dumps().discard(list); static LONG failures; if (first_calls(failures, 6)) log("x2w-render list Close failed 0x%08lx", static_cast(hr)); @@ -2568,6 +2574,7 @@ struct TextureWrite { }; std::unordered_map& written_textures(); ID3D12Resource* sampled_address_texture(Wrapper* resource); +bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); #include "startup_stubs/d3d12_draw.inl" // Queue slot 10, desktop ExecuteCommandLists(count, lists). @@ -2598,6 +2605,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) queue->ExecuteCommandLists(ready_count, ready.data()); } retire_draw_sampler_heaps(queue, ready); + retire_address_uploads(queue, ready); note_submits(queue, submitted); InterlockedIncrement(&render_executes); } diff --git a/src/startup_stubs/gfx10_layout.h b/src/startup_stubs/gfx10_layout.h new file mode 100644 index 000000000..87deac041 --- /dev/null +++ b/src/startup_stubs/gfx10_layout.h @@ -0,0 +1,200 @@ +#pragma once + +// Console (GFX10) texture memory layouts for the non-XOR standard and display swizzle modes, and +// copies between such a layout and row-major texels. +// +// A console resource description carries its swizzle mode in the Layout field as 0x100 + mode. The +// modes handled here are 256 B, 4 KiB and 64 KiB blocks in the standard (S) and display (D) orders: +// 0x101, 0x102, 0x105, 0x106, 0x109 and 0x10a. The address equations, block dimensions and mip-tail +// rules follow AMD addrlib as Mesa carries it under src/amd/addrlib, at the revision +// tools/fetch_addrlib.py pins: Mesa 25.1.0, commit 5c142e46f3f6e752ed745fd48912ebb8fad67145. The three +// files used carry this notice: +// Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved. +// SPDX-License-Identifier: MIT +// - src/gfx10/gfx10SwizzlePattern.h: GFX10_SW_{256,4K,64K}_{S,D}_PATINFO, one-pipe rows, and the +// nibbles they name. +// - src/core/addrlib2.cpp: ComputeThinBlockDimension (a block is 2^ceil(n/2) by 2^floor(n/2) elements) +// and GetMipTailDim (the tail holds mips up to half a block wide and one block high). +// - src/gfx10/gfx10addrlib.cpp: ComputeSurfaceInfoMacroTiled (the tail block comes first in a slice, +// then the mips from the smallest to the largest; offsets and origins inside the tail block). +// The rules are restated here; no addrlib code is included. +// Measurements are in elements: one texel, or one 4x4 block of a block-compressed format. + +#include +#include +#include +#include +#include +#include + +namespace x2w_startup::gfx10 { +constexpr UINT max_mips = 15; + +struct Element { + UINT bytes = 0; // 1, 2, 4, 8 or 16; 0 for a format without a layout here + UINT texels = 1; // side of the texel block one element covers +}; + +inline Element element_of(DXGI_FORMAT format) +{ + const UINT f = static_cast(format); + if ((f >= 70 && f <= 72) || (f >= 79 && f <= 81)) return {8, 4}; // BC1, BC4 + if ((f >= 73 && f <= 78) || (f >= 82 && f <= 84) || (f >= 94 && f <= 99)) return {16, 4}; // BC2, BC3, BC5, BC6H, BC7 + if (f >= 1 && f <= 4) return {16, 1}; // R32G32B32A32 + if (f >= 9 && f <= 18) return {8, 1}; // R16G16B16A16, R32G32 + if ((f >= 23 && f <= 47) || f == 67 || f == 87 || f == 88 || (f >= 90 && f <= 93)) return {4, 1}; + if ((f >= 48 && f <= 59) || f == 85 || f == 86 || f == 115) return {2, 1}; + if (f >= 60 && f <= 65) return {1, 1}; + return {}; +} + +// The swizzle mode of a console description, or ~0u when the Layout field does not hold one. +inline UINT swizzle_mode(const D3D12_RESOURCE_DESC& d) +{ + const UINT layout = static_cast(d.Layout); + return (layout & ~0xffu) == 0x100 ? layout & 0xff : ~0u; +} + +inline UINT block_log2(UINT mode) +{ + switch (mode) { + case 1: case 2: return 8; + case 5: case 6: return 12; + case 9: case 10: return 16; + default: return 0; + } +} + +// A two-dimensional, single-sample texture whose memory this header can address. +inline bool supports(const D3D12_RESOURCE_DESC& d) +{ + const UINT log2 = block_log2(swizzle_mode(d)); + if (!log2 || d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || !element_of(d.Format).bytes) return false; + if (!d.Width || !d.Height || d.Width > 16384 || d.Height > 16384 || !d.DepthOrArraySize) return false; + if (!d.MipLevels || d.MipLevels > max_mips || d.SampleDesc.Count != 1) return false; + return log2 >= 12 || d.MipLevels == 1; // a 256 B block has no mip tail here +} + +struct Layout { + UINT bytes_per_element = 0, texels = 1, width = 0, height = 0, mips = 0, slices = 0; + UINT block_bytes = 0, block_width = 0, block_height = 0; + UINT first_tail = 0; // first mip inside the shared tail block; mips when there is none + std::uint64_t slice_size = 0; + std::array start{}; // byte offset of a mip in its slice + std::array blocks_wide{}, origin_x{}, origin_y{}; + std::array x_bits{}, y_bits{}; // in-block byte offset contributed by a coordinate + + explicit Layout(const D3D12_RESOURCE_DESC& d) + : width(static_cast(d.Width)), height(d.Height), mips(d.MipLevels), slices(d.DepthOrArraySize) + { + const Element element = element_of(d.Format); + bytes_per_element = element.bytes; + texels = element.texels; + const UINT mode = swizzle_mode(d), log2 = block_log2(mode); + UINT element_log2 = 0; + while ((1u << element_log2) < bytes_per_element) ++element_log2; + const UINT count_log2 = log2 - element_log2, width_log2 = (count_log2 + 1) / 2; + block_bytes = 1u << log2; + block_width = 1u << width_log2; + block_height = 1u << (count_log2 - width_log2); + + // Address bits 0-7 of the 256 B micro block, by element size (1, 2, 4, 8, 16 bytes): 'x' or 'y' + // and the coordinate bit, '-' for a bit inside the element. Only the 16-byte standard rows have a + // second source in the tree (bc7_4k_s.h, bc64_chain.h); the display rows that differ from the + // standard ones (1, 8 and 16 bytes) are checked against the addrlib rows alone + // (docs/startup-runtime.md, "Textures published by address"). + static constexpr const char* standard[5] = { + "x0x1x2x3y0y1y2y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1y2x2", "------x0y0y1x1x2", "--------y0y1x0x1"}; + static constexpr const char* display[5] = { + "x0x1x2y1y0y2x3y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1y2x2", "------x0y0x1x2y1", "--------x0y0x1y1"}; + static constexpr UINT micro[5][2] = {{16, 16}, {16, 8}, {8, 8}, {8, 4}, {4, 4}}; + const bool is_display = mode == 2 || mode == 6 || mode == 10; + const char* pattern = (is_display ? display : standard)[element_log2]; + std::array x_at{}, y_at{}; // address bit of each coordinate bit + UINT next_x = 0, next_y = 0; + for (UINT bit = 0; bit < 8; ++bit) { + const UINT index = static_cast(pattern[2 * bit + 1] - '0'); + if (pattern[2 * bit] == 'x') x_at[index] = bit, next_x = (std::max)(next_x, index + 1); + if (pattern[2 * bit] == 'y') y_at[index] = bit, next_y = (std::max)(next_y, index + 1); + } + // Above the micro block the coordinates alternate, y on the even address bits. + for (UINT bit = 8; bit < log2; ++bit) (bit & 1 ? x_at[next_x++] : y_at[next_y++]) = bit; + for (UINT v = 0; v < 256; ++v) + for (UINT bit = 0; bit < 8; ++bit) { + if (bit < next_x && ((v >> bit) & 1)) x_bits[v] |= 1u << x_at[bit]; + if (bit < next_y && ((v >> bit) & 1)) y_bits[v] |= 1u << y_at[bit]; + } + + // Mip sizes for the layout round up at every level (addrlib GetMipSize). + const UINT columns0 = (width + texels - 1) / texels, rows0 = (height + texels - 1) / texels; + const auto shifted = [](UINT v, UINT mip) { return (std::max)(1u, (v + (1u << mip) - 1) >> mip); }; + const UINT tail_mips = log2 - 4; // most mips one tail block holds, for 4 KiB and 64 KiB blocks + first_tail = mips; + std::array size{}; + for (UINT mip = 0; mips > 1 && mip < mips; ++mip) { + const UINT w = shifted(columns0, mip), h = shifted(rows0, mip); + if (w <= block_width / 2 && h <= block_height && mips - mip <= tail_mips) { + first_tail = mip; + break; + } + } + for (UINT mip = 0; mip < first_tail; ++mip) { + const UINT w = shifted(columns0, mip), h = shifted(rows0, mip); + blocks_wide[mip] = (w + block_width - 1) / block_width; + size[mip] = std::uint64_t{blocks_wide[mip]} * ((h + block_height - 1) / block_height) * block_bytes; + } + std::uint64_t offset = first_tail < mips ? block_bytes : 0; + for (UINT mip = first_tail; mip-- > 0;) { + start[mip] = offset; + offset += size[mip]; + } + slice_size = offset; + for (UINT mip = first_tail; mip < mips; ++mip) { + // The position of a tail mip is its byte offset in the block, read back as micro block coordinates. + const UINT m = tail_mips - 1 - (mip - first_tail); + const UINT tail_offset = m > 6 ? 16u << m : m << 8; + UINT x = 0, y = 0; + for (UINT bit = 0; bit < 6; ++bit) { + y |= ((tail_offset >> (8 + 2 * bit)) & 1) << bit; + x |= ((tail_offset >> (9 + 2 * bit)) & 1) << bit; + } + start[mip] = tail_offset; + origin_x[mip] = x * micro[element_log2][0]; + origin_y[mip] = y * micro[element_log2][1]; + } + } + + // Elements a mip holds, with the desktop's mip sizes (rounded down, at least one texel). + UINT columns(UINT mip) const { return ((std::max)(1u, width >> mip) + texels - 1) / texels; } + UINT rows(UINT mip) const { return ((std::max)(1u, height >> mip) + texels - 1) / texels; } + std::uint64_t bytes() const { return slice_size * slices; } + + // Byte offset of element (x, y) of a mip of a slice from the start of the texture. + std::uint64_t address(UINT mip, UINT x, UINT y, UINT slice) const + { + const std::uint64_t base = slice * slice_size; + if (mip >= first_tail) return base + (x_bits[(origin_x[mip] + x) & 255] | y_bits[(origin_y[mip] + y) & 255]); + const std::uint64_t block = std::uint64_t{y / block_height} * blocks_wide[mip] + x / block_width; + return base + start[mip] + block * block_bytes + (x_bits[x % block_width] | y_bits[y % block_height]); + } + + // Copies one subresource from the console layout at `tiled` to rows `pitch` bytes apart at `linear`. + void detile(UINT mip, UINT slice, const unsigned char* tiled, unsigned char* linear, std::size_t pitch) const + { + const UINT w = columns(mip), h = rows(mip); + for (UINT y = 0; y < h; ++y) + for (UINT x = 0; x < w; ++x) + std::memcpy(linear + y * pitch + std::size_t{x} * bytes_per_element, tiled + address(mip, x, y, slice), + bytes_per_element); + } + // The opposite copy, from rows into the console layout. + void tile(UINT mip, UINT slice, unsigned char* tiled, const unsigned char* linear, std::size_t pitch) const + { + const UINT w = columns(mip), h = rows(mip); + for (UINT y = 0; y < h; ++y) + for (UINT x = 0; x < w; ++x) + std::memcpy(tiled + address(mip, x, y, slice), linear + y * pitch + std::size_t{x} * bytes_per_element, + bytes_per_element); + } +}; +} // namespace x2w_startup::gfx10 diff --git a/tests/startup_address_console_check.py b/tests/startup_address_console_check.py new file mode 100644 index 000000000..c07508f63 --- /dev/null +++ b/tests/startup_address_console_check.py @@ -0,0 +1,293 @@ +"""Draw textures published by address (device slot 70) whose texels are in a console layout. + + seven textures, each drawn once; every pixel of the 512x128 target is + compared with the texel the view names; then two held descriptions + and one texture whose address is announced as XG rows after it + was published + gate the upload lifetime control described at check_gate + gate-ring the same draws with X2W_TEST_ADDRESS_UPLOAD_RING=1, which must show the + first payload overwritten + +The backing bytes are built here, independently of src/startup_stubs/gfx10_layout.h, from the address +equations of AMD addrlib's GFX10 pattern tables, written out below. Reference: addrlib as Mesa carries it +under src/amd/addrlib at the revision tools/fetch_addrlib.py pins (Mesa 25.1.0, commit +5c142e46f3f6e752ed745fd48912ebb8fad67145), files src/gfx10/gfx10SwizzlePattern.h, src/gfx10/gfx10addrlib.cpp +and src/core/addrlib2.cpp, each with the notice "Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All +rights reserved. SPDX-License-Identifier: MIT". No addrlib code is included. +""" +from pathlib import Path +import struct +import sys +import tempfile + +from startup_address_srv_check import draw_texture + +TARGET_W, TARGET_H = 512, 128 +RGBA8, BC1 = 28, 71 + +# Address bits 0-7 of the 256-byte micro block by element size; above it y takes the even bits. +STANDARD = {4: "0 0 X0 X1 Y0 Y1 Y2 X2", 8: "0 0 0 X0 Y0 Y1 X1 X2"} +DISPLAY = {4: "0 0 X0 X1 Y0 Y1 Y2 X2", 8: "0 0 0 X0 Y0 X1 X2 Y1"} +MICRO = {4: (8, 8), 8: (8, 4)} + + +class Console: + def __init__(self, width, height, mips, element, texels, layout): + self.width, self.height, self.mips, self.element, self.texels = width, height, mips, element, texels + mode = layout & 0xff + self.log2 = {1: 8, 2: 8, 5: 12, 6: 12, 9: 16, 10: 16}[mode] + bits = (DISPLAY if mode in (2, 6, 10) else STANDARD)[element].split() + x_next, y_next = (sum(b[0] == axis for b in bits) for axis in "XY") + for bit in range(8, self.log2): + if bit & 1: + bits.append(f"X{x_next}") + x_next += 1 + else: + bits.append(f"Y{y_next}") + y_next += 1 + self.bits = bits + self.block_w, self.block_h = 1 << x_next, 1 << y_next + columns, rows = -(-width // texels), -(-height // texels) + size = lambda v, mip: max(1, (v + (1 << mip) - 1) >> mip) + tail_mips = self.log2 - 4 + self.first_tail = mips + if mips > 1: + for mip in range(mips): + if size(columns, mip) <= self.block_w // 2 and size(rows, mip) <= self.block_h and mips - mip <= tail_mips: + self.first_tail = mip + break + block = 1 << self.log2 + self.start, self.blocks_wide, self.origin = {}, {}, {} + offset = block if self.first_tail < mips else 0 + for mip in range(self.first_tail - 1, -1, -1): + self.blocks_wide[mip] = -(-size(columns, mip) // self.block_w) + self.start[mip] = offset + offset += self.blocks_wide[mip] * -(-size(rows, mip) // self.block_h) * block + self.bytes = offset + for mip in range(self.first_tail, mips): + m = tail_mips - 1 - (mip - self.first_tail) + tail = 16 << m if m > 6 else m << 8 + x = sum(((tail >> (9 + 2 * b)) & 1) << b for b in range(6)) + y = sum(((tail >> (8 + 2 * b)) & 1) << b for b in range(6)) + self.origin[mip] = (x * MICRO[element][0], y * MICRO[element][1]) + + def in_block(self, x, y): + value = 0 + for bit, name in enumerate(self.bits): + if name != "0" and ((x if name[0] == "X" else y) >> int(name[1:])) & 1: + value |= 1 << bit + return value + + def columns(self, mip): + return -(-max(1, self.width >> mip) // self.texels) + + def rows(self, mip): + return -(-max(1, self.height >> mip) // self.texels) + + def address(self, mip, x, y): + if mip >= self.first_tail: + ox, oy = self.origin[mip] + return self.in_block(ox + x, oy + y) + block = (y // self.block_h) * self.blocks_wide[mip] + x // self.block_w + return self.start[mip] + (block << self.log2) + self.in_block(x % self.block_w, y % self.block_h) + + +def rgba_texel(mip, x, y): + return bytes(((7 * x + 40 * mip + 1) & 255, (5 * y + 3) & 255, (x ^ (3 * y)) & 255, 255)) + + +def bc1_block(mip, x, y): + # Both endpoints equal and every index 0: sixteen texels of one colour with full or empty channels. + v = (5 * x + 3 * y + mip) % 8 + red, green, blue = v & 1, (v >> 1) & 1, (v >> 2) & 1 + colour = (0xf800 if red else 0) | (0x07e0 if green else 0) | (0x001f if blue else 0) + return struct.pack("> mip), max(1, height >> mip) + image = bytearray(w * h * 4) + for y in range(console.rows(mip)): + for x in range(console.columns(mip)): + at = console.address(mip, x, y) + if at in seen or at + element > len(backing): + raise AssertionError(f"oracle address {at:#x} of mip {mip} ({x},{y}) is shared or outside the texture") + seen.add(at) + if fmt == BC1: + block, colour = bc1_block(mip, x, y) + backing[at:at + 8] = block + for row in range(4 * y, min(4 * y + 4, h)): + for column in range(4 * x, min(4 * x + 4, w)): + image[4 * (row * w + column):4 * (row * w + column) + 4] = colour + else: + backing[at:at + 4] = rgba_texel(mip, x, y) + image[4 * (y * w + x):4 * (y * w + x) + 4] = rgba_texel(mip, x, y) + images.append(image) + return backing, images + + +# Held descriptions: nothing is published and the draw reads a null view (zeros). The first is the first +# case above over an address announced as an XG copy of rows. The second runs past the size the XG +# stand-in reports: 257x257 RGBA8 in 64 KiB blocks is nine blocks (589,824 bytes), and the desktop +# footprint (257 rows of 1,280 bytes) rounded to 64 KiB is 393,216. +HELD = [ + (("RGBA8 96x40 4 KiB standard over XG rows", 96, 40, 1, RGBA8, 0x105, 0), {"X2W_TEST_CONSOLE_XG_ROWS": "1"}, + "console_layout_xg_rows"), + (("RGBA8 257x257 64 KiB standard past the XG size", 257, 257, 1, RGBA8, 0x109, 0), {}, "console_layout_beyond_xg_size"), +] + +# Published, then the address is announced as an XG copy of rows before the draw: the texture published +# there must sample the null view, as a partial-tile BC view does. +LATE = (("RGBA8 96x40 4 KiB standard, XG rows after publication", 96, 40, 1, RGBA8, 0x105, 0), + {"X2W_TEST_CONSOLE_XG_ROWS": "after"}) + + +def check(directory, consumer, backend, case, extra=None, held=None, late=False): + name, width, height, mips, fmt, layout, viewed = case + backing, images = build(width, height, mips, fmt, layout) + source = directory / "texels.bin" + source.write_bytes(backing) + w, h = max(1, width >> viewed), max(1, height >> viewed) + hlsl = ("Texture2D t : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + f" return t.Load(int3(uint(p.x) % {w}, uint(p.y) % {h}, 0));\n}}\n") + trap_log = directory / "trap.log" + modes = {"X2W_TEST_CONSOLE_VIEW": str(source), "X2W_TRAP_LOG": str(trap_log), + "X2W_TEST_CONSOLE_DESC": f"{width},{height},{mips},{fmt},{layout},{viewed}", **(extra or {})} + actual = draw_texture(directory, consumer, backend, hlsl, modes) + if actual is None: + return 77 + if len(actual) != TARGET_W * TARGET_H * 4: + raise AssertionError(f"{name}: readback length {len(actual)}") + log = trap_log.read_text(errors="replace") + if held: + if any(actual): + raise AssertionError(f"{name}: a held description drew texels") + if f"slot70 texture kind 1: {held};" not in log or "published console layout" in log: + raise AssertionError(f"{name}: no '{held}' line in the log, or a publication") + print(f"{backend} {name}: held ({held}), {TARGET_W * TARGET_H} pixels read the null view") + return 0 + if late: + if any(actual): + raise AssertionError(f"{name}: the published texture drew texels after an XG copy of rows was announced") + if "slot70 texture kind 1: published console layout" not in log: + raise AssertionError(f"{name}: no 'published console layout' line in the log") + print(f"{backend} {name}: published, then {TARGET_W * TARGET_H} pixels read the null view") + return 0 + image = images[viewed] + for y in range(TARGET_H): + for x in range(TARGET_W): + pixel = actual[4 * (y * TARGET_W + x):4 * (y * TARGET_W + x) + 4] + expect = image[4 * ((y % h) * w + x % w):4 * ((y % h) * w + x % w) + 4] + if pixel != expect: + raise AssertionError(f"{name}: pixel ({x},{y}) actual {pixel.hex()} expected {expect.hex()}") + if "slot70 texture kind 1: published console layout" not in log: + raise AssertionError(f"{name}: no 'published console layout' line in the log") + print(f"{backend} {name}: {TARGET_W * TARGET_H} RGBA pixels exact") + return 0 + + +GATE_PAYLOADS = 18 + + +def gate_colour(payload): + """The colour of every texel of a payload; tests/startup_address_srv.cpp writes the same bytes.""" + return bytes(((17 * payload + 3) & 255, (255 - 9 * payload) & 255, payload ^ 0x5a, 255)) + + +def check_gate(directory, consumer, backend, ring): + """Uploads recorded while the queue cannot run must still hold their bytes when it does. + + The fixture makes the queue wait on a fence it controls, then records and submits eighteen lists. Each + republishes one 2048x2048 RGBA8 texture (64 KiB standard layout, 16 MiB) from the same address with a new + payload and draws it: payload 0 over the left half of the target, the others over the right half. The list + object and its allocator are reset between submits. Nothing may complete while the fence is unsignalled. + The fixture then signals the fence, waits for the last submit and reads the target back: the left half + must hold payload 0 and the right half payload 17. + + Eighteen 16 MiB uploads are more than the 256 MiB upload ring. With X2W_TEST_ADDRESS_UPLOAD_RING=1 the + uploads come from the ring, the later ones pass over the bytes of payload 0 before the queue has copied + them, and the left half must not hold payload 0. + """ + hlsl = ("Texture2D t : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " return t.Load(int3(uint(p.x) % 2048, uint(p.y) % 2048, 0));\n}\n") + trap_log = directory / "trap.log" + modes = {"X2W_TEST_CONSOLE_GATE": "1", "X2W_TRAP_LOG": str(trap_log)} + if ring: + modes["X2W_TEST_ADDRESS_UPLOAD_RING"] = "1" + actual = draw_texture(directory, consumer, backend, hlsl, modes) + if actual is None: + return 77 + if len(actual) != TARGET_W * TARGET_H * 4: + raise AssertionError(f"gate: readback length {len(actual)}") + first, last = gate_colour(0), gate_colour(GATE_PAYLOADS - 1) + wrong = {"left": 0, "right": 0} + seen = set() + for y in range(TARGET_H): + for x in range(TARGET_W): + pixel = actual[4 * (y * TARGET_W + x):4 * (y * TARGET_W + x) + 4] + side = "left" if x < TARGET_W // 2 else "right" + if pixel != (first if side == "left" else last): + wrong[side] += 1 + seen.add(pixel.hex()) + log = trap_log.read_text(errors="replace") + released = f"x2w-draw by-address uploads: {GATE_PAYLOADS} submits completed and released" + half = TARGET_W * TARGET_H // 2 + if ring: + if not wrong["left"] or wrong["right"]: + raise AssertionError(f"gate-ring: {wrong} wrong pixels; expected the left half overwritten and the right intact") + if "x2w-draw by-address uploads:" in log: + raise AssertionError("gate-ring: the ring control retained upload buffers") + print(f"{backend} gate, uploads from the shared ring (control): {wrong['left']} of {half} left pixels do not hold " + f"payload 0 (found {sorted(seen)[:3]}); right half holds payload {GATE_PAYLOADS - 1}") + return 0 + if wrong["left"] or wrong["right"]: + raise AssertionError(f"gate: {wrong} wrong pixels, found {sorted(seen)[:4]}; expected {first.hex()} left, {last.hex()} right") + if released not in log or f"at most {GATE_PAYLOADS} pending" not in log: + raise AssertionError("gate: no line reporting the retained uploads released after completion:\n" + + "\n".join(line for line in log.splitlines() if "by-address" in line)) + print(f"{backend} gate: {GATE_PAYLOADS} submits held behind the fence; after release the left half holds payload 0 and the " + f"right half payload {GATE_PAYLOADS - 1}, {TARGET_W * TARGET_H} RGBA pixels exact; {GATE_PAYLOADS} retained uploads released") + return 0 + + +if __name__ == "__main__": + if len(sys.argv) not in (3, 4) or (len(sys.argv) == 4 and sys.argv[3] not in ("gate", "gate-ring")): + usage = "usage: startup_address_console_check.py [gate | gate-ring]\n" + sys.exit(usage + "\n\n".join(__doc__.split("\n\n")[:2])) + if len(sys.argv) == 4: + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check_gate(Path(temporary), sys.argv[1], sys.argv[2], sys.argv[3] == "gate-ring")) + for case in CASES: + with tempfile.TemporaryDirectory() as temporary: + result = check(Path(temporary), *sys.argv[1:3], case) + if result: + sys.exit(result) + for case, extra, held in HELD: + with tempfile.TemporaryDirectory() as temporary: + result = check(Path(temporary), *sys.argv[1:3], case, extra, held) + if result: + sys.exit(result) + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:3], LATE[0], LATE[1], late=True)) diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 9f1d3950f..770d4987a 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -222,6 +223,86 @@ int draw_bc_address_srvs(void* guest, void* list) return 0; } +// X2W_TEST_CONSOLE_VIEW names a file of texels and X2W_TEST_CONSOLE_DESC the texture they belong to +// ("width,height,mips,format,layout,viewed mip"). No resource object exists at the address; one mip is +// viewed and drawn over the whole target. With X2W_TEST_CONSOLE_XG_ROWS=1 the address is first announced +// the way the XG stand-in announces a copy of desktop-footprint rows; with =after the announcement comes +// between the publication and the draw. +int draw_console_address_srv(void* guest, void* list) +{ + wchar_t path[MAX_PATH]{}; + const DWORD length = GetEnvironmentVariableW(L"X2W_TEST_CONSOLE_VIEW", path, MAX_PATH); + char text[96]{}; + unsigned width = 0, height = 0, mips = 0, format = 0, layout = 0, viewed = 0; + if (!length || length >= MAX_PATH || !GetEnvironmentVariableA("X2W_TEST_CONSOLE_DESC", text, sizeof(text)) || + std::sscanf(text, "%u,%u,%u,%u,%u,%u", &width, &height, &mips, &format, &layout, &viewed) != 6) return 43; + alignas(4096) static std::array backing{}; + std::ifstream input(path, std::ios::binary); + input.read(backing.data(), backing.size()); + if (!input.gcount() || !input.eof()) return 43; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, static_cast(mips), + static_cast(format), {1, 0}, static_cast(layout), D3D12_RESOURCE_FLAG_NONE}; + ViewAt v{}; + v.view.Format = desc.Format; + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.view.Texture2D.MostDetailedMip = viewed; + v.view.Texture2D.MipLevels = 1; + v.address = ptr(backing.data()); + Word cpu = 0; + if (!bind_view_table(guest, list, cpu)) return 42; + wchar_t rows[8]{}; + GetEnvironmentVariableW(L"X2W_TEST_CONSOLE_XG_ROWS", rows, 8); + if (!std::wcscmp(rows, L"1")) x2w_d3d12_texture_written(backing.data(), backing.size()); + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); + // "after": the announcement follows the publication, before the draw samples the view. + if (!std::wcscmp(rows, L"after")) x2w_d3d12_texture_written(backing.data(), backing.size()); + const D3D12_RECT whole{0, 0, 512, 128}; + invoke(list, 22, 1, ptr(&whole)); + invoke(list, 12, 3, 1); + return 0; +} + +// X2W_TEST_CONSOLE_GATE: one 2048x2048 RGBA8 texture in the 64 KiB standard layout (16 MiB), republished +// from the same address with a new payload before each draw. Every texel of a payload has one colour +// (gate_colour in tests/startup_address_console_check.py), so the bytes do not depend on the layout. The +// draw covers the left or the right half of the 512x128 target. +int draw_gated_console_payload(void* guest, void* list, unsigned payload, bool left) +{ + constexpr unsigned side = 2048; + constexpr std::size_t bytes = std::size_t{side} * side * 4; + static auto* const backing = static_cast(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!backing) return 43; + const unsigned char colour[4] = {static_cast(17 * payload + 3), static_cast(255 - 9 * payload), + static_cast(payload ^ 0x5a), 255}; + for (std::size_t at = 0; at < bytes; at += 4) std::memcpy(backing + at, colour, 4); + static void* heap; + static Word cpu; + if (!heap) { + struct Extended { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word address, size; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + if (FAILED(static_cast(invoke(guest, 14, ptr(&heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&heap))))) return 42; + cpu = invoke(heap, 9); + } + invoke(list, 32, 1, ptr(&heap)); + invoke(list, 36, 0, invoke(heap, 10)); + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, + {1, 0}, static_cast(0x109), D3D12_RESOURCE_FLAG_NONE}; + ViewAt v{}; + v.view.Format = desc.Format; + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.view.Texture2D.MipLevels = 1; + v.address = ptr(backing); + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); + const D3D12_RECT half{left ? 0 : 256, 0, left ? 256 : 512, 128}; + invoke(list, 22, 1, ptr(&half)); + invoke(list, 12, 3, 1); + return 0; +} + // The backing is produced by XG CopyIntoSubresource from a source-built block texture. int draw_bc_chain(void* guest, void* list) { diff --git a/tests/startup_gfx10_layout_check.cpp b/tests/startup_gfx10_layout_check.cpp new file mode 100644 index 000000000..2d539597e --- /dev/null +++ b/tests/startup_gfx10_layout_check.cpp @@ -0,0 +1,304 @@ +// Checks src/startup_stubs/gfx10_layout.h without a device: +// - the address bit of every coordinate bit against the one-pipe rows of addrlib's GFX10 pattern +// tables (written out below as the nibbles those rows name), for six swizzle modes and five element sizes; +// - agreement with the three narrower layouts already in the tree (bc7_4k_s.h, bc64_chain.h, tile64_plan.h); +// - the mip offsets docs/experiments.md records for a 1024x1024 six-mip BC7 chain; +// - that every element of every subresource gets its own bytes inside the texture, and that a +// tile followed by a detile returns the rows it started from. +// +// Reference: AMD addrlib as Mesa carries it under src/amd/addrlib, at the revision tools/fetch_addrlib.py +// pins (Mesa 25.1.0, commit 5c142e46f3f6e752ed745fd48912ebb8fad67145): src/gfx10/gfx10SwizzlePattern.h, +// src/gfx10/gfx10addrlib.cpp and src/core/addrlib2.cpp, each with the notice +// Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved. +// SPDX-License-Identifier: MIT +// The pattern rows are restated below as data; no addrlib code is included. +#include "startup_stubs/address_texture.h" +#include "startup_stubs/gfx10_layout.h" +#include "startup_stubs/bc64_chain.h" +#include "startup_stubs/bc7_4k_s.h" +#include "startup_stubs/tile64_plan.h" + +#include +#include +#include +#include + +namespace { +using x2w_startup::gfx10::Layout; +int failures = 0; + +void fail(const std::string& what) +{ + ++failures; + std::printf("FAIL %s\n", what.c_str()); +} + +D3D12_RESOURCE_DESC texture(UINT width, UINT height, UINT mips, UINT slices, DXGI_FORMAT format, UINT layout) +{ + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = width; + d.Height = height; + d.DepthOrArraySize = static_cast(slices); + d.MipLevels = static_cast(mips); + d.Format = format; + d.SampleDesc.Count = 1; + d.Layout = static_cast(layout); + return d; +} + +// One format per element size: 1, 2, 4, 8 and 16 bytes. +constexpr DXGI_FORMAT by_size[5] = {DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R32G32B32A32_FLOAT}; + +// Address bits from bit 0 up; "0" is a bit inside the element. +struct Equation { + UINT layout; + const char* bits[5]; +}; +const Equation equations[] = { + {0x101, {"X0 X1 X2 X3 Y0 Y1 Y2 Y3", "0 X0 X1 X2 Y0 Y1 Y2 X3", "0 0 X0 X1 Y0 Y1 Y2 X2", "0 0 0 X0 Y0 Y1 X1 X2", + "0 0 0 0 Y0 Y1 X0 X1"}}, + {0x102, {"X0 X1 X2 Y1 Y0 Y2 X3 Y3", "0 X0 X1 X2 Y0 Y1 Y2 X3", "0 0 X0 X1 Y0 Y1 Y2 X2", "0 0 0 X0 Y0 X1 X2 Y1", + "0 0 0 0 X0 Y0 X1 Y1"}}, + {0x105, {"X0 X1 X2 X3 Y0 Y1 Y2 Y3 Y4 X4 Y5 X5", "0 X0 X1 X2 Y0 Y1 Y2 X3 Y3 X4 Y4 X5", + "0 0 X0 X1 Y0 Y1 Y2 X2 Y3 X3 Y4 X4", "0 0 0 X0 Y0 Y1 X1 X2 Y2 X3 Y3 X4", "0 0 0 0 Y0 Y1 X0 X1 Y2 X2 Y3 X3"}}, + {0x106, {"X0 X1 X2 Y1 Y0 Y2 X3 Y3 Y4 X4 Y5 X5", "0 X0 X1 X2 Y0 Y1 Y2 X3 Y3 X4 Y4 X5", + "0 0 X0 X1 Y0 Y1 Y2 X2 Y3 X3 Y4 X4", "0 0 0 X0 Y0 X1 X2 Y1 Y2 X3 Y3 X4", "0 0 0 0 X0 Y0 X1 Y1 Y2 X2 Y3 X3"}}, + {0x109, {"X0 X1 X2 X3 Y0 Y1 Y2 Y3 Y4 X4 Y5 X5 Y6 X6 Y7 X7", "0 X0 X1 X2 Y0 Y1 Y2 X3 Y3 X4 Y4 X5 Y5 X6 Y6 X7", + "0 0 X0 X1 Y0 Y1 Y2 X2 Y3 X3 Y4 X4 Y5 X5 Y6 X6", "0 0 0 X0 Y0 Y1 X1 X2 Y2 X3 Y3 X4 Y4 X5 Y5 X6", + "0 0 0 0 Y0 Y1 X0 X1 Y2 X2 Y3 X3 Y4 X4 Y5 X5"}}, + {0x10a, {"X0 X1 X2 Y1 Y0 Y2 X3 Y3 Y4 X4 Y5 X5 Y6 X6 Y7 X7", "0 X0 X1 X2 Y0 Y1 Y2 X3 Y3 X4 Y4 X5 Y5 X6 Y6 X7", + "0 0 X0 X1 Y0 Y1 Y2 X2 Y3 X3 Y4 X4 Y5 X5 Y6 X6", "0 0 0 X0 Y0 X1 X2 Y1 Y2 X3 Y3 X4 Y4 X5 Y5 X6", + "0 0 0 0 X0 Y0 X1 Y1 Y2 X2 Y3 X3 Y4 X4 Y5 X5"}}, +}; + +void check_equations(bool mutate) +{ + for (const Equation& equation : equations) + for (UINT size = 0; size < 5; ++size) { + UINT layout = equation.layout; + if (mutate && layout == 0x10a) layout = 0x109; // the display order read as the standard one + const Layout l(texture(4096, 4096, 1, 1, by_size[size], layout)); + UINT bit = 0, xs = 0, ys = 0; + for (const char* p = equation.bits[size]; *p; ++bit) { + const char axis = *p++; + UINT index = 0; + if (axis != '0') index = static_cast(*p++ - '0'); + if (*p == ' ') ++p; + if (axis == '0') continue; + const std::uint64_t got = axis == 'X' ? l.address(0, 1u << index, 0, 0) : l.address(0, 0, 1u << index, 0); + if (got != (1ull << bit)) + fail("layout " + std::to_string(equation.layout) + " element " + std::to_string(1u << size) + " " + axis + + std::to_string(index) + ": " + std::to_string(got) + ", expected bit " + std::to_string(bit)); + (axis == 'X' ? xs : ys) += 1; + } + if (l.block_bytes != (1u << bit) || l.block_width != (1u << xs) || l.block_height != (1u << ys)) + fail("layout " + std::to_string(equation.layout) + " element " + std::to_string(1u << size) + ": block size"); + } +} + +void check_bc7_4k() +{ + const UINT sizes[][2] = {{64, 64}, {1024, 2112}, {256, 128}, {3840, 2176}, {100, 36}}; + for (const auto& s : sizes) { + const Layout l(texture(s[0], s[1], 1, 1, DXGI_FORMAT_BC7_UNORM, 0x105)); + const x2w_startup::Bc16Surface surface(s[0], s[1]); + if (l.bytes() != surface.size()) fail("4 KiB BC7 size"); + for (UINT y = 0; y < surface.rows; ++y) + for (UINT x = 0; x < surface.columns; ++x) + if (l.address(0, x, y, 0) != surface.block_offset(x, y)) return fail("4 KiB BC7 block offset"); + } +} + +void check_bc64() +{ + const UINT shapes[][3] = {{1024, 6, 1}, {1024, 9, 1}, {512, 9, 2}, {1024, 9, 2}}; + for (const auto& s : shapes) + for (const DXGI_FORMAT format : {DXGI_FORMAT_BC5_UNORM, DXGI_FORMAT_BC7_UNORM}) { + const D3D12_RESOURCE_DESC d = texture(1024, s[0], s[1], s[2], format, 0x109); + if (!x2w_startup::bc64::supports(d)) return fail("64 KiB chain shape is not one bc64_chain.h takes"); + const Layout l(d); + const x2w_startup::bc64::Chain chain(d); + if (l.bytes() != chain.bytes() || l.first_tail != x2w_startup::bc64::first_tail) fail("64 KiB chain size or tail"); + for (UINT slice = 0; slice < s[2]; ++slice) + for (UINT mip = 0; mip < s[1]; ++mip) + for (UINT y = 0; y < chain.rows(mip); ++y) + for (UINT x = 0; x < chain.columns(mip); ++x) + if (l.address(mip, x, y, slice) != chain.address(mip, x, y, slice)) + return fail("64 KiB chain address at mip " + std::to_string(mip)); + } + // docs/experiments.md: 1024x1024 BC7, six mips, layout 0x109. + const Layout l(texture(1024, 1024, 6, 1, DXGI_FORMAT_BC7_UNORM, 0x109)); + const std::uint64_t offsets[6] = {0x60000, 0x20000, 0x10000, 0x8000, 0x4000, 0x2000}; + if (l.bytes() != 0x160000) fail("documented chain size"); + for (UINT mip = 0; mip < 6; ++mip) + if (l.address(mip, 0, 0, 0) != offsets[mip]) fail("documented offset of mip " + std::to_string(mip)); +} + +void check_tile64() +{ + struct Shape { UINT width, height, mips, slices; DXGI_FORMAT format; }; + const Shape shapes[] = { + {512, 512, 1, 1, DXGI_FORMAT_BC1_UNORM}, {1024, 512, 1, 1, DXGI_FORMAT_BC7_UNORM}, {1024, 128, 1, 1, DXGI_FORMAT_BC3_UNORM}, + {2048, 2048, 12, 1, DXGI_FORMAT_BC1_UNORM}, {4096, 2048, 13, 1, DXGI_FORMAT_BC7_UNORM}, {1024, 1024, 11, 6, DXGI_FORMAT_BC4_UNORM}, + {1024, 1024, 11, 1, DXGI_FORMAT_R8_UNORM}, {512, 512, 10, 2, DXGI_FORMAT_R16_UNORM}, {2048, 1024, 12, 1, DXGI_FORMAT_R8G8B8A8_UNORM}, + {1000, 600, 10, 1, DXGI_FORMAT_BC3_UNORM}, + }; + for (const Shape& s : shapes) { + const D3D12_RESOURCE_DESC d = texture(s.width, s.height, s.mips, s.slices, s.format, 0x10a); + if (!x2w_startup::tile64::Plan::supports(d)) return fail("tile plan refuses a shape of this check"); + const x2w_startup::tile64::Plan plan(d); + const Layout l(d); + const std::string name = std::to_string(s.width) + "x" + std::to_string(s.height) + " format " + std::to_string(s.format); + if (l.first_tail != plan.standard) fail(name + ": first tail mip " + std::to_string(l.first_tail) + " against " + std::to_string(plan.standard)); + if (l.slice_size != std::uint64_t{plan.slice_tiles} * 65536) fail(name + ": slice size"); + for (UINT mip = 0; mip < plan.standard && mip < l.first_tail; ++mip) + if (l.start[mip] != std::uint64_t{plan.start[mip]} * 65536) fail(name + ": start of mip " + std::to_string(mip)); + } +} + +void check_distinct_and_round_trip() +{ + struct Shape { UINT width, height, mips, slices; DXGI_FORMAT format; UINT layout; }; + const Shape shapes[] = { + {1000, 520, 10, 1, DXGI_FORMAT_BC1_UNORM, 0x105}, {300, 200, 9, 2, DXGI_FORMAT_R8_UNORM, 0x109}, + {512, 1056, 1, 1, DXGI_FORMAT_BC1_UNORM, 0x105}, {1024, 2112, 1, 1, DXGI_FORMAT_R16_UNORM, 0x105}, + {640, 360, 10, 1, DXGI_FORMAT_BC7_UNORM, 0x10a}, {257, 129, 9, 3, DXGI_FORMAT_R8G8B8A8_UNORM, 0x106}, + {96, 40, 1, 1, DXGI_FORMAT_R16G16B16A16_FLOAT, 0x102}, {4, 4, 3, 1, DXGI_FORMAT_BC3_UNORM, 0x109}, + {2048, 2048, 12, 1, DXGI_FORMAT_BC5_UNORM, 0x109}, + }; + for (const Shape& s : shapes) { + const D3D12_RESOURCE_DESC d = texture(s.width, s.height, s.mips, s.slices, s.format, s.layout); + const std::string name = std::to_string(s.width) + "x" + std::to_string(s.height) + " layout " + std::to_string(s.layout); + if (!x2w_startup::gfx10::supports(d)) { + fail(name + ": refused"); + continue; + } + const Layout l(d); + const std::size_t total = static_cast(l.bytes()); + std::vector used(total / l.bytes_per_element, 0), tiled(total, 0); + bool ok = total % l.block_bytes == 0; + for (UINT slice = 0; ok && slice < s.slices; ++slice) + for (UINT mip = 0; ok && mip < s.mips; ++mip) { + const UINT w = l.columns(mip), h = l.rows(mip); + const std::size_t pitch = std::size_t{w} * l.bytes_per_element + 16; + std::vector rows(pitch * h), back(pitch * h, 0); + for (std::size_t i = 0; i < rows.size(); ++i) rows[i] = static_cast(i * 31 + mip * 7 + slice * 3 + 1); + for (UINT y = 0; ok && y < h; ++y) + for (UINT x = 0; ok && x < w; ++x) { + const std::uint64_t at = l.address(mip, x, y, slice); + ok = at % l.bytes_per_element == 0 && at + l.bytes_per_element <= total && !used[at / l.bytes_per_element]; + if (ok) used[at / l.bytes_per_element] = 1; + } + if (!ok) break; + l.tile(mip, slice, tiled.data(), rows.data(), pitch); + l.detile(mip, slice, tiled.data(), back.data(), pitch); + for (UINT y = 0; ok && y < h; ++y) + ok = std::memcmp(rows.data() + y * pitch, back.data() + y * pitch, std::size_t{w} * l.bytes_per_element) == 0; + } + if (!ok) fail(name + ": an element outside the texture, shared by two subresources, or changed by a round trip"); + } +} + +void check_refusals() +{ + const D3D12_RESOURCE_DESC good = texture(256, 256, 1, 1, DXGI_FORMAT_BC1_UNORM, 0x105); + if (!x2w_startup::gfx10::supports(good)) fail("plain 4 KiB BC1 texture refused"); + const auto refused = [&](const char* name, D3D12_RESOURCE_DESC d) { + if (x2w_startup::gfx10::supports(d)) fail(std::string("accepted: ") + name); + }; + D3D12_RESOURCE_DESC d = good; + d.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; refused("desktop layout", d); + d = good; d.Layout = static_cast(0x100); refused("linear mode", d); + d = good; d.Layout = static_cast(0x115); refused("XOR mode", d); + d = good; d.Layout = static_cast(0x209); refused("layout outside 0x1xx", d); + d = good; d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; refused("volume", d); + d = good; d.SampleDesc.Count = 4; refused("multisampled", d); + d = good; d.Format = DXGI_FORMAT_R32G32B32_FLOAT; refused("12-byte texels", d); + d = good; d.MipLevels = 16; refused("16 mips", d); + d = good; d.Width = 16385; refused("too wide", d); + d = good; d.DepthOrArraySize = 0; refused("no slices", d); + d = good; d.Layout = static_cast(0x101); d.MipLevels = 2; refused("256 B chain", d); +} + +// Which slot-70 descriptions are taken, and how their texels are read (address_texture.h). +void check_address_textures() +{ + const auto expect = [](const char* name, const D3D12_RESOURCE_DESC& d, bool want) { + if (x2w_startup::console_address_texture(d) != want) fail(std::string("address texture: ") + name); + }; + D3D12_RESOURCE_DESC d = texture(1024, 2112, 1, 1, DXGI_FORMAT_BC1_UNORM, 0x105); + expect("4 KiB BC1", d, true); + d.Flags = static_cast(0x300000); + expect("console-only flag bits", d, true); + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + expect("render target", d, false); + d.Flags = D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; + expect("not sampled", d, false); + expect("64 KiB display R16 chain", texture(512, 512, 10, 1, DXGI_FORMAT_R16_UNORM, 0x10a), true); + expect("desktop layout RGBA8", texture(1, 1, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 0), false); + expect("linear mode R8", texture(256, 128, 1, 1, DXGI_FORMAT_R8_UNORM, 0x100), false); + expect("XOR mode", texture(256, 256, 1, 1, DXGI_FORMAT_BC7_UNORM, 0x119), false); + expect("row-major desktop layout", texture(256, 256, 1, 1, DXGI_FORMAT_BC7_UNORM, 1), false); + expect("unknown element size", texture(256, 256, 1, 1, DXGI_FORMAT_R32G32B32_FLOAT, 0), false); + d = texture(256, 256, 1, 1, DXGI_FORMAT_BC7_UNORM, 0x105); + d.SampleDesc.Count = 2; + expect("multisampled", d, false); + d = texture(256, 256, 1, 1, DXGI_FORMAT_BC7_UNORM, 0x105); + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + expect("volume", d, false); + expect("BC1 width not whole blocks", texture(126, 128, 1, 1, DXGI_FORMAT_BC1_UNORM, 0x105), false); + expect("BC1 height not whole blocks", texture(128, 126, 1, 1, DXGI_FORMAT_BC1_UNORM, 0x10a), false); + expect("RGBA8 odd sides", texture(257, 129, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 0x106), true); + + const D3D12_RESOURCE_DESC chain = texture(512, 512, 10, 4, DXGI_FORMAT_BC7_UNORM, 0x109); + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_BC7_UNORM; + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.Texture2D.MipLevels = 10; + const auto fits = [&](const char* name, bool want) { + if (x2w_startup::address_view_fits(chain, v) != want) fail(std::string("address view: ") + name); + }; + fits("whole chain", true); + v.Texture2D.MipLevels = ~0u; fits("all mips", true); + v.Format = DXGI_FORMAT_BC7_UNORM_SRGB; fits("sRGB view of the same family", true); + v.Format = DXGI_FORMAT_BC3_UNORM; fits("another family", false); + v.Format = DXGI_FORMAT_BC7_UNORM; + v.Texture2D.MipLevels = 11; fits("too many mips", false); + v.Texture2D.MipLevels = 0; fits("no mips", false); + v.Texture2D.MipLevels = 1; v.Texture2D.MostDetailedMip = 10; fits("first mip past the chain", false); + v.Texture2D.MostDetailedMip = 9; fits("last mip", true); + v.Texture2D.PlaneSlice = 1; fits("second plane", false); + v = {}; + v.Format = DXGI_FORMAT_BC7_UNORM; + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + v.Texture2DArray.MipLevels = 10; + v.Texture2DArray.ArraySize = 4; fits("whole array", true); + v.Texture2DArray.FirstArraySlice = 1; fits("array past the last slice", false); + v.Texture2DArray.ArraySize = 3; fits("last three slices", true); + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; fits("cube view", false); +} +} // namespace + +int main(int argc, char** argv) +{ + const bool mutate = argc == 3 && std::string(argv[1]) == "--mutate" && std::string(argv[2]) == "display"; + if (argc != 1 && !mutate) { + std::printf("usage: startup_gfx10_layout_check [--mutate display]\n"); + return 2; + } + check_equations(mutate); + check_bc7_4k(); + check_bc64(); + check_tile64(); + check_distinct_and_round_trip(); + check_refusals(); + check_address_textures(); + if (failures) { + std::printf("startup_gfx10_layout: %d FAILED\n", failures); + return 1; + } + std::printf("startup_gfx10_layout: PASS (30 equations, 5 4 KiB surfaces, 8 64 KiB chains, 10 tile plans, 9 round trips, 11 refusals, 12 address descriptions, 16 views)\n"); + return 0; +} diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 5598e0c02..535c1de62 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -240,7 +240,9 @@ bool bind_bc7(ID3D12Device* desktop, void* guest, const StartupBc7Input& input, int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* pixels, const StartupBc7Input* bc7, DXGI_FORMAT format, std::uint32_t export_word, bool two_targets) { - const bool bc = GetEnvironmentVariableW(L"X2W_TEST_BC_VIEW", nullptr, 0) != 0; + const bool console_view = GetEnvironmentVariableW(L"X2W_TEST_CONSOLE_VIEW", nullptr, 0) != 0; + const bool console_gate = GetEnvironmentVariableW(L"X2W_TEST_CONSOLE_GATE", nullptr, 0) != 0; + const bool bc = console_view || console_gate || GetEnvironmentVariableW(L"X2W_TEST_BC_VIEW", nullptr, 0) != 0; const bool bc_chain = GetEnvironmentVariableW(L"X2W_TEST_BC_CHAIN", nullptr, 0) != 0; const bool integer = format == DXGI_FORMAT_R32_UINT || format == DXGI_FORMAT_R32_SINT; // The translated MRT formats draw one pixel; the other formats keep the 8x4 target. @@ -322,7 +324,51 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* if (bc7) invoke(list, 36, 0, binding.table); invoke(list, 12, 3, 1); } - if (bc) { + if (console_view) { + extern int draw_console_address_srv(void*, void*); + if (const int result = draw_console_address_srv(guest, list)) return result; + } else if (console_gate) { + // X2W_TEST_CONSOLE_GATE: the queue waits on a fence this fixture holds while eighteen lists are + // recorded and submitted on one list object, each after a new payload was written at the same + // address (draw_gated_console_payload). Nothing may complete before the fence is signalled; the + // target is read back after the last submit has completed. + extern int draw_gated_console_payload(void*, void*, unsigned, bool); + constexpr unsigned payloads = 18; + void* gate = nullptr; + if (FAILED(static_cast(invoke(guest, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&gate))))) return 44; + if (FAILED(static_cast(invoke(queue, 17, arg(gate), 1)))) return 45; + D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast(invoke(frame.rtv_heap, 9))}; + const auto next_recording = [&] { + if (FAILED(static_cast(invoke(frame.allocator, 8))) || + FAILED(static_cast(invoke(list, 139, arg(frame.allocator))))) return false; + invoke(list, 50, 1, arg(&rtv)); + invoke(list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + invoke(list, 25, arg(pso)); + return true; + }; + for (unsigned payload = 0; payload < payloads; ++payload) { + if (payload && !next_recording()) return 35; + if (const int result = draw_gated_console_payload(guest, list, payload, payload == 0)) return result; + invoke(list, 9); + invoke(queue, 10, 1, arg(&list)); + if (FAILED(static_cast(invoke(queue, 14, arg(fence), payload + 1)))) return 24; + } + Sleep(250); + if (invoke(fence, 8) != 0) return 46; // a submit completed although the queue was held + if (FAILED(static_cast(invoke(gate, 10, 1)))) return 47; + // One more recording without a draw: its submit is where the stand-in visits the completed ones. + const auto reached = [&](UINT64 value) { + const auto deadline = GetTickCount64() + 60000; + while (invoke(fence, 8) < value && GetTickCount64() < deadline) Sleep(1); + return invoke(fence, 8) == value; + }; + if (!reached(payloads)) return 25; + if (!next_recording()) return 35; + invoke(list, 9); + invoke(queue, 10, 1, arg(&list)); + if (FAILED(static_cast(invoke(queue, 14, arg(fence), payloads + 1))) || !reached(payloads + 1)) return 25; + return read_stream_target(desktop.Get(), frame, pixels); + } else if (bc) { extern int draw_bc_address_srvs(void*, void*); if (const int result = draw_bc_address_srvs(guest, list)) return result; }