From 38e58e1d17c7c99abde4994274fe199c2b5dbc59 Mon Sep 17 00:00:00 2001 From: frozht <73432510+frozht@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:25:23 +0000 Subject: [PATCH] Memory: map_pages asks VirtualQuery once per run of fresh pages `map_pages` asks `committed_page` for the address and for the home of every page; a page not in the working set (every fresh one) fell through to a VirtualQuery, which walks the whole run of pages in one state. A title that maps 98,304 fresh pages (6 GiB) in one call took ~13 s under Wine (~132 us a page); a scratch run of the same call shape measured 186 us a page for 4096 and 16384 pages, 0.26 us a page now. The loop remembers the run each VirtualQuery returned for the addresses and for the homes and answers the next pages from it. The runs are dropped whenever `unmap_away` commits or decommits (it now says so; a page never used is only unmarked and keeps them, so mapping lazy pages again is covered too) and when `move_home_away` hands homes back (every 4096: it now says so). The rest of a step changes only an address, or a home that is not asked about again: the addresses rise, and a page mapped twice is unmapped first. The one exception is an address that is another page's home (a home in plain memory): the answer for it was wrong before the runs too. Tests: 64 fresh pages with a committed one among them took 127 VirtualQuery calls before, 5 now; the same pages mapped again, 128 and at most 8. Pages written and mapped again in one call, at another address or at the same one, keep their contents (they fail when the run is not dropped after `unmap_away` moved a page home). The counter behind the first two is a `cfg(test)` thread-local in `committed_page_in`. Co-Authored-By: Claude Sonnet 5.5 --- crates/xcl/src/hle/kernelx.rs | 184 ++++++++++++++++++++++++++++++++-- 1 file changed, 173 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 69f13e05c..d10e811bd 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -925,16 +925,18 @@ pub unsafe fn write_physical_pages(pages: &[usize], offset: usize, src: &[u8]) - /// A page's data went from `home` to another address: a home in a sparse window is /// decommitted at the end of the call or every 256 MB (`give_back_homes`; its GPU tiles go too: the GPU does -/// not see the page while it is away). -unsafe fn move_home_away(away: &mut Away, home: usize) { +/// not see the page while it is away). True if homes were given back now. +unsafe fn move_home_away(away: &mut Away, home: usize) -> bool { if lazy_home(home) { away.gone.push(home); // (256 MB at a time: a call that maps gigabytes would otherwise hold them twice until // it ends) if away.gone.len() >= 4096 { give_back_homes(away); + return true; } } + false } /// The homes `move_home_away` collected, decommitted in runs of neighbouring pages. @@ -1007,6 +1009,25 @@ fn committed_range(a: usize, len: usize) -> bool { } fn committed_page(a: usize) -> bool { + committed_page_in(a, &mut StateRun::default()) +} + +/// The run of pages around an address that one VirtualQuery found in one state. `map_pages` +/// asks about the pages of a range one after the other and nothing it does in between (a page +/// left lazy) changes that state: a run answers them without asking again (VirtualQuery walks +/// the run to its end, and under Wine 98,304 fresh pages took 13 s). +#[derive(Default)] +struct StateRun { + start: usize, + end: usize, + committed: bool, +} + +/// `committed_page`, remembering in `run` the state of the pages around `a`. +fn committed_page_in(a: usize, run: &mut StateRun) -> bool { + if (run.start..run.end).contains(&a) { + return run.committed; + } // A page in the working set is committed: asking for that is one entry, where VirtualQuery // walks the page table to the end of the committed range the page is in (gigabytes of // homes: 0.25 ms a page, and a scatter of pages from their homes grew with its square). @@ -1016,18 +1037,32 @@ fn committed_page(a: usize) -> bool { { return true; } + #[cfg(test)] + VIRTUAL_QUERIES.with(|n| n.set(n.get() + 1)); let mut m: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - unsafe { mem::VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 && m.State == mem::MEM_COMMIT } + if unsafe { mem::VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 { + return false; + } + let start = m.BaseAddress as usize; + *run = StateRun { start, end: start + m.RegionSize, committed: m.State == mem::MEM_COMMIT }; + run.committed +} + +#[cfg(test)] +thread_local! { + /// The VirtualQuery calls `committed_page_in` made on this thread. + static VIRTUAL_QUERIES: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Copy what is mapped at `at` back home and unmap it (Windows memory is decommitted); the homes -/// in `committed` the caller has committed. -unsafe fn unmap_away(away: &mut Away, at: usize, committed: &std::ops::Range) { +/// in `committed` the caller has committed. True if memory was committed or decommitted (a page +/// never used, or none mapped at `at`, leaves it as it was). +unsafe fn unmap_away(away: &mut Away, at: usize, committed: &std::ops::Range) -> bool { if let Some(page) = away.at.remove(&at) { away.page.remove(&page); // never used where it was mapped: its home still holds the page (zeros) if lazy::unmark(at) { - return; + return false; } // (a home this call has not given back yet is still committed) let own = page_home(page); @@ -1044,6 +1079,9 @@ unsafe fn unmap_away(away: &mut Away, at: usize, committed: &std::ops::Range Option> { + let u = crate::gpu::uma::get()?; + let (mut num, mut pages) = (n, vec![0usize; n]); + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut num, pages.as_mut_ptr()), 1); + if u.is_sparse(page_home(pages[0]).unwrap()) { + return Some(pages); + } + FreeTitlePhysicalPages(std::ptr::null_mut(), n, pages.as_mut_ptr()); + None + } + + /// Pages mapped, half of them written, then all mapped again in one call – at another + /// address or the same one: the written ones keep their contents. The first pages of the + /// call are never-used (nothing to move), the ones after them are moved: what a run of + /// the pages asked about before says is no longer true (the home they moved to is committed + /// by now, the address they left decommitted). + unsafe fn remap_keeps_what_was_written(same_address: bool) { + const N: usize = 8; + let Some(mut pages) = sparse_pages(N) else { return }; + let r1 = mem::VirtualAlloc(std::ptr::null(), N * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + let r2 = if same_address { r1 } else { mem::VirtualAlloc(std::ptr::null(), N * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize }; + assert_eq!(MapTitlePhysicalPages(r1 as *mut c_void, N, 0, 4, pages.as_mut_ptr()) as usize, r1); + for i in N / 2..N { + *((r1 + i * PHYS_PAGE) as *mut u32) = 0x100 + i as u32; + } + assert_eq!(MapTitlePhysicalPages(r2 as *mut c_void, N, 0, 4, pages.as_mut_ptr()) as usize, r2); + for i in 0..N { + let want = if i >= N / 2 { 0x100 + i as u32 } else { 0 }; + assert_eq!(*((r2 + i * PHYS_PAGE) as *const u32), want, "page {i} (same address: {same_address})"); + } + // back home: the pages left lazy are unmarked (a freed one stays marked, and the address + // is another test's later) + assert!(!MapTitlePhysicalPages(std::ptr::null_mut(), N, 0, 4, pages.as_mut_ptr()).is_null()); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), N, pages.as_mut_ptr()), 1); + mem::VirtualFree(r1 as *mut c_void, 0, mem::MEM_RELEASE); + if !same_address { + mem::VirtualFree(r2 as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + #[test] + fn pages_mapped_again_at_another_address_keep_what_was_written() { + unsafe { remap_keeps_what_was_written(false) } + } + + #[test] + fn pages_mapped_again_at_the_same_address_keep_what_was_written() { + unsafe { remap_keeps_what_was_written(true) } + } + + /// Pages never used, mapped again (they are only unmarked: memory is as it was) cost no + /// more queries than the first time. + #[test] + fn mapping_lazy_pages_again_does_not_query_each_page() { + const N: usize = 64; + unsafe { + let Some(mut pages) = sparse_pages(N) else { return }; + let r1 = mem::VirtualAlloc(std::ptr::null(), N * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + let r2 = mem::VirtualAlloc(std::ptr::null(), N * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_eq!(MapTitlePhysicalPages(r1 as *mut c_void, N, 0, 4, pages.as_mut_ptr()) as usize, r1); + for to in [r1, r2] { + let before = VIRTUAL_QUERIES.with(|q| q.get()); + assert_eq!(MapTitlePhysicalPages(to as *mut c_void, N, 0, 4, pages.as_mut_ptr()) as usize, to); + let queries = VIRTUAL_QUERIES.with(|q| q.get()) - before; + assert!(queries <= 8, "{queries} VirtualQuery calls for {N} pages mapped again"); + } + // back home: the pages left lazy are unmarked (a freed one stays marked, and the address + // is another test's later) + assert!(!MapTitlePhysicalPages(std::ptr::null_mut(), N, 0, 4, pages.as_mut_ptr()).is_null()); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), N, pages.as_mut_ptr()), 1); + mem::VirtualFree(r1 as *mut c_void, 0, mem::MEM_RELEASE); + mem::VirtualFree(r2 as *mut c_void, 0, mem::MEM_RELEASE); + } + } + /// `XMemMapPhysicalPagesScatter` against a model of physical pages: random scatters of /// pages to addresses (page 0: unmap), writes through the addresses and maps of the whole /// allocation at its home. After each step every page reads what was last written to it