Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion crates/xcl/src/gpu/uma.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,8 @@ pub struct Uma {
/// cannot take it – a title that commits all of unified memory at start (Unicorn
/// Overlord: 2046 of 2048 MB) left no room for draw arguments, and draws were skipped.
pool: Mutex<(usize, usize, Vec<usize>)>,
/// windows remade as driver heaps (`hle::d3d12x::uma_driver`), one bit each
driver: std::sync::atomic::AtomicU32,
}

/// bytes of XCL's arena pool (`Uma::new`)
Expand Down Expand Up @@ -406,6 +408,7 @@ impl Uma {
views: Mutex::new(views),
shadowed: AtomicBool::new(false),
pool: Mutex::new((0, 0, Vec::new())),
driver: Default::default(),
};
u.reserve_pool(POOL);
return Some(u);
Expand Down Expand Up @@ -520,6 +523,16 @@ impl Uma {
self.window_of(p).is_some_and(|k| self.is_committed_window(k))
}

/// Window `k` is a driver heap now (`hle::d3d12x::uma_driver`).
pub fn set_driver_window(&self, k: usize) {
self.driver.fetch_or(1 << k, std::sync::atomic::Ordering::Relaxed);
}

/// Whether window `k` is a driver heap (`set_driver_window`).
pub fn is_driver_window(&self, k: usize) -> bool {
k < 32 && self.driver.load(std::sync::atomic::Ordering::Relaxed) & (1 << k) != 0
}

