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
21 changes: 16 additions & 5 deletions crates/xcl/src/gpu/recomp/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -721,7 +721,7 @@ pub fn run_with_statics(
tex_back.push((i, rb));
}
list.Close().map_err(e)?;
gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]);
submit_list(&gpu.queue, &list)?;
gpu.value += 1;
wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "kernel dispatch")?;
let mut p = std::ptr::null_mut();
Expand Down Expand Up @@ -1210,7 +1210,7 @@ fn draw_indexed_on(
};
list.CopyTextureRegion(&dst, 0, 0, 0, &src, None);
list.Close().map_err(e)?;
queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]);
submit_list(&queue, &list)?;
wait_for_submission(dev, &queue, &fence, 1, "draw")?;
let mut p = std::ptr::null_mut();
readback.Map(0, None, Some(&mut p)).map_err(e)?;
Expand Down Expand Up @@ -1413,7 +1413,7 @@ pub fn mesh_draw_split(
list.CopyTextureRegion(&dst, 0, 0, 0, &src, None);
list.CopyBufferRegion(&readback, total, &res_buf, 0, res_bytes);
list.Close().map_err(e)?;
gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]);
submit_list(&gpu.queue, &list)?;
gpu.value += 1;
wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "mesh draw")?;
let mut q = std::ptr::null_mut();
Expand Down Expand Up @@ -1548,7 +1548,7 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result<Kern
}
list.CopyBufferRegion(&readback, 0, &res_buf, 0, res_bytes);
list.Close().map_err(e)?;
gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]);
submit_list(&gpu.queue, &list)?;
gpu.value += 1;
wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "arena dispatch")?;
let mut q = std::ptr::null_mut();
Expand Down Expand Up @@ -1727,7 +1727,7 @@ fn dispatch_with(
list.ResourceBarrier(&[transition(&mem_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
list.CopyBufferRegion(&readback, 0, &mem_buf, 0, mem_bytes);
list.Close().map_err(e)?;
queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]);
submit_list(queue, &list)?;
*value += 1;
wait_for_submission(dev, queue, fence, *value, "compute dispatch")?;
let mut q = std::ptr::null_mut();
Expand All @@ -1746,3 +1746,14 @@ fn dispatch_with(
Ok((out, ms))
}
}

/// Submit `list` to `queue`. Under Wine, if another test (e.g. `real::init()`) adopted the
/// process-wide singleton `ID3D12Device` after `queue` was created, `list` carries XCL's
/// extended vtable while `queue` does not go through `real::q_execute_command_lists`, so
/// restore `list`'s native vtable for the call.
unsafe fn submit_list(queue: &ID3D12CommandQueue, list: &ID3D12GraphicsCommandList) -> Result<(), String> {
let cmd: ID3D12CommandList = list.cast().map_err(e)?;
let _guard = crate::hle::d3d12x::real::UnadoptGuard::new(cmd.as_raw());
queue.ExecuteCommandLists(&[Some(cmd)]);
Ok(())
}
56 changes: 51 additions & 5 deletions crates/xcl/src/gpu/uma.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,11 @@ impl Uma {
continue;
}
let c_base = base + (MAX_WINDOWS - 1) * WINDOW;
let cp = unsafe { VirtualAlloc(c_base as *const std::ffi::c_void, committed, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) };
// Under Wine without userfaultfd, MEM_WRITE_WATCH uses mprotect(PROT_READ), which
// triggers amdgpu userptr MMU-notifier evictions and ~100ms GPU stalls on the
// coherent window imported via OpenExistingHeapFromAddress.
let c_flags = if crate::util::under_wine() { MEM_RESERVE | MEM_COMMIT } else { MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH };
let cp = unsafe { VirtualAlloc(c_base as *const std::ffi::c_void, committed, c_flags, PAGE_READWRITE) };
if cp as usize != c_base {
if !cp.is_null() {
unsafe { VirtualFree(cp, 0, MEM_RELEASE) };
Expand Down Expand Up @@ -382,7 +386,8 @@ impl Uma {
for k in 0..windows {
let want = base + k * WINDOW;
// write-watched: textures the title keeps here are uploaded again after CPU writes
let p = unsafe { VirtualAlloc(want as *const std::ffi::c_void, size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) };
let c_flags = if crate::util::under_wine() { MEM_RESERVE | MEM_COMMIT } else { MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH };
let p = unsafe { VirtualAlloc(want as *const std::ffi::c_void, size, c_flags, PAGE_READWRITE) };
if p.is_null() {
break;
}
Expand Down Expand Up @@ -453,7 +458,9 @@ impl Uma {
match self.kinds[k] {
WindowKind::None => k += 1,
WindowKind::Committed(s) => {
out.push((self.base + k * WINDOW, s));
if !crate::util::under_wine() {
out.push((self.base + k * WINDOW, s));
}
k += 1;
}
WindowKind::Sparse => {
Expand Down Expand Up @@ -674,11 +681,44 @@ fn coherent_file() -> std::path::PathBuf {
crate::state::data_dir().join("cache").join("uma_coherent.txt")
}

/// Whether this process is running under Wine on an AMD GPU (`amdgpu`, PCI vendor `0x1002`).
/// On `amdgpu`, a multi-GiB `userptr` BO imported via `OpenExistingHeapFromAddress` stalls
/// every Vulkan submission (~150 ms/frame), whereas NVIDIA Linux does not hit that stall and
/// benefits from a larger coherent window.
fn wine_amd_gpu() -> bool {
static AMD: OnceLock<bool> = OnceLock::new();
*AMD.get_or_init(|| {
if !crate::util::under_wine() {
return false;
}
use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIFactory1, DXGI_ADAPTER_FLAG_SOFTWARE};
let Ok(factory) = (unsafe { CreateDXGIFactory1::<IDXGIFactory1>() }) else {
return false;
};
let mut i = 0u32;
while let Ok(adapter) = unsafe { factory.EnumAdapters1(i) } {
i += 1;
if let Ok(desc) = unsafe { adapter.GetDesc1() } {
if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32) == 0 {
return desc.VendorId == 0x1002;
}
}
}
false
})
}

/// Bytes the coherent window is made with.
pub fn coherent_hint() -> usize {
if let Some(mb) = std::env::var("XCL_COHERENT_MB").ok().and_then(|v| v.parse::<usize>().ok()) {
return (mb << 20).clamp(GRAIN, MAX_SIZE);
}
// Under Wine/vkd3d-proton on Linux (amdgpu), a multi-GiB userptr BO imported via
// OpenExistingHeapFromAddress stalls every GPU submission (~150 ms/frame); keep the
// coherent window at 512 MiB and place overflow title GPU heaps in the sparse VRAM windows.
if wine_amd_gpu() {
return RUNTIME_COMMITTED_CAP;
}
let title = std::fs::read_to_string(coherent_file()).ok().and_then(|s| s.trim().parse::<usize>().ok()).unwrap_or(0);
// only with the commit for all of it: the title's ~13 GB, video memory for its render targets
// and textures (WDDM charges commit for each video-memory allocation too) and the window
Expand Down Expand Up @@ -938,7 +978,13 @@ mod tests {
assert_eq!(u.sparse_release(y), Some(GRAIN));
assert_eq!(u.sparse_release(desc), Some(GRAIN));
assert_eq!(u.sparse_used(), 0);
// Contiguous sparse windows 0..2 are reported as one OS watch region; window 3 as another.
assert_eq!(u.watch_regions(), vec![(u.base(), 3 * WINDOW), (u.base() + 3 * WINDOW, 16 << 20)]);
// Contiguous sparse windows 0..2 are reported as one OS watch region; window 3 as another
// on native Windows (excluded under Wine to avoid amdgpu userptr MMU-notifier stalls).
let expected = if crate::util::under_wine() {
vec![(u.base(), 3 * WINDOW)]
} else {
vec![(u.base(), 3 * WINDOW), (u.base() + 3 * WINDOW, 16 << 20)]
};
assert_eq!(u.watch_regions(), expected);
}
}
9 changes: 7 additions & 2 deletions crates/xcl/src/hle/d3d12x/alloc_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) {
let key = queue as usize;
if !s.fences.contains_key(&key) {
let mut dev: Option<ID3D12Device> = None;
let Some(f) = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).ok()) else { return };
let Some(f) = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| super::real::create_raw_fence(&d).ok()) else { return };
s.fences.insert(key, (f, 0));
}
let (fence, value) = {
Expand Down Expand Up @@ -383,7 +383,10 @@ mod tests {
if !super::super::real::is_adopted(a) {
super::super::real::adopt(a, super::super::real::Kind::CommandAllocator);
}
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap();
let list: ID3D12GraphicsCommandList = {
let _alloc_guard = super::super::real::UnadoptGuard::new(a);
dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap()
};
let l = list.as_raw();
created_on(l as usize, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0);
list.Close().unwrap();
Expand Down Expand Up @@ -416,6 +419,7 @@ mod tests {
let second_alloc = ID3D12CommandAllocator::from_raw_borrowed(&(second as *mut c_void)).unwrap().clone();
assert_eq!(reset_list(l as usize, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0, |pc| {
assert_eq!(pc, second);
let _alloc_guard = super::super::real::UnadoptGuard::new(pc as *mut c_void);
list.Reset(&second_alloc, None).map_or_else(|e| e.code().0, |_| 0)
}), 0);
list.Close().unwrap();
Expand All @@ -432,6 +436,7 @@ mod tests {
// it stays (the next allocator at its address is its own)
assert_eq!(reset_list(l as usize, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0, |pc| {
assert_eq!(pc, a as usize);
let _alloc_guard = super::super::real::UnadoptGuard::new(pc as *mut c_void);
list.Reset(&alloc, None).map_or_else(|e| e.code().0, |_| 0)
}), 0);
list.Close().unwrap();
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/hle/d3d12x/cpu_writes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ pub(super) unsafe fn after(queue: *mut c_void, writes: Vec<Write>) {
return;
}
let Some(dev) = dev else { return };
let Ok(fence) = dev.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) else { return };
let Ok(fence) = super::real::create_raw_fence(&dev) else { return };
v.insert(QueueFence { fence, value: 0 })
}
};
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/hle/d3d12x/late_release.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ impl Held {
let key = q.as_raw() as usize;
if !self.fences.contains_key(&key) {
let mut dev: Option<ID3D12Device> = None;
let made = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).ok());
let made = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| super::real::create_raw_fence(&d).ok());
let Some(f) = made else {
ok = false;
break;
Expand Down
26 changes: 21 additions & 5 deletions crates/xcl/src/hle/d3d12x/list_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,7 @@ impl ListState {
last.1 = last.1.max(end);
}
if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) {
unsafe { super::sparse::ensure_lazy_mapped(va as usize, size as usize) };
if self.sparse_writes.is_empty() {
SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel);
}
Expand Down Expand Up @@ -1489,7 +1490,7 @@ unsafe fn ensure_cell_fence(va: u64, dev: &ID3D12Device, dev_raw: usize) -> Opti
}
}
}
let created: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
let created: ID3D12Fence = real::create_raw_fence(&dev).ok()?;
let mut g = SYNC_GRAPH.lock().unwrap();
let cell = g.get_or_insert_with(SyncGraph::default).cells.entry(va).or_default();
if cell.non_monotonic {
Expand Down Expand Up @@ -2132,7 +2133,7 @@ pub(super) unsafe fn copy_scratch_submitted(queue: *mut c_void, lists: &[*mut c_
if let std::collections::hash_map::Entry::Vacant(entry) = cache.fences.entry(key) {
let mut dev: Option<ID3D12Device> = None;
q.GetDevice(&mut dev).ok()?;
entry.insert((dev?.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).ok()?, 0));
entry.insert((real::create_raw_fence(&dev?).ok()?, 0));
}
let (fence, value) = cache.fences.get_mut(&key)?;
let next = *value + 1;
Expand Down Expand Up @@ -2490,6 +2491,8 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> {
if let Some(spare) = super::title_list::pop_spare(wrapper) {
let ext_spare = *(spare as *const usize);
let reset_hr = super::alloc_pool::reset_list(spare as usize, alloc, ty.0, |pc_alloc| {
let _alloc_guard = real::UnadoptGuard::new(pc_alloc as *mut c_void);
let _pso_guard = real::UnadoptGuard::new(init_pso as *mut c_void);
pc::<unsafe extern "system" fn(*mut c_void, usize, usize) -> i32>(spare, PC_RESET)(spare, pc_alloc, init_pso)
});
real::preserve_vtable(spare, ext_spare);
Expand Down Expand Up @@ -2982,7 +2985,10 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) {
}

let one = [this];
exec(q_raw, 1, one.as_ptr());
{
let _list_guard = real::UnadoptGuard::new(this);
exec(q_raw, 1, one.as_ptr());
}
copy_scratch_submitted(q_raw, &one);
super::alloc_pool::executed(q_raw, &one);
signal_write64_pairs(q_raw, &write64_signals);
Expand Down Expand Up @@ -3035,6 +3041,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) {
let ext_closed = *(target as *const usize);
let init_pso = super::pso_async::resolve_for_bind(bound_pso);
let reset_hr = super::alloc_pool::reset_list(target as usize, alloc, list_type(target).0, |pc_alloc| {
let _alloc_guard = real::UnadoptGuard::new(pc_alloc as *mut c_void);
let _pso_guard = real::UnadoptGuard::new(init_pso as *mut c_void);
pc::<unsafe extern "system" fn(*mut c_void, usize, usize) -> i32>(target, PC_RESET)(target, pc_alloc, init_pso)
});
real::preserve_vtable(target, ext_closed);
Expand Down Expand Up @@ -3611,6 +3619,8 @@ pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usiz
// (the PC allocator the title's allocator stands for now: `alloc_pool`)
let ty = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).and_then(|s| s.list_type).map_or(-1, |t| t.0);
let hr = super::alloc_pool::reset_list(this as usize, alloc, ty, |pc_alloc| {
let _alloc_guard = real::UnadoptGuard::new(pc_alloc as *mut c_void);
let _pso_guard = real::UnadoptGuard::new(resolved as *mut c_void);
pc::<unsafe extern "system" fn(*mut c_void, usize, usize) -> i32>(this, PC_RESET)(this, pc_alloc, resolved)
});
real::preserve_vtable(this, ext);
Expand Down Expand Up @@ -6146,7 +6156,10 @@ mod tests {
execute_with_waits_on(q_comp.as_raw(), &segs_c, |chunk| {
type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void);
let exec: ExecFn = std::mem::transmute(*(*(q_comp.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS));
exec(q_comp.as_raw(), chunk.len() as u32, chunk.as_ptr());
{
let _guards: Vec<_> = chunk.iter().filter_map(|&l| real::UnadoptGuard::new(l)).collect();
exec(q_comp.as_raw(), chunk.len() as u32, chunk.as_ptr());
}
signal_write64_fences(q_comp.as_raw(), chunk);
if chunk.contains(&pc_c0) {
cell_a.store(frame, Ordering::Release);
Expand All @@ -6159,7 +6172,10 @@ mod tests {
execute_with_waits_on(q_dir.as_raw(), &one_d, |chunk| {
type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void);
let exec: ExecFn = std::mem::transmute(*(*(q_dir.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS));
exec(q_dir.as_raw(), chunk.len() as u32, chunk.as_ptr());
{
let _guards: Vec<_> = chunk.iter().filter_map(|&l| real::UnadoptGuard::new(l)).collect();
exec(q_dir.as_raw(), chunk.len() as u32, chunk.as_ptr());
}
signal_write64_fences(q_dir.as_raw(), chunk);
cell_b.store(frame, Ordering::Release);
});
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/hle/d3d12x/present.rs
Original file line number Diff line number Diff line change
Expand Up @@ -570,7 +570,7 @@ unsafe fn new_presenter(queue: usize) -> Option<Presenter> {
let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?;
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).ok()?;
list.Close().ok()?;
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
let fence: ID3D12Fence = super::real::create_raw_fence(dev).ok()?;
let event = CreateEventW(None, false, false, None).ok()?;
Some(Presenter {
queue, dev: dev.clone(), sc: None, w: 0, h: 0, fmt: DXGI_FORMAT_UNKNOWN, alloc, list, fence,
Expand Down
Loading
Loading