Skip to content
Draft
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
189 changes: 176 additions & 13 deletions crates/xcl/src/hle/d3d12x/pso_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ struct Build {
/// This build already has one use record in the bounded eviction-candidate journal.
/// Touched only while recipe retention is enabled.
candidate_queued: AtomicBool,
/// Exact armed eviction visible before its native owners may be detached. Kept separate
/// from recipe state so coordinator locks never overlap the build/rebuild/generation chain.
eviction: Mutex<Option<EvictedBuildToken>>,
done: Mutex<bool>,
cv: Condvar,
/// every stand-in interested in this build was released before it finished
Expand Down Expand Up @@ -310,6 +313,7 @@ impl Build {
last_use_frame: AtomicU64::new(super::present::presents()),
completed_frame: AtomicU64::new(0),
candidate_queued: AtomicBool::new(false),
eviction: Mutex::new(None),
done: Mutex::new(false),
cv: Condvar::new(),
orphan: Default::default(),
Expand Down Expand Up @@ -965,6 +969,38 @@ impl EvictedBuildToken {
&& Weak::ptr_eq(&self.build, &other.build)
&& self.native == other.native
}

fn belongs_to(&self, build: &Build) -> bool {
std::ptr::eq(self.build.as_ptr(), build)
}
}

#[allow(dead_code)]
impl Build {
fn eviction_token(&self) -> Option<EvictedBuildToken> {
self.eviction.lock().unwrap().clone()
}

fn install_eviction_token(&self, token: &EvictedBuildToken) -> bool {
if !token.belongs_to(self) {
return false;
}
let mut installed = self.eviction.lock().unwrap();
if installed.is_some() {
return false;
}
*installed = Some(token.clone());
true
}

fn clear_eviction_token(&self, token: &EvictedBuildToken) -> bool {
let mut installed = self.eviction.lock().unwrap();
if installed.as_ref().is_none_or(|current| !current.exact(token)) {
return false;
}
*installed = None;
true
}
}

struct EvictedBuildEntry {
Expand Down Expand Up @@ -1638,6 +1674,41 @@ struct RestorationCoordinator<const E: usize, const R: usize> {
before_rebuild: Arc<Mutex<Option<Box<dyn FnOnce() + Send>>>>,
}

/// An exact ledger record installed on its build before native detachment can begin. Dropping an
/// uncommitted preparation clears only that record and poisons its ledger slot; committing leaves
/// both visible for a later restoration request.
#[allow(dead_code)]
struct InstalledEviction<'a, const E: usize, const R: usize> {
coordinator: &'a RestorationCoordinator<E, R>,
build: Arc<Build>,
token: Option<EvictedBuildToken>,
}

#[allow(dead_code)]
impl<const E: usize, const R: usize> InstalledEviction<'_, E, R> {
fn token(&self) -> &EvictedBuildToken {
self.token.as_ref().expect("committed eviction preparation")
}

/// Consume only after exact generation revalidation and native detachment have succeeded.
fn commit(mut self) -> EvictedBuildToken {
self.token.take().expect("committed eviction preparation")
}

fn cleanup(&mut self) {
let Some(token) = self.token.take() else { return };
let _ = self.build.clear_eviction_token(&token);
let _ = self.coordinator.evicted.finish(&token, EvictedBuildState::Poisoned);
let _ = self.coordinator.evicted.retire(&token);
}
}

impl<const E: usize, const R: usize> Drop for InstalledEviction<'_, E, R> {
fn drop(&mut self) {
self.cleanup();
}
}

struct RestorationAttempt {
token: RehydrateAttemptToken,
job: Mutex<Option<JobHandle>>,
Expand Down Expand Up @@ -1693,6 +1764,20 @@ impl<const E: usize, const R: usize> RestorationCoordinator<E, R> {
self.evicted.reserve(build, native)
}

/// Arm the exact ledger record, then publish it on the build. A future eviction path must
/// perform its state-chain revalidation and detach only while holding the returned guard.
fn install_eviction<'a>(
&'a self, build: &Arc<Build>, native: LedgerNativeGeneration,
) -> Option<InstalledEviction<'a, E, R>> {
let token = self.reserve_eviction(build, native)?.arm_detach()?;
if !build.install_eviction_token(&token) {
let _ = self.evicted.finish(&token, EvictedBuildState::Poisoned);
let _ = self.evicted.retire(&token);
return None;
}
Some(InstalledEviction { coordinator: self, build: build.clone(), token: Some(token) })
}

