Skip to content

kernelx: check section page liveness for DirectStorage - #3075

Open
ZekkJJ wants to merge 8 commits into
xcl-dev:mainfrom
ZekkJJ:codex/alias-directstorage-page-liveness
Open

ZekkJJ wants to merge 8 commits into
xcl-dev:mainfrom
ZekkJJ:codex/alias-directstorage-page-liveness

Conversation

@ZekkJJ

@ZekkJJ ZekkJJ commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #3074 and the original section-alias stack in #2307 by @adiologydev. The focused commits are cfe04f4 and 4fdd282. 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 4fdd282, 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 cfe04f4, 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

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.

adiologydev and others added 7 commits November 25, 2026 16:39
…addresses

On the console a physical page mapped at several addresses is one page. XCL
keeps a page at one address at a time and copies it when the title maps it
elsewhere (`move_away`), so the other addresses go stale; a retail title maps
its streamed pages into a pool, into the CPU view of a 24 GB reservation and
into that reservation's GPU view (xcl-dev#1031).

`kernelx::sections` is the base for real aliasing: a block of physical pages
is one pagefile-backed SEC_RESERVE section, and a page is mapped as a view of
its 64 KiB slice into a placeholder (MapViewOfFile3 with
MEM_REPLACE_PLACEHOLDER). Every view of a slice is the same memory and a page
takes commit once, when it is committed through any view. Unmapping leaves a
placeholder for the next view. Ordinary reserved memory (write-watched if
asked) can replace part of a placeholder and go back to one.

Nothing calls it yet. Measured in a standalone program on Windows 11 26200
over 200 000 pages: map 2.2 us, unmap 2.75 us, commit 0.9 us a page.
GetWriteWatch refuses a range that holds a view (error 87), and one call
cannot span two neighbouring reservations either.
The upload of title memory to video memory (`d3d12x::sparse`) and the
textures kept in step with title memory learn what the CPU wrote from the
write watch, and a view of a section (`kernelx::sections`) cannot be
write-watched: GetWriteWatch refuses any range that holds one.

`kernelx::guards` keeps the views of a physical page read-only. The first
write through any of them faults; a vectored handler makes that view
writable, notes the page and lets the write go on. `take_dirty` hands over
the pages of every view of each page written – a write through one view is
a write to all of them – and guards those views again before their bytes are
read, so a later write is caught again and an earlier one is in what is read.

Kernel calls do not fault into the handler, they fail: `lazy::ensure`, which
XCL already calls before a kernel call or its own code writes title memory,
opens the guards there first and counts the write. A view committed by the
lazy handler is writable and counts as written. Both take no lock until a
view has been watched.

Nothing watches a view yet.
… fault

A guarded view of a physical page (`kernelx::guards`) is read-only until it
is written. Code of XCL's own that writes there faults into the guard and
goes on, but a kernel call does not fault: ReadFile into such a view fails.
`lazy::ensure` opened the views first, yet the submit thread's `take_dirty`
could guard them again before the write – between DirectStorage's check of
its destination and the copy, or before the kernel wrote a ReadFile buffer.

`guards::open` now returns `Opened`, which keeps its views writable until it
is dropped; `take_dirty` uploads a pinned view but does not guard it again,
and the end of the write counts as a write. `lazy::ensure` returns it and its
callers hold it across their write: the routed ReadFile for a synchronous
read, and the destination checks of DirectStorage and the CPU-side
bottom-of-pipe writes. An overlapped ReadFile writes after the call returns:
its views stay open until its OVERLAPPED is no longer STATUS_PENDING, which
`take_dirty` reads without faulting (the title may free it once done). A
retail title reads 271 MB that way into the CPU view of its 24 GB
reservation 8.5 s after start.

`guards::written` counts a page as written through all its views when XCL
writes it by page number.

Nothing watches a view yet, so nothing changes without views.
…s mapped at

Without it XCL keeps a physical page at one address at a time and copies it
when the title maps it elsewhere; the console shows the page at every
address it is mapped at. A retail title maps its streamed pages into a pool,
into the CPU view of a 24 GB reservation and into that reservation's GPU
view (xcl-dev#1031).

With `XCL_PAGE_ALIAS=1` (`kernelx::alias`):
- a block of physical pages is a section (`kernelx::sections`) with a view
  of its own, through which XCL reads and writes pages by number
  (DirectStorage); the title never maps a page there;
- the title's reservations of 64 KiB pages with no commit (its CPU view, GPU
  view and pool) are placeholders, and a page mapped there is a view of its
  slice, guarded (`kernelx::guards`) so that a write through one view is
  uploaded at all of them; `title_textures` adds those pages to what the
  write watch found;
