Files
nvdriver/tests/timeout-runtime/fixture.rs
LIghtJUNction 32c8728037 Migrate the workspace and kernel crates to Rust edition 2024
Mechanical, behavior-neutral: edition/resolver keys, unsafe extern blocks,
unsafe(no_mangle)/unsafe(export_name), unsafe blocks inside unsafe fn,
r#gen renames, --edition flags in Makefiles/tools, rustfmt style_edition
pinned to 2021 so formatting stays edition-independent, and clippy
collapsible_if allowed workspace-wide (let-chain churn).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-12-02 01:52:38 +08:00

603 lines
21 KiB
Rust

#![allow(dead_code)]
#[path = "../../src/nvidia/kernel/hypervisor.rs"]
mod hypervisor;
#[path = "../../src/nvidia/kernel/pf_software.rs"]
mod pf_software;
#[path = "../../src/nvidia/kernel/registry.rs"]
mod registry;
#[path = "../../src/nvidia/kernel/system_os.rs"]
mod system_os;
#[path = "../../src/nvidia/kernel/system_platform.rs"]
mod system_platform;
#[path = "../../src/nvidia/kernel/thread.rs"]
mod thread;
#[path = "../../src/nvidia/kernel/thread_state.rs"]
mod thread_state;
#[path = "../../src/nvidia/kernel/timeout_runtime.rs"]
mod timeout_runtime;
use nv_rs_abi::NvStatus;
use nv_rs_core::gpu::{
gpu_arch,
pf_construct::{Identity, PciSelection, Profile},
thread_timeout::{Database, Node, Services},
timeout::{config::Hypervisor, GpuId},
};
use std::num::{NonZeroU32, NonZeroU64};
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
unsafe extern "C" {
fn fixture_timeout_word(offset: usize, bytes: usize) -> u64;
fn fixture_registry_options(options: *const core::ffi::c_char);
fn fixture_context(pid: u64, cpu: u32, context: u32, flags: u32);
fn fixture_live() -> u32;
fn fixture_process(value: bool);
}
struct Binding {
logical: NonZeroU64,
}
unsafe impl timeout_runtime::Identity for Binding {
fn resolve(&self, logical: NonZeroU64) -> Result<GpuId, NvStatus> {
if logical == self.logical {
Ok(GpuId(17))
} else {
Err(NvStatus(0x40))
}
}
}
struct Os {
calls: usize,
fail: usize,
}
impl Hypervisor for Os {
fn is_vgx(&mut self) -> Result<bool, NvStatus> {
self.calls += 1;
unsafe {
assert_eq!(fixture_timeout_word(0x1e20, 8), 0x24000000);
if self.calls == 1 {
assert_eq!(fixture_timeout_word(0x1e0c, 4), 0);
} else {
assert_eq!(fixture_timeout_word(0x1e0c, 4), 4_000_000);
assert_eq!(fixture_timeout_word(0x1e14, 4), 8);
assert_eq!(fixture_timeout_word(0x1e18, 4), 1);
}
}
if self.calls == self.fail {
Err(NvStatus(0x44))
} else {
Ok(false)
}
}
}
struct Clock<'a> {
now: u64,
fail: bool,
expected: Option<&'a thread_state::Registry>,
}
impl Services for Clock<'_> {
fn monotonic_ns(&mut self) -> Result<u64, NvStatus> {
if let Some(db) = self.expected {
let db = db.timeout_database();
assert_eq!(
(db.non_compute_ms, db.compute_ms, db.timeout_flags),
(4000, 4000, 8)
);
}
if self.fail {
return Err(NvStatus(0x45));
}
self.now += 1;
Ok(self.now)
}
fn delay_us(&mut self, _: u32) -> Result<(), NvStatus> {
panic!("delay")
}
fn print_node(&mut self, _: &Node) -> Result<(), NvStatus> {
panic!("print")
}
fn log_configured_timeout(&mut self, _: u64) -> Result<(), NvStatus> {
panic!("log")
}
fn assert_timeout(&mut self) -> Result<(), NvStatus> {
panic!("assert")
}
fn schedule_cpu(&mut self) -> Result<NvStatus, NvStatus> {
panic!("schedule")
}
fn log_yield(&mut self) -> Result<(), NvStatus> {
panic!("yield")
}
}
fn with_parent(test: impl FnOnce(&mut pf_software::PfSoftware)) {
unsafe {
fixture_context(42, 0, 0, 0);
}
let mut arch =
pf_software::ArchitectureRegistry::<1>::new(NonZeroU64::new(0x24030000).unwrap());
let key = gpu_arch::Key {
architecture: 0x14,
implementation: 0,
hidrev: 0,
tegra_type: 0,
};
let profile = Profile::from_normal_pci(&PciSelection {
boot42: 0x14000000,
boot4: 0,
virtualization_8f020: None,
linux_is_virtfn: false,
})
.unwrap();
let mut parent = pf_software::PfSoftware::construct_with_architecture(
profile,
&Identity {
word_c9c: 2,
word_ca8: 34,
owner_9d0: 0x24030000,
uuid: None,
},
NonZeroU64::new(0x24000000).unwrap(),
arch.get_or_create(key).unwrap(),
)
.unwrap_or_else(|_| panic!("parent"));
test(&mut parent);
parent.close().unwrap();
arch.close().unwrap();
assert_eq!(unsafe { fixture_live() }, 0);
}
fn database() -> Database {
Database {
setup_flags: 0x87,
timeout_flags: 0,
non_compute_ms: 0,
compute_ms: 0,
compute_gpu_mask: 0,
}
}
#[test]
fn canonical_fields_and_real_current_entry_observe_original_boundaries() {
let _lock = LOCK.lock().unwrap();
with_parent(|parent| {
let reg = thread_state::Registry::new(database(), NonZeroU32::new(1).unwrap()).unwrap();
let mut clock = Clock {
now: 100,
fail: false,
expected: None,
};
let mut entry = unsafe { reg.enter(0, 123, &mut clock) }.unwrap().unwrap();
clock.expected = Some(&reg);
let mut os = Os { calls: 0, fail: 0 };
let mut state = timeout_runtime::Record::new();
let binding = Binding {
logical: parent.logical_base().unwrap(),
};
unsafe {
state
.bind(&binding)
.initialize(parent, &mut entry, &mut os, &mut clock)
}
.unwrap();
assert_eq!(os.calls, 2);
let gpu_state = parent.timeout_gpu_state().unwrap();
assert!(gpu_state.attached_915);
assert!(
!gpu_state.reset_917
&& gpu_state.reset_918 == 0
&& !gpu_state.reset_926
&& !gpu_state.timer_present
);
assert_eq!(state.phase(), timeout_runtime::Phase::Configured);
assert_eq!(
entry.timeout_snapshot().non_compute,
clock.now - 1 + 4_000_000_000
);
state
.bind(&binding)
.with_data(parent, |data| {
assert_eq!(data.default_us, 4_000_000);
assert_eq!(data.gpu, Some(GpuId(17)));
})
.unwrap();
let foreign = Binding {
logical: NonZeroU64::new(7).unwrap(),
};
assert!(state.bind(&foreign).with_data(parent, |_| ()).is_err());
});
}
#[test]
fn second_os_failure_publishes_partial_database_and_quarantines() {
let _lock = LOCK.lock().unwrap();
with_parent(|parent| {
let reg = thread_state::Registry::new(database(), NonZeroU32::new(1).unwrap()).unwrap();
let mut clock = Clock {
now: 100,
fail: false,
expected: None,
};
let mut entry = unsafe { reg.enter(0, 123, &mut clock) }.unwrap().unwrap();
let mut os = Os { calls: 0, fail: 2 };
let mut state = timeout_runtime::Record::new();
let binding = Binding {
logical: parent.logical_base().unwrap(),
};
assert_eq!(
unsafe {
state
.bind(&binding)
.initialize(parent, &mut entry, &mut os, &mut clock)
},
Err(timeout_runtime::Error::Service(NvStatus(0x44)))
);
let db = reg.timeout_database();
assert_eq!(
(db.non_compute_ms, db.compute_ms, db.timeout_flags),
(4000, 0, 0)
);
assert_eq!(
parent.timeout_fields().unwrap().defaults.default_us,
4_000_000
);
assert!(state.bind(&binding).with_data(parent, |_| ()).is_err());
assert_eq!(
unsafe {
state
.bind(&binding)
.initialize(parent, &mut entry, &mut os, &mut clock)
},
Err(timeout_runtime::Error::Quarantined)
);
});
}
#[test]
fn reset_clock_failure_retains_actual_config_and_owner() {
let _lock = LOCK.lock().unwrap();
with_parent(|parent| {
let reg = thread_state::Registry::new(database(), NonZeroU32::new(1).unwrap()).unwrap();
let mut clock = Clock {
now: 100,
fail: false,
expected: None,
};
let mut entry = unsafe { reg.enter(0, 123, &mut clock) }.unwrap().unwrap();
clock.fail = true;
clock.expected = Some(&reg);
let mut state = timeout_runtime::Record::new();
let mut os = Os { calls: 0, fail: 0 };
let binding = Binding {
logical: parent.logical_base().unwrap(),
};
assert_eq!(
unsafe {
state
.bind(&binding)
.initialize(parent, &mut entry, &mut os, &mut clock)
},
Err(timeout_runtime::Error::Service(NvStatus(0x45)))
);
assert_eq!(state.phase(), timeout_runtime::Phase::Unavailable);
assert_eq!(parent.timeout_fields().unwrap().gpu_link, 0x24000000);
});
}
#[test]
fn actual_named_base_then_owned_nbsi_prefix_without_missing_provider_default() {
let _lock = LOCK.lock().unwrap();
with_parent(|parent| unsafe {
fixture_registry_options(c"RmDefaultTimeout=19".as_ptr());
let mut sys = system_os::SystemOs::construct(NonZeroU64::new(0x60000000).unwrap()).unwrap();
parent
.attach_system_os(sys.reference().unwrap().logical_base())
.unwrap();
let mut platform =
system_platform::SystemPlatform::construct(NonZeroU64::new(0x61000000).unwrap())
.unwrap();
let mut nbsi = platform.reference().unwrap();
let mut base = registry::LinuxRegistry::open(parent, sys.reference().unwrap())
.unwrap_or_else(|_| panic!("registry"));
{
let mut fallback = timeout_runtime::InitialNbsi(&mut nbsi);
let mut complete =
registry::CompleteDwordRegistry::new(&mut base, parent, &mut fallback);
assert_eq!(complete.read(c"RmDefaultTimeout").unwrap().value, 19);
assert_eq!(
complete.read(c"RmDefaultTimeoutFlags").unwrap().status,
NvStatus(0x56)
);
}
platform.begin_table_initialization(2).unwrap();
{
let mut fallback = timeout_runtime::InitialNbsi(&mut nbsi);
let mut complete =
registry::CompleteDwordRegistry::new(&mut base, parent, &mut fallback);
assert!(matches!(
complete.read(c"RmDefaultTimeoutFlags"),
Err(NvStatus(0x40))
));
}
fixture_process(false);
{
let mut fallback = timeout_runtime::InitialNbsi(&mut nbsi);
let mut complete =
registry::CompleteDwordRegistry::new(&mut base, parent, &mut fallback);
assert!(matches!(
complete.read(c"RmDefaultTimeout"),
Err(NvStatus(0x40))
));
assert_eq!(
complete.last_base_error(),
Some(registry::Error::Backend(-11))
);
}
fixture_process(true);
base.close().unwrap();
drop(nbsi);
platform.close().unwrap();
sys.close().unwrap();
fixture_registry_options(core::ptr::null());
});
}
struct Log {
events: Vec<nv_rs_core::gpu::timeout::config::registry::Diagnostic>,
fail: bool,
}
impl timeout_runtime::Diagnostics for Log {
fn diagnostic(
&mut self,
parent: &pf_software::PfSoftware,
data: &mut nv_rs_core::gpu::timeout::config::Defaults,
event: nv_rs_core::gpu::timeout::config::registry::Diagnostic,
) -> Result<(), NvStatus> {
use nv_rs_core::gpu::timeout::config::registry::Diagnostic;
let actual = parent.timeout_fields().unwrap();
assert_eq!(actual.defaults.default_us, data.default_us);
assert_eq!(actual.defaults.flags, data.flags);
assert_eq!(actual.override_internal_ms, 0x80000000);
self.events.push(event);
if matches!(event, Diagnostic::AssertInvalidDefaultFlags) {
data.flags = 16;
}
if self.fail {
data.flags = 32;
Err(NvStatus(0x46))
} else {
Ok(())
}
}
fn setup_diagnostic(
&mut self,
_: &pf_software::PfSoftware,
old: u32,
new: u32,
) -> Result<(), NvStatus> {
assert_eq!((old, new), (0x87, 0x83));
Ok(())
}
}
#[test]
fn canonical_registry_checkpoints_zero_override_and_assert_mutation_are_real() {
let _lock = LOCK.lock().unwrap();
for fail in [false, true] {
with_parent(|parent| unsafe {
fixture_registry_options(c"RmOverrideInternalTimeoutsMs=0x80000000;RmDefaultTimeout=99;RmDefaultTimeoutFlags=999;RmThreadStateSetupFlags=0x83".as_ptr());
let mut sys =
system_os::SystemOs::construct(NonZeroU64::new(0x60000000).unwrap()).unwrap();
parent
.attach_system_os(sys.reference().unwrap().logical_base())
.unwrap();
let mut platform =
system_platform::SystemPlatform::construct(NonZeroU64::new(0x61000000).unwrap())
.unwrap();
let mut nbsi = platform.reference().unwrap();
let mut fallback = timeout_runtime::InitialNbsi(&mut nbsi);
let mut base = registry::LinuxRegistry::open(parent, sys.reference().unwrap())
.unwrap_or_else(|_| panic!("registry"));
let reg = thread_state::Registry::new(database(), NonZeroU32::new(1).unwrap()).unwrap();
let mut clock = Clock {
now: 100,
fail: false,
expected: None,
};
let mut entry = reg.enter(0, 123, &mut clock).unwrap().unwrap();
let mut state = timeout_runtime::Record::new();
let mut os = Os { calls: 0, fail: 0 };
let binding = Binding {
logical: parent.logical_base().unwrap(),
};
state
.bind(&binding)
.initialize(parent, &mut entry, &mut os, &mut clock)
.unwrap();
let mut log = Log {
events: Vec::new(),
fail,
};
let result =
state
.bind(&binding)
.apply_overrides(parent, &mut base, &mut fallback, &mut log);
let fields = parent.timeout_fields().unwrap();
assert_eq!(fields.defaults.default_us, 0);
assert_eq!(fields.defaults.reset_us, 0);
assert!(fields.defaults.overridden && fields.defaults.scaled);
assert_eq!(fields.defaults.flags, if fail { 32 } else { 16 });
if fail {
assert_eq!(result, Err(timeout_runtime::Error::Service(NvStatus(0x46))));
assert_eq!(state.phase(), timeout_runtime::Phase::Unavailable);
} else {
result.unwrap();
assert_eq!(log.events.len(), 5);
state
.bind(&binding)
.apply_setup_override(parent, &mut entry, &mut base, &mut fallback, &mut log)
.unwrap();
assert_eq!(reg.timeout_database().setup_flags, 0x83);
}
drop(entry);
base.close().unwrap();
drop(nbsi);
platform.close().unwrap();
sys.close().unwrap();
fixture_registry_options(core::ptr::null());
});
}
}
#[test]
fn unresolved_product_cannot_be_replaced_by_a_native_default() {
assert!(hypervisor::BuildProduct::current().is_err());
}
#[test]
fn persistent_failure_survives_distinct_operation_and_identity_scopes() {
let _lock = LOCK.lock().unwrap();
with_parent(|parent| {
let reg = thread_state::Registry::new(database(), NonZeroU32::new(1).unwrap()).unwrap();
let mut clock = Clock {
now: 100,
fail: false,
expected: None,
};
let mut entry = unsafe { reg.enter(0, 123, &mut clock) }.unwrap().unwrap();
let mut record = timeout_runtime::Record::new();
{
let first_identity = Binding {
logical: parent.logical_base().unwrap(),
};
let mut operation = record.bind(&first_identity);
let mut os = Os { calls: 0, fail: 2 };
assert_eq!(
unsafe { operation.initialize(parent, &mut entry, &mut os, &mut clock) },
Err(timeout_runtime::Error::Service(NvStatus(0x44)))
);
}
// No identity borrow or operation lives here: the pointer-free record
// moves with per-device storage while preserving the actual failure.
let mut stored = Box::new(record);
let saved = stored.partial_defaults().unwrap();
assert_eq!(saved.default_us, 4_000_000);
assert_eq!(
stored.last_error(),
Some(timeout_runtime::Error::Service(NvStatus(0x44)))
);
{
let second_identity = Binding {
logical: parent.logical_base().unwrap(),
};
let mut operation = stored.bind(&second_identity);
let mut os = Os { calls: 0, fail: 0 };
assert_eq!(
unsafe { operation.initialize(parent, &mut entry, &mut os, &mut clock) },
Err(timeout_runtime::Error::Quarantined)
);
assert_eq!(os.calls, 0);
assert_eq!(
operation.with_data(parent, |_| ()),
Err(timeout_runtime::Error::Quarantined)
);
}
assert_eq!(stored.phase(), timeout_runtime::Phase::Unavailable);
assert_eq!(stored.partial_defaults(), Some(saved));
assert_eq!(reg.timeout_database().non_compute_ms, 4000);
});
}
#[test]
fn pending_database_publication_failure_survives_operation_drop() {
let _lock = LOCK.lock().unwrap();
with_parent(|parent| unsafe {
fixture_registry_options(c"RmThreadStateSetupFlags=0x80000087".as_ptr());
let mut sys = system_os::SystemOs::construct(NonZeroU64::new(0x60000000).unwrap()).unwrap();
parent
.attach_system_os(sys.reference().unwrap().logical_base())
.unwrap();
let mut platform =
system_platform::SystemPlatform::construct(NonZeroU64::new(0x61000000).unwrap())
.unwrap();
let mut nbsi = platform.reference().unwrap();
let mut fallback = timeout_runtime::InitialNbsi(&mut nbsi);
let mut base = registry::LinuxRegistry::open(parent, sys.reference().unwrap())
.unwrap_or_else(|_| panic!("registry"));
let reg = thread_state::Registry::new(database(), NonZeroU32::new(1).unwrap()).unwrap();
let mut clock = Clock {
now: 100,
fail: false,
expected: None,
};
let mut entry = reg.enter(0, 123, &mut clock).unwrap().unwrap();
let binding = Binding {
logical: parent.logical_base().unwrap(),
};
let mut record = timeout_runtime::Record::new();
record
.bind(&binding)
.initialize(
parent,
&mut entry,
&mut Os { calls: 0, fail: 0 },
&mut clock,
)
.unwrap();
struct Setup;
impl timeout_runtime::Diagnostics for Setup {
fn diagnostic(
&mut self,
_: &pf_software::PfSoftware,
_: &mut nv_rs_core::gpu::timeout::config::Defaults,
_: nv_rs_core::gpu::timeout::config::registry::Diagnostic,
) -> Result<(), NvStatus> {
panic!("unexpected timeout diagnostic")
}
fn setup_diagnostic(
&mut self,
_: &pf_software::PfSoftware,
old: u32,
new: u32,
) -> Result<(), NvStatus> {
assert_eq!((old, new), (0x87, 0x80000087));
Ok(())
}
}
{
let mut operation = record.bind(&binding);
assert_eq!(
operation.apply_setup_override(
parent,
&mut entry,
&mut base,
&mut fallback,
&mut Setup
),
Err(timeout_runtime::Error::Service(NvStatus::NOT_SUPPORTED))
);
}
assert_eq!(record.phase(), timeout_runtime::Phase::Unavailable);
assert_eq!(record.pending_database().unwrap().setup_flags, 0x80000087);
assert_eq!(reg.timeout_database().setup_flags, 0x87);
{
let operation = record.bind(&binding);
assert_eq!(
operation.with_data(parent, |_| ()),
Err(timeout_runtime::Error::Quarantined)
);
}
assert_eq!(record.pending_database().unwrap().setup_flags, 0x80000087);
drop(entry);
base.close().unwrap();
drop(nbsi);
platform.close().unwrap();
sys.close().unwrap();
fixture_registry_options(core::ptr::null());
});
}
// Compiled separately as negative operational-borrow tests.
#[cfg(nv_rs_timeout_bad_lifetime)]
fn reject_short_identity_pin(
record: &mut timeout_runtime::Record,
) -> timeout_runtime::Operation<'_, Binding> {
let binding = Binding {
logical: NonZeroU64::new(7).unwrap(),
};
record.bind(&binding)
}
#[cfg(nv_rs_timeout_bad_record)]
fn reject_escaping_record(identity: &Binding) -> timeout_runtime::Operation<'_, Binding> {
let mut record = timeout_runtime::Record::new();
record.bind(identity)
}