fn refuse_rehydrate(&self, evicted: &EvictedBuildToken) -> bool {
match self.receipts.reserve_unique(evicted, true) {
Ok(Some(reservation)) => reservation.refused().is_some(),
Expand Down Expand Up @@ -1759,6 +1844,14 @@ impl<const E: usize, const R: usize> RestorationCoordinator<E, R> {
let _ = self.evicted.finish(token, EvictedBuildState::Poisoned);
}
if self.receipts.retire(&record.token) { reconciled += 1 }
// Receipt, build, and ledger locks never overlap. Exact matching makes this safe
// after address or bounded-slot reuse, and retryable failures remain nonterminal.
if self.evicted.state(token).is_some_and(EvictedBuildState::terminal) {
if let Some(build) = token.build.upgrade() {
let _ = build.clear_eviction_token(token);
}
let _ = self.evicted.retire(token);
}
}
let removed = {
let mut attempts = self.attempts.lock().unwrap();
Expand Down Expand Up @@ -3770,6 +3863,54 @@ mod used_tests {
assert!(coordinator.retries(1)[0].token.exact(&evicted));
}

#[test]
fn installed_eviction_is_visible_before_detach_commit() {
let coordinator = RestorationCoordinator::<1, 1>::new(308).unwrap();
let build = ledger_build();
let installed = coordinator.install_eviction(&build, ledger_native(50)).unwrap();
let visible = build.eviction_token().expect("armed eviction was not installed");
assert!(visible.exact(installed.token()));
assert_eq!(coordinator.evicted.state(&visible), Some(EvictedBuildState::Evicted));

let committed = installed.commit();
assert!(build.eviction_token().is_some_and(|token| token.exact(&committed)));
assert!(build.clear_eviction_token(&committed));
assert!(coordinator.evicted.finish(&committed, EvictedBuildState::Poisoned));
assert!(coordinator.evicted.retire(&committed));
}

#[test]
fn failed_eviction_revalidation_clears_and_retires_installation() {
let coordinator = RestorationCoordinator::<1, 1>::new(309).unwrap();
let build = ledger_build();
{
let installed = coordinator.install_eviction(&build, ledger_native(51)).unwrap();
assert!(build.eviction_token().is_some_and(|token| token.exact(installed.token())));
// A future eviction path drops the guard when exact generation revalidation fails.
}
assert!(build.eviction_token().is_none());
assert!(coordinator.evicted.records(1).is_empty());
}

#[test]
fn stale_eviction_token_cannot_clear_reused_installation() {
let coordinator = RestorationCoordinator::<1, 1>::new(310).unwrap();
let build = ledger_build();
let first = coordinator.install_eviction(&build, ledger_native(52)).unwrap().commit();
assert!(build.clear_eviction_token(&first));
assert!(coordinator.evicted.finish(&first, EvictedBuildState::Poisoned));
assert!(coordinator.evicted.retire(&first));

let second = coordinator.install_eviction(&build, ledger_native(53)).unwrap().commit();
assert_eq!(first.slot, second.slot);
assert_ne!(first.slot_generation, second.slot_generation);
assert!(!build.clear_eviction_token(&first));
assert!(build.eviction_token().is_some_and(|token| token.exact(&second)));
assert!(build.clear_eviction_token(&second));
assert!(coordinator.evicted.finish(&second, EvictedBuildState::Poisoned));
assert!(coordinator.evicted.retire(&second));
}

#[test]
fn rehydrate_registry_atomically_returns_existing_before_readiness() {
let build = ledger_build(); let evicted = receipt_evicted(&build, 49);
Expand Down Expand Up @@ -3891,30 +4032,50 @@ mod used_tests {
};
drop(build); drop(queued);
assert_eq!(coordinator.reconcile(1), 1);
assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Released));
assert_eq!(coordinator.evicted.state(&evicted), None);
assert_eq!(coordinator.reconcile(1), 0);
assert!(coordinator.retries(1).is_empty());
}

