Repository navigation
KernelX / title textures: a GPU view of the title's CPU memory reads the CPU view (retail intro video, no green screen) - #283
Conversation
|
A physical page mapped into a GPU view before its first use is not seen as mapped. The test below, on
test (in title_textures.rs's tests)#[test]
fn a_lazily_mapped_page_in_a_gpu_view_is_its_own_source() {
use crate::hle::kernelx;
use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE};
const VIEW: usize = 16 << 20;
unsafe {
let Some(_) = crate::gpu::uma::get() else { return };
let cpu = VirtualAlloc(std::ptr::null(), VIEW, MEM_RESERVE, PAGE_READWRITE) as usize;
let gpu = VirtualAlloc(std::ptr::null(), VIEW, MEM_RESERVE, PAGE_READWRITE) as usize;
kernelx::mirrors::reserved(cpu, VIEW, 0x2040_2000, 0x04);
kernelx::mirrors::reserved(gpu, VIEW, 0x2040_2000, 0x801);
assert_eq!(mirror_source(gpu + 0x2_0000), cpu + 0x2_0000); // nothing mapped: the CPU view
let (mut n, mut pages) = (1usize, [0usize; 1]);
assert_eq!(kernelx::AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1);
let at = gpu + 0x2_0000;
assert_eq!(kernelx::MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, at);
let before = mirror_source(at);
(at as *mut u32).write_volatile(7); // its first use commits it
let after = mirror_source(at);
let mut none = [0usize; 1];
kernelx::MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, none.as_mut_ptr());
kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), 1, pages.as_mut_ptr());
kernelx::mirrors::released(cpu);
VirtualFree(cpu as *mut c_void, 0, MEM_RELEASE);
VirtualFree(gpu as *mut c_void, 0, MEM_RELEASE);
assert_eq!(after, at);
assert_eq!(before, at, "a page mapped at the address but not used yet is its source too"); // fails
}
}A possible fix: ask Your description says the retail game maps physical pages only into the CPU view, so this may not affect the intro video. It matters for any title that maps fresh pages into a GPU view and places textures there. Tested
Not tested
🤖 Claude Opus 5.5 |
… memory reads the CPU view Their work, merged as it is. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
94bfcf0 to
2a64505
Compare
|
Test report on NVIDIA. This PR fixes the green intro here. Tested at Setup: RTX 5070 Ti (16 GB), driver 616.92 (32-lane waves), AMD Ryzen 7 7700X, 32 GB RAM, Windows 11 Pro 26300. Release build, DXC 1.8.2502.11, warm DXIL cache. Retail title 1.0.2.1.
On main with temporary logging (one 40 s run), the logs match your description:
Not tested: head AI-assisted: Claude Code (Claude Fable 5.2 ran the builds and runs; Claude Opus 5.5 wrote this report). No game files attached. |
|
Confirmed on Windows + NVIDIA: the retail title's intro video plays instead of solid green. Setup: RTX 4070 12 GB (driver 617.42), Ryzen 7 7800X3D, 32 GB RAM, Windows 11, DXC 1.9.2609, release build, Stack: main Result:
|
|
Confirming on an AMD RX 7800 XT (16 GB, driver 32.0.32015.7029), GTA VI retail: with About the low frame rate you noted: on this machine it was 8–9 presents per 2 s during the video. Timing the upload path (a local counter around each step of
It is a separate change from this PR ( diff (gpu/tiling.rs, +86)diff --git a/crates/xcl/src/gpu/tiling.rs b/crates/xcl/src/gpu/tiling.rs
index 7d9f4be..4074307 100644
--- a/crates/xcl/src/gpu/tiling.rs
+++ b/crates/xcl/src/gpu/tiling.rs
@@ -395,6 +395,61 @@ impl Chain {
/// level `i` of array slice `slice` (`src` = the slice's bytes) → linear rows of elements;
/// bytes past the end of `src` read as 0
pub fn detile_level(&self, src: &[u8], i: usize, slice: usize) -> Vec<u8> {
+ let l = self.levels[i];
+ // a level in the mip tail starts inside a block: element by element (small levels)
+ if l.origin != (0, 0) {
+ return self.detile_level_slow(src, i, slice);
+ }
+ let lay = &self.layout;
+ let e = 1usize << lay.elem_log2;
+ let (w, h) = (l.width, l.height);
+ let mut out = vec![0u8; w * h * e];
+ let (bw, bh, bd) = (lay.block_w, lay.block_h, lay.block_d);
+ let pitch_blocks = l.pitch.div_ceil(bw);
+ let hi = |t: &[u32], c: usize, b: usize| t[(c / b) % t.len()];
+ // linear: each row is contiguous (blocks of 256 B one row high, side by side)
+ if lay.mode == 0 && lay.base_xor == 0 {
+ let row = w * e;
+ for y in 0..h {
+ let o = l.offset + y * pitch_blocks * lay.block_bytes;
+ if o < src.len() {
+ let n = row.min((src.len() - o) / e * e);
+ out[y * row..y * row + n].copy_from_slice(&src[o..o + n]);
+ }
+ }
+ return out;
+ }
+ // tiled: what the row and the block give, once per row and per block (`offset_z`)
+ let z = lay.oz[slice % bd] ^ hi(&lay.hz, slice, bd);
+ for y in 0..h {
+ let yo = lay.oy[y % bh] ^ hi(&lay.hy, y, bh) ^ z;
+ let row_base = l.offset + (y / bh) * pitch_blocks * lay.block_bytes;
+ for bx in 0..w.div_ceil(bw) {
+ let bo = yo ^ lay.hx[bx % lay.hx.len()];
+ let base = row_base + bx * lay.block_bytes;
+ let x0 = bx * bw;
+ let n = bw.min(w - x0);
+ let d0 = (y * w + x0) * e;
+ if base + lay.block_bytes <= src.len() {
+ for xi in 0..n {
+ let o = base + ((lay.ox[xi] ^ bo) as usize ^ lay.base_xor);
+ out[d0 + xi * e..d0 + xi * e + e].copy_from_slice(&src[o..o + e]);
+ }
+ } else {
+ for xi in 0..n {
+ let o = base + ((lay.ox[xi] ^ bo) as usize ^ lay.base_xor);
+ if let Some(s) = src.get(o..o + e) {
+ out[d0 + xi * e..d0 + xi * e + e].copy_from_slice(s);
+ }
+ }
+ }
+ }
+ }
+ out
+ }
+
+ /// `detile_level` element by element (`element_at` for each)
+ pub fn detile_level_slow(&self, src: &[u8], i: usize, slice: usize) -> Vec<u8> {
let l = self.levels[i];
let e = 1usize << self.layout.elem_log2;
let mut out = vec![0u8; l.width * l.height * e];
@@ -488,6 +543,37 @@ mod tests {
}
}
+ /// The fast `detile_level` (per row and per block) gives what the element-by-element one
+ /// gives: every mode, element size and pipe configuration, levels in and out of the tail,
+ /// array slices, a base swizzle, and a source cut short.
+ #[test]
+ fn fast_detile_matches_element_by_element() {
+ let mut modes = vec![0u32];
+ modes.extend(MODES);
+ for mode in modes {
+ for e in 0..5u32 {
+ for cfg in configs() {
+ let Some(mut lay) = Layout::new(mode, e, cfg) else { continue };
+ if mode != 0 {
+ lay.base_xor = (0x5a5 << e) & (lay.block_bytes - 1) & !((1 << e) - 1);
+ }
+ let c = Chain::new(lay, 70, 37, 1, 4);
+ let mut src = vec![0u8; c.slice_bytes * 2];
+ for (k, b) in src.iter_mut().enumerate() {
+ *b = (k as u32).wrapping_mul(2654435761).rotate_right(13) as u8;
+ }
+ for i in 0..c.levels.len() {
+ for slice in 0..2 {
+ assert_eq!(c.detile_level(&src, i, slice), c.detile_level_slow(&src, i, slice), "mode {mode} e {e} {cfg:?} level {i} slice {slice}");
+ }
+ let short = &src[..c.slice_bytes / 3];
+ assert_eq!(c.detile_level(short, i, 0), c.detile_level_slow(short, i, 0), "mode {mode} e {e} {cfg:?} level {i}, cut short");
+ }
+ }
+ }
+ }
+ }
+
/// Every level of a chain (with a mip tail) gets its own elements: tiling all levels with
/// distinct values and detiling them gives each back unchanged.
#[test]Tested: AI-assisted (Claude Code, Claude Opus 5.5). |
… use, and later mappings move the source (review of PR ivall#283) mirror_source decided "mapped" by MEM_COMMIT, but a physical page mapped at plain reserved address space is committed only at its first access (kernelx::lazy): a texture on such a page read the CPU view instead of the page mapped under it. kernelx::physical_page_at asks the away map, which holds lazy pages too. The source was also fixed at register. Mapping or unmapping physical pages inside a GPU view (and freeing pages mapped there) now bumps kernelx::gpu_view_map_gen; at the next look the textures in GPU views get their source again, and one whose source changed is uploaded from the new one. Mappings elsewhere (all of a retail game's ~54,000 a minute) do not bump it, so the check costs nothing there. Test: a_lazily_mapped_page_in_a_gpu_view_is_its_own_source (Kalmarv's, extended with a texture registered before the mapping). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Thanks: both points are right. Fixed in a2bfbed (and the branch is rebased onto #252's updated head, 065be41). Lazily mapped pages.
Tests: Not re-run with the game for this commit. The PC's free commit has since dropped below XCL's 17 GB threshold ( 🤖 Claude Opus 5.5 |
…u text) A retail game reserves 24 GB of 64 KiB pages (VirtualAlloc flags 0x20402000) and commits 2.2 GB of large pages with a graphics protection (flags 0x20003000, protection 0x2404). Neither fits a sparse or the coherent window, so both fell through to plain memory without MEM_WRITE_WATCH. Textures the title places there are kept in step with the memory (d3d12x::title_textures), which relies on GetWriteWatch to see CPU writes: they were uploaded once, empty, and never again (128+ textures in the first 45 s). One of them is the game's 2048x2048 A8_UNORM glyph atlas, which the CPU fills as text is laid out. Its GPU copy stayed zero, so every glyph drawn from it (the x-height letters: a c e m n o r s u v w x z) was missing from the menus; letters drawn by the vector path (ascenders, descenders, capitals) were fine. Found by a GPU readback of the atlas (zero) against its CPU view (glyphs) while the menu was on screen. The fallback VirtualAlloc now reserves GPU-visible memory (gpu_visible_fallback: MEM_GRAPHICS, MEM_LARGE_PAGES / MEM_64K_PAGES, or a PAGE_GRAPHICS_* protection) with MEM_WRITE_WATCH and records it with the graphics reservations (reserve_watched), whose ranges title_textures watches. Cost, measured on the game (RTX 5070 Ti): the write-watch scan goes from ~0.5 ms to 2.0-2.7 ms a submit once the menus have loaded, ~5-6 GB of kept-in-step textures now being scanned; 1093 frames in 80 s against 1297. Test: gpu_visible_fallback_memory_is_write_watched calls the fallback directly (through VirtualAlloc the unified-memory windows take these sizes when they have room); it fails without MEM_WRITE_WATCH. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…video) A retail game reserves 24 GB of 64 KiB pages twice in a row (VirtualAlloc flags 0x20402000): once PAGE_READWRITE, once PAGE_NOACCESS | PAGE_GRAPHICS_NOACCESS (0x801). It maps physical pages only into the first (XMemMapPhysicalPages, ~54,000 calls in the first minute), yet places GPU resources at the same offset in the second: its Bink video planes are decoded by the CPU into the first view (BinkRegisterFrameBuffers), and the video shader samples R8 textures at those addresses plus the reservation's size. On the console the second reservation is a GPU-only view of the first; here it was separate, empty memory, so the video drew zero luma and chroma: a green screen for ~15 s after the first A press. kernelx::mirrors pairs such a no-access graphics reservation of 64 KiB pages with the most recent CPU-readable one of the same size (forgotten when either is released). title_textures keeps a texture placed in the GPU view, where no physical page is mapped, in step with the same offset in the CPU view: its bytes are read and its CPU writes watched there (Entry::src), while its title address (GetGPUVirtualAddress, GPU copies into it) stays the GPU view's. A page mapped at the address counts before its first use too (kernelx::physical_page_at asks the away map, lazy pages included), and mapping or unmapping pages inside a GPU view (gpu_view_map_gen) makes the textures there take their source again at the next look, uploaded from the new one. Mappings elsewhere do not bump it, so they cost nothing. The 4K planes are now uploaded each video frame: 12.4 fps during the video against 17 fps of green before (RTX 5070 Ti). Tests: gpu_view_reservations_name_their_cpu_view; a_lazily_mapped_page_in_a_gpu_view_is_its_own_source (by Kalmarv in the review, extended with a texture registered before the mapping). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
a2bfbed to
9bd7635
Compare
|
Test report on a retail title: with this PR the intro video shows a picture instead of solid green. What was run
Result
I did not open the captures of this particular run. On another run of the same two changes (in my fork, on top of main: Not tested
Both runs were on my machine; Claude Code (Claude Fable 5.2) ran the script and wrote this report. |
|
On a GTX 1070 (8 GB, no mesh shaders), the texture alias handling ran on PR revision I compared two local release builds on the Series X profile. The control was a 40-PR integration branch based on
On the Series S profile, the same #283 binary reached 2,318 presents with 96 black captures before a different breakpoint at 151.932 s ( Ryzen 7 5800X, 64 GB RAM, Windows 10 IoT Enterprise LTSC 19044.7846, NVIDIA 581.80, DXC 1.8.2502.11, Agility SDK 1.619.6, title 1.0.2.1. Each run used a fresh title data directory with Codex (GPT-6) ran the local tests and prepared this report. |
|
Tested on Linux (Wine, NVIDIA): the intro video is no longer solid green – it shows the picture – but it plays at about 5 fps. Tested commit: Tested
Not tested
AI use
|
|
Data point from a different NVIDIA card (RTX 3060 Ti 8 GB, driver 32.0.16.1742, Ryzen 7 9800X3D, Windows 11, main 4017f8f + #300 + #294, release, So on this card the visible failure may be one step earlier than the GPU-view aliasing (texture data never arrives, BCPack refused - #208/#273), or the same zero-read you describe with a different clear colour. Happy to run a build with this PR + #252 stacked and report what the intro does here. AI use: GPT-6.2 Astra (API model selector) wrote this comment from our run's log; the human contributor observed the screen. |
Can confirm the same, the 5 FPS might be a separate problem |
|
Tested on AMD (RDNA3), since the PR's numbers are from an NVIDIA card. Build: Result: the intro video plays with its real picture. Without #283 the same build draws every movie frame as Frame rate: the video ran at ~6 fps on this card with the detile as it is now; One thing to avoid: skipping the Not tested: NVIDIA, other titles, whole workspace suite. AI-assisted: DeepSeek V4.1 Flash wrote this report from our runs. |
Handle 16-byte constant-buffer records, upload intro textures from their CPU view, and decode BC1 BCPack streams. Share bounded texture pages, batch upload staging, and tolerate pages decommitted during streaming reads. Includes work from ivall/xcl ivall#208, ivall#244, ivall#252, ivall#254, ivall#269 and ivall#283. DirectStorage late destination pages are already in the base. Assisted-by: OpenAI Codex (gpt-6.2-sol)
…e regressions Ported from ivall/xcl#283 (comment) by gw1337x. Preserve the old checked behavior for noncanonical base XORs and extend the contributor differential test with partial elements, truncated rows, zero/base swizzles, tails, modes and pipe configurations.
|
Follow-up to my detile comment above: with the detile fixed, the rest of the upload path showed up once the title streams its world after the video. Same machine (RX 7800 XT, GTA VI), What it was:
The change (
diff on main 4017f8f (gpu/texture.rs, title_textures.rs: +215 −2)diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs
index 1008d76..cff3864 100644
--- a/crates/xcl/src/gpu/texture.rs
+++ b/crates/xcl/src/gpu/texture.rs
@@ -225,6 +225,146 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items
Ok(failed)
}
+/// Uploads that do not wait: one command list, allocators and upload buffers reused once the
+/// GPU is past them, a fence the title's queues wait for on the GPU (`upload`). Made for the
+/// title textures kept in step with its memory: re-uploaded every frame (a video's planes,
+/// streaming), a new allocator, list, upload buffer and fence and a CPU wait for each batch held
+/// a retail game's frames for seconds while it loaded its world.
+pub struct Uploader {
+ fence: ID3D12Fence,
+ value: u64,
+ list: Option<ID3D12GraphicsCommandList>,
+ /// allocators and the fence value their last list ran to
+ allocs: std::collections::VecDeque<(ID3D12CommandAllocator, u64)>,
+ /// upload buffers in use: (fence value, buffer, bytes)
+ busy: std::collections::VecDeque<(u64, ID3D12Resource, u64)>,
+ /// the textures copied into, held until the GPU is past the copy (the title may release
+ /// one meanwhile: a final release with the copy in flight removed the device)
+ dests: std::collections::VecDeque<(u64, ID3D12Resource)>,
+ /// upload buffers the GPU is done with: (bytes, buffer)
+ free: Vec<(u64, ID3D12Resource)>,
+ free_bytes: u64,
+}
+
+// D3D12 objects are free-threaded
+unsafe impl Send for Uploader {}
+
+/// an upload buffer's bytes at least: the textures of a batch are placed in one, one after another
+const UPLOADER_CHUNK: u64 = 64 << 20;
+
+/// upload buffers kept for reuse at most
+const UPLOADER_FREE_CAP: u64 = 512 << 20;
+
+impl Uploader {
+ pub unsafe fn new(dev: &ID3D12Device) -> Result<Uploader, String> {
+ let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(err)?;
+ Ok(Uploader { fence, value: 0, list: None, allocs: Default::default(), busy: Default::default(), dests: Default::default(), free: Vec::new(), free_bytes: 0 })
+ }
+
+ /// The fence and the value the title's queues wait for to see every upload so far.
+ pub fn done_at(&self) -> (&ID3D12Fence, u64) {
+ (&self.fence, self.value)
+ }
+
+ unsafe fn recycle(&mut self) -> u64 {
+ let done = self.fence.GetCompletedValue();
+ while self.dests.front().is_some_and(|d| d.0 <= done) {
+ self.dests.pop_front();
+ }
+ while self.busy.front().is_some_and(|b| b.0 <= done) {
+ let (_, buf, bytes) = self.busy.pop_front().unwrap();
+ if self.free_bytes + bytes <= UPLOADER_FREE_CAP {
+ self.free_bytes += bytes;
+ self.free.push((bytes, buf));
+ }
+ }
+ done
+ }
+
+ /// A free upload buffer of `size` bytes or more (not over twice), else a new one (a power
+ /// of two from `UPLOADER_CHUNK`, so they can be reused). A batch's textures share one
+ /// (`upload`): a buffer each, of 1 MiB at least, made 5 GB of upload buffers in 18 s while
+ /// a retail game streamed thousands of small textures.
+ unsafe fn take(dev: &ID3D12Device, free: &mut Vec<(u64, ID3D12Resource)>, free_bytes: &mut u64, size: u64) -> Result<(ID3D12Resource, u64), String> {
+ let size = size.max(UPLOADER_CHUNK);
+ let best = free.iter().enumerate().filter(|(_, f)| f.0 >= size && f.0 <= size * 2).min_by_key(|(_, f)| f.0).map(|(i, _)| i);
+ if let Some(i) = best {
+ let (bytes, buf) = free.swap_remove(i);
+ *free_bytes -= bytes;
+ return Ok((buf, bytes));
+ }
+ let bytes = size.next_power_of_two();
+ Ok((buffer(dev, bytes)?, bytes))
+ }
+
+ /// `upload_batch` without the wait: the work goes to `queue`, and the title's queues wait
+ /// for `done_at` on the GPU before work that samples the textures.
+ pub unsafe fn upload(&mut self, dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec<Subresource>, Vec<D3D12_RESOURCE_STATES>)]) -> Result<Vec<(usize, String)>, String> {
+ if items.is_empty() {
+ return Ok(Vec::new());
+ }
+ let done = self.recycle();
+ let alloc = match self.allocs.front() {
+ Some((_, v)) if *v <= done => {
+ let (a, _) = self.allocs.pop_front().unwrap();
+ a.Reset().map_err(err)?;
+ a
+ }
+ _ => dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(err)?,
+ };
+ let list = match &self.list {
+ Some(l) => {
+ l.Reset(&alloc, None).map_err(err)?;
+ l.clone()
+ }
+ None => {
+ let l: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?;
+ self.list = Some(l.clone());
+ l
+ }
+ };
+ let mut used: Vec<(ID3D12Resource, u64)> = Vec::new();
+ let mut failed = Vec::new();
+ // the buffer being filled: (buffer, its bytes, bytes used)
+ let mut cur: Option<(ID3D12Resource, u64, u64)> = None;
+ for (k, (res, subs, states)) in items.iter().enumerate() {
+ let (free, free_bytes) = (&mut self.free, &mut self.free_bytes);
+ let r = record_upload_with(dev, &list, res, subs, states, states, &mut |size| {
+ let fits = cur.as_ref().is_some_and(|c| c.2.next_multiple_of(512) + size <= c.1);
+ if !fits {
+ if let Some((b, bytes, _)) = cur.take() {
+ used.push((b, bytes));
+ }
+ let (b, bytes) = Self::take(dev, free, free_bytes, size)?;
+ cur = Some((b, bytes, 0));
+ }
+ let c = cur.as_mut().unwrap();
+ let at = c.2.next_multiple_of(512);
+ c.2 = at + size;
+ Ok((c.0.clone(), at))
+ });
+ if let Err(e) = r {
+ failed.push((k, e));
+ }
+ }
+ if let Some((b, bytes, _)) = cur.take() {
+ used.push((b, bytes));
+ }
+ list.Close().map_err(err)?;
+ queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).map_err(err)?)]);
+ self.value += 1;
+ queue.Signal(&self.fence, self.value).map_err(err)?;
+ for (b, bytes) in used {
+ self.busy.push_back((self.value, b, bytes));
+ }
+ for (res, _, _) in items {
+ self.dests.push_back((self.value, res.clone()));
+ }
+ self.allocs.push_back((alloc, self.value));
+ Ok(failed)
+ }
+}
+
/// Record the copy of `subs` into `res` on `list` (barriers from `before` and back to `after`);
/// the staging buffer returned must live until the list has run.
pub unsafe fn record_upload(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, subs: &[Subresource], before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> Result<ID3D12Resource, String> {
@@ -241,6 +381,20 @@ pub unsafe fn record_upload_states(
subs: &[Subresource],
before: &[D3D12_RESOURCE_STATES],
after: &[D3D12_RESOURCE_STATES],
+) -> Result<ID3D12Resource, String> {
+ record_upload_with(dev, list, res, subs, before, after, &mut |size| buffer(dev, size).map(|b| (b, 0)))
+}
+
+/// `record_upload_states` with the staging memory from `staging`: an upload heap buffer and
+/// the offset (a multiple of 512) of the bytes asked in it.
+pub unsafe fn record_upload_with(
+ dev: &ID3D12Device,
+ list: &ID3D12GraphicsCommandList,
+ res: &ID3D12Resource,
+ subs: &[Subresource],
+ before: &[D3D12_RESOURCE_STATES],
+ after: &[D3D12_RESOURCE_STATES],
+ staging: &mut dyn FnMut(u64) -> Result<(ID3D12Resource, u64), String>,
) -> Result<ID3D12Resource, String> {
validate_subresources(subs)?;
let rd = res.GetDesc();
@@ -264,7 +418,10 @@ pub unsafe fn record_upload_states(
));
}
}
- let up = buffer(dev, total)?;
+ let (up, base) = staging(total)?;
+ for fp in fps.iter_mut() {
+ fp.Offset += base;
+ }
let mut p = std::ptr::null_mut();
up.Map(0, None, Some(&mut p)).map_err(err)?;
for ((s, fp), &nrows) in subs.iter().zip(&fps).zip(&rows) {
diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs
index 2d8194e..e3066b9 100644
--- a/crates/xcl/src/hle/d3d12x/title_textures.rs
+++ b/crates/xcl/src/hle/d3d12x/title_textures.rs
@@ -314,6 +314,9 @@ pub(super) unsafe fn refresh(queue: *mut c_void) {
}
let _refresh = REFRESH.lock().unwrap();
own_work(|| refresh_once(queue));
+ if !sync_uploads() {
+ wait_for_uploads(queue);
+ }
}
unsafe fn refresh_once(queue: *mut c_void) {
@@ -457,7 +460,23 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) {
continue;
}
};
- match own_work(|| texture::upload_batch(dev, &queue, &batch)) {
+ let r = if sync_uploads() {
+ own_work(|| texture::upload_batch(dev, &queue, &batch))
+ } else {
+ let mut ups = UPLOADERS.lock().unwrap();
+ let up = match ups.get_mut(&device) {
+ Some(u) => u,
+ None => match texture::Uploader::new(dev) {
+ Ok(u) => ups.entry(device).or_insert(u),
+ Err(e) => {
+ warn(&e);
+ continue;
+ }
+ },
+ };
+ own_work(|| up.upload(dev, &queue, &batch))
+ };
+ match r {
Ok(failed) => {
for (_, e) in failed {
warn(&e);
@@ -469,6 +488,43 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) {
}
}
+/// `XCL_SYNC_UPLOADS=1`: each batch of uploads waited for on the CPU (as before `Uploader`)
+fn sync_uploads() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var("XCL_SYNC_UPLOADS").is_ok_and(|v| v.trim() == "1"))
+}
+
+/// the uploaders, per device (`texture::Uploader`)
+static UPLOADERS: Mutex<BTreeMap<usize, texture::Uploader>> = Mutex::new(BTreeMap::new());
+/// title queue → the upload fence value it last waited for
+static UPLOAD_WAITED: Mutex<BTreeMap<usize, u64>> = Mutex::new(BTreeMap::new());
+
+/// Before the title's work on `queue`: it waits on the GPU for the uploads made so far on its
+/// device (a fence of another device cannot be waited for: with two devices in one process – the
+/// tests – that left a queue's work unrun).
+unsafe fn wait_for_uploads(queue: *mut c_void) {
+ let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return };
+ let ups = UPLOADERS.lock().unwrap();
+ if ups.is_empty() {
+ return;
+ }
+ let mut dev: Option<ID3D12Device> = None;
+ if q.GetDevice(&mut dev).is_err() {
+ return;
+ }
+ let Some(dev) = dev else { return };
+ let Some(up) = ups.get(&(dev.as_raw() as usize)) else { return };
+ let (fence, value) = up.done_at();
+ if value == 0 {
+ return;
+ }
+ let mut w = UPLOAD_WAITED.lock().unwrap();
+ if w.get(&(queue as usize)).copied().unwrap_or(0) < value {
+ let _ = q.Wait(fence, value);
+ w.insert(queue as usize, value);
+ }
+}
+
/// `XCL_TRACE_FRAME`: how much of a title texture's top level is not zero, each time it is
/// uploaded (the first 48 uploads of textures of 64x64 and more).
fn note_content(va: usize, r: &ID3D12Resource, subs: &[texture::Subresource]) {Tested:
Not tested: the diff on its own with the title; no It is separate from this PR; here for anyone who wants to pick it up. AI-assisted (Claude Code, Claude Opus 5.5). |
Stacked on #252: this branch contains #252's commit (862a0d4) followed by this one (94bfcf0). Review/merge #252 first; this PR's own diff is the last commit.
What was wrong
After the first A press, a retail game showed a solid green screen (
0x008700) for ~15 s before its menus. Green is what a YUV→RGB shader gives for zero luma and chroma. The draws in that stretch come from one pixel shader that samples three R8 planes (3840x2160 + 2x 1920x1080): the game's Bink video.BinkRegisterFrameBuffers(traced withXCL_TRACE_IMPORTS) gets frame buffers in one reservation, which the CPU decoder writes.XCL_WATCH_SRV-style logging of the views) lie at the same addresses + 0x6_0000_0000, in a second reservation.The game reserves 24 GB of 64 KiB pages twice in a row (flags
0x20402000): firstPAGE_READWRITE, thenPAGE_NOACCESS | PAGE_GRAPHICS_NOACCESS(0x801). It maps physical pages (XMemMapPhysicalPages, ~60k calls in the first minute) only into the first, never into the second, yet places GPU resources at the same offset in the second. On the console the second reservation is a GPU-only view of the first. Under XCL it was separate, empty memory.Change
kernelx::mirrors: a no-access graphics reservation of 64 KiB pages is paired with the most recent CPU-readable reservation of the same size (dropped when either is released).source(va)names the CPU-view address behind a GPU-view address.title_textures: a texture placed in a GPU view where nothing is mapped is kept in step with the same offset in the CPU view. Its bytes are read and its CPU writes watched there (Entry::src). Its title address (address():GetGPUVirtualAddress, GPU copies into it) stays the GPU view's.It needs the CPU view to be write-watched, which is what #252 adds for these fallback reservations.
Scope: only kept-in-step textures follow the CPU view. Buffers the title might place in such a GPU view are not covered. Mapping the same pages into both views (true aliasing through a section) would cover everything, but XCL's physical pages move between addresses by commit/decommit, and views of a section can neither be write-watched nor decommitted.
Testing
gpu_view_reservations_name_their_cpu_view(pairing, offsets, end of range, release).cargo test --workspace: 653 passed, 0 failed, 40 ignored (RTX 5070 Ti, driver 32.0.16.1088).XCL_PRESS_AT=45:A, frame dumps): the intro video plays after the A press instead of the green screen. 512+ textures found in the GPU view within 90 s.🤖 Generated with Claude Code