Compare commits

..
Author SHA1 Message Date
ates 655102c06c Merge origin/main into track-c/782-implicit-shadows
Conflicts with #781, #787 and #791: gpu_writes.cpp keeps #791's in-order execute and calls bx_xbox_placed_note_submission first; placed_x.cpp keeps the flat buffer-view block and marks it with bx_console_mark_cbv_of(..., resource); test_d3d12_console_texture_contents has three views and reads back the two placed textures in round 2; CHANGELOG.md keeps both sides.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-02 02:30:18 +03:00
ates 9c92845fae Merge origin/main into track-c/782-implicit-shadows
CHANGELOG conflict with #778's entry: both entries kept.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-01 18:51:52 +03:00
ates 58956469ef CHANGELOG: one host storage per placed texture; implicit shadows released (#782)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-01 18:42:54 +03:00
ates f76b60f162 d3d12_xs: a placed texture's contents live in its host texture, not a side copy (#782, #745)
On the console a placed texture has one storage. Its contents from title memory are now uploaded into the host shadow itself (read-only shadows are made with simultaneous access, so the upload promotes them from COMMON without barriers that contradict the title's), and the side copy is dropped: every view and copy command of the texture sees the texels, and a drawn texture no longer occupies a second host texture. test_d3d12_console_texture_contents copies each placed texture out after a translated draw has read it and checks every texel (both fail with the side copy).

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-01 18:39:24 +03:00
ates c545d15530 d3d12_xs: release a texture copy's upload buffer once the GPU has copied from it (#782)
A texture's upload buffer (as large as the texture) was kept for the life of its copy. It is now released once the copy's fence has passed and made again only when a later check finds the title memory changed.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-01 17:49:33 +03:00
ates 714d90baf8 d3d12_xs: release implicit shadows the title has replaced (#782)
CreatePlacedRawShaderResourceViewX / CreatePlacedRawUnorderedAccessViewX
back each view of placed memory with a host resource of the shim's own,
made per (address, shape) and kept for the life of the process. The
target build streams textures and buffers through recycled memory: about
58,000 such resources a minute, an 11 GB footprint after about 140 s.

A new view whose title memory overlaps an older implicit shadow of
another address or shape now retires that shadow: the title reuses
memory only once it no longer uses the old contents. The host resource
is released 64 queue submissions later, as a margin for host work in
flight; its texture-contents copy is retired through its own fence;
translated-draw markers of it stop referencing it and resolve to null
views; a constant view whose fallback lay in it falls back to a null
view instead. Releases are logged as `implicit_shadows` when the total
passes a power of two.

test_d3d12_placed_implicit_release views four slots 256 times with new
shapes: 256 resources made, at most 4 live, at least 128 released, and a
view with the live shadow's address and shape reuses it.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-01 17:30:13 +03:00
ates d18c2d514a d3d12_xs: claim #782 (host resources for placed raw views are never released)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-12-01 17:21:41 +03:00
10 changed files with 590 additions and 103 deletions

No files matched your search

+6
View File
@@ -10,6 +10,12 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Fixed
- **`d3d12_xs.dll`: a placed texture has one host storage; host resources for title memory are released** (#782, #745).
- **One storage per texture.** A texture placed in title memory now gets its contents uploaded into its host shadow itself, not into a side copy. On the console a placed texture has one storage, and now every view and copy command of it sees the texels; before, only views resolved for translated draws did, and copy commands read an empty texture. Read-only shadows are made with simultaneous access, so the upload promotes them from COMMON without barriers that contradict the title's own. A drawn texture no longer occupies a second host texture.
- **Upload buffers.** A texture's upload buffer is released once the GPU has copied from it, and made again only if a later check finds the title memory changed.
- **Implicit shadows.** `CreatePlacedRawShaderResourceViewX` and `CreatePlacedRawUnorderedAccessViewX` back each view with a host resource of the shim's own, which was made per (address, shape) and kept for the life of the process. A new view whose title memory overlaps an older implicit shadow of another address or shape now retires that shadow. The host resource is released 64 queue submissions later. Translated-draw markers of it then resolve to null views, and a constant view's fallback that lay in it is dropped.
- **Effect on memory.** The target build's footprint on a 16 GB Mac (Series S profile) is about the same as before, 10 to 11 GB after about two minutes. Most of it is the title's own memory and one host texture per placed texture, which this design needs.
- **Tests.** `test_d3d12_console_texture_contents` copies each placed texture out after a translated draw and checks every texel. `test_d3d12_placed_implicit_release` views four slots 256 times with new shapes and checks that at most one host resource per slot stays live.
- **`d3d12_xs`: GPU value writes and waits in title memory take effect in list order, and Execute no longer blocks on them** (#773). `Wait32/64BitValueX` were all evaluated on the CPU before a submission went to the host (a busy loop of up to 10 s each), and every `Write*BitValue*X` was stored only after the host had finished the whole submission, so each Execute that carried a write waited for the GPU, and a wait on a write earlier in the same submission could only time out. A submission that carries them is now split at its lists: a list's waits hold the host queue on a fence before it (the fence slot itself, or a fence a per-queue worker signals once the value holds, checked with sleeps instead of a spin), and its writes are stored by that worker when the host GPU has finished the list. Inside one list, waits still count as being at its start and writes at its end. New test `test_d3d12_gpu_value_order` (a wait on a write earlier in the same submission, a wait on a value the CPU stores later, two writes to one address).
- **`d3d12_xs`: `GetResourceAllocationInfo` answers textures with `Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN` in the console's default tiling** (#708). On the console `UNKNOWN` selects the default tiling mode (GDK documentation of `XG_RESOURCE_DESC::Layout`), but `d3d12_xs` passed such textures to the host, which has no console tiling. The target build sizes some of its loads that way (call-site observation): a 128x4 `R16G16B16A16_UNORM` texture came back as 4096 bytes where the GDK's XG gives 16384 (4 KB tiles, layout `0x105`), so it asked for a quarter of a 16 KB compressed chunk; its loader asserts on that, and `XCRDAPI.dll` refused the 47 such requests per run. With the GDK's XG loaded, these textures now get XG's size and alignment for the layout as given, as #710 does for explicit console layouts; buffers keep the host's answer. `test_d3d12_gdk_xg_sizes` checks an `UNKNOWN`-layout texture and uses a buffer as the host-answered case.
- **`chad.dll`: `XDspConnectWithMaximumStreamLimit` connects again, so the target build no longer stops after 64 frames** (follow-up to #780). Since #780 connecting was refused with `E_NOTIMPL`, and the target build then hits its own assert a few seconds later and exits with status 3 (every default run; the same `main` with the earlier `chad.dll` runs on). Connecting now succeeds with a placeholder client handle and is logged as not modelled (`BX_STUB_LOG`); activating a stream on it is refused with `E_NOTIMPL`, and `XDspDisconnect` closes it. The prototypes from #780 stay, so nothing is written outside the documented outputs. `test_audio_input` and `test_integration_boot` check the new answers.
+52 -9
View File
@@ -24,8 +24,9 @@
* known here): a title that reads its descriptors back, rather than only copying them, would
* see it. Entries without a marker are left as the host heap has them and are logged.
*
* Limits, logged when met: a registered texture is kept referenced for the life of the process;
* a table changed between a draw and the submission of its list is read at submission.
* Limits, logged when met: a registered texture is kept referenced until the shim releases it
* (placed_x.cpp releases implicit shadows the title has replaced; their markers then resolve to null
* views); a table changed between a draw and the submission of its list is read at submission.
*/
#include "console_pipelines.h"
@@ -77,15 +78,21 @@ struct View {
std::mutex g_view_lock;
std::vector<View> g_views(1); // id 0 is never used
std::vector<std::string> g_view_keys(1);
std::unordered_map<std::string, uint32_t> g_view_ids;
std::unordered_map<const ID3D12Resource*, std::vector<uint32_t>> g_views_of; // resource -> ids of its views
uint32_t intern(const std::string& key, const View& view) {
/* `owner`: the resource the view depends on, when the shim may release it early; an SRV's own
resource otherwise. */
uint32_t intern(const std::string& key, const View& view, ID3D12Resource* owner = nullptr) {
std::lock_guard<std::mutex> guard(g_view_lock);
auto it = g_view_ids.find(key);
if (it != g_view_ids.end()) return it->second;
const uint32_t id = static_cast<uint32_t>(g_views.size());
g_views.push_back(view);
g_view_keys.push_back(key);
if (view.resource) view.resource->AddRef();
if (const ID3D12Resource* index = owner ? owner : view.resource) g_views_of[index].push_back(id);
g_view_ids.emplace(key, id);
return id;
}
@@ -159,21 +166,28 @@ void resolve(ID3D12Device* device, const char* key, const BxConsoleUse& use, uin
std::lock_guard<std::mutex> guard(g_view_lock);
ok = words[1] != 0 && words[1] < g_views.size();
if (ok) view = g_views[words[1]];
// Held for this resolve: bx_console_forget_resource may drop the registry's reference.
if (ok && view.resource) view.resource->AddRef();
}
const D3D12_CPU_DESCRIPTOR_HANDLE host = bx_xbox_host_cpu_handle({static_cast<SIZE_T>(entry)});
uint64_t total = 0;
// A view whose resource the shim has released (an implicit shadow the title replaced) resolves
// to a null view: never to memory that is gone.
const bool released = ok && view.texture && !view.resource;
if (ok && !use.texture && !view.texture) {
D3D12_CONSTANT_BUFFER_VIEW_DESC copy{};
// Fresh bytes from title memory when it can be read; otherwise the view as created.
// Fresh bytes from title memory when it can be read; otherwise the view as created, or a
// null view when the buffer behind it has been released.
if (constant_copy(device, view.title_va, view.cbv.SizeInBytes, &copy)) {
device->CreateConstantBufferView(&copy, host);
} else {
device->CreateConstantBufferView(&view.cbv, host);
device->CreateConstantBufferView(view.cbv.BufferLocation ? &view.cbv : nullptr, host);
}
++g_resolved;
} else if (ok && use.texture && view.texture) {
} else if (ok && use.texture && view.texture && !(released && !view.has_srv_desc)) {
// A texture placed in title memory is read through a copy of its contents (#745).
device->CreateShaderResourceView(bx_xbox_texture_contents(view.resource, uploads), view.has_srv_desc ? &view.srv : nullptr, host);
ID3D12Resource* contents = released ? nullptr : bx_xbox_texture_contents(view.resource, uploads);
device->CreateShaderResourceView(contents, view.has_srv_desc ? &view.srv : nullptr, host);
++g_resolved;
} else if (sampled(g_unmarked, &total)) {
log(BX_LOG_WARN, "console_descriptor",
@@ -183,11 +197,13 @@ void resolve(ID3D12Device* device, const char* key, const BxConsoleUse& use, uin
ok ? "a view of the other kind" : "no view this layer created", words[0], words[1], words[2], words[3],
static_cast<unsigned long long>(total), static_cast<unsigned long long>(g_resolved.load()));
}
if (ok && view.resource) view.resource->Release();
}
} // namespace
void bx_console_mark_cbv(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc) {
void bx_console_mark_cbv_of(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc,
ID3D12Resource* owner) {
if (!bx_console_shaders_enabled() || !title_handle) return;
View view;
view.cbv = host_desc;
@@ -195,7 +211,34 @@ void bx_console_mark_cbv(uint64_t title_handle, uint64_t title_va, const D3D12_C
char key[80];
std::snprintf(key, sizeof(key), "c%llx:%llx:%u", static_cast<unsigned long long>(title_va),
static_cast<unsigned long long>(host_desc.BufferLocation), host_desc.SizeInBytes);
write_marker(title_handle, intern(key, view));
write_marker(title_handle, intern(key, view, owner));
}
void bx_console_mark_cbv(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc) {
bx_console_mark_cbv_of(title_handle, title_va, host_desc, nullptr);
}
void bx_console_forget_resource(ID3D12Resource* resource) {
if (!resource) return;
std::vector<ID3D12Resource*> references;
{
std::lock_guard<std::mutex> guard(g_view_lock);
auto it = g_views_of.find(resource);
if (it == g_views_of.end()) return;
for (const uint32_t id : it->second) {
View& v = g_views[id];
if (v.resource == resource) {
references.push_back(resource);
v.resource = nullptr;
}
if (!v.texture) v.cbv.BufferLocation = 0; // the fallback lay in the released buffer
// A new view made later with the same description gets a new id.
auto key = g_view_ids.find(g_view_keys[id]);
if (key != g_view_ids.end() && key->second == id) g_view_ids.erase(key);
}
g_views_of.erase(it);
}
for (ID3D12Resource* r : references) r->Release();
}
void bx_console_mark_srv(uint64_t title_handle, ID3D12Resource* host, const D3D12_SHADER_RESOURCE_VIEW_DESC* host_desc) {
+7
View File
@@ -60,7 +60,14 @@ bool bx_console_pipeline_info(BxConsolePipeline* pipeline, ID3D12Device** device
/* console_descriptors.cpp: descriptors the title copies itself. `title_handle` is the title's
descriptor handle (an address in its descriptor memory). */
void bx_console_mark_cbv(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc);
/* As bx_console_mark_cbv, for a constant view whose host fallback lies in `owner`, a resource the
shim may release early (bx_console_forget_resource). */
void bx_console_mark_cbv_of(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc,
ID3D12Resource* owner);
void bx_console_mark_srv(uint64_t title_handle, ID3D12Resource* host, const D3D12_SHADER_RESOURCE_VIEW_DESC* host_desc);
/* The shim is releasing `resource` (placed_x.cpp, implicit shadows): views marked with it stop
referencing it. A marker of such a view resolves to a null view from then on. */
void bx_console_forget_resource(ID3D12Resource* resource);
/* Direct3D copied `count` descriptors between title handles: the title-side bytes follow. */
void bx_console_copy_title(uint64_t dest, uint64_t src, UINT count);
void bx_console_note_table(ID3D12GraphicsCommandList* list, UINT param, uint64_t title_handle);
+1
View File
@@ -242,6 +242,7 @@ void execute(void* self, UINT count, ID3D12CommandList* const* lists) {
auto* queue = bx_xbox_host<ID3D12CommandQueue>(self);
BxXboxUnwrapArray<ID3D12CommandList> host(lists, count);
if (!host.ok()) return;
bx_xbox_placed_note_submission(); // releases implicit shadows replaced long enough ago (#782)
std::vector<std::vector<Write>> ops(count);
bool any = false;
{
+253 -88
View File
@@ -44,6 +44,9 @@ struct Shadow {
D3D12_RESOURCE_DESC desc;
ULONGLONG title_attributes; // non-zero: title_va came from XMemAlloc and is freed with the resource
int mapped = 0; // outstanding Map calls on title memory (buffers)
bool implicit = false; // made for a view of placed memory (implicit_shadow); owned by this table
bool simultaneous = false; // texture made with D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS
uint64_t span = 0; // implicit: the bytes of title memory the resource covers
};
// Copies between a buffer's title memory and its host resource, when the host is CPU-mappable.
@@ -106,9 +109,26 @@ HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURC
bx_note_console_format(desc.Format, "CreatePlacedResourceX");
host_desc.Format = bx_host_resource_format(desc.Format);
}
// A texture the GPU never writes gets its contents from title memory, uploaded into it by the
// shim (bx_xbox_texture_contents). Simultaneous access lets that copy promote the texture from
// COMMON without barriers of the shim's own against the states the title's barriers name.
constexpr UINT kGpuWrites = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL |
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
const bool simultaneous = !buffer && host_desc.SampleDesc.Count <= 1 && !(static_cast<UINT>(host_desc.Flags) & kGpuWrites);
if (simultaneous) host_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS;
ID3D12Resource* resource = nullptr;
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &host_desc, D3D12_RESOURCE_STATE_COMMON,
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
bool made_simultaneous = simultaneous && SUCCEEDED(hr);
if (simultaneous && FAILED(hr)) { // the host refuses the flag: without it, uploads use barriers from COMMON
static std::atomic<bool> noted{false};
if (!noted.exchange(true)) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "placed_x_shadow", "the host refuses simultaneous access on a texture; made without it");
}
host_desc.Flags = static_cast<D3D12_RESOURCE_FLAGS>(host_desc.Flags & ~D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS);
hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &host_desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
}
char detail[224];
std::snprintf(detail, sizeof(detail), "%s title_va=0x%llx dim=%d width=%llu height=%u format=%d hr=0x%08lx",
method, static_cast<unsigned long long>(title_va), static_cast<int>(desc.Dimension),
@@ -132,7 +152,9 @@ HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURC
// Contents are copied only for views of translated draws (bx_xbox_texture_contents).
BX_STUB_LOG("d3d12_xs.dll", "CreatePlacedResourceX(texture contents)");
}
if (!remember({resource, title_va, desc.Width, buffer, desc, 0})) {
Shadow record{resource, title_va, desc.Width, buffer, desc, 0};
record.simultaneous = made_simultaneous;
if (!remember(record)) {
resource->Release();
return E_OUTOFMEMORY;
}
@@ -156,17 +178,63 @@ bool same_shape(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) {
a.DepthOrArraySize == b.DepthOrArraySize && a.MipLevels == b.MipLevels && a.Format == b.Format;
}
// A view of placed memory with no resource object: reuse the shadow made for the same address
// and shape, or make one. These shadows live for the rest of the process (logged).
// The bytes of title memory a placed resource of `desc` covers: XG's size for console layouts,
// 256-byte rows for the linear layout, packed elements otherwise. At least 1.
uint64_t title_span(const D3D12_RESOURCE_DESC& desc) {
if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return desc.Width ? desc.Width : 1;
uint64_t size = 0, alignment = 0;
if (static_cast<UINT>(desc.Layout) > 0x100 && bx_gdk_xg_layout_size(desc, &size, &alignment) && size) return size;
bool block = false;
const UINT element = bx_texture_element_bytes(desc.Format, &block);
const uint64_t width = block ? (desc.Width + 3) / 4 : desc.Width;
const uint64_t height = block ? (desc.Height + 3) / 4 : desc.Height;
uint64_t row = width * (element ? element : 4);
if (static_cast<UINT>(desc.Layout) == 0x100) row = (row + 255) / 256 * 256;
size = row * (height ? height : 1) * (desc.DepthOrArraySize ? desc.DepthOrArraySize : 1);
return size ? size : 1;
}
// Implicit shadows the title has replaced, released once enough submissions have passed.
void retire_implicit(const std::vector<ID3D12Resource*>& hosts);
/*
* A view of placed memory with no resource object: reuse the shadow made for the same address
* and shape, or make one (#782). A title streams textures and buffers through recycled memory, so
* a new view whose title range overlaps an older implicit shadow of another address or shape means
* the title has placed something else there and no longer uses the old one: that shadow is retired
* and released later (retire_implicit). Without this, every (address, shape) a title ever viewed kept
* a host resource for the life of the process.
*/
ID3D12Resource* implicit_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURCE_DESC& desc) {
const uint64_t span = title_span(desc);
std::vector<ID3D12Resource*> replaced;
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
if (g_shadows[i].title_va == title_va && same_shape(g_shadows[i].desc, desc)) return g_shadows[i].host;
}
for (size_t i = 0; i < g_count;) {
const Shadow& s = g_shadows[i];
if (s.implicit && title_va < s.title_va + s.span && s.title_va < title_va + span) {
replaced.push_back(s.host);
g_shadows[i] = g_shadows[--g_count];
} else {
++i;
}
}
}
if (!replaced.empty()) retire_implicit(replaced);
ID3D12Resource* resource = nullptr;
return SUCCEEDED(make_shadow(device, title_va, desc, "implicit shadow for a placed view", &resource)) ? resource : nullptr;
if (FAILED(make_shadow(device, title_va, desc, "implicit shadow for a placed view", &resource))) return nullptr;
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = g_count; i-- > 0;) {
if (g_shadows[i].host == resource) {
g_shadows[i].implicit = true;
g_shadows[i].span = span;
break;
}
}
return resource;
}
// The Xbox view descriptions start with the PC description's 40 bytes; ResourceLocation follows.
@@ -181,19 +249,22 @@ uint64_t view_location(const void* xbox_desc) {
}
/*
* Texture contents (#745). A texture placed in title memory gets its pixels from that memory when
* a view of it is resolved for a translated draw (console_descriptors.cpp): into a copy of its host
* texture on a default heap, which the view then reads. The texels are written into an upload
* buffer of the copy's own (persistently mapped) and copied into it by the GPU, on a list the shim
* executes on the submitting queue ahead of the title's lists (BxTextureUploads); the copy is only
* ever in the shim's states (shader resource, or copy destination during that list). A linear layout (D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR, 0x100) is copied
* Texture contents (#745, #782). On the console a placed texture has one storage, the title's
* memory. Here its one host storage is the shadow texture itself: when a view of it is resolved for
* a translated draw (console_descriptors.cpp), its pixels are uploaded from title memory into the
* shadow, so every view and copy command of the texture sees them. The texels are written into an
* upload buffer (persistently mapped while it exists) and copied by the GPU, on a list the shim
* executes on the submitting queue ahead of the title's lists (BxTextureUploads). A read-only shadow
* has simultaneous access (make_shadow), so that copy promotes it from COMMON and it decays back
* after the list, without barriers that would contradict the states the title's own barriers name.
* A linear layout (D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR, 0x100) is copied
* row by row: rows in title memory are 256-byte aligned, the layout XG reports for linear
* textures. Other console layouts are untiled through the GDK's XG library (ADR 0010).
*
* The copy is made the first time a translated draw reads the texture, and returned only once its
* upload has been recorded (until then, and after a failure, the view reads `host` and the next
* draw tries again). An upload buffer is not written again until the GPU is past its last copy;
* until then a check is put off. Because a title may still be filling a texture (streaming) when it is first drawn, a
* The upload is made the first time a translated draw reads the texture (until then, and after a
* failure, the shadow is empty and the next draw tries again). An upload buffer is not written
* again until the GPU is past its last copy, and is released then (#782): made again only when a
* check finds the title memory changed. Until then a check is put off. Because a title may still be filling a texture (streaming) when it is first drawn, a
* later draw checks whether the title memory changed: a hash over a sample of it (64 bytes every
* 64 KiB, and the last 64). A texture found changed is checked again at its next draw, so one the
* title rewrites every frame (a video's planes) is copied as often as it changes; a check that finds
@@ -204,18 +275,16 @@ uint64_t view_location(const void* xbox_desc) {
* Accepted risk: a change that falls entirely between the sampled 64-byte lines is not seen, and
* the texture keeps its earlier contents until a sampled line changes too.
*
* Limit: the contents live in this side copy, not in the host texture. Only views resolved for
* translated draws read it; a copy command out of the texture, or any other view, reads the empty
* host texture (bx_xbox_note_texture_copy_source logs the first such copy).
* Limit: contents are uploaded when a translated draw first reads the texture. A copy command or
* view of a texture no translated draw has read yet still sees an empty shadow.
*/
enum class TextureKind { None, Linear, Tiled };
constexpr UINT kConsoleLayoutLinear = 0x100;
constexpr uint64_t kTextureCheckMs = 16; // the first wait after a check found no change
constexpr uint64_t kTextureCheckMaxMs = 4000;
struct TextureCopy {
ID3D12Resource* copy = nullptr; // owned; default heap, D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE
ID3D12Resource* upload = nullptr; // owned; upload heap, mapped at `mapped`
struct TextureUpload {
ID3D12Resource* upload = nullptr; // owned; upload heap, mapped at `mapped`; null while not needed
uint8_t* mapped = nullptr;
std::vector<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> footprints;
std::vector<UINT> rows;
@@ -226,9 +295,10 @@ struct TextureCopy {
uint64_t sample = 0; // the sample hash the copy was made from
ID3D12Fence* fence = nullptr; // the upload list's fence and the value after the last copy
uint64_t fence_value = 0;
uint64_t upload_bytes = 0; // the upload buffer's size; the buffer exists only while needed
};
std::mutex g_texture_lock;
std::unordered_map<const void*, TextureCopy> g_texture_copies; // host texture -> its copy
std::unordered_map<const void*, TextureUpload> g_texture_uploads; // host texture -> its upload state
/* FNV-1a over 64 bytes every 64 KiB of [va, va + bytes), and the last 64 bytes. */
uint64_t sample_hash(uint64_t va, uint64_t bytes) {
@@ -268,8 +338,43 @@ void note_texture_skipped(const D3D12_RESOURCE_DESC& desc, const char* why) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "texture_contents", detail);
}
/* A default-heap copy of `host`'s description and an upload buffer for all its subresources. */
bool make_texture_copy(ID3D12Resource* host, TextureCopy& t) {
/* The upload buffer of `t` (t.upload_bytes, persistently mapped at t.mapped), made when a copy is
about to be written. Released again once the GPU has copied from it (#782): a texture whose title
memory never changes keeps only its copy. */
HRESULT make_upload(ID3D12Device* device, TextureUpload& t) {
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_UPLOAD;
D3D12_RESOURCE_DESC buffer{};
buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buffer.Width = t.upload_bytes;
buffer.Height = 1;
buffer.DepthOrArraySize = 1;
buffer.MipLevels = 1;
buffer.SampleDesc.Count = 1;
buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
HRESULT hr = t.upload_bytes ? device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&t.upload))
: E_INVALIDARG;
if (SUCCEEDED(hr) && t.upload) hr = t.upload->Map(0, nullptr, reinterpret_cast<void**>(&t.mapped));
if (FAILED(hr) || !t.mapped) {
if (t.upload) t.upload->Release();
t.upload = nullptr;
t.mapped = nullptr;
return FAILED(hr) ? hr : E_FAIL;
}
return S_OK;
}
HRESULT make_upload(ID3D12Resource* owner, TextureUpload& t) {
ID3D12Device* device = nullptr;
if (!owner || FAILED(owner->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) || !device) return E_FAIL;
const HRESULT hr = make_upload(device, t);
device->Release();
return hr;
}
/* The footprints of all of `host`'s subresources and an upload buffer for them. */
bool prepare_upload(ID3D12Resource* host, TextureUpload& t) {
ID3D12Device* device = nullptr;
if (FAILED(host->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) || !device) return false;
const D3D12_RESOURCE_DESC desc = host->GetDesc();
@@ -279,36 +384,18 @@ bool make_texture_copy(ID3D12Resource* host, TextureCopy& t) {
std::vector<UINT64> row_bytes(subresources);
UINT64 total = 0;
device->GetCopyableFootprints(&desc, 0, subresources, 0, t.footprints.data(), t.rows.data(), row_bytes.data(), &total);
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&t.copy));
D3D12_RESOURCE_DESC buffer{};
buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buffer.Width = total;
buffer.Height = 1;
buffer.DepthOrArraySize = 1;
buffer.MipLevels = 1;
buffer.SampleDesc.Count = 1;
buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
heap.Type = D3D12_HEAP_TYPE_UPLOAD;
if (SUCCEEDED(hr) && total) {
hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&t.upload));
}
if (SUCCEEDED(hr) && t.upload) hr = t.upload->Map(0, nullptr, reinterpret_cast<void**>(&t.mapped));
t.upload_bytes = total;
const HRESULT hr = total ? make_upload(device, t) : E_FAIL;
device->Release();
if (FAILED(hr) || !total || !t.mapped) {
bx_xbox_log_host_failure("XboxResource", "CreateCommittedResource(texture contents copy)", FAILED(hr) ? hr : E_FAIL);
if (t.upload) t.upload->Release();
if (t.copy) t.copy->Release();
t = TextureCopy{};
if (FAILED(hr) || !t.mapped) {
bx_xbox_log_host_failure("XboxResource", "CreateCommittedResource(texture contents upload buffer)", FAILED(hr) ? hr : E_FAIL);
t = TextureUpload{};
return false;
}
return true;
}
/* Upload buffers and copies the GPU may still be reading, released once their fence passes. */
/* Upload buffers the GPU may still be reading, released once their fence passes. */
struct Retired {
ID3D12Resource* resource;
ID3D12Fence* fence;
@@ -316,16 +403,16 @@ struct Retired {
};
std::vector<Retired> g_retired; // under g_texture_lock
void retire_locked(TextureCopy& t) {
for (ID3D12Resource* r : {t.upload, t.copy}) {
if (!r) continue;
void retire_locked(TextureUpload& t) {
if (t.upload) {
if (t.fence && t.fence->GetCompletedValue() < t.fence_value) {
g_retired.push_back({r, t.fence, t.fence_value});
g_retired.push_back({t.upload, t.fence, t.fence_value});
} else {
r->Release();
t.upload->Release();
}
}
t.upload = t.copy = nullptr;
t.upload = nullptr;
t.mapped = nullptr;
}
void sweep_retired_locked() {
@@ -340,6 +427,85 @@ void sweep_retired_locked() {
}
}
/*
* Implicit shadows the title replaced (#782). The title reuses memory only once its own GPU work on
* the old contents is done, so the host resource is no longer needed by the title; it is still
* released only kReleaseAfter queue submissions later, as a margin for host work in flight. Its
* texture-contents copy is retired through the copy's own fence (retire_locked), and translated-draw
* markers of it stop referencing it (bx_console_forget_resource) and resolve to null views.
*/
constexpr uint64_t kReleaseAfter = 64; // queue submissions
struct RetiredShadow {
ID3D12Resource* host;
uint64_t submission;
};
std::mutex g_implicit_lock;
std::vector<RetiredShadow> g_implicit_retired; // under g_implicit_lock
std::atomic<uint64_t> g_submissions{0};
std::atomic<uint64_t> g_implicit_retired_total{0};
std::atomic<uint64_t> g_implicit_released_total{0};
void retire_implicit(const std::vector<ID3D12Resource*>& hosts) {
{
std::lock_guard<std::mutex> guard(g_texture_lock);
for (ID3D12Resource* host : hosts) {
auto upload = g_texture_uploads.find(host);
if (upload != g_texture_uploads.end()) {
retire_locked(upload->second);
g_texture_uploads.erase(upload);
}
}
}
const uint64_t now = g_submissions.load();
std::lock_guard<std::mutex> guard(g_implicit_lock);
for (ID3D12Resource* host : hosts) g_implicit_retired.push_back({host, now});
g_implicit_retired_total += hosts.size();
}
void sweep_implicit() {
const uint64_t now = g_submissions.load();
std::vector<ID3D12Resource*> release;
size_t pending = 0;
{
std::lock_guard<std::mutex> guard(g_implicit_lock);
for (size_t i = 0; i < g_implicit_retired.size();) {
if (g_implicit_retired[i].submission + kReleaseAfter <= now) {
release.push_back(g_implicit_retired[i].host);
g_implicit_retired[i] = g_implicit_retired.back();
g_implicit_retired.pop_back();
} else {
++i;
}
}
pending = g_implicit_retired.size();
}
if (release.empty()) return;
for (ID3D12Resource* host : release) {
bx_console_forget_resource(host);
host->Release();
}
const uint64_t before = g_implicit_released_total.fetch_add(release.size());
const uint64_t after = before + release.size();
// Logged at the first release and whenever the total passes a power of two.
auto bits = [](uint64_t v) {
int n = 0;
for (; v; v >>= 1) ++n;
return n;
};
if (before == 0 || bits(after) > bits(before)) {
size_t live = 0;
{
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) live += g_shadows[i].implicit ? 1 : 0;
}
char detail[160];
std::snprintf(detail, sizeof(detail), "live=%zu retired=%llu released=%llu pending=%zu", live,
static_cast<unsigned long long>(g_implicit_retired_total.load()), static_cast<unsigned long long>(after),
pending);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "implicit_shadows", detail);
}
}
} // namespace
extern "C" {
@@ -396,7 +562,8 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const
D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{};
cbv.BufferLocation = resource->GetGPUVirtualAddress() + offset;
cbv.SizeInBytes = static_cast<UINT>((bytes + 255) & ~255ull);
if (bytes) bx_console_mark_cbv(dest.ptr, view_location(xbox_desc) + offset, cbv);
// The fallback lies in the implicit shadow, which is released if the title replaces it.
if (bytes) bx_console_mark_cbv_of(dest.ptr, view_location(xbox_desc) + offset, cbv, resource);
}
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
@@ -579,21 +746,28 @@ ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads*
// the upload writes the entry's buffer and records onto the submission's list.
std::lock_guard<std::mutex> guard(g_texture_lock);
sweep_retired_locked();
TextureCopy& known = g_texture_copies[host];
if (!known.copy || known.title_va != shadow.title_va) {
TextureUpload& known = g_texture_uploads[host];
if (!known.upload_bytes || known.title_va != shadow.title_va) {
retire_locked(known);
known = TextureCopy{};
if (!make_texture_copy(host, known)) {
g_texture_copies.erase(host);
note_texture_skipped(shadow.desc, "the host refused a copy or its upload buffer");
known = TextureUpload{};
if (!prepare_upload(host, known)) {
g_texture_uploads.erase(host);
note_texture_skipped(shadow.desc, "the host refused its upload buffer");
return host;
}
known.title_va = shadow.title_va;
}
const uint64_t now = GetTickCount64();
if (known.filled && now - known.checked_at < known.interval) return known.copy;
if (known.filled && now - known.checked_at < known.interval) return host;
// The GPU is still copying from this buffer (from an earlier submission): check later.
if (known.fence && known.fence->GetCompletedValue() < known.fence_value) return known.filled ? known.copy : host;
if (known.fence && known.fence->GetCompletedValue() < known.fence_value) return host;
// The GPU is past the last copy: the upload buffer is not needed until the title memory
// changes, and is made again then (#782).
if (known.filled && known.upload) {
known.upload->Release();
known.upload = nullptr;
known.mapped = nullptr;
}
known.checked_at = now;
// The title memory the texture occupies.
uint64_t bytes = 0;
@@ -619,6 +793,8 @@ ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads*
sample = sample_hash(shadow.title_va, bytes);
if (filled && sample == known.sample) {
hr = S_FALSE; // checked, unchanged
} else if (!known.upload && FAILED(hr = make_upload(host, known))) {
// no upload buffer: logged below, the next draw tries again
} else if (kind == TextureKind::Linear) {
const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& fp = known.footprints[0];
const size_t row = static_cast<size_t>(shadow.desc.Width) * element;
@@ -635,22 +811,24 @@ ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads*
}
if (hr == S_OK) {
ID3D12GraphicsCommandList* list = uploads->list;
// A simultaneous-access shadow is promoted from COMMON by the copy and decays back after
// the list; one without it (the host refused the flag) is moved explicitly from COMMON.
D3D12_RESOURCE_BARRIER b{};
b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
b.Transition.pResource = known.copy;
b.Transition.pResource = host;
b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
b.Transition.StateBefore = D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE;
b.Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON;
b.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST;
list->ResourceBarrier(1, &b);
if (!shadow.simultaneous) list->ResourceBarrier(1, &b);
for (UINT sub = 0; sub < subresources; ++sub) {
D3D12_TEXTURE_COPY_LOCATION dst{known.copy, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
D3D12_TEXTURE_COPY_LOCATION dst{host, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
dst.SubresourceIndex = sub;
D3D12_TEXTURE_COPY_LOCATION src{known.upload, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
src.PlacedFootprint = known.footprints[sub];
list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
}
std::swap(b.Transition.StateBefore, b.Transition.StateAfter);
list->ResourceBarrier(1, &b);
if (!shadow.simultaneous) list->ResourceBarrier(1, &b);
uploads->recorded = true;
known.fence = uploads->fence;
known.fence_value = uploads->value;
@@ -680,25 +858,12 @@ ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads*
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "texture_contents", detail);
}
}
return known.filled ? known.copy : host;
return host;
}
void bx_xbox_note_texture_copy_source(ID3D12Resource* source) {
if (!source) return;
{
std::lock_guard<std::mutex> guard(g_texture_lock);
auto it = g_texture_copies.find(source);
if (it == g_texture_copies.end() || !it->second.filled) return;
}
static std::atomic<bool> logged{false};
if (logged.exchange(true)) return;
const D3D12_RESOURCE_DESC d = source->GetDesc();
char detail[200];
std::snprintf(detail, sizeof(detail),
"a copy command reads texture %llux%u format=%d, whose contents are in a side copy only; the copy reads the empty "
"host texture (logged once)",
static_cast<unsigned long long>(d.Width), d.Height, static_cast<int>(d.Format));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "texture_contents", detail);
void bx_xbox_placed_note_submission() {
++g_submissions;
sweep_implicit();
}
void bx_xbox_placed_forget(IUnknown* host) {
@@ -715,10 +880,10 @@ void bx_xbox_placed_forget(IUnknown* host) {
}
{
std::lock_guard<std::mutex> guard(g_texture_lock);
auto copy = g_texture_copies.find(host);
if (copy != g_texture_copies.end()) {
retire_locked(copy->second);
g_texture_copies.erase(copy);
auto upload = g_texture_uploads.find(host);
if (upload != g_texture_uploads.end()) {
retire_locked(upload->second);
g_texture_uploads.erase(upload);
}
}
if (gone.title_attributes) XMemFree(reinterpret_cast<void*>(gone.title_va), gone.title_attributes);
-1
View File
@@ -310,7 +310,6 @@ void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_
if (src) {
s = *src;
s.pResource = bx_xbox_unwrap_as(s.pResource);
bx_xbox_note_texture_copy_source(s.pResource);
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyTextureRegion(dst ? &d : nullptr, x, y, z, src ? &s : nullptr, box);
}
+3 -2
View File
@@ -248,8 +248,6 @@ struct BxTextureUploads {
backed-off interval); `host` itself for everything else, without `uploads`, and until a copy
has been recorded (failures are logged). */
ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads* uploads);
/* Logs once when a copy command reads a texture whose contents are only in that side copy. */
void bx_xbox_note_texture_copy_source(ID3D12Resource* source);
/* Logs a host call that failed (`host_call_failed`), so a refusal is never silent. */
void bx_xbox_log_host_failure(const char* iface, const char* method, HRESULT hr);
@@ -466,6 +464,9 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Reso
D3D12_CPU_DESCRIPTOR_HANDLE dest);
/* Drops the shadow record of a destroyed resource. */
void bx_xbox_placed_forget(IUnknown* host);
/* gpu_writes.cpp, at each ExecuteCommandLists: counts submissions and releases implicit shadows
retired long enough ago (placed_x.cpp). */
void bx_xbox_placed_note_submission();
/* Command-list slots whose structures carry interface pointers, unwrapped before the host call.
The Xbox ResourceBarrier also returns the actions it took; 0 is returned. */
@@ -33,7 +33,9 @@
* buffer: the target build makes the views of its menu textures this way, once per frame. These
* are the three ways a title makes a view of a placed texture.
* Each is drawn into its own target and read back; the expected image is the texel formula above,
* independent of the shim. Without the copy the texture is empty and the draw is black.
* independent of the shim. Without the copy the texture is empty and the draw is black. A placed
* texture has one storage (#782): in round 2, a copy command out of each placed texture itself reads
* the same texels the draw did.
*
* Four rounds of the three draws:
* 1. the linear texture's memory (one page) is PAGE_NOACCESS: its copy fails (logged), the
@@ -478,6 +480,7 @@ int main() {
auto committed = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource);
void* targets[kViews] = {};
void* readbacks[kViews] = {};
void* texture_readbacks[kViews] = {}; // copies out of the placed textures themselves (round 2)
for (int i = 0; i < kViews; ++i) {
hr = committed(dev, &default_heap, D3D12_HEAP_FLAG_NONE, &target_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
__uuidof(ID3D12Resource), &targets[i]);
@@ -486,6 +489,9 @@ int main() {
hr = committed(dev, &readback_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
__uuidof(ID3D12Resource), &readbacks[i]);
CHECK(hr == S_OK && readbacks[i], "readback buffer %d hr=0x%08lx", i, static_cast<unsigned long>(hr));
hr = committed(dev, &readback_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
__uuidof(ID3D12Resource), &texture_readbacks[i]);
CHECK(hr == S_OK && texture_readbacks[i], "texture readback buffer %d hr=0x%08lx", i, static_cast<unsigned long>(hr));
}
void* upload = nullptr;
buffer_desc.Width = 64 * 1024;
@@ -605,6 +611,20 @@ int main() {
src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
slot<CopyTextureFn>(list, kListCopyTextureRegion)(list, &dst, 0, 0, 0, &src, nullptr);
}
if (round == 2) {
// A copy command out of the placed texture itself, after a translated draw has read it:
// a placed texture has one storage, so the copy sees the same texels the draw did.
for (int i = 0; i < 2; ++i) {
D3D12_TEXTURE_COPY_LOCATION dst{};
dst.pResource = static_cast<ID3D12Resource*>(texture_readbacks[i]);
dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, kReadPitch};
D3D12_TEXTURE_COPY_LOCATION src{};
src.pResource = static_cast<ID3D12Resource*>(textures[i]);
src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
slot<CopyTextureFn>(list, kListCopyTextureRegion)(list, &dst, 0, 0, 0, &src, nullptr);
}
}
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "round %d: list Close", round);
void* lists[] = {list};
slot<ExecuteFn>(queue, kQueueExecuteCommandLists)(queue, 1, lists);
@@ -643,6 +663,17 @@ int main() {
CHECK(VirtualProtect(linear_bytes, 4096, PAGE_READWRITE, &old_protect), "VirtualProtect(PAGE_READWRITE)");
if (!run_round(2)) return 1;
for (int i = 0; i < kViews; ++i) check(2, i, 0);
for (int i = 0; i < 2; ++i) {
static const char* names[2] = {"linear (0x100)", "tiled through XG (0x105)"};
void* result = nullptr;
hr = slot<MapFn>(texture_readbacks[i], kResMap)(texture_readbacks[i], 0, nullptr, &result);
CHECK(hr == S_OK && result, "texture readback %d Map hr=0x%08lx", i, static_cast<unsigned long>(hr));
if (!result) continue;
const unsigned wrong = wrong_pixels(static_cast<const uint8_t*>(result), names[i], 0);
CHECK(wrong == 0, "a copy command out of the %s texture itself reads its texels: %u of %u pixel(s) differ", names[i], wrong,
kSize * kSize);
slot<UnmapFn>(texture_readbacks[i], kResUnmap)(texture_readbacks[i], 0, nullptr);
}
// Round 3: the title rewrites the linear texture; the others are unchanged. After the check
// interval a draw copies the changed texture again and not the others.
for (UINT y = 0; y < kSize; ++y) {
@@ -682,8 +713,8 @@ int main() {
std::printf("note: no BX_LOG_FILE; the log checks did not run\n");
}
for (void* object : {view_heap, rtv_heap, upload, readbacks[2], readbacks[1], readbacks[0], targets[2], targets[1], targets[0],
textures[1], textures[0],
for (void* object : {view_heap, rtv_heap, upload, texture_readbacks[2], texture_readbacks[1], texture_readbacks[0], readbacks[2],
readbacks[1], readbacks[0], targets[2], targets[1], targets[0], textures[1], textures[0],
pipeline, root, fence, list, allocator, queue, dev}) {
slot<ReleaseFn>(object, kRelease)(object);
}
@@ -0,0 +1,6 @@
# Host resources made for views of placed memory (CreatePlacedRawShaderResourceViewX) are released
# once the title places something else in that memory (#782). Needs D3DMetal; reads the shim log
# (BX_LOG_FILE, set by bx-cli run).
add_executable(test_d3d12_placed_implicit_release main.cpp)
target_compile_definitions(test_d3d12_placed_implicit_release PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_placed_implicit_release PRIVATE d3d12_xs kernel32 uuid)
@@ -0,0 +1,228 @@
/*
* Conformance test: host resources made for views of placed memory are released once the title
* places something else in that memory (#782).
*
* CreatePlacedRawShaderResourceViewX makes a view of title memory at an address from a resource
* description, with no resource object. d3d12_xs backs each such view with a host resource of its
* own (an implicit shadow). A title streams textures through recycled memory, so over a run it
* views thousands of (address, shape) pairs; before #782 every one kept a host resource for the
* life of the process (the target build reached an 11 GB footprint in about 140 s).
*
* The program views four 64 KiB slots of its own memory 256 times, each view with a shape not used
* before, so each view replaces the one before it in that slot. After each view the queue executes
* an empty command list (the shim releases replaced shadows a number of submissions later), then
* 80 more submissions follow. Expected, from the program alone:
* - 256 host resources are made (no (address, shape) repeats);
* - at the end at most 4 are live (one per slot), and at least 128 have been released (the shim
* logs `implicit_shadows ... released=N` when the count passes a power of two);
* - a view with the same address and shape as the live one reuses it: no new host resource.
* Without the release, no `implicit_shadows` line is logged and all 256 stay live.
*
* Slots (Xbox-layout tables, ADR 0009): 2 Release; device 9 CreateCommandAllocator,
* 14 CreateDescriptorHeap, 48 CreateCommandQueueX, 70 CreatePlacedRawShaderResourceViewX,
* 73 CreateCommandListX; descriptor heap 9 GetCPUDescriptorHandleForHeapStart; command list 9 Close;
* queue 10 ExecuteCommandLists.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr int kRelease = 2;
constexpr int kDevCreateCommandAllocator = 9, kDevCreateDescriptorHeap = 14, kDevCreateCommandQueueX = 48;
constexpr int kDevCreatePlacedRawShaderResourceViewX = 70, kDevCreateCommandListX = 73;
constexpr int kHeapGetCpuStart = 9, kListClose = 9, kQueueExecuteCommandLists = 10;
constexpr int kSlots = 4;
constexpr int kViews = 256;
constexpr int kFlush = 80; // submissions after the last view
int g_checks = 0;
int g_failed = 0;
#define CHECK(cond, ...) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_placed_implicit_release:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
struct QueueDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, EngineOrPipeIndex, QueueIndex;
};
struct ListDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, NodeMask, ResourceBarrierBatchSize;
};
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
using CreateHeapFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_DESCRIPTOR_HEAP_DESC*, REFIID, void**);
using HeapStartFn = D3D12_CPU_DESCRIPTOR_HANDLE(STDMETHODCALLTYPE*)(void*);
using CreatePlacedRawSrvXFn = void(STDMETHODCALLTYPE*)(void*, const D3D12_RESOURCE_DESC*, const void*, D3D12_CPU_DESCRIPTOR_HANDLE);
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* f = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
std::fclose(f);
}
return text;
}
size_t count_of(const std::string& text, const char* needle) {
size_t n = 0;
for (size_t pos = text.find(needle); pos != std::string::npos; pos = text.find(needle, pos + 1)) ++n;
return n;
}
/* The highest `released=` value among `implicit_shadows` lines, and the `live=` of that line. */
bool last_release_line(const std::string& text, unsigned long long* released, unsigned long long* live) {
bool found = false;
*released = 0;
*live = 0;
for (size_t pos = text.find("\"implicit_shadows\""); pos != std::string::npos; pos = text.find("\"implicit_shadows\"", pos + 1)) {
const size_t l = text.find("live=", pos), r = text.find("released=", pos);
if (l == std::string::npos || r == std::string::npos) continue;
const unsigned long long rel = std::strtoull(text.c_str() + r + 9, nullptr, 10);
if (!found || rel >= *released) {
*released = rel;
*live = std::strtoull(text.c_str() + l + 5, nullptr, 10);
found = true;
}
}
return found;
}
/* View `i`: slot i % 4, a 2D R8G8B8A8 texture in the linear console layout whose width is new for
every view of the slot (16, 20, ... 268 texels by 4 rows: at most 5 KiB of a 64 KiB slot), as a
title streaming different textures through the same memory makes them. */
D3D12_RESOURCE_DESC view_desc(int i) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
d.Width = 16 + 4 * static_cast<UINT64>(i / kSlots);
d.Height = 4;
d.DepthOrArraySize = 1;
d.MipLevels = 1;
d.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
d.SampleDesc.Count = 1;
d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x100);
return d;
}
} // namespace
int main() {
const std::string before = read_log();
alignas(8) unsigned char title_params[80] = {};
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
std::memcpy(title_params, &version, sizeof(version));
void* dev = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
if (hr == E_NOINTERFACE) {
std::printf("SKIP: test_d3d12_placed_implicit_release: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
return 77;
}
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
if (!dev) return 1;
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
void* queue = nullptr;
void* allocator = nullptr;
void* list = nullptr;
slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue);
slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
&allocator);
slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr, __uuidof(ID3D12GraphicsCommandList), &list);
D3D12_DESCRIPTOR_HEAP_DESC heap_desc{};
heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
heap_desc.NumDescriptors = kSlots;
void* heap = nullptr;
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &heap_desc, __uuidof(ID3D12DescriptorHeap), &heap);
void* memory = VirtualAlloc(nullptr, kSlots * 64 * 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!queue || !allocator || !list || !heap || !memory) {
std::fprintf(stderr, "FAIL: test_d3d12_placed_implicit_release: setup (hr=0x%08lx)\n", static_cast<unsigned long>(hr));
return 1;
}
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close");
const D3D12_CPU_DESCRIPTOR_HANDLE start = slot<HeapStartFn>(heap, kHeapGetCpuStart)(heap);
auto create = slot<CreatePlacedRawSrvXFn>(dev, kDevCreatePlacedRawShaderResourceViewX);
auto execute = slot<ExecuteFn>(queue, kQueueExecuteCommandLists);
void* lists[] = {list};
struct alignas(8) {
D3D12_SHADER_RESOURCE_VIEW_DESC pc;
uint64_t location;
} xbox_srv{};
xbox_srv.pc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
xbox_srv.pc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
xbox_srv.pc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
xbox_srv.pc.Texture2D.MipLevels = 1;
for (int i = 0; i < kViews; ++i) {
const D3D12_RESOURCE_DESC d = view_desc(i);
xbox_srv.location = reinterpret_cast<uint64_t>(memory) + static_cast<uint64_t>(i % kSlots) * 64 * 1024;
create(dev, &d, &xbox_srv, {start.ptr + static_cast<SIZE_T>(i % kSlots) * 32});
execute(queue, 1, lists);
}
for (int i = 0; i < kFlush; ++i) execute(queue, 1, lists);
// The live view of slot 0 again, same address and shape: reused, not made anew.
const std::string mid = read_log();
{
const D3D12_RESOURCE_DESC d = view_desc(kViews - kSlots);
xbox_srv.location = reinterpret_cast<uint64_t>(memory);
create(dev, &d, &xbox_srv, {start.ptr});
}
const std::string log = read_log();
if (!log.empty()) {
const std::string mine = log.substr(before.size() <= log.size() ? before.size() : 0);
const std::string after_mid = log.substr(mid.size() <= log.size() ? mid.size() : 0);
const size_t made = count_of(mine, "implicit shadow for a placed view");
CHECK(made == kViews, "every view of a new shape made a host resource (%zu of %d)", made, kViews);
unsigned long long released = 0, live = 0;
const bool logged = last_release_line(mine, &released, &live);
CHECK(logged, "replaced host resources are released (an implicit_shadows line is logged)");
CHECK(released >= 128, "at least 128 replaced host resources are released (%llu)", released);
CHECK(live <= kSlots, "at most one host resource per slot is live (%llu)", live);
CHECK(count_of(after_mid, "implicit shadow for a placed view") == 0,
"a view with the live shadow's address and shape reuses it (%zu new)", count_of(after_mid, "implicit shadow for a placed view"));
} else {
std::printf("note: no BX_LOG_FILE; the log checks did not run\n");
}
for (void* object : {heap, list, allocator, queue, dev}) slot<ReleaseFn>(object, kRelease)(object);
VirtualFree(memory, 0, MEM_RELEASE);
std::printf("%s: test_d3d12_placed_implicit_release (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS",
g_checks - g_failed, g_checks);
return g_failed ? 1 : 0;
}