#[test]
fn restoration_coordinator_poisons_mismatch_without_touching_reused_slot() {
let coordinator = RestorationCoordinator::<1, 1>::new(305).unwrap();
let first_build = ledger_build();
let first = coordinated_evicted(&coordinator, &first_build, 45);
assert!(coordinator.refuse_rehydrate(&first));
assert!(coordinator.evicted.rehydrate_queued(&first));
fn restoration_coordinator_release_clears_installation_and_reuses_capacity() {
let coordinator = RestorationCoordinator::<1, 1>::new(303).unwrap();
let build = ledger_build();
let evicted = coordinator.install_eviction(&build, ledger_native(43)).unwrap().commit();
let queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, true).unwrap() {
RestorationQueue::Queued(queued) => queued, _ => unreachable!(),
};
assert!(queued.complete(RehydrateCompletion::Released));
assert_eq!(coordinator.reconcile(1), 1);
assert_eq!(coordinator.evicted.state(&first), Some(EvictedBuildState::Poisoned));
assert!(coordinator.evicted.retire(&first));
assert!(build.eviction_token().is_none());
assert_eq!(coordinator.evicted.state(&evicted), None);
drop(coordinator.install_eviction(&build, ledger_native(44)).expect("terminal slot was not reusable"));
assert_eq!(coordinator.reconcile(1), 0);
assert!(coordinator.retries(1).is_empty());
}

let second_build = ledger_build();
let second = coordinated_evicted(&coordinator, &second_build, 46);
#[test]
fn restoration_coordinator_stale_terminal_cannot_clear_reused_installation() {
let coordinator = RestorationCoordinator::<1, 1>::new(305).unwrap();
let build = ledger_build();
let first = coordinator.install_eviction(&build, ledger_native(45)).unwrap().commit();
let queued = match coordinator.queue_rehydrate(&first, RehydratePriority::Background, true).unwrap() {
RestorationQueue::Queued(queued) => queued, _ => unreachable!(),
};
assert!(queued.complete(RehydrateCompletion::Released));
assert_eq!(coordinator.reconcile(1), 1);
let second = coordinator.install_eviction(&build, ledger_native(46)).unwrap().commit();
assert_eq!(first.slot, second.slot);
assert_ne!(first.slot_generation, second.slot_generation);
assert!(coordinator.receipts.reserve(&first).unwrap().refused().is_some());
assert_eq!(coordinator.reconcile(1), 1);
assert_eq!(coordinator.evicted.state(&second), Some(EvictedBuildState::Evicted),
"a stale receipt poisoned a reused eviction slot");
assert!(build.eviction_token().is_some_and(|token| token.exact(&second)),
"a stale terminal receipt cleared the replacement installation");
assert!(build.clear_eviction_token(&second));
assert!(coordinator.evicted.finish(&second, EvictedBuildState::Poisoned));
assert!(coordinator.evicted.retire(&second));
assert_eq!(coordinator.reconcile(1), 0);
}

Expand All @@ -3928,15 +4089,17 @@ mod used_tests {
let job = build.job.lock().unwrap().take().unwrap(); complete(&build, job());
let replacement = recipe.pin_with_residency(raw).0.unwrap();
let coordinator = RestorationCoordinator::<1, 1>::new(304).unwrap();
let evicted = coordinated_evicted(&coordinator, &build, 44);
let evicted = coordinator.install_eviction(&build, ledger_native(44)).unwrap().commit();
let queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Foreground, false).unwrap() {
RestorationQueue::Queued(queued) => queued, _ => unreachable!(),
};
let proof = queued.replacement(&build, &replacement).unwrap();
assert!(queued.complete_success(proof));
assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::RehydrateQueued));
assert_eq!(coordinator.reconcile(1), 1);
assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Restored));
assert!(build.eviction_token().is_none());
assert_eq!(coordinator.evicted.state(&evicted), None);
drop(coordinator.install_eviction(&build, ledger_native(45)).expect("restored slot was not reusable"));
assert_eq!(coordinator.reconcile(1), 0);
let raw_owner = build.real.swap(0, Ordering::AcqRel);
drop(build); release(raw_owner); drop(replacement); drop(recipe);
Expand Down
Loading