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
15 changes: 15 additions & 0 deletions crates/xcl/src/gpu/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,21 @@ pub(crate) fn select_indices<S: AsRef<str>>(names: &[S], sel: &Selector) -> Vec<
Vec::new()
}

/// PCI vendor of the adapter the D3D12 backend opens, from the hardware adapters in
/// high-performance order as `(name, vendor)`: the first one `sel` allows, else the first one
/// `auto` allows (`real::init` falls back the same way); `None` for `warp` or no hardware.
pub(crate) fn chosen_vendor<S: AsRef<str>>(adapters: &[(S, u32)], sel: &Selector) -> Option<u32> {
if *sel == Selector::Warp {
return None;
}
let names: Vec<&str> = adapters.iter().map(|(n, _)| n.as_ref()).collect();
let mut picked = select_indices(&names, sel);
if picked.is_empty() {
picked = select_indices(&names, &Selector::Auto);
}
picked.first().map(|&i| adapters[i].1)
}

/// The adapter's name from its description.
pub fn name(desc: &DXGI_ADAPTER_DESC1) -> String {
let n = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len());
Expand Down
23 changes: 22 additions & 1 deletion crates/xcl/src/gpu/adapter_tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::{select_indices, Selector};
use super::{chosen_vendor, select_indices, Selector};

