Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 48 additions & 6 deletions docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -11789,11 +11789,32 @@ ctest --preset release --no-tests=error -R '^(startup_memory_srv_report|startup_

The translated draw path can sample a read-only BC3_UNORM or BC7_UNORM SRV
published through device slot 70 without a prior resource object. The tested
layout is 0x105, 4 KiB standard non-XOR. Width and height must be multiples of
64 texels, with one mip, one slice, and one sample. Each tile holds 16 by 16
compressed blocks. The runtime copies the 16-byte blocks to their desktop
footprint rows before uploading them. Ordinary placed R8 views and the XG
BC7 layout probe retain their existing behavior.
layout is 0x105, 4 KiB standard non-XOR. Width and height must be whole 4x4
blocks, with one mip, one slice, and one sample. Each tile holds 16 by 16
compressed blocks. A partial last tile column or row is padded to a whole tile,
as AMD addrlib does for a single-mip thin surface (Mesa
`5c142e46f3f6e752ed745fd48912ebb8fad67145`, `src/amd/addrlib/src/gfx10/gfx10addrlib.cpp`):
`ComputeSurfaceInfoMacroTiled` aligns pitch and height to the block size, with
no mip tail for one mip, and `ComputeSurfaceAddrFromCoordMacroTiled` takes a
block's tile index as its block row times the tiles per padded pitch, plus its
block column. The runtime copies the visible 16-byte blocks to their desktop
footprint rows before uploading them. Ordinary placed R8 views and the XG BC7
layout probe retain their existing behavior.

A view with a partial last tile stays refused in two cases. The first is when
the last copy the XG stand-in announced to that address wrote desktop-footprint
rows, not tiles, whether that copy came before the first publication there or
after it. A copy from the opt-in BC7 4 KiB layout writes tiles and does not hold
the view. A row copy leaves previously published descriptor bytes intact,
and the translated sampler binds a null texture while the last write is a row
copy. It can sample the view again after a tiled write is announced.
The second is when the padded tiles are larger than the size the XG stand-in
reports for the description (the desktop footprint rounded to 64 KiB): the
bytes past that size may belong to something else, and a readability probe
cannot tell. For example, 1028 by 1028 pads to 1,183,744 bytes against a
reported 1,179,648. The first publication at an address of a partial-tile view
logs its size, format, tiled byte count, and how many of the first and last
4 KiB are non-zero, with a hash; a refused one logs its reason instead.

Keep the complete tiled guest allocation readable for the view's sampling
lifetime. The producer stores the view identity in the title heap. The
Expand All @@ -11810,9 +11831,30 @@ RTX 4060 Laptop (32.0.16.1656) and WARP (10.0.26100.9818) each matched
65,536 RGBA pixels per format. The swapped-tile control changed 16,384
of 16,384 pixels for BC3 and 15,360 for BC7.

The same test draws a 100 by 68 texture of each format from the same four
tiles, whose last tile column and row are partial. The padding blocks hold
distinct valid blocks; texels outside the texture must load as zero, and the
log must report 16,384 tiled bytes. A reference that uses the tile pitch of the
unpadded width (one tile instead of two) differs from the image in 1,600 pixels
for BC3 and 1,500 for BC7. The test also requires refusals for 98 by 68 and
100 by 66 (not whole blocks), 1028 by 1028 (past the reported size) and a
100 by 68 view over memory announced as an XG copy, and a second request for a
100 by 68 address after a row copy over its published view; that request must
leave the destination descriptor naming the view it held. A draw through the
already-published token after a row write must read zero. The test requires publication of
a 256 by 196 view, whose padded size equals the reported 64 KiB and whose width
is whole tiles, and of a 100 by 68 view over memory announced by the opt-in BC7
copy. Each of these changes makes the test fail: restoring the 64-texel check,
dropping the height check, requiring both dimensions to be partial, refusing at
an equal size, dropping the announced-copy refusal, ignoring which copy was
announced, or rounding the tile rows down in `Bc16Surface`. The last also fails
`startup_bc7_4k_s`. On Windows 11 build
26300 with the debug layer off, RTX 5090 (32.0.16.2135) and WARP
(10.0.26100.10068) matched all 65,536 RGBA pixels per case.

