Skip to content
Draft
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ A gamepad is recommended ([Controls](#controls)). The game folder is never modif
| **kernelx** | ✅ | title memory (budget from MicrosoftGame.Config, physical pages), threads on the PC's processors, modules, OS / console info | unit + end-to-end tests |
| **Memory** | ✅ | title graphics memory shared by CPU and GPU without copies, up to 16 GB (4 GiB windows) | GPU tests: loads, stores and atomics across windows |
| **File system** | ✅ | console paths (`GAME:`, `G:`, `D:` …) → the game folder; writes go to an overlay, the game folder is never modified; the console's drives: `S:\` (persistent local storage) and `T:\` (temp) in the title's data folder; free disk space answered for console paths | end-to-end: the test title's folder stays byte-identical; PLS and free space through the real call path |
| **DirectStorage** | ✅ | the console's DirectStorage queues: file and memory sources, zlib, and BCPack – the console's texture compression – for BC1, BC3, BC4, BC5, BC6H and BC7 (BC2 and the hardware swizzle are refused) | unit tests on synthetic streams; retail BCPack chunks of all six modes byte-identical with a reference decoder (`XCL_SAMPLE_BCPACK`) |
| **DirectStorage** | ✅ | the console's DirectStorage queues: file and memory sources, queued event notifications, zlib, and BCPack – the console's texture compression – for BC1, BC3, BC4, BC5, BC6H and BC7 (BC2 and the hardware swizzle are refused) | unit tests on synthetic streams; retail BCPack chunks of all six modes byte-identical with a reference decoder (`XCL_SAMPLE_BCPACK`) |

</details>

Expand Down
30 changes: 25 additions & 5 deletions crates/xcl/src/hle/dstorage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,18 @@
//! * queue: QueryInterface, AddRef, Release, EnqueueRequest, EnqueueStatus(array, index),
//! EnqueueSignal(fence, value), Submit, CancelRequestsWithTag(mask, value), Close,
//! GetErrorEvent, RetrieveErrorRecord (0x290 bytes), Query (0x1C: the desc, then empty
//! slots u16 @0x18 and requests until the automatic submit u16 @0x1A), then 6 more,
//! slots u16 @0x18 and requests until the automatic submit u16 @0x1A), then the X1
//! EnqueueSetEvent(handle) method and 5 more,
//! * file: QueryInterface, AddRef, Release, Close, GetHandle, 2 unknown, GetId, then 4 more;
//! status array: QueryInterface, AddRef, Release, IsComplete(index), GetHResult(index),
//! then 5 more.
//!
//! Each queue has a worker thread: submitted requests run in order (file reads through the
//! VFS like the title's own, memory copies, zlib, BCPack where `hle::bcpack` rebuilds the
//! blocks of the mode), a status entry gets the first failure of the requests since the
//! previous one, a signal sets the fence from the CPU. Methods not listed are logged and
//! answer E_NOTIMPL; BCPack BC2 and modes above 7, and the hardware swizzle, are refused.
//! previous one, a signal sets the fence from the CPU, and an event signals a Win32 waiter.
//! Unlisted methods log and answer E_NOTIMPL. BCPack BC2, modes above 7, and the hardware
//! swizzle are refused.

#![allow(non_snake_case)]

Expand All @@ -36,7 +38,7 @@ mod parallel;

use std::ffi::c_void;
use std::os::windows::fs::FileExt;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering};
use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock};
Expand All @@ -45,7 +47,7 @@ use serde::{Deserialize, Serialize};
use windows_sys::core::GUID;
use windows_sys::Win32::Foundation::{CloseHandle, DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE};
use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT};
use windows_sys::Win32::System::Threading::{CreateEventW, GetCurrentProcess, ResetEvent, SetEvent};
use windows_sys::Win32::System::Threading::{CreateEventW, GetCurrentProcess, ResetEvent, SetEvent, EVENT_MODIFY_STATE};

use crate::util::{HRESULT, S_OK};

