kernelx: check section page liveness for DirectStorage #3075

Open
ZekkJJ wants to merge 8 commits from upstream-pr/3075 into main
ZekkJJ commented 2026-11-27 21:43:50 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by ZekkJJ on 2026-11-27T21:43:50Z.


Stacked on #3074 and the original section-alias stack in #2307 by @adiologydev. The focused commits are cfe04f431e and 4fdd282403. Focused diff

DirectStorage rereads eligible destination page lists when a request runs. After enabling #2307, its liveness check still used the conventional page index. Valid section-backed IDs failed the check, so the worker used the old list and could write a successful request to the previous page. This follows the existing late-fill and stack snapshot contract from #1405.

What is in it

  • Check the section-backed page index in alias mode. Recover the individual-release bitmap from the historical section integration so freed IDs cannot pass validation while neighboring pages in the section are live.

  • Verify that a duplicate free leaves the neighboring allocation alive, a freed ID cannot be used for a new mapping or DirectStorage access, and an existing view retains its bytes until unmapped.

  • Resolve the source before unmapping the destination. Return the ordinary invalid-parameter error for a released ID and keep the old destination view intact. Serialize alias mapping and copy-back with physical-page and alias-space release so the private home view remains valid through Windows mapping and copy calls. Page-fault handlers can still acquire the state mutex.

  • Add deterministic cases for a source released after preflight, a multi-page rejection before the first destination changes, and duplicate releases at indices 63 and 64 in a 65-page block.

Tested

  • RTX 4060 Laptop GPU 8 GiB (driver 32.0.16.1656), Ryzen 7 8845HS, 16 GiB RAM, Windows 11 build 26200, Rust 1.98.1 MSVC.

  • With XCL_PAGE_ALIAS=1 at parent 785d7dc5533edc8577c9a8e8e221acd40d980d23, hle::dstorage::tests::a_destination_page_rewritten_after_enqueue failed its 256-byte comparison. The updated page was still zero after the worker reported success.

  • On cfe04f431e6d9e0fdd18128064cbf546ee9fa747, cargo test -p xcl --lib hle::kernelx::alias::tests -- --test-threads=1 --nocapture gave 7 passed. cargo test -p xcl --lib hle::dstorage::tests -- --test-threads=1 --nocapture gave 19 passed, including the same byte comparison and the existing stack-snapshot assertions. Both used XCL_PAGE_ALIAS=1, with 0 failures, ignored tests, or explicit capability skips.

  • On review head 4fdd282403, the opt-in single-threaded alias suite passed 9 tests and DirectStorage passed 19 tests, with 0 failures, ignored tests, or explicit skips. Both new regressions passed. Only the focused library tests were rebuilt on this head.

  • On the previous head cfe04f431e, the clean release build passed. The complete workspace command with built fixtures reported 1,486 pass statuses, 1 failure, and 47 ignored. There were 27 explicit skip notices (21 missing wave64, 3 unsupported per-lane forms, 1 Developer Mode requirement, 1 missing heap-window capability, and 1 default-mode alias opt-in skip). The D32S8 VRAM fixture returned 0x80004005 in the threaded run, as it had on an initial run of the parent. It passed the isolated rerun on this head.
    Regression run

The Series S preflight for this review expired with 5178 MiB free RAM and 14637 MiB free commit, below the guarded thresholds of 6,600 and 18,000 MiB. The clean main release was ready for reuse. Fresh smoke blocks and the updated-head retail comparison remain pending.

The RTX 5070 Ti Prestream report is consistent with a resource field being left stale or overwritten by a wrong-page write. The reported base contains the same conventional-only liveness check, and a separate RTX 3090 capture tied stale DirectStorage page lists to garbage pointers, including the same +0x4da6315 breakpoint. The 5070 Ti run changed two switches and supplies no asset provenance or matching page history. Its cause remains unverified. Correlation would require the asset offset and expected bytes, the enqueue and execution page IDs, the selected destination and the guest's later read for that same request. RTX 5070 Ti report · RTX 3090 page history · Maintainer's alias-mode note

