mirror of
https://github.com/ivall/xcl.git
synced 2026-11-24 05:14:57 +01:00
Physical pages mapped into reserved address space
Fortnite streams textures by reserving graphics address space and mapping physical pages into it, which XCL refused. A graphics reservation is now Windows address space reserved with MEM_WRITE_WATCH and remembered; a page (number = UMA page index + 1, 0 = unmap) lives in its allocation's UMA block, and mapping pages at another address, in any order, commits it and copies their data there - unmapping or mapping them elsewhere copies it back, so a page keeps its contents and is in one place at a time. Textures placed in such memory read only the committed pages and are uploaded again after the mapping and the writes (the reservations are watched like unified memory). Tests: reverse-order mapping, moving, unmapping and remapping a page (xmem); a texture placed in an empty pool shows its texels once a page is mapped in and written (GPU).
This commit is contained in:
+10
-2
@@ -651,8 +651,16 @@ The EXE (+ EOSSDK) imports 31 functions from console libraries: MFPlat `MFResetD
|
||||
DirectStorage reads) and uploads them again (on an XCL queue, waiting for it). Unreadable memory (reserved, not mapped)
|
||||
reads as zero. The test title writes a 64KB_S_X array through XG, places it, reads every subresource back through
|
||||
the GPU, rewrites one and sees it after the next ExecuteCommandLists. Not yet: GPU writes into the title's memory
|
||||
(copies to the address), mapping physical pages into reserved address space (Fortnite's streaming does that), the
|
||||
upload without a CPU wait, the state if the title moved the texture out of its initial one.
|
||||
(copies to the address), the upload without a CPU wait, the state if the title moved the texture out of its initial
|
||||
one.
|
||||
- **Physical pages mapped into reserved address space** (Fortnite's texture streaming, `kernelx`): a graphics
|
||||
reservation (VirtualAlloc / XMemVirtualAlloc, MEM_RESERVE without commit) is Windows address space reserved with
|
||||
MEM_WRITE_WATCH and remembered; a page (number = UMA page index + 1, 0 = unmap) lives in its allocation's UMA block;
|
||||
mapping pages at another address, in any order, commits it and copies their data there, unmapping (null / 0 pages,
|
||||
or mapping them elsewhere) copies it back – a page is in one place at a time and keeps its contents (no aliasing:
|
||||
two addresses of one page at once are not possible this way). Title textures placed there read only the committed
|
||||
pages and are uploaded again after the mapping / the writes. Tests: reverse-order mapping, moving a page, unmapping
|
||||
and mapping it again (xmem); a texture placed in an empty pool gets its texels once a page is mapped in (GPU).
|
||||
- XGameRuntime task queues: handles are looked up in a set of live ones before being read – an XAsync completing on a
|
||||
worker after its queue was closed read freed memory (a rare lib-test panic in `queue_from`).
|
||||
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//! samples that memory, laid out as the console's layout library says (`hle::xg`, checked
|
||||
//! against the console's own). Here a PC texture holds a detiled copy: uploaded when the
|
||||
//! texture is created and again before the title's next ExecuteCommandLists once the CPU wrote
|
||||
//! any of its pages (unified memory is write-watched, `gpu::uma`) – textures streamed in after
|
||||
//! creation (mips loaded later, DirectStorage) included.
|
||||
//! any of its pages (unified memory and the title's graphics reservations are write-watched,
|
||||
//! `gpu::uma`, `kernelx::VirtualAlloc`) – textures streamed in after creation (mips loaded
|
||||
//! later, physical pages mapped in, DirectStorage) included.
|
||||
//!
|
||||
//! The copy waits for the GPU on an XCL queue of the device. Memory that is not readable
|
||||
//! (reserved, not mapped yet) reads as zero. GPU writes into the title's memory (copies to the
|
||||
@@ -58,7 +59,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize,
|
||||
let tex = xg::Texture::new(desc).map_err(|hr| format!("layout {hr:#x}"))?;
|
||||
let bytes = tex.size() as usize;
|
||||
let e = Entry { device: device as usize, va, tex: Arc::new(tex), state };
|
||||
if crate::gpu::uma::get().is_some_and(|u| u.contains(va)) {
|
||||
if crate::gpu::uma::get().is_some_and(|u| u.contains(va)) || crate::hle::kernelx::in_graphics_reservation(va) {
|
||||
ResetWriteWatch(va as *const c_void, bytes);
|
||||
}
|
||||
let upload = (e.device, e.va, Arc::clone(&e.tex), e.state);
|
||||
@@ -93,8 +94,8 @@ unsafe fn refresh_once() {
|
||||
let Some(u) = crate::gpu::uma::get() else { return };
|
||||
let mut dirty: Vec<usize> = Vec::new();
|
||||
let mut page = 0x1000u32;
|
||||
for k in 0..u.windows() {
|
||||
let (base, size) = u.window(k);
|
||||
let regions: Vec<(usize, usize)> = (0..u.windows()).map(|k| u.window(k)).chain(crate::hle::kernelx::graphics_reservations()).collect();
|
||||
for (base, size) in regions {
|
||||
loop {
|
||||
let mut buf = vec![std::ptr::null_mut::<c_void>(); 16384];
|
||||
let mut n = buf.len();
|
||||
@@ -135,16 +136,36 @@ unsafe fn refresh_once() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `len` bytes at `at`: the committed, readable pages copied, the rest zero (a streaming pool
|
||||
/// has only some of its pages mapped).
|
||||
unsafe fn read_committed(at: usize, len: usize) -> Vec<u8> {
|
||||
use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT};
|
||||
let mut out = vec![0u8; len];
|
||||
let mut p = at;
|
||||
while p < at + len {
|
||||
let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
|
||||
if VirtualQuery(p as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 {
|
||||
break;
|
||||
}
|
||||
let end = (m.BaseAddress as usize + m.RegionSize).min(at + len);
|
||||
let readable = m.State == MEM_COMMIT && m.Protect & 0xEE != 0 && m.Protect & 0x100 == 0; // R / RW / WC / X-R…, no guard
|
||||
if readable {
|
||||
std::ptr::copy_nonoverlapping(p as *const u8, out.as_mut_ptr().add(p - at), end - p);
|
||||
}
|
||||
p = end;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every subresource (D3D12 order) of a texture from the title's memory at `va`.
|
||||
unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec<Subresource> {
|
||||
let c = &tex.chain;
|
||||
let bpe = tex.bpe as usize;
|
||||
let mut out = Vec::with_capacity(tex.array as usize * c.levels.len());
|
||||
for s in 0..tex.array as usize {
|
||||
let at = va + s * c.slice_bytes;
|
||||
let slice: &[u8] = if crate::gpu::shader::readable(at, c.slice_bytes) { std::slice::from_raw_parts(at as *const u8, c.slice_bytes) } else { &[] };
|
||||
let slice = read_committed(va + s * c.slice_bytes, c.slice_bytes);
|
||||
for (i, l) in c.levels.iter().enumerate() {
|
||||
out.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width * bpe, data: c.detile_level(slice, i, s) });
|
||||
out.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width * bpe, data: c.detile_level(&slice, i, s) });
|
||||
}
|
||||
}
|
||||
out
|
||||
|
||||
+122
-35
@@ -119,14 +119,39 @@ pub fn sanitize_protect(p: u32) -> u32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Graphics address space the title reserved (no commit) – where it maps physical pages (a
|
||||
/// texture streaming pool): base → size. Write-watched, like unified memory, so textures in it
|
||||
/// follow CPU writes (`d3d12x::title_textures`).
|
||||
static GRAPHICS_RESERVATIONS: std::sync::Mutex<std::collections::BTreeMap<usize, usize>> = std::sync::Mutex::new(std::collections::BTreeMap::new());
|
||||
|
||||
/// The title's graphics reservations (base, size).
|
||||
pub fn graphics_reservations() -> Vec<(usize, usize)> {
|
||||
GRAPHICS_RESERVATIONS.lock().unwrap().iter().map(|(&b, &s)| (b, s)).collect()
|
||||
}
|
||||
|
||||
/// Whether `p` lies in one of the title's graphics reservations.
|
||||
pub fn in_graphics_reservation(p: usize) -> bool {
|
||||
GRAPHICS_RESERVATIONS.lock().unwrap().range(..=p).next_back().is_some_and(|(&b, &s)| p < b + s)
|
||||
}
|
||||
|
||||
const MEM_WRITE_WATCH: u32 = 0x20_0000;
|
||||
|
||||
/// Graphics memory (MEM_GRAPHICS, committed, no fixed address) comes from the unified
|
||||
/// memory region the GPU uses directly (`gpu::uma`); everything else from Windows.
|
||||
/// memory region the GPU uses directly (`gpu::uma`); a graphics reservation (no commit) is
|
||||
/// write-watched address space of Windows; everything else from Windows.
|
||||
pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: u32, p: u32) -> *mut c_void {
|
||||
if addr.is_null() && t & MEM_GRAPHICS != 0 && t & 0x1000 != 0 {
|
||||
if let Some(q) = crate::gpu::uma::get().and_then(|u| u.alloc(size, 0)) {
|
||||
return q as *mut c_void;
|
||||
}
|
||||
}
|
||||
if addr.is_null() && t & MEM_GRAPHICS != 0 && t & 0x2000 != 0 {
|
||||
let q = mem::VirtualAlloc(addr, size, mem::MEM_RESERVE | MEM_WRITE_WATCH, sanitize_protect(p));
|
||||
if !q.is_null() {
|
||||
GRAPHICS_RESERVATIONS.lock().unwrap().insert(q as usize, size);
|
||||
return q;
|
||||
}
|
||||
}
|
||||
mem::VirtualAlloc(addr, size, sanitize_alloc_type(t), sanitize_protect(p))
|
||||
}
|
||||
|
||||
@@ -142,6 +167,9 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
if t & 0x8000 != 0 {
|
||||
GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize));
|
||||
}
|
||||
mem::VirtualFree(addr, size, t)
|
||||
}
|
||||
|
||||
@@ -382,14 +410,47 @@ pub unsafe extern "system" fn ToolingMemoryStatus(buf: *mut u32) -> BOOL {
|
||||
}
|
||||
|
||||
/// Title physical pages (64 KiB) emulated in the unified memory region: an allocation is one
|
||||
/// contiguous UMA block, page numbers = offset / 64 KiB in UMA. Mapping consecutive pages
|
||||
/// returns their UMA address (GPU-visible, no copy); choosing that same address is supported.
|
||||
/// A different address or scattered pages cannot alias memory this way – logged and refused.
|
||||
/// contiguous UMA block – its pages' home; a page's number is its UMA page index + 1 (0 means
|
||||
/// "none": unmap). Mapping consecutive pages at their home (or at no chosen address) returns
|
||||
/// that UMA address (GPU-visible, no copy). Mapping pages at another address – address space
|
||||
/// the title reserved, in any order – commits it and copies their data there; unmapping them
|
||||
/// (or mapping them elsewhere) copies it back home: a page is in one place at a time and keeps
|
||||
/// its contents.
|
||||
const PHYS_PAGE: usize = 0x1_0000;
|
||||
|
||||
/// first page number → (pages in the block, pages still allocated)
|
||||
static PHYS_BLOCKS: std::sync::Mutex<std::collections::BTreeMap<usize, (usize, usize)>> = std::sync::Mutex::new(std::collections::BTreeMap::new());
|
||||
|
||||
/// Pages mapped away from home: address → page, and page → address.
|
||||
#[derive(Default)]
|
||||
struct Away {
|
||||
at: std::collections::BTreeMap<usize, usize>,
|
||||
page: std::collections::HashMap<usize, usize>,
|
||||
}
|
||||
static AWAY: std::sync::Mutex<Option<Away>> = std::sync::Mutex::new(None);
|
||||
|
||||
/// The home address of page `page` if it belongs to a live allocation.
|
||||
fn page_home(page: usize) -> Option<usize> {
|
||||
let u = crate::gpu::uma::get()?;
|
||||
let index = page.checked_sub(1)?;
|
||||
let blocks = PHYS_BLOCKS.lock().ok()?;
|
||||
let (&first, &(count, live)) = blocks.range(..=index).next_back()?;
|
||||
(live > 0 && index < first.checked_add(count)?).then(|| u.base().checked_add(index.checked_mul(PHYS_PAGE)?)).flatten().filter(|&p| p + PHYS_PAGE <= u.base() + u.size())
|
||||
}
|
||||
|
||||
/// Copy what is mapped at `at` back home and unmap it (Windows memory is decommitted).
|
||||
unsafe fn unmap_away(away: &mut Away, at: usize) {
|
||||
if let Some(page) = away.at.remove(&at) {
|
||||
away.page.remove(&page);
|
||||
if let Some(home) = page_home(page) {
|
||||
std::ptr::copy_nonoverlapping(at as *const u8, home as *mut u8, PHYS_PAGE);
|
||||
}
|
||||
if !crate::gpu::uma::get().is_some_and(|u| u.contains(at)) {
|
||||
mem::VirtualFree(at as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe extern "system" fn AllocateTitlePhysicalPages(_p: HANDLE, _t: u32, num: *mut usize, arr: *mut usize) -> BOOL {
|
||||
if num.is_null() || arr.is_null() || *num == 0 {
|
||||
fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER);
|
||||
@@ -407,7 +468,7 @@ pub unsafe extern "system" fn AllocateTitlePhysicalPages(_p: HANDLE, _t: u32, nu
|
||||
};
|
||||
let first = (block as usize - u.base()) / PHYS_PAGE;
|
||||
for i in 0..n {
|
||||
*arr.add(i) = first + i;
|
||||
*arr.add(i) = first + i + 1;
|
||||
}
|
||||
PHYS_BLOCKS.lock().unwrap().insert(first, (n, n));
|
||||
1
|
||||
@@ -419,9 +480,17 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr:
|
||||
fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER);
|
||||
return 0;
|
||||
}
|
||||
// freed pages mapped elsewhere: that address keeps whatever it holds, the mapping goes
|
||||
if let Some(away) = AWAY.lock().unwrap().as_mut() {
|
||||
for i in 0..n {
|
||||
if let Some(at) = away.page.remove(&*arr.add(i)) {
|
||||
away.at.remove(&at);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut g = PHYS_BLOCKS.lock().unwrap();
|
||||
for i in 0..n {
|
||||
let page = *arr.add(i);
|
||||
let Some(page) = (*arr.add(i)).checked_sub(1) else { continue };
|
||||
// the block holding this page
|
||||
let Some((&first, &(count, _))) = g.range(..=page).next_back() else { continue };
|
||||
if page >= first + count {
|
||||
@@ -438,38 +507,56 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr:
|
||||
}
|
||||
|
||||
pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _t: u32, _p: u32, arr: *mut usize) -> *mut c_void {
|
||||
let Some(u) = crate::gpu::uma::get() else { return std::ptr::null_mut() };
|
||||
if n == 0 || arr.is_null() {
|
||||
if crate::gpu::uma::get().is_none() || n == 0 || (va.is_null() && arr.is_null()) {
|
||||
fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER);
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
let first = *arr;
|
||||
let consecutive = (1..n).all(|i| first.checked_add(i).is_some_and(|page| *arr.add(i) == page));
|
||||
let at = consecutive.then(|| {
|
||||
let end_page = first.checked_add(n)?;
|
||||
let blocks = PHYS_BLOCKS.lock().ok()?;
|
||||
let (&block_first, &(block_pages, live_pages)) = blocks.range(..=first).next_back()?;
|
||||
let block_end = block_first.checked_add(block_pages)?;
|
||||
if live_pages == 0 || end_page > block_end {
|
||||
return None;
|
||||
}
|
||||
let offset = first.checked_mul(PHYS_PAGE)?;
|
||||
let bytes = n.checked_mul(PHYS_PAGE)?;
|
||||
let address = u.base().checked_add(offset)?;
|
||||
let end = address.checked_add(bytes)?;
|
||||
(end <= u.base().checked_add(u.size())?).then_some(address as *mut c_void)
|
||||
}).flatten();
|
||||
if let Some(at) = at {
|
||||
if va.is_null() || va == at {
|
||||
return at;
|
||||
}
|
||||
let pages: Vec<usize> = if arr.is_null() { vec![0; n] } else { (0..n).map(|i| *arr.add(i)).collect() };
|
||||
if pages.iter().any(|&p| p != 0 && page_home(p).is_none()) {
|
||||
fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER);
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
static WARNED: AtomicU32 = AtomicU32::new(0);
|
||||
if WARNED.fetch_add(1, Ordering::Relaxed) < 5 {
|
||||
crate::xlog_warn!("MapTitlePhysicalPages({va:?}, {n} pages, consecutive: {consecutive}) – mapping at a chosen address / of scattered pages not supported yet");
|
||||
let mut g = AWAY.lock().unwrap();
|
||||
let away = g.get_or_insert_with(Away::default);
|
||||
// consecutive pages at their home (or no address chosen): that UMA memory itself
|
||||
let consecutive = pages[0] != 0 && (1..n).all(|i| pages[0].checked_add(i) == Some(pages[i]));
|
||||
let home = if consecutive { page_home(pages[0]).filter(|_| page_home(pages[n - 1]).is_some()) } else { None };
|
||||
if va.is_null() || home == Some(va as usize) {
|
||||
let Some(home) = home else {
|
||||
fnd::SetLastError(fnd::ERROR_NOT_SUPPORTED); // scattered pages need an address
|
||||
return std::ptr::null_mut();
|
||||
};
|
||||
for &p in &pages {
|
||||
if let Some(&at) = away.page.get(&p) {
|
||||
unmap_away(away, at);
|
||||
}
|
||||
}
|
||||
return home as *mut c_void;
|
||||
}
|
||||
fnd::SetLastError(fnd::ERROR_NOT_SUPPORTED);
|
||||
std::ptr::null_mut()
|
||||
let base = va as usize;
|
||||
if !base.is_multiple_of(PHYS_PAGE) {
|
||||
fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER);
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
let in_uma = |a: usize| crate::gpu::uma::get().is_some_and(|u| u.contains(a));
|
||||
for (i, &p) in pages.iter().enumerate() {
|
||||
let at = base + i * PHYS_PAGE;
|
||||
unmap_away(away, at);
|
||||
if p == 0 {
|
||||
continue;
|
||||
}
|
||||
if let Some(&old) = away.page.get(&p) {
|
||||
unmap_away(away, old);
|
||||
}
|
||||
if !in_uma(at) && mem::VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() {
|
||||
fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS);
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
std::ptr::copy_nonoverlapping(page_home(p).unwrap() as *const u8, at as *mut u8, PHYS_PAGE);
|
||||
away.at.insert(at, p);
|
||||
away.page.insert(p, at);
|
||||
}
|
||||
va
|
||||
}
|
||||
|
||||
/// `BOOL XMemAllocatePhysicalPages(XALLOC_ATTRIBUTES, SIZE_T* count, ULONG64* pages)`: the
|
||||
@@ -992,13 +1079,13 @@ mod tests {
|
||||
assert!(MapTitlePhysicalPages(std::ptr::null_mut(), 2, 0, 4, scattered.as_mut_ptr()).is_null());
|
||||
// Page numbers must refer to one registered allocation; arithmetic is checked before
|
||||
// constructing an address inside the reserved UMA region.
|
||||
let mut outside = [u.size() / PHYS_PAGE];
|
||||
let mut outside = [u.size() / PHYS_PAGE + 1];
|
||||
assert!(MapTitlePhysicalPages(std::ptr::null_mut(), 1, 0, 4, outside.as_mut_ptr()).is_null());
|
||||
let mut wrapping = [usize::MAX];
|
||||
assert!(MapTitlePhysicalPages(std::ptr::null_mut(), 2, 0, 4, wrapping.as_mut_ptr()).is_null());
|
||||
// freed: the block is gone (other tests use UMA at the same time, so not `u.used()`)
|
||||
assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 3, pages.as_mut_ptr()), 1);
|
||||
assert!(!PHYS_BLOCKS.lock().unwrap().contains_key(&pages[0]));
|
||||
assert!(!PHYS_BLOCKS.lock().unwrap().contains_key(&(pages[0] - 1)));
|
||||
assert!(MapTitlePhysicalPages(std::ptr::null_mut(), 3, 0, 4, pages.as_mut_ptr()).is_null());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -649,6 +649,87 @@ pub fn title_texture() -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A texture placed in a streaming pool before any memory is there: address space reserved,
|
||||
/// the texture placed at it (#44, its texels read as zero), then a physical page mapped in and
|
||||
/// the texels written – the GPU sees them after the next ExecuteCommandLists.
|
||||
pub fn streamed_texture() -> Result<(), String> {
|
||||
unsafe {
|
||||
let dev = device()?;
|
||||
let slot = |obj: *mut c_void, i: usize| *(*(obj as *const *const usize)).add(i);
|
||||
let mut desc = D3D12_RESOURCE_DESC {
|
||||
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
|
||||
Width: 64,
|
||||
Height: 64,
|
||||
DepthOrArraySize: 1,
|
||||
MipLevels: 1,
|
||||
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
|
||||
..Default::default()
|
||||
};
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT(0x105); // 4KB_S: 16 KB
|
||||
let mut xg = std::ptr::null_mut();
|
||||
ensure!(XGCreateTextureComputer(&desc, &mut xg) == 0, "XGCreateTextureComputer");
|
||||
let page = 0x1_0000usize;
|
||||
let va = crate::XMemVirtualAlloc(std::ptr::null(), page, 0x2000, 1u64 << 29, 4) as usize;
|
||||
ensure!(va != 0, "reservation");
|
||||
type PlacedX = unsafe extern "system" fn(*mut c_void, u64, *const D3D12_RESOURCE_DESC, u32, *const c_void, *const windows::core::GUID, *mut *mut c_void) -> HRESULT;
|
||||
let mut raw = std::ptr::null_mut();
|
||||
let hr = std::mem::transmute::<usize, PlacedX>(slot(dev.as_raw(), 44))(dev.as_raw(), va as u64, &desc, 0, std::ptr::null(), &ID3D12Resource::IID, &mut raw);
|
||||
ensure!(hr >= 0 && !raw.is_null(), "CreatePlacedResourceX hr={hr:#x}");
|
||||
let tex = ID3D12Resource::from_raw(raw);
|
||||
let (mut n, mut pages) = (1usize, [0u64; 1]);
|
||||
ensure!(crate::XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()) != 0, "XMemAllocatePhysicalPages");
|
||||
ensure!(crate::XMemMapPhysicalPages(va as *mut c_void, 1, pages.as_mut_ptr()) as usize == va, "XMemMapPhysicalPages");
|
||||
let texels: Vec<u8> = (0..64 * 64 * 4).map(|i: u32| (i as u8).wrapping_mul(13) ^ 0x5A).collect();
|
||||
type Into = unsafe extern "system" fn(*mut c_void, *mut u8, u32, u32, *const u8, u32, u32) -> HRESULT;
|
||||
ensure!(std::mem::transmute::<usize, Into>(slot(xg, 8))(xg, va as *mut u8, 0, 0, texels.as_ptr(), 256, 256 * 64) == 0, "CopyIntoSubresource");
|
||||
|
||||
let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).map_err(e)?;
|
||||
let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
|
||||
let mut total = 0u64;
|
||||
dev.GetCopyableFootprints(&tex.GetDesc(), 0, 1, 0, Some(&mut fp), None, None, Some(&mut total));
|
||||
let mut rb: Option<ID3D12Resource> = None;
|
||||
dev.CreateCommittedResource(
|
||||
&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
|
||||
D3D12_HEAP_FLAG_NONE,
|
||||
&D3D12_RESOURCE_DESC {
|
||||
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
|
||||
Width: total,
|
||||
Height: 1,
|
||||
DepthOrArraySize: 1,
|
||||
MipLevels: 1,
|
||||
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
|
||||
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
|
||||
..Default::default()
|
||||
},
|
||||
D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
None,
|
||||
&mut rb,
|
||||
)
|
||||
.map_err(e)?;
|
||||
let rb = rb.ok_or("no readback buffer")?;
|
||||
let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?;
|
||||
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(e)?;
|
||||
let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } };
|
||||
let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&tex), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } };
|
||||
list.CopyTextureRegion(&dst, 0, 0, 0, &src, None);
|
||||
list.Close().map_err(e)?;
|
||||
queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>().map_err(e)?)]);
|
||||
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?;
|
||||
wait(&queue, &fence, 1)?;
|
||||
let mut p = std::ptr::null_mut();
|
||||
rb.Map(0, None, Some(&mut p)).map_err(e)?;
|
||||
let same = (0..64usize).all(|y| std::slice::from_raw_parts((p as *const u8).add(fp.Offset as usize + y * fp.Footprint.RowPitch as usize), 256) == &texels[y * 256..(y + 1) * 256]);
|
||||
rb.Unmap(0, None);
|
||||
ensure!(same, "the texture does not have the texels mapped in after it was placed");
|
||||
drop(tex);
|
||||
ensure!(crate::XMemFreePhysicalPages(1, pages.as_mut_ptr()) != 0, "XMemFreePhysicalPages");
|
||||
std::mem::transmute::<usize, unsafe extern "system" fn(*mut c_void) -> u32>(slot(xg, 1))(xg);
|
||||
crate::VirtualFree(va as *mut c_void, 0, 0x8000);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render_triangle() -> Result<(), String> {
|
||||
unsafe {
|
||||
let dev = device()?;
|
||||
|
||||
@@ -247,6 +247,31 @@ fn main() {
|
||||
Ok(())
|
||||
});
|
||||
|
||||
check("xmem: physical pages mapped into reserved address space keep their contents", || unsafe {
|
||||
let (reserve, rw, graphics) = (0x2000u32, 4u32, 1u64 << 29);
|
||||
let page = 0x1_0000usize;
|
||||
let va = XMemVirtualAlloc(std::ptr::null(), 4 * page, reserve, graphics, rw) as usize;
|
||||
ensure!(va != 0 && va.is_multiple_of(page), "reservation {va:#x}");
|
||||
let (mut n, mut pages) = (2usize, [0u64; 2]);
|
||||
ensure!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()) != 0, "XMemAllocatePhysicalPages");
|
||||
// in the reverse order, one page in: page b at va + 1, page a at va + 2
|
||||
let mut ba = [pages[1], pages[0]];
|
||||
ensure!(XMemMapPhysicalPages((va + page) as *mut c_void, 2, ba.as_mut_ptr()) as usize == va + page, "map b, a");
|
||||
*((va + page) as *mut u32) = 0xB;
|
||||
*((va + 2 * page) as *mut u32) = 0xA;
|
||||
// page a moves to va: its data with it
|
||||
let mut a = [pages[0]];
|
||||
ensure!(XMemMapPhysicalPages(va as *mut c_void, 1, a.as_mut_ptr()) as usize == va, "map a at va");
|
||||
ensure!(*(va as *const u32) == 0xA, "page a moved without its data");
|
||||
// unmapped (null pages) and mapped again further on: still its data
|
||||
ensure!(XMemMapPhysicalPages(va as *mut c_void, 1, std::ptr::null_mut()) as usize == va, "unmap");
|
||||
ensure!(XMemMapPhysicalPages((va + 3 * page) as *mut c_void, 1, a.as_mut_ptr()) as usize == va + 3 * page, "map a again");
|
||||
ensure!(*((va + 3 * page) as *const u32) == 0xA && *((va + page) as *const u32) == 0xB, "contents after remapping");
|
||||
ensure!(XMemFreePhysicalPages(2, pages.as_mut_ptr()) != 0, "XMemFreePhysicalPages");
|
||||
ensure!(VirtualFree(va as *mut c_void, 0, 0x8000) != 0, "VirtualFree");
|
||||
Ok(())
|
||||
});
|
||||
|
||||
check("kernelx: graphics memory lives in the GPU-visible 4 GiB-aligned region (UMA)", || unsafe {
|
||||
let attrs = 1u64 << 29; // memory type 1: graphics
|
||||
let a = XMemAlloc(0x20000, attrs);
|
||||
@@ -479,6 +504,7 @@ fn main() {
|
||||
check("D3D12.X: console command list memory methods (writes, timestamp, fill, copy)", gpu::console_list_methods);
|
||||
check("DirectStorage (xcrdapi): a file read into memory, status + D3D12 fence", gpu::direct_storage);
|
||||
check("D3D12.X: a texture in title memory (XG layout, #44) follows CPU writes", gpu::title_texture);
|
||||
check("D3D12.X: a texture in a streaming pool gets its texels once pages are mapped in", gpu::streamed_texture);
|
||||
check("XAudio2: console flags/device, XMA2 voice plays silence, PCM passes, callbacks", audio::xaudio2_console_voices);
|
||||
|
||||
let failures = FAILURES.load(Ordering::SeqCst);
|
||||
|
||||
Reference in New Issue
Block a user