- a page mapped anywhere else (a placeholder region the title made in a
  sparse window) is moved there and back with its bytes, as before.

Pages are committed on first use as before (`kernelx::lazy`); whether a page
is committed is a bit per page: asking Windows walked the rest of a fresh
block, and a title mapping 100 000 new pages one at a time took 20 s longer
to its first frame.

Measured in a traced run of a retail title: 3 blocks (11 360, 2 960 and
99 776 pages), 131 072 map calls in 150 s, nearly all single pages into its
plain reservations, none at a page's home, no commit inside them.
The alias path must forward a null page array as an unmap, as the conventional path does after xcl-dev#495. Advancing the null pointer makes the second entry look like an array at address 0x8.

Test a two-entry scatter unmap, surviving aliases, swapped remapping, and release through the section-backed path from xcl-dev#2307.

Assisted-by: Codex (model version not exposed)
The worker rereads late-filled destination lists, but the conventional liveness index never recognizes an alias allocation. Use section-backed IDs in alias mode and remember individual releases while their backing block remains open.

Recover the liveness correction from the historical section-alias integration on top of xcl-dev#2307. Verify a partially released block and the existing late-filled DirectStorage request in alias mode.

Assisted-by: Codex (model version not exposed)

@Kalmarv Kalmarv left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 4fdd282. 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.

@Lum7nt

Lum7nt commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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.

Resolve the source before changing the destination. Serialize alias map and move-back operations with physical-page and alias-space release, keeping the home view valid until the operation finishes. Leave the state mutex available to page-fault handlers.

Cover a source invalidated after preflight and the 63/64 release bitmap boundary, as suggested by Kalmarv.

Assisted-by: Codex (model version not exposed)
@throny

throny commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator

merge-check claim
head: 4fdd282

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

throny commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator

merge-check
base: db3921d
head: 4fdd282
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 db3921d: 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
ZekkJJ marked this pull request as ready for review November 28, 2026 17:32
@ZekkJJ

ZekkJJ commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

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

jessenic pushed a commit to jessenic/xcl that referenced this pull request Nov 28, 2026
The queue's CopyPageMappingsBatchX maps pool pages into GPU views; on the
console a GPU-view page then shows the physical page mapped at its pool page
at the time of the call. xcl-dev#1055 decodes the calls and keeps a record of them;
with physical pages aliasing (`kernelx::alias`) the GPU view is a reservation
of views, so the decoded mappings are made for real: each GPU-view page
becomes a view of the physical page mapped at its pool page now, or is
unmapped (kind 2, or nothing mapped at the pool page). Textures in the GPU
view then read the page at their own address (`title_textures` prefers an
address with a physical page mapped), and a write through any view of the
page is uploaded at all of them.

Without the switch nothing changes: the call is recorded as in xcl-dev#1055.

(cherry picked from commit 64ad64c)

Lab port: fitted onto the follow-ups of xcl-dev#3074/xcl-dev#3075, which this commit's parent (xcl-dev#2307) did not have: apply_page_mappings holds the mapping lock for the call and passes it to map_one (now a Result), with the pool page looked up under it; a pool page whose view outlived its freed page counts as an empty pool page instead of ending the call midway (test added). The textures on the mapped pages are named to title_textures through the lab's per-page changed list (mirrors::note_changed, after the pages are in place) instead of upstream's note_gpu_view_mapping, which bumps the generation and has every texture's source read again: the title's calls come by the hundred.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
jessenic added a commit to jessenic/xcl that referenced this pull request Nov 28, 2026
… stand down, and the log says which is at work

Lab port of the upstream alias stack (xcl-dev#2293, xcl-dev#2294, xcl-dev#2307, xcl-dev#2308, xcl-dev#3074,
xcl-dev#3075). The lab's two stopgaps for a physical page at more than one address
keep the page at ONE address and move it (bring_page / bring_range,
XCL_PAGE_BRING) or its video memory (sparse::share_page, XCL_PAGE_SHARE=1).
With real aliases a page is at every address the title mapped it at, outside
the sparse windows, and an address it is not at was unmapped by the title:
both stand down when XCL_PAGE_ALIAS=1. With the switch not set they are as
they were.

One line at start-up (the first time the switch is asked) names which of the
three is at work; with aliases, a line at the first view and at each power
of two from 1024 on says how many pages are shown at how many addresses and
how many of them at more than one (guards::view_counts).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@KOLESNiii

Copy link
Copy Markdown
Contributor

Review of 4fdd282 (#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 4fdd282 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, 4fdd282 + 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 4fdd282 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

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

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

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

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

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants