From 2c5fe3ffe418b13c0a9cb1c735dc287db3149efc Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:20:28 -0500 Subject: [PATCH] =?UTF-8?q?Memory:=20a=20scatter=20or=20map=20home=20of=20?= =?UTF-8?q?n=20pages=20costs=20O(n),=20not=20O(n=C2=B2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit VirtualQuery's cost grows with the run of pages in one state that follows the address: on homes written as a whole it took 0.25 ms or more a call. map_pages asked it about each page's home, and the walk was the rest of the allocation, so scattering 16,384 pages from their home took 24 s, and mapping them home again 10 s. - committed_page asks the working set first: a valid page is committed, one entry. Only a page outside it (committed but untouched, or not committed) still goes to VirtualQuery. - commit_homes asks VirtualQuery once per run, not once per page. - A map at home tells unmap_away which homes it has just committed. A page away at an address among them leaves that address committed: it is one of the homes now. Tests: a model of physical pages (4 seeds x 600 random scatters, writes and maps home), a page away at another page's home mapped home with it, a home decommitted inside one call, and an ignored timing test (scatter_timing). Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/xcl/src/hle/kernelx.rs | 244 ++++++++++++++++++++++++++++++++-- 1 file changed, 235 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 0b8f2a3fa..148be1175 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -862,7 +862,7 @@ unsafe fn commit_homes(home: usize, n: usize) -> bool { return true; } let len = n * PHYS_PAGE; - if (0..n).all(|i| committed_page(home + i * PHYS_PAGE)) { + if committed_range(home, len) { return true; } if mem::VirtualAlloc(home as *const c_void, len, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { @@ -875,13 +875,37 @@ unsafe fn commit_homes(home: usize, n: usize) -> bool { true } +/// Whether all of `[a, a + len)` is committed: one VirtualQuery per run of pages in one state +/// (page by page each asked walked the rest of the run). +fn committed_range(a: usize, len: usize) -> bool { + let mut p = a; + while p < a + len { + let mut m: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + if unsafe { mem::VirtualQuery(p as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 || m.State != mem::MEM_COMMIT { + return false; + } + p = m.BaseAddress as usize + m.RegionSize; + } + true +} + fn committed_page(a: usize) -> bool { + // 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). + let mut ws = windows_sys::Win32::System::ProcessStatus::PSAPI_WORKING_SET_EX_INFORMATION { VirtualAddress: a as *mut c_void, ..Default::default() }; + if unsafe { windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx(thr::GetCurrentProcess(), &mut ws as *mut _ as *mut c_void, std::mem::size_of_val(&ws) as u32) } != 0 + && unsafe { ws.VirtualAttributes.Flags } & 1 != 0 + { + return true; + } 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 } } -/// Copy what is mapped at `at` back home and unmap it (Windows memory is decommitted). -unsafe fn unmap_away(away: &mut Away, at: usize) { +/// 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) { 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) @@ -889,13 +913,15 @@ unsafe fn unmap_away(away: &mut Away, at: usize) { return; } // (a home this call has not given back yet is still committed) + let own = page_home(page); let pending = away.gone.len(); - away.gone.retain(|&h| Some(h) != page_home(page)); - let home = if away.gone.len() < pending { page_home(page) } else { page_home(page).and_then(|h| home_again(h)) }; + away.gone.retain(|&h| Some(h) != own); + let home = if away.gone.len() < pending || own.is_some_and(|h| committed.contains(&h)) { own } else { own.and_then(|h| home_again(h)) }; if let Some(home) = home { std::ptr::copy_nonoverlapping(at as *const u8, home as *mut u8, PHYS_PAGE); } - if !crate::gpu::uma::get().is_some_and(|u| u.is_committed(at)) { + // (an address among the homes the caller maps back is one of them: it stays) + if !committed.contains(&at) && !crate::gpu::uma::get().is_some_and(|u| u.is_committed(at)) { if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { crate::hle::d3d12x::sparse::decommitted(at, PHYS_PAGE); } @@ -1014,7 +1040,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) away.gone.retain(|&h| h < home || h >= home + n * PHYS_PAGE); for &p in &pages { if let Some(&at) = away.page.get(&p) { - unmap_away(away, at); + unmap_away(away, at, &(home..home + n * PHYS_PAGE)); } } return home as *mut c_void; @@ -1027,12 +1053,12 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) let in_uma = |a: usize| crate::gpu::uma::get().is_some_and(|u| u.is_committed(a)); for (i, &p) in pages.iter().enumerate() { let at = base + i * PHYS_PAGE; - unmap_away(away, at); + unmap_away(away, at, &(0..0)); if p == 0 { continue; } if let Some(&old) = away.page.get(&p) { - unmap_away(away, old); + unmap_away(away, old, &(0..0)); } let fresh = !in_uma(at) && !committed_page(at); let home = page_home(p).unwrap(); @@ -1863,6 +1889,206 @@ mod tests { } } + /// `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 + /// wherever it is mapped, a page never written reads zeros, and an address with no page is + /// not committed. + #[test] + fn scatter_matches_a_model_of_physical_pages() { + unsafe { + let Some(_) = crate::gpu::uma::get() else { return }; + const PAGES: usize = 24; + const SLOTS: usize = 32; + for seed in 1..=4u64 { + let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + let mut next = move || { + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + x.wrapping_mul(0x2545_F491_4F6C_DD1D) + }; + let mut n = PAGES; + let mut pages = [0usize; PAGES]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let r = mem::VirtualAlloc(std::ptr::null(), SLOTS * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert!(r != 0); + let slot = |s: usize| r + s * PHYS_PAGE; + // model: what each page holds (first and last dword), where it is (None: home) + let mut value = [(0u32, 0u32); PAGES]; + let mut at: [Option; PAGES] = [None; PAGES]; + let mut held: [Option; SLOTS] = [None; SLOTS]; + let mut home: Option = None; + let read = |a: usize| ((a as *const u32).read_volatile(), ((a + PHYS_PAGE - 4) as *const u32).read_volatile()); + for step in 0..600 { + match next() % 8 { + // a scatter of 1–4 (slot, page or none) + 0..=3 => { + let k = 1 + (next() % 4) as usize; + let mut addrs = Vec::new(); + let mut ids = Vec::new(); + for _ in 0..k { + let s = (next() % SLOTS as u64) as usize; + let p = if next() % 5 == 0 { None } else { Some((next() % PAGES as u64) as usize) }; + addrs.push(slot(s) as *mut c_void); + ids.push(p.map_or(0, |p| pages[p] as u64)); + // model, in call order: what the slot held goes home; the page leaves + // where it was + if let Some(q) = held[s].take() { + at[q] = None; + } + if let Some(p) = p { + if let Some(old) = at[p].take() { + held[old] = None; + } + at[p] = Some(s); + held[s] = Some(p); + } + } + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), k, ids.as_mut_ptr()), 1, "seed {seed} step {step}"); + } + // a write through a mapped slot + 4..=6 => { + let s = (next() % SLOTS as u64) as usize; + if let Some(p) = held[s] { + let v = ((next() as u32) | 1, (next() as u32) | 1); + (slot(s) as *mut u32).write_volatile(v.0); + ((slot(s) + PHYS_PAGE - 4) as *mut u32).write_volatile(v.1); + value[p] = v; + } + } + // the whole allocation at its home: every page leaves its slot + _ => { + let h = MapTitlePhysicalPages(std::ptr::null_mut(), PAGES, 0, 4, pages.as_mut_ptr()) as usize; + assert!(h != 0); + home = Some(h); + at = [None; PAGES]; + held = [None; SLOTS]; + for (p, &v) in value.iter().enumerate() { + assert_eq!(read(h + p * PHYS_PAGE), v, "seed {seed} step {step}: page {p} at home"); + } + } + } + for s in 0..SLOTS { + match held[s] { + Some(p) => assert_eq!(read(slot(s)), value[p], "seed {seed} step {step}: page {p} at slot {s}"), + None => assert!(!committed_page(slot(s)), "seed {seed} step {step}: slot {s} has no page but is committed"), + } + } + } + let _ = home; + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), PAGES, pages.as_mut_ptr()), 1); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + } + } + } + + /// A home a page went back to in a call, then decommitted in the same call because another + /// page was mapped at that address and unmapped again, is not taken as committed: mapping + /// its page away does not read decommitted memory. + #[test] + fn a_home_decommitted_in_the_same_call_is_asked_again() { + unsafe { + let Some(_) = crate::gpu::uma::get() else { return }; + let mut n = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let (p, q) = (pages[0], pages[1]); + let h = page_home(p).unwrap(); + let r = mem::VirtualAlloc(std::ptr::null(), 2 * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + let (s, t) = (r as *mut c_void, (r + PHYS_PAGE) as *mut c_void); + let mut one = [p as u64]; + assert_eq!(XMemMapPhysicalPagesScatter(&s, 1, one.as_mut_ptr()), 1); + *(s as *mut u32) = 7; + // one call: p home (h holds it), q at h, h unmapped (decommitted), p to t + let at = [s, h as *mut c_void, h as *mut c_void, t]; + let mut ids = [0, q as u64, 0, p as u64]; + assert_eq!(XMemMapPhysicalPagesScatter(at.as_ptr(), 4, ids.as_mut_ptr()), 1); + // (t reads: committed, or committed on first use) + let _ = (t as *const u32).read_volatile(); + assert!(!committed_page(s as usize)); + let mut none = [0u64, 0]; + let both = [s, t]; + assert_eq!(XMemMapPhysicalPagesScatter(both.as_ptr(), 2, none.as_mut_ptr()), 1); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + /// A page mapped at another page's home, then the whole allocation mapped back home: the + /// first page goes home and leaves that address committed, as the second one's home. + #[test] + fn a_page_away_at_another_home_goes_home_with_it() { + unsafe { + let Some(_) = crate::gpu::uma::get() else { return }; + let mut n = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let (q, p) = (pages[0], pages[1]); + let h = page_home(p).unwrap(); + let r = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + let s = r as *mut c_void; + let mut one = [p as u64]; + assert_eq!(XMemMapPhysicalPagesScatter(&s, 1, one.as_mut_ptr()), 1); + *(s as *mut u32) = 7; + let at = h as *mut c_void; + let mut one = [q as u64]; + assert_eq!(XMemMapPhysicalPagesScatter(&at, 1, one.as_mut_ptr()), 1); + *(h as *mut u32) = 9; + let home = MapTitlePhysicalPages(std::ptr::null_mut(), 2, 0, 4, pages.as_mut_ptr()) as usize; + assert_eq!(home, page_home(q).unwrap()); + assert_eq!(*(home as *const u32), 9); + assert_eq!(*(h as *const u32), 7); + assert!(!committed_page(r)); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + /// Timing (`--ignored --nocapture`; `XCL_SCATTER_PAGES=4096,8192`): pages written at their + /// home, scattered from there into a reservation in one call, scattered again in reverse, + /// and mapped back home. + #[test] + #[ignore] + fn scatter_timing() { + let sizes: Vec = std::env::var("XCL_SCATTER_PAGES").ok().map_or(vec![4096, 8192, 16384], |v| v.split(',').map(|s| s.parse().unwrap()).collect()); + let ms = |t: std::time::Instant| t.elapsed().as_secs_f64() * 1e3; + for n in sizes { + unsafe { + let mut cnt = n; + let mut pages = vec![0usize; n]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut cnt, pages.as_mut_ptr()), 1); + let h = MapTitlePhysicalPages(std::ptr::null_mut(), n, 0, 4, pages.as_mut_ptr()) as usize; + assert!(h != 0); + for i in 0..n { + *((h + i * PHYS_PAGE) as *mut u32) = i as u32 + 1; + } + let r = mem::VirtualAlloc(std::ptr::null(), n * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + let addrs: Vec<*mut c_void> = (0..n).map(|i| (r + i * PHYS_PAGE) as *mut c_void).collect(); + let mut ids: Vec = pages.iter().map(|&p| p as u64).collect(); + let t = std::time::Instant::now(); + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), n, ids.as_mut_ptr()), 1); + let from_home = ms(t); + ids.reverse(); + let t = std::time::Instant::now(); + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), n, ids.as_mut_ptr()), 1); + let reverse = ms(t); + for i in (0..n).step_by(97) { + assert_eq!(*((r + i * PHYS_PAGE) as *const u32), (n - i) as u32); + } + let t = std::time::Instant::now(); + assert_eq!(MapTitlePhysicalPages(std::ptr::null_mut(), n, 0, 4, pages.as_mut_ptr()) as usize, h); + let back = ms(t); + for i in (0..n).step_by(97) { + assert_eq!(*((h + i * PHYS_PAGE) as *const u32), i as u32 + 1); + } + eprintln!("scatter_timing pages={n} from_home={from_home:.1}ms reverse={reverse:.1}ms back_home={back:.1}ms"); + FreeTitlePhysicalPages(std::ptr::null_mut(), n, pages.as_mut_ptr()); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + } + } + } + #[test] fn title_memory_status_reports_budget() { let mut s: TitleMemoryStatusT = unsafe { std::mem::zeroed() };