```powershell
cmake --build --preset release --target startup_stream_consumer startup_stub_consumer d3d12_xs_shim
ctest --preset release --no-tests=error --output-on-failure -R '^(startup_address_(bc_view|srv)_(hardware|warp)|startup_xg_bc7_layout|bc7_tile_swizzle)$'
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)$'
```

### Six BC5/BC7 mips on a 64 KiB standard layout
Expand Down
75 changes: 72 additions & 3 deletions src/startup_stubs/d3d12_memory_srv.inl
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,42 @@ bool tiled_bc_srv(const D3D12_RESOURCE_DESC& r)
static_cast<UINT>(r.Layout) == 0x105 && r.Alignment == 0 &&
(r.Flags == D3D12_RESOURCE_FLAG_NONE || static_cast<UINT>(r.Flags) == 0x300000) &&
r.Width <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && r.Height <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION &&
r.Width % 64 == 0 && r.Height % 64 == 0;
// A single mip pads its pitch and height to whole 4 KiB tiles (Bc16Surface); the desktop
// texture needs whole 4x4 blocks.
r.Width && r.Height && r.Width % 4 == 0 && r.Height % 4 == 0;
}

// One line for the first publication of a view whose last tile row or column is partial. A published
// view gets a content summary, so a title run can tell console-tiled data from zeros; a held one names
// why it stays refused.
void log_partial_tile_view(const D3D12_RESOURCE_DESC& r, u64 address, const char* held, bool published)
{
static LONG lines, unpublished;
const auto bytes = x2w_startup::Bc16Surface(r).size();
if (!published) {
if (first_calls(unpublished, 8))
log("x2w-d3d12 Device::slot70 partial-tile BC view %llux%u format %d layout 0x%x: %s, %llu tiled bytes",
r.Width, r.Height, r.Format, static_cast<unsigned>(r.Layout), held ? held : "texture_unavailable", bytes);
return;
}
if (!first_calls(lines, 64)) return;
const auto* data = reinterpret_cast<const unsigned char*>(address);
const auto nonzero = [&](u64 from) {
unsigned count = 0;
for (u64 i = from; i < from + 4096; ++i) count += data[i] != 0;
return count;
};
// publish_tiled_texture already found the whole range readable.
log("x2w-d3d12 Device::slot70 partial-tile BC view %llux%u format %d layout 0x%x: published, %llu tiled bytes, "
"nonzero first/last 4 KiB %u/%u hash %016llx", r.Width, r.Height, r.Format, static_cast<unsigned>(r.Layout),
bytes, nonzero(0), nonzero(bytes - 4096), hash_memory(data, static_cast<std::size_t>(bytes)));
}

// The size the XG stand-in reports for a description: desktop copyable footprints rounded to 64 KiB.
u64 xg_reported_bytes(Wrapper* device, const D3D12_RESOURCE_DESC& desc)
{
const x2w_startup::SliceFootprints plan(device_of(device), sanitized(desc), 1);
return plan.size == UINT64_MAX ? 0 : (plan.size + 0xFFFF) & ~u64{0xFFFF};
}