/// Whether `[p, p + len)` lies in a committed coherent window – memory that is committed and
/// read-write as a whole, so it needs no `VirtualQuery` (which walks a region to its end to
/// size it: on a 4 GiB window ~40 ms a call, a retail game's DirectStorage requests crawled).
Expand Down Expand Up @@ -685,6 +698,7 @@ impl Uma {
views: Mutex::new(Default::default()),
shadowed: AtomicBool::new(false),
pool: Mutex::new((0, 0, Vec::new())),
driver: Default::default(),
});
}
for p in got {
Expand Down Expand Up @@ -734,7 +748,11 @@ impl Uma {
match self.kinds[k] {
WindowKind::None | WindowKind::View => k += 1,
WindowKind::Committed(s) => {
out.push((self.base + k * WINDOW, s));
if let Some(segs) = driver_watch_segments(k) {
out.extend(segs);
} else {
out.push((self.base + k * WINDOW, s));
}
k += 1;
}
WindowKind::Sparse => {
Expand Down Expand Up @@ -1131,6 +1149,25 @@ impl Uma {

/// The title's graphics memory (created on first use; `XCL_UMA_MB`, default 2048;
/// `XCL_UMA_WINDOWS=4|8|16`, default 4, with 8/16 requiring `XCL_HEAP_WINDOWS=1`).
/// Per-window write-watched sub-ranges of mixed driver windows (`XCL_UMA_DRIVER=mixed:...`): only
/// their CUSTOM segments are write-watched, not the GPU_UPLOAD one.
static DRIVER_WATCH_SEGMENTS: Mutex<Vec<(usize, Vec<(usize, usize)>)>> = Mutex::new(Vec::new());

/// Window `k` was remade as several driver-heap segments; only `segs` are write-watched.
pub fn set_driver_watch_segments(k: usize, segs: Vec<(usize, usize)>) {
let mut g = DRIVER_WATCH_SEGMENTS.lock().unwrap();
if let Some(entry) = g.iter_mut().find(|(wk, _)| *wk == k) {
entry.1 = segs;
} else {
g.push((k, segs));
}
}

fn driver_watch_segments(k: usize) -> Option<Vec<(usize, usize)>> {
let g = DRIVER_WATCH_SEGMENTS.lock().unwrap();
g.iter().find(|(wk, _)| *wk == k).map(|(_, segs)| segs.clone())
}

pub fn get() -> Option<&'static Uma> {
GLOBAL
.get_or_init(|| {
Expand Down
31 changes: 31 additions & 0 deletions crates/xcl/src/hle/d3d12x/alloc_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,19 @@ fn unpin(s: &mut State, list: usize) {
}
}

/// `list` (a closed segment) is parked as a spare: its recording is over and it is reset before
/// it records again, so it no longer holds its allocator. Its last submit stays (`in_flight`)
/// and the allocator's own submit marks still keep it until the GPU is past them.
pub(super) fn park_list(list: usize) {
let mut g = STATE.lock().unwrap();
let Some(s) = g.as_mut() else { return };
if let Some(backing) = s.of_list.remove(&list) {
if let Some(b) = s.backings.get_mut(&backing) {
b.users.remove(&list);
}
}
}

/// Reset `list` on the title's allocator `alloc`, committing its new recording association
/// only after native Reset succeeds. No pool lock is held across the driver call.
pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) -> HRESULT) -> HRESULT {
Expand Down Expand Up @@ -510,6 +523,24 @@ mod tests {
assert!(s.backings[&other].users.contains(&elsewhere));
}

/// A parked spare stops holding its allocator: once nothing else records on it and no submit
/// is pending, the allocator is free again.
#[test]
fn a_parked_spare_no_longer_holds_its_allocator() {
let mut ids = Box::new([0u8; 2]);
let alloc = ids.as_mut_ptr() as usize;
let spare = alloc + 1;
created_on(spare, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0);
let held = |l: usize| STATE.lock().unwrap().as_ref().unwrap().backings[&alloc].users.contains(&l);
assert!(held(spare), "the new list records on the allocator");
park_list(spare);
let g = STATE.lock().unwrap();
let s = g.as_ref().unwrap();
assert!(!s.of_list.contains_key(&spare) && unsafe { s.backings[&alloc].free() }, "a parked spare must not pin the allocator");
drop(g);
ids[0] = 0;
}

#[test]
fn a_spare_whose_reset_fails_stays_available_for_retry() {
let (alloc, spare, list) = (0x1000usize, 0x2000usize, 0x3000usize);
Expand Down
3 changes: 3 additions & 0 deletions crates/xcl/src/hle/d3d12x/list_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3907,6 +3907,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) {
for seg in reclaimed {
super::bind::reset(seg as *mut c_void, 0, 0);
clear_segment_state(seg);
// a spare now: it does not hold its allocator until it records again (after both
// submits above, so the allocator keeps their marks)
super::alloc_pool::park_list(seg);
}
if let Some(s) = recording(primary as usize).lock().unwrap().as_mut().and_then(|m| m.get_mut(&(primary as usize))) {
s.allocator = alloc;
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/hle/d3d12x/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ mod submit_cost;
mod texture_upload;
pub mod title_textures;
pub mod view_want;
mod uma_driver;
pub mod vram;
mod worker_pool;

Expand Down
58 changes: 45 additions & 13 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,21 @@ pub fn abi_root_signature() -> Option<ID3D12RootSignature> {
/// lifetime.
static UMA_BUFFER: Mutex<Vec<(usize, u64)>> = Mutex::new(Vec::new());
/// the committed UMA windows opened as D3D12 heaps (indexed by window `k`; `None` for sparse windows)
static UMA_HEAPS: Mutex<Vec<Option<usize>>> = Mutex::new(Vec::new());
/// Window heaps for `CreatePlacedResource` inside coherent UMA windows: for each window `k`,
/// contiguous `(seg_offset, seg_len, heap_raw)` segments (1 entry for single-heap windows, N for
/// `XCL_UMA_DRIVER=mixed:...`).
static UMA_HEAPS: Mutex<Vec<Vec<(usize, usize, usize)>>> = Mutex::new(Vec::new());

fn uma_heap_for(k: usize, offset: usize, len: usize) -> Option<(usize, usize)> {
let g = UMA_HEAPS.lock().unwrap();
let segs = g.get(k)?;
for &(seg_off, seg_len, heap_raw) in segs {
if offset >= seg_off && offset.saturating_add(len) <= seg_off.saturating_add(seg_len) {
return Some((heap_raw, offset - seg_off));
}
}
None
}
/// console buffers placed in unified memory: resource → (address, bytes)
/// address, bytes, whether XCL allocated the memory (not: the title's own, CreatePlacedResourceX)
type UmaBuffer = (usize, usize, bool);
Expand Down Expand Up @@ -396,12 +410,29 @@ unsafe fn open_uma(device: &ID3D12Device) {
};
let n = u.shader_windows();
let mut bufs: Vec<(usize, u64)> = vec![(0, 0); n];
let mut heaps: Vec<Option<usize>> = vec![None; n];
let mut heaps: Vec<Vec<(usize, usize, usize)>> = vec![Vec::new(); n];
let mut shadows: Vec<(usize, ID3D12Resource)> = Vec::new();
for k in 0..n {
if !u.is_committed_window(k) {
continue;
}
// on NVIDIA the window becomes a driver CUSTOM write-back L0 heap at its own address: the
// GPU's loads and atomics on imported pages are an order of magnitude slower (`uma_driver`)
if shadow_choice() != Some(true) && super::uma_driver::wanted(device) {
let (base, size) = u.window(k);
match super::uma_driver::remake_window(device, base, size, u.committed_window() == Some(k)) {
Ok(remade) => {
u.set_driver_window(k);
if let Some(segs) = remade.watched_regions {
crate::gpu::uma::set_driver_watch_segments(k, segs);
}
bufs[k] = (remade.buf_raw, remade.gpu_va);
heaps[k] = remade.heaps;
continue;
}
Err(e) => crate::xlog_warn!("D3D12.X: coherent window {k} stays imported: {e}"),
}
}
let made = open(k).and_then(|heap| {
let shadowed = heap.is_none();
let heap = match heap {
Expand All @@ -421,7 +452,7 @@ unsafe fn open_uma(device: &ID3D12Device) {
match made {
Ok((buf_raw, va, heap_raw)) => {
bufs[k] = (buf_raw, va);
heaps[k] = Some(heap_raw);
heaps[k] = vec![(0, u.window(k).1, heap_raw)];
}
Err(e) => {
crate::xlog_warn!("D3D12.X: UMA not available to the GPU: {e}");
Expand Down Expand Up @@ -1639,11 +1670,12 @@ fn uma_shadowed() -> bool {

/// Sanitize a console buffer description and initial state for placement in a coherent
/// cross-adapter UMA heap (`OpenExistingHeapFromAddress`).
fn sanitize_coherent_buffer(desc: &D3D12_RESOURCE_DESC, state: usize) -> (D3D12_RESOURCE_DESC, u32) {
fn sanitize_coherent_buffer(desc: &D3D12_RESOURCE_DESC, state: usize, cross_adapter: bool) -> (D3D12_RESOURCE_DESC, u32) {
let mut d = *desc;
d.Flags = D3D12_RESOURCE_FLAGS(d.Flags.0 & 0xFF);
// a shadowed window's heap is video memory, not a cross-adapter heap over process memory
if !uma_shadowed() {
// a shadowed window's heap is video memory, not a cross-adapter heap over process memory;
// nor is a driver heap (`uma_driver`)
if cross_adapter && !uma_shadowed() {
d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER;
}
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
Expand Down Expand Up @@ -1682,10 +1714,10 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta
return None;
};
// the heap from OpenExistingHeapFromAddress is cross-adapter: row-major + sanitized flags & state
let (d, st) = sanitize_coherent_buffer(&d, state);
let k = u.window_of(p)?;
let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?;
let hr = dev_create_placed_resource(this, heap, p - u.window(k).0, &d as *const _ as usize, st as usize, clear, riid, ppv);
let (d, st) = sanitize_coherent_buffer(&d, state, !u.is_driver_window(k));
let (heap, heap_off) = uma_heap_for(k, p - u.window(k).0, d.Width as usize)?;
let hr = dev_create_placed_resource(this, heap, heap_off, &d as *const _ as usize, st as usize, clear, riid, ppv);
if hr < 0 || (*ppv).is_null() {
u.free(p);
static ONCE: AtomicU64 = AtomicU64::new(0);
Expand Down Expand Up @@ -1772,14 +1804,14 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc:
}
return Some(hr);
}
let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?;
if !u.shadowed() {
let (heap, heap_off) = uma_heap_for(k, start - base, delta + bytes)?;
if !u.shadowed() && !u.is_driver_window(k) {
d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER;
}
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
d.Alignment = 0;
d.Width = (delta + bytes) as u64;
let hr = dev_create_placed_resource(this, heap, start - base, &d as *const _ as usize, state as usize, clear as usize, riid, ppv);
let hr = dev_create_placed_resource(this, heap, heap_off, &d as *const _ as usize, state as usize, clear as usize, riid, ppv);
if hr < 0 || (*ppv).is_null() {
return None;
}
Expand Down Expand Up @@ -9785,7 +9817,7 @@ mod readback_routing_tests {
};
let console_state = 0x0010_0000usize | (D3D12_RESOURCE_STATE_COPY_DEST.0 as usize);

let (clean, st) = sanitize_coherent_buffer(&raw_desc, console_state);
let (clean, st) = sanitize_coherent_buffer(&raw_desc, console_state, true);
assert_eq!(clean.Alignment, 0);
assert_eq!(clean.Layout, D3D12_TEXTURE_LAYOUT_ROW_MAJOR);
assert_eq!(
Expand Down
5 changes: 5 additions & 0 deletions crates/xcl/src/hle/d3d12x/texture_upload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,11 @@ unsafe fn read<R>(pages: Option<&PageMap>, at: usize, len: usize, f: impl FnOnce
f(&s[..len])
});
}
// a GPU_UPLOAD segment of a mixed driver window: by the GPU's copy (CPU reads of that video
// memory through the BAR are slow)
if let Some(bytes) = super::uma_driver::read_vram_bytes(at, len) {
return f(&bytes);
}
if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) {
return f(std::slice::from_raw_parts(at as *const u8, len));
}
Expand Down
7 changes: 7 additions & 0 deletions crates/xcl/src/hle/d3d12x/title_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,13 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso:
for seg in moved {
super::bind::reset(seg as *mut c_void, 0, 0);
super::list_x::clear_segment_state(seg);
// a spare records again only after its next Reset: it does not hold its
// allocator meanwhile
super::alloc_pool::park_list(seg);
}
// nor does the previous recording a stand-in now replaces: it is not reset here either
if stand_in.is_some() {
super::alloc_pool::park_list(primary as usize);
}
}
*((this as usize + F_RING_AT) as *mut usize) = 0;
Expand Down
5 changes: 5 additions & 0 deletions crates/xcl/src/hle/d3d12x/title_textures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2723,6 +2723,11 @@ unsafe fn title_bytes(at: usize, len: usize) -> std::borrow::Cow<'static, [u8]>
// submits make the race likely); the copy goes through the kernel, which gives zeros for it.
static SAFE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let safe = *SAFE.get_or_init(|| std::env::var("XCL_TEXTURE_SAFE_READ").is_ok_and(|v| v.trim() == "1"));
// a GPU_UPLOAD segment of a mixed driver window: by the GPU's copy (CPU reads of that video
// memory through the BAR are slow)
if let Some(bytes) = super::uma_driver::read_vram_bytes(at, len) {
return std::borrow::Cow::Owned(bytes);
}
if !safe && crate::gpu::shader::readable(at, len) {
std::borrow::Cow::Borrowed(std::slice::from_raw_parts(at as *const u8, len))
} else {
Expand Down
Loading
Loading