Not tested

  • Retail world entry, GPU rendering correctness in alias mode, AMD/Intel hardware and Wine.
  • A release racing an already running copy and explicit-submit timing (#1599) are separate issues. The measured historical aliasing savings are reported on #3074 and belong to that integration.

AI use

Codex (GPT-6 family, exact runtime variant unavailable) recovered and isolated the correction, reproduced the failure, ran the tests, and drafted the report.

<!-- greyfinch-sync:ivall/xcl:issue:5533460450 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3075). Originally posted by [ZekkJJ](https://github.com/ZekkJJ) on 2026-11-27T21:43:50Z. --- Stacked on #3074 and the original section-alias stack in #2307 by @adiologydev. The focused commits are cfe04f431e6d9e0fdd18128064cbf546ee9fa747 and 4fdd282403236f149a8d2184790c25adf00d1947. [Focused diff](https://github.com/ZekkJJ/xcl/compare/785d7dc5533edc8577c9a8e8e221acd40d980d23...4fdd282403236f149a8d2184790c25adf00d1947) DirectStorage rereads eligible destination page lists when a request runs. After enabling #2307, its liveness check still used the conventional page index. Valid section-backed IDs failed the check, so the worker used the old list and could write a successful request to the previous page. This follows the existing late-fill and stack snapshot contract from #1405. **What is in it** - Check the section-backed page index in alias mode. Recover the individual-release bitmap from the historical section integration so freed IDs cannot pass validation while neighboring pages in the section are live. - Verify that a duplicate free leaves the neighboring allocation alive, a freed ID cannot be used for a new mapping or DirectStorage access, and an existing view retains its bytes until unmapped. - Resolve the source before unmapping the destination. Return the ordinary invalid-parameter error for a released ID and keep the old destination view intact. Serialize alias mapping and copy-back with physical-page and alias-space release so the private home view remains valid through Windows mapping and copy calls. Page-fault handlers can still acquire the state mutex. - Add deterministic cases for a source released after preflight, a multi-page rejection before the first destination changes, and duplicate releases at indices 63 and 64 in a 65-page block. **Tested** - RTX 4060 Laptop GPU 8 GiB (driver `32.0.16.1656`), Ryzen 7 8845HS, 16 GiB RAM, Windows 11 build 26200, Rust 1.98.1 MSVC. - With `XCL_PAGE_ALIAS=1` at parent `785d7dc5533edc8577c9a8e8e221acd40d980d23`, `hle::dstorage::tests::a_destination_page_rewritten_after_enqueue` failed its 256-byte comparison. The updated page was still zero after the worker reported success. - On `cfe04f431e6d9e0fdd18128064cbf546ee9fa747`, `cargo test -p xcl --lib hle::kernelx::alias::tests -- --test-threads=1 --nocapture` gave 7 passed. `cargo test -p xcl --lib hle::dstorage::tests -- --test-threads=1 --nocapture` gave 19 passed, including the same byte comparison and the existing stack-snapshot assertions. Both used `XCL_PAGE_ALIAS=1`, with 0 failures, ignored tests, or explicit capability skips. - On review head 4fdd282403236f149a8d2184790c25adf00d1947, the opt-in single-threaded alias suite passed 9 tests and DirectStorage passed 19 tests, with 0 failures, ignored tests, or explicit skips. Both new regressions passed. Only the focused library tests were rebuilt on this head. - On the previous head cfe04f431e6d9e0fdd18128064cbf546ee9fa747, the clean release build passed. The complete workspace command with built fixtures reported 1,486 pass statuses, 1 failure, and 47 ignored. There were 27 explicit skip notices (21 missing wave64, 3 unsupported per-lane forms, 1 Developer Mode requirement, 1 missing heap-window capability, and 1 default-mode alias opt-in skip). The D32S8 VRAM fixture returned `0x80004005` in the threaded run, as it had on an initial run of the parent. It passed the isolated rerun on this head. **Regression run** The Series S preflight for this review expired with 5178 MiB free RAM and 14637 MiB free commit, below the guarded thresholds of 6,600 and 18,000 MiB. The clean main release was ready for reuse. Fresh smoke blocks and the updated-head retail comparison remain pending. The RTX 5070 Ti Prestream report is consistent with a resource field being left stale or overwritten by a wrong-page write. The reported base contains the same conventional-only liveness check, and a separate RTX 3090 capture tied stale DirectStorage page lists to garbage pointers, including the same +0x4da6315 breakpoint. The 5070 Ti run changed two switches and supplies no asset provenance or matching page history. Its cause remains unverified. Correlation would require the asset offset and expected bytes, the enqueue and execution page IDs, the selected destination and the guest's later read for that same request. [RTX 5070 Ti report](https://github.com/xcl-dev/xcl/pull/2307#issuecomment-7174846273) · [RTX 3090 page history](https://github.com/xcl-dev/xcl/pull/1405#issuecomment-7150898002) · [Maintainer's alias-mode note](https://github.com/xcl-dev/xcl/pull/1405#issuecomment-7168063270) **Not tested** - Retail world entry, GPU rendering correctness in alias mode, AMD/Intel hardware and Wine. - A release racing an already running copy and explicit-submit timing (#1599) are separate issues. The measured historical aliasing savings are reported on #3074 and belong to that integration. **AI use** Codex (GPT-6 family, exact runtime variant unavailable) recovered and isolated the correction, reproduced the failure, ran the tests, and drafted the report.
Kalmarv commented 2026-11-27 21:51:20 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-11-27T21:51:20Z.

Review: COMMENTED


Reviewed the focused commit against 785d7dc5. The section lookup checks the block extent before indexing the bitmap. Under the state mutex, only the first free of each ID decrements the live count. Duplicate frees preserve neighboring IDs, and existing section views retain their backing. The nonempty DirectStorage reread predicate takes a consistent snapshot of the whole ID list.

I found one mapping caller that still assumes this lookup cannot fail (inline). Separately, the existing DirectStorage copy has a lifetime limitation already acknowledged in the description. The worker rechecks IDs while resolving addresses, but the resolved home or moved-page addresses have no lifetime guard during the copy. A release or remap concurrent with an in-flight copy therefore remains outside the guarantee. A future fix would need to hold the backing mapping stable through the transfer.

I reran both test groups on Windows at cfe04f43 with XCL_PAGE_ALIAS=1 and one test thread. All 26 passed (7 alias, 19 DirectStorage). The runtime log confirmed the rewritten-list path executed. That covers the duplicate-free, surviving-view and stack-snapshot cases. A useful additional bitmap edge is a 65-page block with releases on either side of indices 63 and 64. I did not run a retail title or a concurrency stress test.

<!-- greyfinch-sync:ivall/xcl:review:6093666506 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3075#pullrequestreview-6093666506). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-11-27T21:51:20Z. **Review:** COMMENTED --- Reviewed the focused commit against `785d7dc5`. The section lookup checks the block extent before indexing the bitmap. Under the state mutex, only the first free of each ID decrements the live count. Duplicate frees preserve neighboring IDs, and existing section views retain their backing. The nonempty DirectStorage reread predicate takes a consistent snapshot of the whole ID list. I found one mapping caller that still assumes this lookup cannot fail (inline). Separately, the existing DirectStorage copy has a lifetime limitation already acknowledged in the description. The worker rechecks IDs while resolving addresses, but the resolved home or moved-page addresses have no lifetime guard during the copy. A release or remap concurrent with an in-flight copy therefore remains outside the guarantee. A future fix would need to hold the backing mapping stable through the transfer. I reran both test groups on Windows at `cfe04f43` with `XCL_PAGE_ALIAS=1` and one test thread. All 26 passed (7 alias, 19 DirectStorage). The runtime log confirmed the rewritten-list path executed. That covers the duplicate-free, surviving-view and stack-snapshot cases. A useful additional bitmap edge is a 65-page block with releases on either side of indices 63 and 64. I did not run a retail title or a concurrency stress test.
Kalmarv commented 2026-11-27 21:51:21 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-11-27T21:51:21Z.

Code review location: crates/xcl/src/hle/kernelx/alias.rs; line 79

@@ -0,0 +1,580 @@
+//! Physical pages that show at every address they are mapped at (`XCL_PAGE_ALIAS=1`).
+//!
+//! Without it a physical page is kept at one address at a time and moved (copied) when the
+//! title maps it elsewhere. With it a block of physical pages is a section (`sections`): the
+//! title's reservations of 64 KiB pages are placeholders ("spaces"), and mapping a page there
+//! maps a view of its slice, so every address the title mapped it at shows the same memory.
+//! The views are guarded (`guards`): a write through one is uploaded at all of them.
+//!
+//! Each block also has a view of its own (its home, never given to the title) through which
+//! XCL reads and writes pages by number (DirectStorage destinations). A retail title never maps
+//! a page at its home, so homes are plain address space, not the GPU-visible sparse windows.
+//!
+//! A page mapped at an address outside a space (a placeholder region the title made in a
+//! sparse window) is moved there as before: its bytes are copied there and back again when it
+//! is unmapped. While it is away its views show what it held when it left.
+
+use std::collections::{BTreeMap, HashMap};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
+
+use windows_sys::Win32::Foundation as fnd;
+use windows_sys::Win32::System::Memory as mem;
+
+use super::sections::{self, Section, PAGE};
+use super::{guards, lazy, page_index, page_number, NEXT_PAGE_INDEX};
+
+/// `XCL_PAGE_ALIAS=1` turns physical page aliasing on (default: off).
+pub fn enabled() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| std::env::var("XCL_PAGE_ALIAS").is_ok_and(|v| v.trim() == "1"))
+}
+
+struct Block {
+    section: Arc<Section>,
+    /// XCL's own view of the whole block
+    home: usize,
+    /// pages not freed yet
+    live: usize,
+    /// Individual IDs may be freed before their backing block and surviving views.
+    freed: Vec<u64>,
+    /// one bit a page: committed (asking Windows walked the rest of a block's uncommitted run –
+    /// a retail title mapping 100 000 fresh pages one at a time waited 20 s for its first frame)
+    committed: Arc<Vec<AtomicU64>>,
+}
+
+impl Block {
+    fn has_page(&self, index: usize) -> bool {
+        index < self.section.pages() && self.freed[index / 64] & (1 << (index % 64)) == 0
+    }
+}
+
+#[derive(Default)]
+struct State {
+    /// first page index → block
+    blocks: BTreeMap<usize, Block>,
+    /// the title's reservations kept as placeholders: base → size
+    spaces: BTreeMap<usize, usize>,
+    /// address (64 KiB) in a space → (page number, its section, the page's index in it)
+    views: BTreeMap<usize, (usize, Arc<Section>, usize)>,
+    /// pages moved to an address outside the spaces: page → address, and address → page
+    away: HashMap<usize, usize>,
+    away_at: BTreeMap<usize, usize>,
+}
+
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+
+fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    f(g.get_or_insert_with(State::default))
+}
+
+impl State {
+    /// (block's section, the page's index in it, its address in the home view) of page number `page`
+    fn page(&self, page: usize) -> Option<(Arc<Section>, usize, usize)> {
+        let index = page_index(page)?;
+        let (&first, b) = self.blocks.range(..=index).next_back()?;
+        let i = index - first;
+        b.has_page(i).then(|| (b.section.clone(), i, b.home + i * PAGE))

Please handle a failed second lookup in map_one before tearing down the destination mapping. This change makes State::page return None immediately for an individually released ID. map validates under one lock acquisition, then map_one relinquishes the old destination and calls s.page(page).unwrap() under another. A concurrent release can therefore panic even while the rest of the source block remains live. The parent already had this gap on final block release. Resolving the source before changing the destination and returning the normal mapping error on a missing ID would cover this newly affected case. A regression should also assert that the old destination view stays intact on rejection.

<!-- greyfinch-sync:ivall/xcl:review-comment:4723887950 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3075#discussion_r4723887950). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-11-27T21:51:21Z. **Code review location:** `crates/xcl/src/hle/kernelx/alias.rs`; line 79 ~~~~diff @@ -0,0 +1,580 @@ +//! Physical pages that show at every address they are mapped at (`XCL_PAGE_ALIAS=1`). +//! +//! Without it a physical page is kept at one address at a time and moved (copied) when the +//! title maps it elsewhere. With it a block of physical pages is a section (`sections`): the +//! title's reservations of 64 KiB pages are placeholders ("spaces"), and mapping a page there +//! maps a view of its slice, so every address the title mapped it at shows the same memory. +//! The views are guarded (`guards`): a write through one is uploaded at all of them. +//! +//! Each block also has a view of its own (its home, never given to the title) through which +//! XCL reads and writes pages by number (DirectStorage destinations). A retail title never maps +//! a page at its home, so homes are plain address space, not the GPU-visible sparse windows. +//! +//! A page mapped at an address outside a space (a placeholder region the title made in a +//! sparse window) is moved there as before: its bytes are copied there and back again when it +//! is unmapped. While it is away its views show what it held when it left. + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows_sys::Win32::Foundation as fnd; +use windows_sys::Win32::System::Memory as mem; + +use super::sections::{self, Section, PAGE}; +use super::{guards, lazy, page_index, page_number, NEXT_PAGE_INDEX}; + +/// `XCL_PAGE_ALIAS=1` turns physical page aliasing on (default: off). +pub fn enabled() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PAGE_ALIAS").is_ok_and(|v| v.trim() == "1")) +} + +struct Block { + section: Arc<Section>, + /// XCL's own view of the whole block + home: usize, + /// pages not freed yet + live: usize, + /// Individual IDs may be freed before their backing block and surviving views. + freed: Vec<u64>, + /// one bit a page: committed (asking Windows walked the rest of a block's uncommitted run – + /// a retail title mapping 100 000 fresh pages one at a time waited 20 s for its first frame) + committed: Arc<Vec<AtomicU64>>, +} + +impl Block { + fn has_page(&self, index: usize) -> bool { + index < self.section.pages() && self.freed[index / 64] & (1 << (index % 64)) == 0 + } +} + +#[derive(Default)] +struct State { + /// first page index → block + blocks: BTreeMap<usize, Block>, + /// the title's reservations kept as placeholders: base → size + spaces: BTreeMap<usize, usize>, + /// address (64 KiB) in a space → (page number, its section, the page's index in it) + views: BTreeMap<usize, (usize, Arc<Section>, usize)>, + /// pages moved to an address outside the spaces: page → address, and address → page + away: HashMap<usize, usize>, + away_at: BTreeMap<usize, usize>, +} + +static STATE: Mutex<Option<State>> = Mutex::new(None); + +fn with<R>(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +impl State { + /// (block's section, the page's index in it, its address in the home view) of page number `page` + fn page(&self, page: usize) -> Option<(Arc<Section>, usize, usize)> { + let index = page_index(page)?; + let (&first, b) = self.blocks.range(..=index).next_back()?; + let i = index - first; + b.has_page(i).then(|| (b.section.clone(), i, b.home + i * PAGE)) ~~~~ --- Please handle a failed second lookup in `map_one` before tearing down the destination mapping. This change makes `State::page` return `None` immediately for an individually released ID. `map` validates under one lock acquisition, then `map_one` relinquishes the old destination and calls `s.page(page).unwrap()` under another. A concurrent release can therefore panic even while the rest of the source block remains live. The parent already had this gap on final block release. Resolving the source before changing the destination and returning the normal mapping error on a missing ID would cover this newly affected case. A regression should also assert that the old destination view stays intact on rejection.
Lum7nt commented 2026-11-27 21:54:04 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Lum7nt on 2026-11-27T21:54:04Z.


Native Windows 11 + NVIDIA RTX 3060 verification of PR #3075

Tested PR #3075 head cfe04f431e6d9e0fdd18128064cbf546ee9fa747 on native Windows 11 on NVIDIA RTX 3060 (12 GB, native wave32).

Environment

  • GPU: NVIDIA GeForce RTX 3060 (12 GB / 12,115 MiB VRAM), driver 32.0.15.8142 (WDDM 3.2)
  • CPU / RAM / OS: Intel Core i5-10400 CPU @ 2.90GHz (6C / 12T), 32 GB RAM, Windows 11 Build 22631 (NT 10.0.22631.0)
  • Toolchain: rustc 1.100.0 (0ef1bc386 2026-11-09) x86_64-pc-windows-msvc, Windows SDK DXC 1.8.2502.11 / dxil 1.8.2502.11

Test Results

  1. Kernelx Alias Tests (XCL_PAGE_ALIAS=1):
cargo test -p xcl --lib hle::kernelx::alias::tests -- --nocapture
  • a_freed_page_id_is_rejected_while_its_neighbor_and_existing_view_survive — PASS
  • a_page_not_from_the_title_is_refused — PASS
  • a_page_mapped_into_two_spaces_is_one_page_and_writes_reach_both — PASS
  • pages_read_and_written_by_number_are_the_pages_the_title_sees — PASS
  • scatter_without_pages_unmaps_only_the_listed_aliases — PASS
  • remapping_an_address_shows_the_new_page_and_keeps_the_old_one — PASS
  • a_page_moved_outside_the_spaces_goes_and_comes_back_with_its_bytes — PASS
    Result: 7 passed; 0 failed; 0 ignored; 0 skipped (0.02s).
  1. DirectStorage Liveness & Rewritten Destination Tests (XCL_PAGE_ALIAS=1):
cargo test -p xcl --lib hle::dstorage::tests -- --nocapture
  • a_destination_page_rewritten_after_enqueue — PASS (verified that updated destination page receives payload while previous/stale page is rejected under alias::pages_live)
  • a_destination_page_filled_in_after_enqueue — PASS
  • physical_page_destinations_and_sources — PASS
  • All 19 DirectStorage test fixtures — PASS (0.28s).
  1. D3D12 Integration Verification (d3d12_resource_and_sync under XCL_PAGE_ALIAS=1):
cargo test -p xcl --test d3d12_resource_and_sync
  • Result: 3 passed; 0 failed; 0 ignored; 0 skipped (0.56s) on the live RTX 3060 D3D12 device.

Observations

  • Verified that alias::pages_live correctly traverses section blocks via block.has_page and individual-release bitmaps (b.freed), accurately identifying live section-backed page IDs for DirectStorage late-fill rereads.
  • Neighboring pages within the same section remain accessible after individual frees, and duplicate frees do not corrupt the active block or adjacent views.

AI disclosure: Testing executed independently on physical hardware; report drafted with agent assistance.

<!-- greyfinch-sync:ivall/xcl:comment:7228853745 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3075#issuecomment-7228853745). Originally posted by [Lum7nt](https://github.com/Lum7nt) on 2026-11-27T21:54:04Z. --- ### Native Windows 11 + NVIDIA RTX 3060 verification of PR #3075 Tested PR #3075 head `cfe04f431e6d9e0fdd18128064cbf546ee9fa747` on native Windows 11 on NVIDIA RTX 3060 (12 GB, native wave32). ### Environment - **GPU:** NVIDIA GeForce RTX 3060 (12 GB / 12,115 MiB VRAM), driver `32.0.15.8142` (WDDM 3.2) - **CPU / RAM / OS:** Intel Core i5-10400 CPU @ 2.90GHz (6C / 12T), 32 GB RAM, Windows 11 Build 22631 (NT 10.0.22631.0) - **Toolchain:** `rustc 1.100.0 (0ef1bc386 2026-11-09)` x86_64-pc-windows-msvc, Windows SDK DXC `1.8.2502.11` / dxil `1.8.2502.11` ### Test Results 1. **Kernelx Alias Tests (`XCL_PAGE_ALIAS=1`):** ```powershell cargo test -p xcl --lib hle::kernelx::alias::tests -- --nocapture ``` - `a_freed_page_id_is_rejected_while_its_neighbor_and_existing_view_survive` — **PASS** - `a_page_not_from_the_title_is_refused` — **PASS** - `a_page_mapped_into_two_spaces_is_one_page_and_writes_reach_both` — **PASS** - `pages_read_and_written_by_number_are_the_pages_the_title_sees` — **PASS** - `scatter_without_pages_unmaps_only_the_listed_aliases` — **PASS** - `remapping_an_address_shows_the_new_page_and_keeps_the_old_one` — **PASS** - `a_page_moved_outside_the_spaces_goes_and_comes_back_with_its_bytes` — **PASS** **Result:** **7 passed; 0 failed; 0 ignored; 0 skipped** (0.02s). 2. **DirectStorage Liveness & Rewritten Destination Tests (`XCL_PAGE_ALIAS=1`):** ```powershell cargo test -p xcl --lib hle::dstorage::tests -- --nocapture ``` - `a_destination_page_rewritten_after_enqueue` — **PASS** (verified that updated destination page receives payload while previous/stale page is rejected under `alias::pages_live`) - `a_destination_page_filled_in_after_enqueue` — **PASS** - `physical_page_destinations_and_sources` — **PASS** - All 19 DirectStorage test fixtures — **PASS** (0.28s). 3. **D3D12 Integration Verification (`d3d12_resource_and_sync` under `XCL_PAGE_ALIAS=1`):** ```powershell cargo test -p xcl --test d3d12_resource_and_sync ``` - **Result:** **3 passed; 0 failed; 0 ignored; 0 skipped** (0.56s) on the live RTX 3060 D3D12 device. ### Observations - Verified that `alias::pages_live` correctly traverses section blocks via `block.has_page` and individual-release bitmaps (`b.freed`), accurately identifying live section-backed page IDs for DirectStorage late-fill rereads. - Neighboring pages within the same section remain accessible after individual frees, and duplicate frees do not corrupt the active block or adjacent views. *AI disclosure: Testing executed independently on physical hardware; report drafted with agent assistance.*
ZekkJJ commented 2026-11-27 21:59:40 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by ZekkJJ on 2026-11-27T21:59:40Z.

Code review location: crates/xcl/src/hle/kernelx/alias.rs; line 79

@@ -0,0 +1,580 @@
+//! Physical pages that show at every address they are mapped at (`XCL_PAGE_ALIAS=1`).
+//!
+//! Without it a physical page is kept at one address at a time and moved (copied) when the
+//! title maps it elsewhere. With it a block of physical pages is a section (`sections`): the
+//! title's reservations of 64 KiB pages are placeholders ("spaces"), and mapping a page there
+//! maps a view of its slice, so every address the title mapped it at shows the same memory.
+//! The views are guarded (`guards`): a write through one is uploaded at all of them.
+//!
+//! Each block also has a view of its own (its home, never given to the title) through which
+//! XCL reads and writes pages by number (DirectStorage destinations). A retail title never maps
+//! a page at its home, so homes are plain address space, not the GPU-visible sparse windows.
+//!
+//! A page mapped at an address outside a space (a placeholder region the title made in a
+//! sparse window) is moved there as before: its bytes are copied there and back again when it
+//! is unmapped. While it is away its views show what it held when it left.
+
+use std::collections::{BTreeMap, HashMap};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
+
+use windows_sys::Win32::Foundation as fnd;
+use windows_sys::Win32::System::Memory as mem;
+
+use super::sections::{self, Section, PAGE};
+use super::{guards, lazy, page_index, page_number, NEXT_PAGE_INDEX};
+
+/// `XCL_PAGE_ALIAS=1` turns physical page aliasing on (default: off).
+pub fn enabled() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| std::env::var("XCL_PAGE_ALIAS").is_ok_and(|v| v.trim() == "1"))
+}
+
+struct Block {
+    section: Arc<Section>,
+    /// XCL's own view of the whole block
+    home: usize,
+    /// pages not freed yet
+    live: usize,
+    /// Individual IDs may be freed before their backing block and surviving views.
+    freed: Vec<u64>,
+    /// one bit a page: committed (asking Windows walked the rest of a block's uncommitted run –
+    /// a retail title mapping 100 000 fresh pages one at a time waited 20 s for its first frame)
+    committed: Arc<Vec<AtomicU64>>,
+}
+
+impl Block {
+    fn has_page(&self, index: usize) -> bool {
+        index < self.section.pages() && self.freed[index / 64] & (1 << (index % 64)) == 0
+    }
+}
+
+#[derive(Default)]
+struct State {
+    /// first page index → block
+    blocks: BTreeMap<usize, Block>,
+    /// the title's reservations kept as placeholders: base → size
+    spaces: BTreeMap<usize, usize>,
+    /// address (64 KiB) in a space → (page number, its section, the page's index in it)
+    views: BTreeMap<usize, (usize, Arc<Section>, usize)>,
+    /// pages moved to an address outside the spaces: page → address, and address → page
+    away: HashMap<usize, usize>,
+    away_at: BTreeMap<usize, usize>,
+}
+
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+
+fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    f(g.get_or_insert_with(State::default))
+}
+
+impl State {
+    /// (block's section, the page's index in it, its address in the home view) of page number `page`
+    fn page(&self, page: usize) -> Option<(Arc<Section>, usize, usize)> {
+        let index = page_index(page)?;
+        let (&first, b) = self.blocks.range(..=index).next_back()?;
+        let i = index - first;
+        b.has_page(i).then(|| (b.section.clone(), i, b.home + i * PAGE))

Addressed in 4fdd282403. It resolves the source before changing the destination and reports ERROR_INVALID_PARAMETER if the ID has been released. A separate mapping lock serializes the complete native map and move-back path with page and alias-space release. This protects the raw home view as well as the section object, while leaving STATE available to the fault handlers.

The regression deterministically releases the source after preflight and checks that the destination still maps its old bytes for both a partial release and a final block release. The new 65-page test covers releases at indices 63 and 64, duplicate releases, and surviving neighbors. The opt-in run passed 9 alias tests and 19 DirectStorage tests, with no skips. Stabilizing the worker's page addresses during a concurrent DirectStorage transfer remains a separate issue.

<!-- greyfinch-sync:ivall/xcl:review-comment:4723931845 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3075#discussion_r4723931845). Originally posted by [ZekkJJ](https://github.com/ZekkJJ) on 2026-11-27T21:59:40Z. **Code review location:** `crates/xcl/src/hle/kernelx/alias.rs`; line 79 ~~~~diff @@ -0,0 +1,580 @@ +//! Physical pages that show at every address they are mapped at (`XCL_PAGE_ALIAS=1`). +//! +//! Without it a physical page is kept at one address at a time and moved (copied) when the +//! title maps it elsewhere. With it a block of physical pages is a section (`sections`): the +//! title's reservations of 64 KiB pages are placeholders ("spaces"), and mapping a page there +//! maps a view of its slice, so every address the title mapped it at shows the same memory. +//! The views are guarded (`guards`): a write through one is uploaded at all of them. +//! +//! Each block also has a view of its own (its home, never given to the title) through which +//! XCL reads and writes pages by number (DirectStorage destinations). A retail title never maps +//! a page at its home, so homes are plain address space, not the GPU-visible sparse windows. +//! +//! A page mapped at an address outside a space (a placeholder region the title made in a +//! sparse window) is moved there as before: its bytes are copied there and back again when it +//! is unmapped. While it is away its views show what it held when it left. + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows_sys::Win32::Foundation as fnd; +use windows_sys::Win32::System::Memory as mem; + +use super::sections::{self, Section, PAGE}; +use super::{guards, lazy, page_index, page_number, NEXT_PAGE_INDEX}; + +/// `XCL_PAGE_ALIAS=1` turns physical page aliasing on (default: off). +pub fn enabled() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PAGE_ALIAS").is_ok_and(|v| v.trim() == "1")) +} + +struct Block { + section: Arc<Section>, + /// XCL's own view of the whole block + home: usize, + /// pages not freed yet + live: usize, + /// Individual IDs may be freed before their backing block and surviving views. + freed: Vec<u64>, + /// one bit a page: committed (asking Windows walked the rest of a block's uncommitted run – + /// a retail title mapping 100 000 fresh pages one at a time waited 20 s for its first frame) + committed: Arc<Vec<AtomicU64>>, +} + +impl Block { + fn has_page(&self, index: usize) -> bool { + index < self.section.pages() && self.freed[index / 64] & (1 << (index % 64)) == 0 + } +} + +#[derive(Default)] +struct State { + /// first page index → block + blocks: BTreeMap<usize, Block>, + /// the title's reservations kept as placeholders: base → size + spaces: BTreeMap<usize, usize>, + /// address (64 KiB) in a space → (page number, its section, the page's index in it) + views: BTreeMap<usize, (usize, Arc<Section>, usize)>, + /// pages moved to an address outside the spaces: page → address, and address → page + away: HashMap<usize, usize>, + away_at: BTreeMap<usize, usize>, +} + +static STATE: Mutex<Option<State>> = Mutex::new(None); + +fn with<R>(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +impl State { + /// (block's section, the page's index in it, its address in the home view) of page number `page` + fn page(&self, page: usize) -> Option<(Arc<Section>, usize, usize)> { + let index = page_index(page)?; + let (&first, b) = self.blocks.range(..=index).next_back()?; + let i = index - first; + b.has_page(i).then(|| (b.section.clone(), i, b.home + i * PAGE)) ~~~~ --- Addressed in 4fdd282403236f149a8d2184790c25adf00d1947. It resolves the source before changing the destination and reports ERROR_INVALID_PARAMETER if the ID has been released. A separate mapping lock serializes the complete native map and move-back path with page and alias-space release. This protects the raw home view as well as the section object, while leaving STATE available to the fault handlers. The regression deterministically releases the source after preflight and checks that the destination still maps its old bytes for both a partial release and a final block release. The new 65-page test covers releases at indices 63 and 64, duplicate releases, and surviving neighbors. The opt-in run passed 9 alias tests and 19 DirectStorage tests, with no skips. Stabilizing the worker's page addresses during a concurrent DirectStorage transfer remains a separate issue.
throny commented 2026-11-28 16:50:13 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by throny on 2026-11-28T16:50:13Z.


merge-check claim
head: 4fdd282403

The diff of this PR contains #3074, so the check covers both. I also run the lib tests once with XCL_PAGE_ALIAS=1.

<!-- greyfinch-sync:ivall/xcl:comment:7242549998 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3075#issuecomment-7242549998). Originally posted by [throny](https://github.com/throny) on 2026-11-28T16:50:13Z. --- merge-check claim head: 4fdd282403236f149a8d2184790c25adf00d1947 The diff of this PR contains #3074, so the check covers both. I also run the lib tests once with `XCL_PAGE_ALIAS=1`.
throny commented 2026-11-28 16:54:31 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by throny on 2026-11-28T16:54:31Z.


merge-check
base: db3921dc
head: 4fdd282403
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2169 passed, 0 failed, 48 ignored on the merge result, switch off (27 SKIPPED lines; base alone at db3921dc: 2145 passed, 0 failed, 48 ignored, 26 SKIPPED; the extra one is this PR's scatter_without_pages_unmaps_only_the_listed_aliases, which needs the switch). Also XCL_PAGE_ALIAS=1 cargo test -p xcl --lib --no-fail-fast -- --test-threads=4 on the same tree: 2024 passed, 11 failed, 28 ignored. The 11: two GPU tests in title_textures (gpu_mirror_upload_follows_cpu_writes_and_later_mapping_changes, gpu_uploads_on_the_title_queue_run_before_its_later_work_and_are_released) and nine in hle::kernelx::tests (a_home_decommitted_in_the_same_call_is_asked_again, a_page_away_at_another_home_goes_home_with_it, a_page_away_from_home_is_committed_once, mapping_fresh_pages_does_not_query_each_page, mapping_lazy_pages_again_does_not_query_each_page, pages_mapped_again_at_another_address_keep_what_was_written, pages_mapped_again_at_the_same_address_keep_what_was_written, physical_pages_in_uma, scatter_matches_a_model_of_physical_pages). I did not sort them into "test of the other mode's internals" and "real difference"; the two that say pages keep what was written, the scatter model and the two GPU upload tests deserve the author's look.
review: this diff contains #3074 and the still-open #2307, so merging it merges both. Switch off (default): by reading, behaviour is the same as main. No exception handler is installed, every branch asks the switch first, and the one changed signature (lazy::ensure) has three callers on main, all updated. One small cost remains with the switch off: lazy::commit takes the alias state lock on every lazy commit without asking the switch first. Switch on, open points: (1) the copy by page number used for DirectStorage holds no lock while a free or an unmap of the same page can run (main holds its lock across the copy); acknowledged in the thread as out of scope. (2) Only ReadFile opens guarded views before the kernel writes; other kernel read calls into a guarded view would fail. (3) While an overlapped read keeps a view open, the title's own writes to that page are not seen as dirty until the read completes. (4) The write-fault handler is first in the chain and would also take a fault the title set up itself with its own protection on a mapped view. (5) The upload of such views to the GPU is not shown: the two GPU tests above fail in this mode, as the description of #3074 says for one of them. Process: the required PR description check fails because the regression run has no xcl-smoke blocks; the PR is about 1,540 lines (about 960 without tests) and the description does not say why it cannot be split; the whole suite was not run on this head by the author (it is now, above).
performance: nothing measured by me. A tester on #3074 reports one A/B pair on an RTX 3080 with the switch on: 19-26 instead of 5-6 presents per 2 s and 20.9 instead of 33.4 GB peak commit. No translator source changes: no re-translation.
verdict: not yet: as a default-off switch the code is close (suite clean, default path unchanged by reading), but it needs the two smoke blocks, #2307 and #3074 merged first or the stack stated as one unit, and a word on the 11 tests that fail with the switch on. I will re-check a new head quickly: this stack matters for the dark picture and for memory.
hardware / tool and model: RTX 4080 16 GB (621.40), i9-12900K, Windows 11 26300, Rust 1.100.0, debug. Claude Code; merge, build and suite run by Claude Fable 5.2, diff review by Claude Opus 5.5 (every hunk read; nothing run on the GPU beyond the suite).

<!-- greyfinch-sync:ivall/xcl:comment:7242605865 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3075#issuecomment-7242605865). Originally posted by [throny](https://github.com/throny) on 2026-11-28T16:54:31Z. --- merge-check base: db3921dc head: 4fdd282403236f149a8d2184790c25adf00d1947 merge: clean build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2169 passed, 0 failed, 48 ignored on the merge result, switch off (27 SKIPPED lines; base alone at db3921dc: 2145 passed, 0 failed, 48 ignored, 26 SKIPPED; the extra one is this PR's scatter_without_pages_unmaps_only_the_listed_aliases, which needs the switch). Also `XCL_PAGE_ALIAS=1 cargo test -p xcl --lib --no-fail-fast -- --test-threads=4` on the same tree: 2024 passed, 11 failed, 28 ignored. The 11: two GPU tests in title_textures (gpu_mirror_upload_follows_cpu_writes_and_later_mapping_changes, gpu_uploads_on_the_title_queue_run_before_its_later_work_and_are_released) and nine in hle::kernelx::tests (a_home_decommitted_in_the_same_call_is_asked_again, a_page_away_at_another_home_goes_home_with_it, a_page_away_from_home_is_committed_once, mapping_fresh_pages_does_not_query_each_page, mapping_lazy_pages_again_does_not_query_each_page, pages_mapped_again_at_another_address_keep_what_was_written, pages_mapped_again_at_the_same_address_keep_what_was_written, physical_pages_in_uma, scatter_matches_a_model_of_physical_pages). I did not sort them into "test of the other mode's internals" and "real difference"; the two that say pages keep what was written, the scatter model and the two GPU upload tests deserve the author's look. review: this diff contains #3074 and the still-open #2307, so merging it merges both. Switch off (default): by reading, behaviour is the same as main. No exception handler is installed, every branch asks the switch first, and the one changed signature (lazy::ensure) has three callers on main, all updated. One small cost remains with the switch off: lazy::commit takes the alias state lock on every lazy commit without asking the switch first. Switch on, open points: (1) the copy by page number used for DirectStorage holds no lock while a free or an unmap of the same page can run (main holds its lock across the copy); acknowledged in the thread as out of scope. (2) Only ReadFile opens guarded views before the kernel writes; other kernel read calls into a guarded view would fail. (3) While an overlapped read keeps a view open, the title's own writes to that page are not seen as dirty until the read completes. (4) The write-fault handler is first in the chain and would also take a fault the title set up itself with its own protection on a mapped view. (5) The upload of such views to the GPU is not shown: the two GPU tests above fail in this mode, as the description of #3074 says for one of them. Process: the required PR description check fails because the regression run has no xcl-smoke blocks; the PR is about 1,540 lines (about 960 without tests) and the description does not say why it cannot be split; the whole suite was not run on this head by the author (it is now, above). performance: nothing measured by me. A tester on #3074 reports one A/B pair on an RTX 3080 with the switch on: 19-26 instead of 5-6 presents per 2 s and 20.9 instead of 33.4 GB peak commit. No translator source changes: no re-translation. verdict: not yet: as a default-off switch the code is close (suite clean, default path unchanged by reading), but it needs the two smoke blocks, #2307 and #3074 merged first or the stack stated as one unit, and a word on the 11 tests that fail with the switch on. I will re-check a new head quickly: this stack matters for the dark picture and for memory. hardware / tool and model: RTX 4080 16 GB (621.40), i9-12900K, Windows 11 26300, Rust 1.100.0, debug. Claude Code; merge, build and suite run by Claude Fable 5.2, diff review by Claude Opus 5.5 (every hunk read; nothing run on the GPU beyond the suite).
ZekkJJ commented 2026-11-28 19:53:17 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by ZekkJJ on 2026-11-28T19:53:17Z.


@bmjask mind reviewing this when you get a chance? We've got independent retail validation now, with noticeable rendering and stability improvements.

<!-- greyfinch-sync:ivall/xcl:comment:7244877937 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3075#issuecomment-7244877937). Originally posted by [ZekkJJ](https://github.com/ZekkJJ) on 2026-11-28T19:53:17Z. --- @bmjask mind reviewing this when you get a chance? We've got independent retail validation now, with noticeable rendering and stability improvements.
KOLESNiii commented 2026-11-28 21:26:50 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by KOLESNiii on 2026-11-28T21:26:50Z.


Review of 4fdd2824 (#3211 workstream B): one finding, with a regression test that fails here and passes with a one-line fix.

alias::read / alias::write resolve page addresses and then copy without MAPPINGS. copy_pages (alias.rs:382-406) resolves each page through bytes_of, which takes and releases STATE per page, then copies with no lock held. MAPPINGS serialises map, free and free_space, but not this copy. The conventional path holds AWAY across both resolve and copy (read_physical_pages / write_physical_pages in kernelx.rs), so in alias mode the guarantee is weaker than the one it replaces. Two interleavings:

  • A DirectStorage write (dstorage.rs:345, :981) resolves a page's home. The title then frees the block's last live page, and free unmaps and releases the home (alias.rs:216-219). The copy writes into released address space.
  • A DirectStorage write resolves the page's away address. A concurrent remap then runs unmap_away, which copies the page home and then decommits the away address (alias.rs:304-325). The write either faults, or lands after the copy home and is lost.

Test. A #[cfg(test)] hook runs between resolve and copy. It frees the page from another thread and asserts that the free has not completed within 1 s.

  • At 4fdd2824 it fails: the page's home was released while a write into it was in flight.
  • With MAPPINGS taken at the top of copy_pages, before resolving, it passes, and the free completes after the write. The lock order MAPPINGS → STATE is the same as in map / free, and the fault handlers take only STATE.
Patch (fix + test hook + test)
@@ unsafe fn copy_pages(pages: &[usize], offset: usize, len: usize, mut f: impl FnM
     if offset >= PAGE || pages.len() < need {
         return false;
     }
+    // the addresses resolved below stay valid until the copy is done: no page of a block is
+    // freed (its home released) or moved (an address outside the spaces decommitted) meanwhile
+    let _mapping = MAPPINGS.lock().unwrap_or_else(|e| e.into_inner());
     let mut addrs = Vec::with_capacity(need);
     for &p in &pages[..need] {
         let Some(a) = bytes_of(p, write) else { return false };
         addrs.push((p, a));
     }
+    #[cfg(test)]
+    if let Some(hook) = tests::AFTER_RESOLVE.with(|h| h.borrow_mut().take()) {
+        hook();
+    }
@@ mod tests {
     use super::guards::tests::SERIAL;
 
+    thread_local! {
+        /// Run once by `copy_pages` on this thread, between resolving its pages and copying.
+        pub(super) static AFTER_RESOLVE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
+    }
+
+    #[test]
+    fn a_page_cannot_be_freed_while_a_write_by_number_copies_into_it() {
+        let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
+        let p = pages(1);
+        let freer = std::sync::Arc::new(std::sync::Mutex::new(None));
+        let slot = freer.clone();
+        let page = p[0];
+        AFTER_RESOLVE.with(|h| *h.borrow_mut() = Some(Box::new(move || {
+            // the title frees the block (its last page: the home goes) as the copy is about to start
+            let (tx, rx) = std::sync::mpsc::channel();
+            *slot.lock().unwrap() = Some(std::thread::spawn(move || {
+                unsafe { free(&[page]) };
+                let _ = tx.send(());
+            }));
+            assert!(rx.recv_timeout(std::time::Duration::from_secs(1)).is_err(), "the page's home was released while a write into it was in flight");
+        })));
+        unsafe {
+            assert!(write(&p, 0, &[0x5b; 64]));
+        }
+        if let Some(t) = freer.lock().unwrap().take() {
+            t.join().unwrap();
+        }
+        assert!(!pages_live(&p), "the free went through once the write was done");
+    }

Tested (RTX 2070 SUPER, Windows 11, debug, 4fdd2824 + the patch above plus the test from the #2307 comment, cargo test -p xcl --lib <filter> -- --test-threads=1):

  • hle::kernelx::: 68 passed, 0 failed, 1 ignored; SKIPPED: scatter_without_pages_unmaps_only_the_listed_aliases (XCL_PAGE_ALIAS=1 required).
  • hle::kernelx:: with XCL_PAGE_ALIAS=1: 59 passed, 9 failed, 1 ignored. The same 9 fail at 4fdd2824 without the patch (57 passed, 9 failed). They are conventional-path tests in kernelx::tests that run with the alias variable set, e.g. physical_pages_in_uma and scatter_matches_a_model_of_physical_pages.
  • hle::dstorage:: with XCL_PAGE_ALIAS=1: 31 passed, 0 failed.

Nit: scatter_without_pages_unmaps_only_the_listed_aliases skips unless XCL_PAGE_ALIAS=1 is set, and CI does not set it, so #3074's regression test does not run by default.

Not tested: retail title, AMD, the race under real DirectStorage load (the test forces the order).

AI use: Claude Code (Claude Opus 5.5) did the review and wrote the test and fix; the comment was checked by @KOLESNiii before posting.

<!-- greyfinch-sync:ivall/xcl:comment:7246024825 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3075#issuecomment-7246024825). Originally posted by [KOLESNiii](https://github.com/KOLESNiii) on 2026-11-28T21:26:50Z. --- Review of 4fdd2824 (#3211 workstream B): one finding, with a regression test that fails here and passes with a one-line fix. **`alias::read` / `alias::write` resolve page addresses and then copy without `MAPPINGS`.** `copy_pages` (alias.rs:382-406) resolves each page through `bytes_of`, which takes and releases `STATE` per page, then copies with no lock held. `MAPPINGS` serialises `map`, `free` and `free_space`, but not this copy. The conventional path holds `AWAY` across both resolve and copy (`read_physical_pages` / `write_physical_pages` in kernelx.rs), so in alias mode the guarantee is weaker than the one it replaces. Two interleavings: - A DirectStorage write (`dstorage.rs:345`, `:981`) resolves a page's home. The title then frees the block's last live page, and `free` unmaps and releases the home (alias.rs:216-219). The copy writes into released address space. - A DirectStorage write resolves the page's away address. A concurrent remap then runs `unmap_away`, which copies the page home and then decommits the away address (alias.rs:304-325). The write either faults, or lands after the copy home and is lost. **Test.** A `#[cfg(test)]` hook runs between resolve and copy. It frees the page from another thread and asserts that the free has not completed within 1 s. - At 4fdd2824 it fails: `the page's home was released while a write into it was in flight`. - With `MAPPINGS` taken at the top of `copy_pages`, before resolving, it passes, and the free completes after the write. The lock order MAPPINGS → STATE is the same as in `map` / `free`, and the fault handlers take only `STATE`. <details><summary>Patch (fix + test hook + test)</summary> ```diff @@ unsafe fn copy_pages(pages: &[usize], offset: usize, len: usize, mut f: impl FnM if offset >= PAGE || pages.len() < need { return false; } + // the addresses resolved below stay valid until the copy is done: no page of a block is + // freed (its home released) or moved (an address outside the spaces decommitted) meanwhile + let _mapping = MAPPINGS.lock().unwrap_or_else(|e| e.into_inner()); let mut addrs = Vec::with_capacity(need); for &p in &pages[..need] { let Some(a) = bytes_of(p, write) else { return false }; addrs.push((p, a)); } + #[cfg(test)] + if let Some(hook) = tests::AFTER_RESOLVE.with(|h| h.borrow_mut().take()) { + hook(); + } @@ mod tests { use super::guards::tests::SERIAL; + thread_local! { + /// Run once by `copy_pages` on this thread, between resolving its pages and copying. + pub(super) static AFTER_RESOLVE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) }; + } + + #[test] + fn a_page_cannot_be_freed_while_a_write_by_number_copies_into_it() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(1); + let freer = std::sync::Arc::new(std::sync::Mutex::new(None)); + let slot = freer.clone(); + let page = p[0]; + AFTER_RESOLVE.with(|h| *h.borrow_mut() = Some(Box::new(move || { + // the title frees the block (its last page: the home goes) as the copy is about to start + let (tx, rx) = std::sync::mpsc::channel(); + *slot.lock().unwrap() = Some(std::thread::spawn(move || { + unsafe { free(&[page]) }; + let _ = tx.send(()); + })); + assert!(rx.recv_timeout(std::time::Duration::from_secs(1)).is_err(), "the page's home was released while a write into it was in flight"); + }))); + unsafe { + assert!(write(&p, 0, &[0x5b; 64])); + } + if let Some(t) = freer.lock().unwrap().take() { + t.join().unwrap(); + } + assert!(!pages_live(&p), "the free went through once the write was done"); + } ``` </details> **Tested** (RTX 2070 SUPER, Windows 11, debug, 4fdd2824 + the patch above plus the test from the #2307 comment, `cargo test -p xcl --lib <filter> -- --test-threads=1`): - `hle::kernelx::`: 68 passed, 0 failed, 1 ignored; SKIPPED: `scatter_without_pages_unmaps_only_the_listed_aliases` (XCL_PAGE_ALIAS=1 required). - `hle::kernelx::` with `XCL_PAGE_ALIAS=1`: 59 passed, 9 failed, 1 ignored. The same 9 fail at 4fdd2824 without the patch (57 passed, 9 failed). They are conventional-path tests in `kernelx::tests` that run with the alias variable set, e.g. `physical_pages_in_uma` and `scatter_matches_a_model_of_physical_pages`. - `hle::dstorage::` with `XCL_PAGE_ALIAS=1`: 31 passed, 0 failed. Nit: `scatter_without_pages_unmaps_only_the_listed_aliases` skips unless `XCL_PAGE_ALIAS=1` is set, and CI does not set it, so #3074's regression test does not run by default. **Not tested:** retail title, AMD, the race under real DirectStorage load (the test forces the order). AI use: Claude Code (Claude Opus 5.5) did the review and wrote the test and fix; the comment was checked by @KOLESNiii before posting.
Foniass commented 2026-12-01 09:27:08 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T09:27:08Z.


Triage (#1607) – head 4fdd282

Stacked on #3074 and #2307; the own commits are cfe04f4 (section-backed liveness for DirectStorage page lists, with a per-block freed bitmap) and 4fdd282 (a MAPPINGS lock serializing map/copy-back with page and space release, and resolving the source before unmapping the destination). No other open PR makes these changes.
The second commit is a separate change from the title (mapping serialization), so it could be its own PR. No correctness problems found in the diff.
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

<!-- greyfinch-sync:ivall/xcl:comment:7306720140 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3075#issuecomment-7306720140). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T09:27:08Z. --- **Triage (#1607)** – head 4fdd282 Stacked on #3074 and #2307; the own commits are `cfe04f4` (section-backed liveness for DirectStorage page lists, with a per-block freed bitmap) and `4fdd282` (a `MAPPINGS` lock serializing map/copy-back with page and space release, and resolving the source before unmapping the destination). No other open PR makes these changes. The second commit is a separate change from the title (mapping serialization), so it could be its own PR. No correctness problems found in the diff. Recommendation: keep open. AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.
Foniass commented 2026-12-01 10:43:06 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T10:43:06Z.


Review (head 4fdd282, diff read, not a merge-check; conflicts with main, PR description red: no smoke block on this head):

  • The DirectStorage copy still races with a free. copy_pages (alias.rs ~382-406), reached from dstorage.rs ~345 / ~981 through kernelx.rs ~1057, finds each page's address and copies without the MAPPINGS lock that this PR takes in map / free / free_space. So the liveness check at dstorage.rs ~950 can pass, the title frees the page, and the copy writes into released memory or is lost. KOLESNiii posted a test that fails here and a one-line fix.
  • A possible deadlock (unverified). MAPPINGS stays held while calling into D3D12.X sparse code (move_to -> commit_sparse, unmap_away -> sparse::decommitted). Anything there that calls back into alias would deadlock.
  • Scope.
    • Most of the +1,540 lines are the unmerged #2293 / #2307 and #3074; this PR's own two commits are about 270 lines.
    • Commit 4fdd282 (serialising mappings) is a separate change from what the title says.
    • The 11 tests that fail with XCL_PAGE_ALIAS=1 in throny's merge-check are still unanswered.
  • Conflicts in kernelx.rs, kernelx/lazy.rs and vfs_hooks.rs, probably from #1221 / #1355 on main.

Fine: the per-block freed bitmap can't index out of range (Section.pages == n), duplicate frees are ignored, and the source page is now resolved before the destination is unmapped. The cost is one lock and a map lookup per page, only with XCL_PAGE_ALIAS=1. Related: #2307, #3074, #2308.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7308604237 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3075#issuecomment-7308604237). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T10:43:06Z. --- Review (head 4fdd282, diff read, not a merge-check; conflicts with main, `PR description` red: no smoke block on this head): - **The DirectStorage copy still races with a free.** `copy_pages` (`alias.rs` ~382-406), reached from `dstorage.rs` ~345 / ~981 through `kernelx.rs` ~1057, finds each page's address and copies without the `MAPPINGS` lock that this PR takes in `map` / `free` / `free_space`. So the liveness check at `dstorage.rs` ~950 can pass, the title frees the page, and the copy writes into released memory or is lost. KOLESNiii posted a test that fails here and a one-line fix. - **A possible deadlock** (unverified). `MAPPINGS` stays held while calling into D3D12.X sparse code (`move_to` -> `commit_sparse`, `unmap_away` -> `sparse::decommitted`). Anything there that calls back into `alias` would deadlock. - **Scope.** - Most of the +1,540 lines are the unmerged #2293 / #2307 and #3074; this PR's own two commits are about 270 lines. - Commit 4fdd282 (serialising mappings) is a separate change from what the title says. - The 11 tests that fail with `XCL_PAGE_ALIAS=1` in throny's merge-check are still unanswered. - Conflicts in `kernelx.rs`, `kernelx/lazy.rs` and `vfs_hooks.rs`, probably from #1221 / #1355 on main. Fine: the per-block freed bitmap can't index out of range (`Section.pages == n`), duplicate frees are ignored, and the source page is now resolved before the destination is unmapped. The cost is one lock and a map lookup per page, only with `XCL_PAGE_ALIAS=1`. Related: #2307, #3074, #2308. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3075:upstream-pr/3075'
git switch 'upstream-pr/3075'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3075'
git switch 'upstream-pr/3075'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3075'
git switch 'upstream-pr/3075'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3075'
git switch 'main'
git merge --squash 'upstream-pr/3075'
git switch 'main'
git merge --ff-only 'upstream-pr/3075'
git switch 'main'
git merge 'upstream-pr/3075'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
xcl-dev/xcl!3075
No description provided.