bool supports_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v)
Expand Down Expand Up @@ -133,6 +168,20 @@ struct TiledAddressTexture {
std::unordered_map<Wrapper*, TiledAddressTexture> tiled_srv_textures;
std::unordered_multimap<u64, Wrapper*> tiled_srv_addresses;

bool partial_tiled_bc(const D3D12_RESOURCE_DESC& desc)
{
return tiled_bc_srv(desc) && (desc.Width % 64 || desc.Height % 64);
}

bool latest_texture_write_is_rows(u64 address)
{
AcquireSRWLockShared(&written_lock);
const auto found = written_textures().find(address);
const bool rows = found != written_textures().end() && found->second.desktop_rows;
ReleaseSRWLockShared(&written_lock);
return rows;
}

Wrapper* publish_tiled_texture(Wrapper* device, u64 address, const D3D12_RESOURCE_DESC& desc)
{
const auto bytes = x2w_startup::bc64::supports(desc) ? x2w_startup::bc64::Chain(desc).bytes() : x2w_startup::Bc16Surface(desc).size();
Expand Down Expand Up @@ -164,6 +213,10 @@ ID3D12Resource* sampled_address_texture(Wrapper* resource)
if (!resource->own().tiled_address_srv) return static_cast<ID3D12Resource*>(resource->own().real);
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) &&
latest_texture_write_is_rows(reinterpret_cast<u64>(resource->own().title_memory)))
return nullptr;
if (!sampled.desktop) {
const auto desc = sanitized(sampled.desc);
const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT};
Expand Down Expand Up @@ -230,11 +283,27 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou
view_slot<18, 2>(self, reinterpret_cast<u64>(buffer), reinterpret_cast<u64>(&adjusted), destination, 0);
return;
}
Wrapper* texture = (tiled_bc_srv(*resource) || x2w_startup::bc64::supports(*resource)) ? publish_tiled_texture(self, input->address, *resource)
// A partial-tile view stays refused when the last XG stand-in copy to the address wrote desktop-footprint
// rows, or when its padded tiles run past the size the stand-in reported, which the title may not own.
bool first = false;
const char* held = nullptr;
if (partial_tiled_bc(*resource)) {
{
std::lock_guard lock(tiled_srv_mutex);
first = !tiled_srv_addresses.count(input->address);
}
if (latest_texture_write_is_rows(input->address)) held = "partial_tile_xg_rows";
else if (x2w_startup::Bc16Surface(*resource).size() > xg_reported_bytes(self, *resource))
held = "partial_tile_beyond_xg_size";
}
Wrapper* texture = held ? nullptr
: (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);
if (!texture) {
if (first_calls(refused, 8))
log_refused_memory_srv("unavailable texture at the supplied base and layout", "texture_unavailable", resource, input, destination);
log_refused_memory_srv("unavailable texture at the supplied base and layout", held ? held : "texture_unavailable",
resource, input, destination);
return;
}
view_slot<18, 2>(self, reinterpret_cast<u64>(texture), reinterpret_cast<u64>(&input->view), destination, 0);
Expand Down
2 changes: 2 additions & 0 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2384,6 +2384,7 @@ extern SRWLOCK written_lock;
struct TextureWrite {
u64 generation = 0;
UINT bc7_width = 0, bc7_height = 0;
bool desktop_rows = false; // the last XG copy wrote desktop-footprint rows (not the opt-in BC7 tiles)
};
std::unordered_map<u64, TextureWrite>& written_textures();
ID3D12Resource* sampled_address_texture(Wrapper* resource);
Expand Down Expand Up @@ -3816,6 +3817,7 @@ void note_texture_write(void* base, UINT bc7_width, UINT bc7_height)
++written.generation;
written.bc7_width = bc7_width;
written.bc7_height = bc7_height;
written.desktop_rows = !bc7_width;
ReleaseSRWLockExclusive(&written_lock);
}
} // namespace
Expand Down
132 changes: 106 additions & 26 deletions tests/startup_address_bc_view_check.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
"""Draw 2×2 4 KiB tiled BC3/BC7 textures from guest addresses, including swapped tiles."""
from pathlib import Path
import re
import struct
import subprocess
import sys
import tempfile

from bc7_draw_check import make_block as bc7_block
from bc7_tiles_check import block_index
from startup_address_srv_check import draw_texture
from startup_address_srv_check import prepare_draw_cache

WIDTH, HEIGHT = 128, 128
HLSL = ("Texture2D<float4> t : register(t0);\n"
"float4 main(float4 p : SV_Position) : SV_Target {\n"
f" return t.Load(int3(uint(p.x) % {WIDTH}, uint(p.y), 0));\n}}\n")


def bc3_block(x, y):
Expand All @@ -35,42 +40,117 @@ def make_surface(encode):
return tiled, rgba


