| // Copyright 2026 The Fuchsia Authors | |
| // | |
| // Use of this source code is governed by a MIT-style | |
| // license that can be found in the LICENSE file or at | |
| // https://opensource.org/licenses/MIT | |
| /// Platform suspend tests. | |
| #[unittest::suite(name = "platform_suspend_tests")] | |
| mod tests { | |
| use crate::arch_rs::{InterruptDisableGuard, curr_cpu_num}; | |
| use crate::kernel::auto_preempt_disabler::AutoPreemptDisabler; | |
| use crate::kernel::mp::{self, MpIpiTarget, cpu_num_to_mask}; | |
| use crate::kernel::scheduler::peek_active_mask; | |
| use crate::kernel::thread::{self, DEFAULT_PRIORITY, ThreadPtr, sleep_relative}; | |
| use crate::kernel::types::{BOOT_CPU_ID, cpu_num_t, remove_cpu_from_mask}; | |
| use crate::platform_rs::power::{ | |
| PlatformAllowDomainPowerDown, platform_supports_suspend_cpu, | |
| platform_supports_suspend_system, platform_suspend_cpu, platform_suspend_system, | |
| }; | |
| use crate::platform_rs::timer::{ | |
| DurationBoot, DurationMono, InstantMono, current_boot_time, current_mono_time, zx_sec, | |
| }; | |
| use core::ffi::{CStr, c_void}; | |
| use core::marker::PhantomData; | |
| use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; | |
| use kprint::kprintln; | |
| use unittest::{assert_eq, assert_err, assert_ok, assert_true, subtest, unwrap_ok}; | |
| use zx_status::Status; | |
| use zx_types::{ZX_OK, ZX_TIME_INFINITE}; | |
| /// Creates two worker threads pinned to `cpu_a` and `cpu_b` and resumes both only if both | |
| /// succeed, forgetting `a` if creating `b` fails. | |
| /// | |
| /// # Safety | |
| /// | |
| /// - `entry_a` and `entry_b` must be safe to run on kernel-only worker threads with `args.0` | |
| /// and `args.1` (and must neither detach their thread nor change their own CPU affinity). | |
| /// - `cpu_a` and `cpu_b` must be valid active CPU numbers. | |
| /// - Must be called in post-threading context where blocking is permitted with no thread lock, | |
| /// scheduler queue lock, spinlock, or active `ChainLockTransaction` held. | |
| unsafe fn start_worker_pair( | |
| name_a: &'static CStr, | |
| entry_a: extern "C" fn(*mut c_void) -> i32, | |
| cpu_a: cpu_num_t, | |
| name_b: &'static CStr, | |
| entry_b: extern "C" fn(*mut c_void) -> i32, | |
| cpu_b: cpu_num_t, | |
| args: (*mut c_void, *mut c_void), | |
| ) -> Result<(ThreadPtr, ThreadPtr), Status> { | |
| // SAFETY: `name_a` is a static `CStr`; `entry_a`, `args.0`, and context preconditions are | |
| // forwarded from the caller. | |
| let a = unsafe { | |
| thread::create_with_priority(name_a.as_ptr(), entry_a, args.0, DEFAULT_PRIORITY) | |
| }?; | |
| // SAFETY: `name_b` is a static `CStr`; `entry_b`, `args.1`, and context preconditions are | |
| // forwarded from the caller. | |
| let b = match unsafe { | |
| thread::create_with_priority(name_b.as_ptr(), entry_b, args.1, DEFAULT_PRIORITY) | |
| } { | |
| Ok(b) => b, | |
| Err(err) => { | |
| // SAFETY: `a` is an unresumed `Initial` thread not used afterwards. | |
| unsafe { a.forget() }; | |
| return Err(err); | |
| } | |
| }; | |
| // SAFETY: `a` and `b` are newly created, non-destroyed `Thread`s with no locks or | |
| // `ChainLockTransaction` held. | |
| unsafe { | |
| a.set_cpu_affinity(cpu_num_to_mask(cpu_a)); | |
| b.set_cpu_affinity(cpu_num_to_mask(cpu_b)); | |
| } | |
| // SAFETY: `a` and `b` are non-idle, non-detached `Initial` threads with no spinlocks or | |
| // `ChainLockTransaction` held. | |
| unsafe { | |
| a.resume(); | |
| b.resume(); | |
| } | |
| Ok((a, b)) | |
| } | |
| /// Runs `f` on a freshly spawned kernel-only worker thread (no user `VmAspace` attached). | |
| /// | |
| /// # Safety | |
| /// | |
| /// Must be called in post-threading context where blocking is permitted, with no thread lock, | |
| /// scheduler queue lock, spinlock, or active `ChainLockTransaction` held. | |
| unsafe fn run_on_kernel_thread<R: Send, F: FnOnce() -> R + Send>( | |
| name: &'static CStr, | |
| f: F, | |
| ) -> Result<R, Status> { | |
| struct Task<F, R> { | |
| op: Option<F>, | |
| result: Option<R>, | |
| } | |
| extern "C" fn entry<F: FnOnce() -> R, R>(arg_ptr: *mut c_void) -> i32 { | |
| // SAFETY: `arg_ptr` points to `task` on the caller's stack, exclusively accessed by | |
| // this thread until `t.join` returns below. | |
| let task = unsafe { &mut *arg_ptr.cast::<Task<F, R>>() }; | |
| if let Some(op) = task.op.take() { | |
| task.result = Some(op()); | |
| } | |
| 0 | |
| } | |
| let mut task = Task { op: Some(f), result: None }; | |
| let task_ptr = core::ptr::from_mut(&mut task).cast::<c_void>(); | |
| // SAFETY: `name` is a static `CStr`, `task` outlives the worker thread (joined below), and | |
| // context preconditions are forwarded from the caller. | |
| let t = unsafe { | |
| thread::create_with_priority(name.as_ptr(), entry::<F, R>, task_ptr, DEFAULT_PRIORITY) | |
| }?; | |
| // SAFETY: `t` is a newly created, non-idle, non-detached `Thread` with no locks held. | |
| unsafe { t.resume() }; | |
| // SAFETY: `t` is a live, non-detached worker thread joined only here with `INFINITE`. | |
| let _ = unsafe { t.join(InstantMono::INFINITE) } | |
| .expect("uninterruptible infinite join on non-detached thread cannot fail"); | |
| Ok(task.result.expect("worker entry always populates result")) | |
| } | |
| /// Pins the current thread to `cpu` and returns a `!Send + !Sync` guard that restores its | |
| /// previous affinity. | |
| /// | |
| /// # Safety | |
| /// | |
| /// Must be called in post-threading context with no thread lock, scheduler queue lock, or | |
| /// active `ChainLockTransaction` held on entry or when the guard drops on this same thread. | |
| unsafe fn pin_current_to_cpu(cpu: cpu_num_t) -> zr::Deferred<impl FnOnce()> { | |
| // SAFETY: Caller guarantees post-threading context with no locks or transaction held. | |
| let current = unsafe { ThreadPtr::current() }; | |
| // SAFETY: `current` is live and the caller guarantees no locks or transaction held. | |
| let previous_affinity = unsafe { current.set_cpu_affinity(cpu_num_to_mask(cpu)) }; | |
| let not_send_sync: PhantomData<*mut ()> = PhantomData; | |
| zr::defer(move || { | |
| let _not_send_sync = not_send_sync; | |
| // SAFETY: Runs on the same thread in post-threading context with no locks or | |
| // transaction held. | |
| let current = unsafe { ThreadPtr::current() }; | |
| // SAFETY: `current` is live and no locks or transaction are held. | |
| unsafe { current.set_cpu_affinity(previous_affinity) }; | |
| }) | |
| } | |
| /// Selects `(cpu_a, cpu_b)` from active CPUs (`BOOT_CPU_ID` as `cpu_b`, a secondary as | |
| /// `cpu_a`). | |
| fn select_secondary_and_boot_cpu() -> Result<Option<(cpu_num_t, cpu_num_t)>, Status> { | |
| let mut active_cpus = peek_active_mask(); | |
| if active_cpus.count_ones() <= 1 { | |
| return Ok(None); | |
| } | |
| if (active_cpus & cpu_num_to_mask(BOOT_CPU_ID)) == 0 { | |
| return Err(Status::BAD_STATE); | |
| } | |
| let cpu_b: cpu_num_t = BOOT_CPU_ID; | |
| active_cpus &= !cpu_num_to_mask(BOOT_CPU_ID); | |
| let cpu_a: cpu_num_t = remove_cpu_from_mask(&mut active_cpus); | |
| Ok(Some((cpu_a, cpu_b))) | |
| } | |
| /// Verifies that `platform_suspend_cpu` fails with `Status::NOT_SUPPORTED` when unsupported. | |
| #[test] | |
| fn cpu_suspend_not_supported() { | |
| if platform_supports_suspend_cpu() { | |
| kprintln!("platform_suspend_cpu is supported, skipping test"); | |
| return true; | |
| } | |
| let suspend = || { | |
| let _apd = AutoPreemptDisabler::new(); | |
| let _irqd = InterruptDisableGuard::new(); | |
| // SAFETY: Runs on a freshly spawned kernel-only worker thread with preemption and | |
| // interrupts disabled. | |
| unsafe { platform_suspend_cpu(PlatformAllowDomainPowerDown::No) } | |
| }; | |
| // SAFETY: Normal post-threading test context with no locks or `ChainLockTransaction` held. | |
| let status = unwrap_ok!( | |
| unsafe { run_on_kernel_thread(c"cpu_suspend_not_supported", suspend) }, | |
| "failed to create worker thread" | |
| ); | |
| assert_err!(status, Status::NOT_SUPPORTED); | |
| } | |
| /// Verifies that `platform_suspend_cpu` returns promptly when an IPI is already pending. | |
| #[test] | |
| fn cpu_suspend_pending_ipi() { | |
| if !platform_supports_suspend_cpu() { | |
| kprintln!("platform_suspend_cpu is not supported, skipping test"); | |
| return true; | |
| } | |
| let suspend = || { | |
| let _apd = AutoPreemptDisabler::new(); | |
| let _irqd = InterruptDisableGuard::new(); | |
| let curr_cpu = curr_cpu_num(); | |
| // Pend an interrupt to ourselves to ensure that `platform_suspend_cpu` returns | |
| // quickly. | |
| mp::interrupt(MpIpiTarget::Mask, cpu_num_to_mask(curr_cpu)); | |
| // SAFETY: Runs on a freshly spawned kernel-only worker thread with preemption and | |
| // interrupts disabled. | |
| unsafe { platform_suspend_cpu(PlatformAllowDomainPowerDown::No) } | |
| }; | |
| // SAFETY: Normal post-threading test context with no locks or `ChainLockTransaction` held. | |
| let status = unwrap_ok!( | |
| unsafe { run_on_kernel_thread(c"cpu_suspend_pending_ipi", suspend) }, | |
| "failed to create worker thread" | |
| ); | |
| assert_ok!(status); | |
| } | |
| /// Verifies that one CPU can wake another suspended CPU via an IPI. | |
| #[test] | |
| fn cpu_suspend_one_wakes_another() { | |
| // This test creates two threads, A and B. Each on their own CPU. A will suspend and wait | |
| // to be woken by B. B will wait to observe that A has suspended before waking it via IPI. | |
| // Because A might wake from suspend due to a stray interrupt, we retry the test until it | |
| // succeeds, an error occurs or the timeout has elapsed. | |
| const TIMEOUT: DurationBoot = DurationBoot(zx_sec(10)); | |
| if !platform_supports_suspend_cpu() { | |
| kprintln!("platform_suspend_cpu is not supported, skipping test"); | |
| return true; | |
| } | |
| // First, select the CPU that will wake the other. Choose the boot CPU because we know it | |
| // must be active and because we want the suspending CPU to be one of the secondaries since | |
| // they receive fewer (if any) hardware interrupts (SPIs). | |
| let Some((cpu_a, cpu_b)) = unwrap_ok!(select_secondary_and_boot_cpu()) else { | |
| kprintln!("not enough active CPUs, skipping test"); | |
| return true; | |
| }; | |
| enum State { | |
| Ready = 0, | |
| Suspending = 1, | |
| Done = 2, | |
| } | |
| struct Arg { | |
| target: cpu_num_t, | |
| /// Single-variable monotonic state (`Ready` -> `Suspending` -> `Done`); | |
| /// `Release`/`Acquire` suffices without `SeqCst`. | |
| target_state: AtomicU32, | |
| } | |
| extern "C" fn a_entry(arg_ptr: *mut c_void) -> i32 { | |
| // SAFETY: `arg_ptr` points to `arg` on the caller's stack, which outlives both worker | |
| // threads (both are joined before `arg` drops). | |
| let arg = unsafe { &*arg_ptr.cast::<Arg>() }; | |
| let _apd = AutoPreemptDisabler::new(); | |
| let _irqd = InterruptDisableGuard::new(); | |
| arg.target_state.store(State::Suspending as u32, Ordering::Release); | |
| // SAFETY: Runs on a kernel-only worker thread with preemption and interrupts disabled. | |
| let status = unsafe { platform_suspend_cpu(PlatformAllowDomainPowerDown::No) }; | |
| arg.target_state.store(State::Done as u32, Ordering::Release); | |
| Status::result_into_raw(status) | |
| } | |
| extern "C" fn b_entry(arg_ptr: *mut c_void) -> i32 { | |
| // SAFETY: `arg_ptr` points to `arg` on the caller's stack, which outlives both worker | |
| // threads (both are joined before `arg` drops). | |
| let arg = unsafe { &*arg_ptr.cast::<Arg>() }; | |
| // Wait until the target reports that it's about to suspend. | |
| let mut reported = arg.target_state.load(Ordering::Acquire); | |
| while reported == State::Ready as u32 { | |
| libarch::r#yield(); | |
| reported = arg.target_state.load(Ordering::Acquire); | |
| } | |
| if reported == State::Suspending as u32 { | |
| // Wait a short amount of time, see that the thread is still suspended, | |
| // then wake it. | |
| let _ = sleep_relative(DurationMono::from_micros(200)); | |
| if arg.target_state.load(Ordering::Acquire) == State::Suspending as u32 { | |
| mp::interrupt(MpIpiTarget::Mask, cpu_num_to_mask(arg.target)); | |
| return ZX_OK; | |
| } | |
| } | |
| // Somehow the CPU must have returned from suspend. | |
| Status::BAD_STATE.into_raw() | |
| } | |
| // Run this thread on CPU B for the duration of the test. Otherwise, this thread may be | |
| // running on CPU A when it resumes thread A. If thread A then preempts it, this thread is | |
| // stuck in CPU A's run queue and cannot start thread B until CPU A wakes for some other | |
| // reason (e.g. the preemption timer), at which point thread A has already returned and the | |
| // attempt is wasted. | |
| // SAFETY: Normal post-threading test context with no locks or `ChainLockTransaction` held. | |
| let _restore_affinity = unsafe { pin_current_to_cpu(cpu_b) }; | |
| assert_eq!(cpu_b, curr_cpu_num()); | |
| let start = current_boot_time(); | |
| let mut attempt: usize = 0; | |
| while current_boot_time() - start < TIMEOUT { | |
| kprintln!("attempt {}", attempt); | |
| attempt += 1; | |
| let arg = Arg { target: cpu_a, target_state: AtomicU32::new(State::Ready as u32) }; | |
| let arg_ptr = core::ptr::from_ref(&arg).cast::<c_void>().cast_mut(); | |
| // Create both threads before resuming either so that, if creating one fails, the | |
| // other is not left suspended on `cpu_a` with no thread B to wake it. | |
| // SAFETY: `arg` outlives both worker threads (joined below), `cpu_a`/`cpu_b` are | |
| // active CPUs, and blocking is permitted with no locks or `ChainLockTransaction` held. | |
| let pair = unsafe { | |
| start_worker_pair( | |
| c"one_wakes_another-a", | |
| a_entry, | |
| cpu_a, | |
| c"one_wakes_another-b", | |
| b_entry, | |
| cpu_b, | |
| (arg_ptr, arg_ptr), | |
| ) | |
| }; | |
| let (a, b) = unwrap_ok!(pair); | |
| // SAFETY: `a` is a live, non-detached worker thread joined only here with `INFINITE`. | |
| let a_ret = unsafe { a.join(InstantMono::INFINITE) } | |
| .expect("uninterruptible infinite join on non-detached thread cannot fail"); | |
| // Join `b` before checking `a_ret` so `arg` outlives `b` on failure too (`a_entry` | |
| // unconditionally stores `State::Done` before exiting, so `b_entry` finishes too). | |
| // SAFETY: `b` is a live, non-detached worker thread joined only here with `INFINITE`. | |
| let b_ret = unsafe { b.join(InstantMono::INFINITE) } | |
| .expect("uninterruptible infinite join on non-detached thread cannot fail"); | |
| assert_ok!(Status::ok(a_ret)); | |
| let b_status = Status::ok(b_ret); | |
| // Perhaps CPU-A woke from suspend early. Try again. | |
| if b_status == Err(Status::BAD_STATE) { | |
| continue; | |
| } | |
| assert_ok!(b_status); | |
| return true; | |
| } | |
| kprintln!("failed to complete successfully before timeout"); | |
| assert_true!(false); | |
| } | |
| /// Verifies that a CPU does not lose a pending IPI when it suspends and resumes. | |
| #[test] | |
| fn cpu_suspend_sync_exec() { | |
| // Thread A, on CPU A, disables interrupts and waits for thread B, on the boot CPU, to start | |
| // an `mp::sync_exec` targeting CPU A. Thread A then suspends CPU A. The resulting generic | |
| // IPI is either already pending when CPU A suspends or it wakes CPU A. Either way, it must | |
| // still be pending when CPU A resumes so that the task runs once thread A re-enables | |
| // interrupts. Otherwise, thread B's `mp::sync_exec` would not return. | |
| // | |
| // Note, this test only exercises the resume path that reinitializes the CPU's interrupt | |
| // state on platforms where suspending a CPU may power it down. | |
| const TIMEOUT: DurationMono = DurationMono::from_seconds(10); | |
| if !platform_supports_suspend_cpu() { | |
| kprintln!("platform_suspend_cpu is not supported, skipping test"); | |
| return true; | |
| } | |
| // As in `cpu_suspend_one_wakes_another`, thread B runs on the boot CPU and thread A runs on | |
| // one of the secondaries. | |
| let Some((cpu_a, cpu_b)) = unwrap_ok!(select_secondary_and_boot_cpu()) else { | |
| kprintln!("not enough active CPUs, skipping test"); | |
| return true; | |
| }; | |
| #[fbl::ref_counted] | |
| #[derive(fbl::Recyclable)] | |
| #[repr(C)] | |
| struct Arg { | |
| target: cpu_num_t, | |
| /// Set by thread A once interrupts are disabled (`Release`/`Acquire` handoff). | |
| ready: AtomicBool, | |
| /// Set by thread B just before `mp::sync_exec` (`Release`/`Acquire` handoff). | |
| sending: AtomicBool, | |
| } | |
| extern "C" fn a_entry(arg_ptr: *mut c_void) -> i32 { | |
| // SAFETY: `arg_ptr` is an owned raw `fbl::RefPtr<Arg>` from `into_raw`. | |
| let arg = unsafe { fbl::RefPtr::from_raw(arg_ptr.cast::<Arg>()) }; | |
| let status = { | |
| let _apd = AutoPreemptDisabler::new(); | |
| let _irqd = InterruptDisableGuard::new(); | |
| arg.ready.store(true, Ordering::Release); | |
| while !arg.sending.load(Ordering::Acquire) { | |
| libarch::r#yield(); | |
| } | |
| // SAFETY: Runs on a kernel-only worker thread with preemption and interrupts | |
| // disabled. | |
| unsafe { platform_suspend_cpu(PlatformAllowDomainPowerDown::No) } | |
| }; | |
| // Drop `arg` after `_irqd` and `_apd` so any final `RefPtr` deallocation runs with | |
| // preemption and interrupts enabled. | |
| drop(arg); | |
| Status::result_into_raw(status) | |
| } | |
| extern "C" fn b_entry(arg_ptr: *mut c_void) -> i32 { | |
| let target = { | |
| // SAFETY: `arg_ptr` is an owned raw `fbl::RefPtr<Arg>` from `into_raw`. | |
| let arg = unsafe { fbl::RefPtr::from_raw(arg_ptr.cast::<Arg>()) }; | |
| while !arg.ready.load(Ordering::Acquire) { | |
| libarch::r#yield(); | |
| } | |
| let target = arg.target; | |
| arg.sending.store(true, Ordering::Release); | |
| target | |
| }; | |
| // `arg` is dropped above so this thread releases its `RefPtr` before `mp::sync_exec`, | |
| // which may block indefinitely on IPI loss. | |
| // SAFETY: `MpIpiTarget::Mask` does not require interrupts to be disabled. | |
| unsafe { mp::sync_exec(MpIpiTarget::Mask, cpu_num_to_mask(target), || {}) }; | |
| ZX_OK | |
| } | |
| // Run this thread on CPU B for the duration of the test. Otherwise, this thread may be | |
| // running on CPU A when it resumes thread A. If thread A then preempts it before it has | |
| // resumed thread B, thread A would spin, with interrupts disabled, waiting for thread B, | |
| // which this thread can no longer resume because it is stuck in CPU A's run queue. CPU A | |
| // would make no progress until another CPU happened to steal this thread, and the lockup | |
| // detector would report CPU A. | |
| // SAFETY: Normal post-threading test context with no locks or `ChainLockTransaction` held. | |
| let _restore_affinity = unsafe { pin_current_to_cpu(cpu_b) }; | |
| assert_eq!(cpu_b, curr_cpu_num()); | |
| let arg = unwrap_ok!(fbl::make_ref_counted!(Arg { | |
| target: cpu_a, | |
| ready: AtomicBool::new(false), | |
| sending: AtomicBool::new(false), | |
| })); | |
| let arg_a = fbl::RefPtr::into_raw(arg.clone()).cast::<c_void>().cast_mut(); | |
| let arg_b = fbl::RefPtr::into_raw(arg).cast::<c_void>().cast_mut(); | |
| // Create both threads before resuming either so that, if creating one fails, the other is | |
| // not left running (e.g. thread A spinning forever on CPU A with interrupts disabled). | |
| // SAFETY: `arg_a` and `arg_b` are owned `fbl::RefPtr<Arg>`s (reclaimed on `Err` below), | |
| // `cpu_a`/`cpu_b` are active CPUs, and blocking is permitted with no locks held. | |
| let pair = unsafe { | |
| start_worker_pair( | |
| c"suspend_sync_exec-a", | |
| a_entry, | |
| cpu_a, | |
| c"suspend_sync_exec-b", | |
| b_entry, | |
| cpu_b, | |
| (arg_a, arg_b), | |
| ) | |
| }; | |
| let (a, b) = unwrap_ok!(pair.inspect_err(|_| { | |
| // SAFETY: `start_worker_pair` never runs entry points on `Err`, so `arg_a`/`arg_b` | |
| // remain unconsumed owned `fbl::RefPtr<Arg>` references. | |
| drop(unsafe { fbl::RefPtr::from_raw(arg_a.cast::<Arg>()) }); | |
| // SAFETY: As above for `arg_b`. | |
| drop(unsafe { fbl::RefPtr::from_raw(arg_b.cast::<Arg>()) }); | |
| })); | |
| // SAFETY: `a` is a live, non-detached worker thread joined only here with `INFINITE`. | |
| let a_ret = unsafe { a.join(InstantMono::INFINITE) } | |
| .expect("uninterruptible infinite join on non-detached thread cannot fail"); | |
| let mut detach_b = zr::defer(move || { | |
| // SAFETY: `b` is a live, non-detached thread not joined or detached elsewhere and no | |
| // locks or `ChainLockTransaction` are held. | |
| let _ = unsafe { b.detach() }; | |
| }); | |
| assert_ok!(Status::ok(a_ret)); | |
| // If the IPI was lost, thread B's `mp::sync_exec` does not return (at least not until some | |
| // later generic IPI targets CPU A). Fail rather than hang in that case. | |
| // SAFETY: `b` is a live, non-detached worker thread joined only here with no locks held. | |
| let b_join = unsafe { b.join(current_mono_time() + TIMEOUT) }; | |
| let b_ret = unwrap_ok!(b_join); | |
| detach_b.cancel(); | |
| let b_status = Status::ok(b_ret); | |
| assert_ok!(b_status); | |
| } | |
| /// Unplugs secondary CPUs, runs `platform_suspend_system` on a fresh kernel-only thread on | |
| /// `BOOT_CPU_ID`, and restores secondary CPUs and thread affinity before returning. | |
| /// | |
| /// # Safety | |
| /// | |
| /// Must be called in post-threading context where blocking is permitted, with no thread lock, | |
| /// scheduler queue lock, spinlock, or active `ChainLockTransaction` held. | |
| unsafe fn run_system_suspend_test( | |
| name: &'static CStr, | |
| pend_ipi: bool, | |
| expected: Result<(), Status>, | |
| ) -> bool { | |
| (subtest!(|| { | |
| if cfg!(target_arch = "riscv64") { | |
| // TODO(https://fxbug.dev/42086046): Re-enable when RISC-V supports CPU hotplug. | |
| kprintln!("skipping test, hotplug only supported on x64 and arm64"); | |
| return true; | |
| } | |
| // SAFETY: Caller guarantees post-threading context with no locks or transaction held; | |
| // `_restore_cpus` drops before `_restore_affinity` so CPUs return before affinity does. | |
| let _restore_affinity = unsafe { pin_current_to_cpu(BOOT_CPU_ID) }; | |
| assert_eq!(BOOT_CPU_ID, curr_cpu_num()); | |
| let online_before = mp::get_online_mask(); | |
| let _restore_cpus = zr::defer(move || { | |
| let to_hotplug = online_before & !mp::get_online_mask(); | |
| if to_hotplug != 0 { | |
| let status = mp::hotplug_cpu_mask(to_hotplug); | |
| assert!( | |
| status.is_ok(), | |
| "mp::hotplug_cpu_mask({:#x}) failed: {}", | |
| to_hotplug, | |
| Status::result_into_raw(status), | |
| ); | |
| // Bound the wait so that a CPU which fails to come back produces a clear | |
| // failure rather than a hang. Subsequent tests could not run correctly without | |
| // it anyway. | |
| let deadline = current_mono_time() + DurationMono::from_seconds(10); | |
| while (mp::get_online_mask() & to_hotplug) != to_hotplug | |
| || (peek_active_mask() & to_hotplug) != to_hotplug | |
| { | |
| assert!( | |
| current_mono_time() < deadline, | |
| "timed out waiting for CPUs {:#x} to come online \ | |
| (online {:#x}, active {:#x})", | |
| to_hotplug, | |
| mp::get_online_mask(), | |
| peek_active_mask(), | |
| ); | |
| let _ = sleep_relative(DurationMono::from_micros(200)); | |
| } | |
| } | |
| }); | |
| let secondaries = online_before & !cpu_num_to_mask(BOOT_CPU_ID); | |
| if secondaries != 0 { | |
| assert_ok!(mp::unplug_cpu_mask(secondaries, ZX_TIME_INFINITE)); | |
| } | |
| assert_eq!(cpu_num_to_mask(BOOT_CPU_ID), mp::get_online_mask()); | |
| let suspend = || { | |
| let _apd = AutoPreemptDisabler::new(); | |
| let curr_cpu = curr_cpu_num(); | |
| if curr_cpu != BOOT_CPU_ID { | |
| return (curr_cpu, Err(Status::BAD_STATE)); | |
| } | |
| let _irqd = InterruptDisableGuard::new(); | |
| if pend_ipi { | |
| // Pend an interrupt to ourselves to ensure that `platform_suspend_system` | |
| // returns quickly. | |
| mp::interrupt(MpIpiTarget::Mask, cpu_num_to_mask(curr_cpu)); | |
| } | |
| // SAFETY: Runs on a freshly spawned kernel-only worker thread on `BOOT_CPU_ID` | |
| // while all secondaries are unplugged, with preemption and interrupts disabled. | |
| let status = unsafe { platform_suspend_system() }; | |
| (curr_cpu, status) | |
| }; | |
| // SAFETY: Context preconditions are forwarded from `run_system_suspend_test`. | |
| let (curr_cpu, status) = unwrap_ok!( | |
| unsafe { run_on_kernel_thread(name, suspend) }, | |
| "failed to create worker thread" | |
| ); | |
| assert_eq!(BOOT_CPU_ID, curr_cpu); | |
| match expected { | |
| Ok(()) => { | |
| assert_ok!(status); | |
| } | |
| Err(err) => { | |
| assert_err!(status, err); | |
| } | |
| } | |
| }))() | |
| } | |
| /// Verifies that `platform_suspend_system` fails with `Status::NOT_SUPPORTED` when unsupported. | |
| #[test] | |
| fn system_suspend_not_supported() { | |
| // Secondary CPUs are unplugged so that all of `platform_suspend_system`'s preconditions are | |
| // met. | |
| if platform_supports_suspend_system() { | |
| kprintln!("platform_suspend_system is supported, skipping test"); | |
| return true; | |
| } | |
| // SAFETY: Normal post-threading test context with no locks or `ChainLockTransaction` held. | |
| let ok = unsafe { | |
| run_system_suspend_test( | |
| c"system_suspend_not_supported", | |
| false, | |
| Err(Status::NOT_SUPPORTED), | |
| ) | |
| }; | |
| assert_true!(ok); | |
| } | |
| /// Verifies that `platform_suspend_system` returns promptly when an IPI is already pending. | |
| #[test] | |
| fn system_suspend_pending_ipi() { | |
| if !platform_supports_suspend_system() { | |
| kprintln!("platform_suspend_system is not supported, skipping test"); | |
| return true; | |
| } | |
| // SAFETY: Normal post-threading test context with no locks or `ChainLockTransaction` held. | |
| let ok = unsafe { run_system_suspend_test(c"system_suspend_pending_ipi", true, Ok(())) }; | |
| assert_true!(ok); | |
| } | |
| } |