Expand Down Expand Up @@ -1033,6 +1035,7 @@ enum Entry {
Status(Arc<StatusInner>, u32),
/// a fence (one reference held) and the value it gets
Signal(FenceRef, u64),
SetEvent(OwnedHandle),
#[cfg(test)]
/// Test-only barrier to hold the worker deterministically while testing submitted-batch cancellation.
Gate(Arc<std::sync::Barrier>),
Expand Down Expand Up @@ -1197,6 +1200,9 @@ impl QueueInner {
Entry::Signal(fence, value) => unsafe {
fence.signal(value);
},
Entry::SetEvent(event) => unsafe {
SetEvent(event.as_raw_handle());
},
#[cfg(test)]
Entry::Gate(b) => {
b.wait();
Expand Down Expand Up @@ -1274,6 +1280,7 @@ fn queue_vtbl() -> &'static [usize] {
queue_get_error_event as usize,
queue_retrieve_error_record as usize,
queue_query as usize,
queue_enqueue_set_event as usize, // IDStorageQueueX1
],
18,
)
Expand Down Expand Up @@ -1439,6 +1446,19 @@ unsafe extern "system" fn queue_enqueue_signal(p: *mut c_void, fence: *mut c_voi
q.enqueue(Entry::Signal(FenceRef(fence as usize), value));
}

unsafe extern "system" fn queue_enqueue_set_event(p: *mut c_void, event: HANDLE) {
let q = queue(p);
if q.closed.load(Ordering::Acquire) || event.is_null() {
return;
}
// Retain a separate handle until the marker reaches the worker or is discarded.
let mut duplicate = std::ptr::null_mut();
let me = GetCurrentProcess();
if DuplicateHandle(me, event, me, &mut duplicate, EVENT_MODIFY_STATE, 0, 0) != 0 {
q.enqueue(Entry::SetEvent(OwnedHandle::from_raw_handle(duplicate)));
}
}

unsafe extern "system" fn queue_submit(p: *mut c_void) {
let q = queue(p);
if !q.closed.load(Ordering::Acquire) {
Expand Down
102 changes: 100 additions & 2 deletions crates/xcl/src/hle/dstorage/parallel_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ use super::super::*;
use super::*;
use std::io::Write;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{FromRawHandle, OwnedHandle};
use std::panic::{self, AssertUnwindSafe};
use std::path::PathBuf;
use std::ptr::null_mut;
use std::thread;
use std::time::{Duration, Instant};
use windows_sys::Win32::Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT};
use windows_sys::Win32::System::Threading::WaitForSingleObject;

const TIMEOUT: Duration = Duration::from_secs(5);
const TEST_BUDGET: usize = 1024 * 1024;
Expand Down Expand Up @@ -109,11 +112,15 @@ struct TestQueue(*mut c_void);

impl TestQueue {
fn new(pool: Option<Arc<DecompressPool>>, hook: Option<TestHook>) -> Self {
Self::with_desc(64, &IID_QUEUE, pool, hook)
}

fn with_desc(capacity: u16, iid: &GUID, pool: Option<Arc<DecompressPool>>, hook: Option<TestHook>) -> Self {
let mut desc = [0; 0x18];
desc[8..10].copy_from_slice(&64u16.to_le_bytes());
desc[8..10].copy_from_slice(&capacity.to_le_bytes());
let mut raw = null_mut();
assert_eq!(
unsafe { factory_create_queue(null_mut(), desc.as_ptr(), &IID_QUEUE, &mut raw) },
unsafe { factory_create_queue(null_mut(), desc.as_ptr(), iid, &mut raw) },
S_OK
);
let queue = Self(raw);
Expand All @@ -137,6 +144,14 @@ impl TestQueue {
unsafe { queue_enqueue_status(self.0, status.0, slot) };
}

fn enqueue_set_event(&self, event: &OwnedHandle) {
unsafe {
let vtable = *(self.0 as *const *const usize);
let enqueue: unsafe extern "system" fn(*mut c_void, HANDLE) = std::mem::transmute(*vtable.add(12));
enqueue(self.0, event.as_raw_handle());
}
}

fn submit(&self) {
unsafe { queue_submit(self.0) };
}
Expand Down Expand Up @@ -262,6 +277,89 @@ fn await_later_preparation(events: &mpsc::Receiver<TestEvent>) {
}
}

fn completion_event() -> OwnedHandle {
let event = unsafe { CreateEventW(null_mut(), 1, 0, null_mut()) };
assert!(!event.is_null());
unsafe { OwnedHandle::from_raw_handle(event) }
}

#[test]
fn completion_event_auto_submits_a_half_full_sequential_queue() {
with_deadline(|| {
let payload = vec![0x7b; 48 * 1024];
let file = TestFile::compressed(&[&payload]);
let mut output = vec![0x5d; payload.len()];
let queue = TestQueue::with_desc(6, &IID_QUEUE_X1, None, None);
let status = TestStatus::new(1);
let event = completion_event();
unsafe { queue.enqueue(&file.request(0, output.as_mut_ptr() as usize, 1)) };
queue.status(&status, 0);
assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 0) }, WAIT_TIMEOUT);
queue.enqueue_set_event(&event);

assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 2_000) }, WAIT_OBJECT_0);
assert_eq!(status.result(0), S_OK);
assert_eq!(output, payload);
});
}