def check(directory, consumer, backend, fmt):
def source_block(x, y, tile_pitch, swapped):
"""The block of the 2x2 tile grid that a detile with this tile pitch shows at block (x, y)."""
tile = (y // 16) * tile_pitch + x // 16
tile ^= swapped
return (tile % 2) * 16 + x % 16, (tile // 2) * 16 + y % 16


def expected_panels(rgba, width, height, tile_pitch):
"""Four panels of 128x128 texels. A partial view with a later row write reads as null."""
image = bytearray(4 * WIDTH * 4 * HEIGHT)
for panel, swapped in enumerate((0, 1, 1, 0)):
if panel == 3 and (width % 64 or height % 64):
continue
for y in range(height):
for x in range(width):
bx, by = source_block(x // 4, y // 4, tile_pitch, swapped)
start = 4 * ((by * 4 + y % 4) * 128 + bx * 4 + x % 4)
pos = 4 * (y * 4 * WIDTH + panel * WIDTH + x)
image[pos:pos + 4] = rgba[start:start + 4]
return bytes(image) # texels outside the texture load as zero


class Drawer:
"""Translates the pipeline once, then draws each case with the same shader cache."""

def __init__(self, directory, consumer, backend):
self.directory, self.consumer, self.backend, self.prepared = directory, consumer, backend, None

def __call__(self, modes):
if self.prepared is None:
self.prepared = prepare_draw_cache(self.directory, self.consumer, HLSL, modes, "srv 0 tex2d table 0 0")
env, args, output = self.prepared
output.unlink(missing_ok=True) # no case reads the previous case's pixels
env = {key: value for key, value in env.items() if key != "X2W_TEST_BC3"} # the consumer tests presence
result = subprocess.run([*args, self.backend, output], env={**env, **modes}, capture_output=True, text=True)
print(result.stdout, end="")
if result.returncode == 77:
return None
if result.returncode:
raise RuntimeError(f"consumer failed ({result.returncode})\n{result.stderr[-5000:]}")
return output.read_bytes()


def check(directory, draw, backend, fmt, width, height):
tiled, rgba = make_surface(bc3_block if fmt == "BC3" else bc7_block)
source = directory / "tiled.bin"
source.write_bytes(tiled)
hlsl = ("Texture2D<float4> t : register(t0);\n"
"float4 main(float4 p : SV_Position) : SV_Target {\n"
f" return t.Load(int3(uint(p.x) % {WIDTH}, uint(p.y), 0));\n}}\n")
modes = {"X2W_TEST_BC_VIEW": str(source)}
trap_log = directory / "trap.log"
modes = {"X2W_TEST_BC_VIEW": str(source), "X2W_TEST_BC_SIZE": f"{width}x{height}", "X2W_TRAP_LOG": str(trap_log)}
if fmt == "BC3":
modes["X2W_TEST_BC3"] = "1"
actual = draw_texture(directory, consumer, backend, hlsl, modes)
actual = draw(modes)
if actual is None:
return 77
if len(actual) != WIDTH * 4 * HEIGHT * 4:
raise AssertionError(f"{fmt} readback length {len(actual)}")
different = 0
for y in range(HEIGHT):
for x in range(WIDTH):
normal = 4 * (y * 128 + x)
swapped = 4 * (y * 128 + (x ^ 64))
different += rgba[normal:normal + 4] != rgba[swapped:swapped + 4]
for panel, source_index in enumerate((normal, swapped, swapped, normal)):
pos = 4 * ((y * 4 + panel) * WIDTH + x)
pixel = actual[pos:pos + 4]
expect = rgba[source_index:source_index + 4]
if pixel != expect:
raise AssertionError(f"{fmt} panel {panel} ({x},{y}) actual {pixel.hex()} expected {expect.hex()}")
if different == 0:
expected = expected_panels(rgba, width, height, 2)
for pos in range(0, len(expected), 4):
if actual[pos:pos + 4] != expected[pos:pos + 4]:
y, x = divmod(pos // 4, 4 * WIDTH)
raise AssertionError(f"{fmt} {width}x{height} panel {x // WIDTH} ({x % WIDTH},{y}) "
f"actual {actual[pos:pos + 4].hex()} expected {expected[pos:pos + 4].hex()}")
# Controls: exchanged tiles, and for a partial last tile column the tile pitch of the unpadded width.
swapped = sum(expected[p:p + 4] != expected[p + 4 * WIDTH:p + 4 * WIDTH + 4]
for p in range(0, len(expected), 4) if (p // 4) % (4 * WIDTH) < WIDTH)
if swapped == 0:
raise AssertionError("Swapping the tiles did not change the reference image")
print(f"{backend} {fmt}: {4 * WIDTH * HEIGHT} RGBA pixels exact; exchanged tiles differ in {different}/{WIDTH * HEIGHT}")
columns = width // 4
unpadded = 0
if columns % 16:
wrong = expected_panels(rgba, width, height, columns // 16)
unpadded = sum(actual[p:p + 4] != wrong[p:p + 4] for p in range(0, len(actual), 4))
if unpadded == 0:
raise AssertionError("The unpadded tile pitch did not change the image")
log = trap_log.read_text(errors="replace")
code = 77 if fmt == "BC3" else 98
partial = width % 64 or height % 64
tiled_bytes = 16384 # 2 x 2 tiles of 4 KiB, partial or not
refusals = [("unsupported_description", width - 2, height), ("unsupported_description", width, height - 2),
("partial_tile_beyond_xg_size", 1028, 1028)]
if partial:
refusals.append(("partial_tile_xg_rows", width, height))
for reason, w, h in refusals:
if not re.search(rf"Device::slot70 .*: reason={reason} res\{{dim=3 fmt={code} size={w}x{h}x1 ", log):
raise AssertionError(f"{fmt}: no {reason} refusal for {w}x{h}")
lines = re.findall(r"partial-tile BC view (\d+x\d+) format \d+ layout 0x105: (\w+), (\d+) tiled bytes", log)
# One line per first publication at an address: the first backing and the exchanged one, the 256x196
# boundary (padded size equal to the reported size), the backing announced as XG rows (refused), the
# one announced as opt-in tiled BC7 blocks, and the one published before an XG row copy over it.
view = f"{width}x{height}"
boundary = [("256x196", "published", "65536")]
published = (view, "published", str(tiled_bytes))
expected = ([published] * 2 + boundary + [(view, "partial_tile_xg_rows", str(tiled_bytes)), published, published]
if partial else boundary)
# Rows announced before the first publication, and rows copied over a published view: both refused.
held = re.findall(rf"reason=partial_tile_xg_rows res\{{dim=3 fmt={code} size={view}x1 ", log)
if len(held) != (2 if partial else 0):
raise AssertionError(f"{fmt}: {len(held)} partial_tile_xg_rows refusals for {view}")
if lines != expected:
raise AssertionError(f"{fmt}: partial-tile lines {lines}, expected {expected}")
print(f"{backend} {fmt} {width}x{height}: {4 * WIDTH * HEIGHT} RGBA pixels exact; exchanged tiles differ in "
f"{swapped} texels; unpadded tile pitch differs in {unpadded}; {len(refusals)} refusals as expected")
return 0


if __name__ == "__main__":
for fmt in ("BC3", "BC7"):
with tempfile.TemporaryDirectory() as temporary:
result = check(Path(temporary), *sys.argv[1:], fmt)
if result:
sys.exit(result)
consumer, backend = sys.argv[1:3]
with tempfile.TemporaryDirectory() as shared:
draw = Drawer(Path(shared), consumer, backend)
for fmt, width, height in (("BC3", 128, 128), ("BC7", 128, 128), ("BC3", 100, 68), ("BC7", 100, 68)):
with tempfile.TemporaryDirectory() as temporary:
result = check(Path(temporary), draw, backend, fmt, width, height)
if result:
sys.exit(result)
Loading
Loading