#[test]
fn selector_parsing() {
Expand Down Expand Up @@ -53,3 +53,24 @@ fn numeric_selector_falls_back_to_model_token_when_out_of_range() {
assert!(select_indices(&two, &Selector::parse("80")).is_empty());
assert_eq!(select_indices(&two, &Selector::parse("2080")), vec![0]);
}

#[test]
fn chosen_vendor_is_the_adapter_the_backend_opens() {
const AMD: u32 = 0x1002;
const NV: u32 = 0x10de;
const INTEL: u32 = 0x8086;
// hybrid machines, hardware adapters in high-performance order (the dedicated GPU first)
let nv_dgpu_amd_igpu = [("NVIDIA GeForce RTX 4070", NV), ("AMD Radeon(TM) Graphics", AMD)];
let amd_dgpu_intel_igpu = [("AMD Radeon RX 7900 XT", AMD), ("Intel(R) UHD Graphics 770", INTEL)];
assert_eq!(chosen_vendor(&nv_dgpu_amd_igpu, &Selector::Auto), Some(NV), "AMD iGPU must not make an NVIDIA run 'AMD'");
assert_eq!(chosen_vendor(&amd_dgpu_intel_igpu, &Selector::Auto), Some(AMD), "an AMD dGPU behind an Intel iGPU is still AMD");
// `d3d12_adapter` / `XCL_ADAPTER` choose the other one
assert_eq!(chosen_vendor(&nv_dgpu_amd_igpu, &Selector::parse("radeon")), Some(AMD));
assert_eq!(chosen_vendor(&nv_dgpu_amd_igpu, &Selector::Index(1)), Some(AMD));
assert_eq!(chosen_vendor(&amd_dgpu_intel_igpu, &Selector::parse("intel")), Some(INTEL));
// a selector that matches nothing falls back to `auto`, as `real::init` does
assert_eq!(chosen_vendor(&amd_dgpu_intel_igpu, &Selector::parse("geforce")), Some(AMD));
// WARP or no hardware adapter: no vendor
assert_eq!(chosen_vendor(&amd_dgpu_intel_igpu, &Selector::Warp), None);
assert_eq!(chosen_vendor::<&str>(&[], &Selector::Auto), None);
}
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 @@ -733,7 +733,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 @@ -1222,7 +1222,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 @@ -1425,7 +1425,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 @@ -1561,7 +1561,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 @@ -1779,7 +1779,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 @@ -1798,3 +1798,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(())
}
59 changes: 51 additions & 8 deletions crates/xcl/src/gpu/uma.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,10 +265,14 @@ impl Uma {
}
let mut win_allocs = Vec::with_capacity(1 + coh_wins);
win_allocs.push(base);
// 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 (`wine_amd_gpu`).
let c_flags = if wine_amd_gpu() { MEM_RESERVE | MEM_COMMIT } else { MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH };
let mut ok = true;
for (c, &c_size) in coh_sizes.iter().enumerate() {
let c_base = base + (sparse_wins + c) * WINDOW;
let cp = unsafe { VirtualAlloc(c_base as *const std::ffi::c_void, c_size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) };
let cp = unsafe { VirtualAlloc(c_base as *const std::ffi::c_void, c_size, c_flags, PAGE_READWRITE) };
if cp as usize != c_base {
if !cp.is_null() {
unsafe { VirtualFree(cp, 0, MEM_RELEASE) };
Expand Down Expand Up @@ -490,7 +494,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 wine_amd_gpu() { 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 @@ -561,7 +566,9 @@ impl Uma {
match self.kinds[k] {
WindowKind::None => k += 1,
WindowKind::Committed(s) => {
out.push((self.base + k * WINDOW, s));
if !wine_amd_gpu() {
out.push((self.base + k * WINDOW, s));
}
k += 1;
}
WindowKind::Sparse => {
Expand Down Expand Up @@ -782,12 +789,40 @@ fn coherent_file() -> std::path::PathBuf {
crate::state::data_dir().join("cache").join("uma_coherent.txt")
}

/// Whether this process is running under Wine and XCL's D3D12 adapter (`d3d12_adapter` /
/// `XCL_ADAPTER`, as `real::init` picks it) is an AMD GPU (`amdgpu`, PCI vendor `0x1002`).
/// On `amdgpu`, a multi-GiB `userptr` BO imported via `OpenExistingHeapFromAddress` stalls
/// every Vulkan submission (~150 ms/frame), and write-watching it (`mprotect`) evicts it; NVIDIA
/// Linux does not hit that stall and keeps a larger, write-watched coherent window.
pub(crate) fn wine_amd_gpu() -> bool {
static AMD: OnceLock<bool> = OnceLock::new();
*AMD.get_or_init(|| {
if !crate::util::under_wine() {
return false;
}
use crate::gpu::adapter::{self, Selector};
use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, IDXGIFactory6, DXGI_CREATE_FACTORY_FLAGS};
let Ok(factory) = (unsafe { CreateDXGIFactory2::<IDXGIFactory6>(DXGI_CREATE_FACTORY_FLAGS(0)) }) else {
return false;
};
let hw: Vec<(String, u32)> = adapter::hardware(&factory).iter().map(|(_, d)| (adapter::name(d), d.VendorId)).collect();
let sel = Selector::from_env_or(&crate::state::config().d3d12_adapter);
adapter::chosen_vendor(&hw, &sel) == Some(0x1002)
})
}

/// Bytes the coherent window(s) are made with for a runtime layout of `windows` windows.
pub fn coherent_hint_for(windows: usize) -> usize {
let cap = max_coherent_bytes(windows);
if let Some(mb) = std::env::var("XCL_COHERENT_MB").ok().and_then(|v| v.parse::<usize>().ok()) {
return (mb << 20).clamp(GRAIN, cap);
}
// 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 @@ -1101,8 +1136,14 @@ 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 on amdgpu to avoid userptr MMU-notifier stalls).
let expected = if wine_amd_gpu() {
vec![(u.base(), 3 * WINDOW)]
} else {
vec![(u.base(), 3 * WINDOW), (u.base() + 3 * WINDOW, 16 << 20)]
};
assert_eq!(u.watch_regions(), expected);
}

#[test]
Expand Down Expand Up @@ -1135,13 +1176,15 @@ mod tests {
assert_eq!(u.sparse_release(d), Some(ld));
assert_eq!(u.sparse_release(r), Some(big));
assert_eq!(u.sparse_used(), 0);
assert_eq!(
u.watch_regions(),
let expected = if wine_amd_gpu() {
vec![(u.base(), MAX_RUNTIME_SPARSE_WINDOWS * WINDOW)]
} else {
vec![
(u.base(), MAX_RUNTIME_SPARSE_WINDOWS * WINDOW),
(u.base() + MAX_RUNTIME_SPARSE_WINDOWS * WINDOW, 16 << 20),
]
);
};
assert_eq!(u.watch_regions(), expected);
}
}

Expand Down
26 changes: 20 additions & 6 deletions crates/xcl/src/hle/d3d12x/alloc_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,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 @@ -452,12 +452,15 @@ 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();
let lists = [Some(list.cast::<ID3D12CommandList>().unwrap())];
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
let fence: ID3D12Fence = super::super::real::create_raw_fence(&dev).unwrap();
let done = |v: u64| {
queue.Signal(&fence, v).unwrap();
let start = std::time::Instant::now();
Expand All @@ -467,7 +470,10 @@ mod tests {
assert!(fence.GetCompletedValue() >= v, "the queue finishes");
};

queue.ExecuteCommandLists(&lists);
{
let _list_guard = super::super::real::UnadoptGuard::new(l);
queue.ExecuteCommandLists(&lists);
}
executed(queue.as_raw(), &[l]);
done(1);

Expand All @@ -476,7 +482,10 @@ mod tests {
let second = current(a as usize);
assert_ne!(second, a as usize, "the list still holds its recording: another PC allocator takes the place");
// … and submits the recording again
queue.ExecuteCommandLists(&lists);
{
let _list_guard = super::super::real::UnadoptGuard::new(l);
queue.ExecuteCommandLists(&lists);
}
executed(queue.as_raw(), &[l]);
done(2);
assert!(dev.GetDeviceRemovedReason().is_ok(), "the recording was still there");
Expand All @@ -485,10 +494,14 @@ 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();
queue.ExecuteCommandLists(&lists);
{
let _list_guard = super::super::real::UnadoptGuard::new(l);
queue.ExecuteCommandLists(&lists);
}
executed(queue.as_raw(), &[l]);
done(3);

Expand All @@ -501,6 +514,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 @@ -173,7 +173,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
Loading
Loading