#[test]
fn completion_event_waits_for_parallel_retirement_and_keeps_its_handle() {
with_deadline(|| {
let payload = vec![0x4d; 48 * 1024];
let file = TestFile::compressed(&[&payload]);
let mut output = vec![0; payload.len()];
let mut failed = vec![0x72; payload.len()];
let pool = test_pool(2, TEST_BUDGET);
let (gate, milestones, release) = gated_hook(TestEvent::BeforeDecode(1));
let last_retired = Arc::new(AtomicU64::new(0));
let retired = Arc::clone(&last_retired);
let hook = Arc::new(move |event| {
if let TestEvent::Retired(seq) = event {
retired.store(seq, Ordering::Release);
}
gate(event);
});
let queue = TestQueue::with_desc(64, &IID_QUEUE_X1, Some(pool), Some(hook));
let status = TestStatus::new(1);
let event = completion_event();
let observer = event.try_clone().unwrap();

let mut short = file.request(0, failed.as_mut_ptr() as usize, 2);
short[0x30..0x34].copy_from_slice(&(file.chunks[0].1 + 1).to_le_bytes());
unsafe {
queue.enqueue(&file.request(0, output.as_mut_ptr() as usize, 1));
queue.enqueue(&short);
}
queue.enqueue_set_event(&event);
queue.status(&status, 0);
queue.submit();

assert_eq!(receive(&milestones), TestEvent::BeforeDecode(1));
let early_wait = unsafe { WaitForSingleObject(observer.as_raw_handle(), 0) };
drop(event);
release.send(()).unwrap();
assert_eq!(early_wait, WAIT_TIMEOUT);
assert_eq!(unsafe { WaitForSingleObject(observer.as_raw_handle(), 2_000) }, WAIT_OBJECT_0);
assert_eq!(last_retired.load(Ordering::Acquire), 2);
assert_eq!(status.wait(0), E_END_OF_FILE);
assert_eq!(output, payload);
assert!(failed.iter().all(|&byte| byte == 0x72));
});
}

#[test]
fn completion_event_close_discards_the_pending_marker() {
let queue = TestQueue::with_desc(64, &IID_QUEUE_X1, None, None);
let event = completion_event();
queue.enqueue_set_event(&event);
assert_eq!(queue.inner().pending.lock().unwrap().entries.len(), 1);
unsafe { queue_close(queue.0) };

assert!(queue.inner().pending.lock().unwrap().entries.is_empty());
assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 0) }, WAIT_TIMEOUT);
}

#[test]
fn parallel_out_of_order_completion_retires_fifo() {
with_deadline(|| {
Expand Down
Loading