| // Copyright 2020 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 | |
| /// kernel stack tests | |
| #[cfg(ktest)] | |
| #[unittest::suite(name = "kstack")] | |
| mod kstack_tests { | |
| use core::ffi::{c_int, c_void}; | |
| use core::hint::black_box; | |
| use core::ptr::{read_volatile, write_volatile}; | |
| use core::sync::atomic::{AtomicBool, Ordering}; | |
| use kprint::kprintln; | |
| use unittest::unwrap_ok; | |
| use crate::kernel::auto_preempt_disabler::AutoPreemptDisabler; | |
| use crate::kernel::mp::{self, MpIpiTarget}; | |
| use crate::kernel::scheduler::{BaseProfile, peek_active_mask}; | |
| use crate::kernel::thread::{DEFAULT_PRIORITY, ThreadPtr, create_etc}; | |
| use crate::kernel::types::{ | |
| INVALID_CPU, cpu_mask_t, cpu_num_t, cpu_num_to_mask, remove_cpu_from_mask, | |
| }; | |
| use crate::platform_rs::timer::{DurationMono, InstantMono, current_mono_time}; | |
| use crate::thread_stack::internal::MACHINE_STACK_SIZE; | |
| /// Test that the kernel is able to handle interrupts when half the kernel stack is used. | |
| #[test] | |
| fn kstack_interrupt_depth() { | |
| const SIZE: usize = MACHINE_STACK_SIZE as usize / 2; | |
| zr::static_assert!(SIZE > 0); | |
| let mut buffer = [0u8; SIZE]; | |
| // Spin for a bit while we have a large, active buffer on the kernel stack. | |
| // This gives us a window for interrupts to occur; any that do will have to make do with | |
| // half the stack consumed. | |
| let mut i: usize = 0; | |
| let now = current_mono_time(); | |
| while current_mono_time() < now + DurationMono::from_millis(100) { | |
| // Touch the buffer to ensure it is not optimized out. | |
| // SAFETY: `buffer` is an initialized local `[u8; SIZE]` with `SIZE > 0`, so | |
| // `&raw const buffer[0]` is aligned and valid for reads of one initialized `u8`. | |
| let val = unsafe { read_volatile(&raw const buffer[0]) }; | |
| // SAFETY: `buffer` is a uniquely owned local `[u8; SIZE]` with `SIZE > 0`, so | |
| // `&raw mut buffer[i % SIZE]` is aligned and valid for writes of `u8`. | |
| unsafe { write_volatile(&raw mut buffer[i % SIZE], val) }; | |
| i = i.wrapping_add(1); | |
| libarch::r#yield(); | |
| } | |
| } | |
| /// Same as `kstack_interrupt_depth`, with SafeStack disabled (no-op without SafeStack). | |
| #[test] | |
| #[sanitize(safestack = "off")] | |
| fn kstack_interrupt_depth_no_safestack() { | |
| // SafeStack is disabled on this function so the buffer lives on the machine stack. | |
| #[cfg(sanitize = "safestack")] | |
| { | |
| const SIZE: usize = MACHINE_STACK_SIZE as usize / 2; | |
| zr::static_assert!(SIZE > 0); | |
| let mut buffer = [0u8; SIZE]; | |
| // Spin for a bit while we have a large, active buffer on the kernel stack. | |
| // Just like the above test, though with safe-stack disabled. | |
| let mut i: usize = 0; | |
| let now = current_mono_time(); | |
| while current_mono_time() < now + DurationMono::from_millis(100) { | |
| // Touch the buffer to ensure it is not optimized out. | |
| // SAFETY: `buffer` is an initialized local `[u8; SIZE]` with `SIZE > 0`, so | |
| // `&raw const buffer[0]` is aligned and valid for reads of one initialized `u8`. | |
| let val = unsafe { read_volatile(&raw const buffer[0]) }; | |
| // SAFETY: `buffer` is a uniquely owned local `[u8; SIZE]` with `SIZE > 0`, so | |
| // `&raw mut buffer[i % SIZE]` is aligned and valid for writes of `u8`. | |
| unsafe { write_volatile(&raw mut buffer[i % SIZE], val) }; | |
| i = i.wrapping_add(1); | |
| libarch::r#yield(); | |
| } | |
| } | |
| #[cfg(not(sanitize = "safestack"))] | |
| { | |
| kprintln!("SafeStack is not enabled; skipping test"); | |
| } | |
| } | |
| /// Test that we can handle an `mp::sync_exec` callback while half the kernel stack is used. | |
| #[test] | |
| fn kstack_mp_sync_exec() { | |
| // We need 2 or more CPUs for this test, CPU-A and CPU-B. The thread calling into this test | |
| // will be pinned to CPU-A and the thread spawned by this test will be pinned to CPU-B. | |
| let mut mask: cpu_mask_t = peek_active_mask(); | |
| let cpu_a: cpu_num_t = remove_cpu_from_mask(&mut mask); | |
| let cpu_b: cpu_num_t = remove_cpu_from_mask(&mut mask); | |
| if cpu_a == INVALID_CPU || cpu_b == INVALID_CPU { | |
| kprintln!("not enough active cpus; skipping test"); | |
| return true; | |
| } | |
| struct Context { | |
| ready: AtomicBool, | |
| done: AtomicBool, | |
| } | |
| let context = Context { ready: AtomicBool::new(false), done: AtomicBool::new(false) }; | |
| /// Worker thread entry point that holds `SIZE` bytes on the machine stack until | |
| /// `Context::done` becomes `true`. | |
| /// | |
| /// # Safety | |
| /// | |
| /// The caller must ensure that `arg` is non-null, aligned for `Context`, and points to a | |
| /// live, initialized `Context` valid for shared reads and atomic accesses until `spin_fn` | |
| /// returns, with no conflicting `&mut Context` alias. | |
| unsafe extern "C" fn spin_fn(arg: *mut c_void) -> c_int { | |
| // Ensure that no other thread runs on this CPU for the duration of the test. The goal | |
| // here is to have the IPI interrupt *this* thread and push its frame onto *this* | |
| // thread's stack. | |
| let _preempt_disable = AutoPreemptDisabler::new(); | |
| const SIZE: usize = MACHINE_STACK_SIZE as usize / 2; | |
| zr::static_assert!(SIZE > 0); | |
| let mut buffer = [0u8; SIZE]; | |
| // SAFETY: By `spin_fn`'s safety contract, `arg` is non-null, aligned, and points to | |
| // a live, initialized `Context` with no conflicting `&mut Context` for the duration | |
| // of this call; `Context` holds only `AtomicBool` fields, supporting shared atomic | |
| // operations. | |
| let context = unsafe { &*arg.cast::<Context>() }; | |
| context.ready.store(true, Ordering::SeqCst); | |
| // Touch the buffer to ensure it is not optimized out; opaque indexing keeps all | |
| // `SIZE` bytes on the machine stack without SROA shrinking `buffer`. | |
| // SAFETY: `buffer` is an initialized local `[u8; SIZE]` with `SIZE > 0`, so | |
| // `&raw const buffer[0]` is aligned and valid for reads of one initialized `u8`. | |
| let val = unsafe { read_volatile(&raw const buffer[0]) }; | |
| // SAFETY: `buffer` is a uniquely owned local `[u8; SIZE]` with `SIZE > 0`, so | |
| // `&raw mut buffer[black_box(1) % SIZE]` is aligned and valid for writes of `u8`. | |
| unsafe { write_volatile(&raw mut buffer[black_box(1) % SIZE], val) }; | |
| while !context.done.load(Ordering::SeqCst) { | |
| // Wait for a bit while we have a large, active buffer on the kernel stack. | |
| // `mp::sync_exec`'s callback will run on our CPU; we want to check that it succeeds | |
| // even when `SIZE` bytes of kernel stack space are consumed by (this) thread | |
| // context. | |
| libarch::r#yield(); | |
| } | |
| 0 | |
| } | |
| // Current thread runs on CPU-A... | |
| // SAFETY: Kernel unit tests run on a valid kernel thread after `LK_INIT_LEVEL_THREADING` | |
| // initialization. | |
| let current = unsafe { ThreadPtr::current() }; | |
| // SAFETY: `current` points to the live current `Thread`, and no thread lock, scheduler | |
| // queue lock, or `ChainLockTransaction` is held on this CPU. | |
| let old_affinity = unsafe { current.set_cpu_affinity(cpu_num_to_mask(cpu_a)) }; | |
| let _restore_affinity = zr::defer(|| { | |
| // SAFETY: `_restore_affinity` drops on the same live test thread before it exits, with | |
| // interrupts enabled and no thread lock, scheduler queue lock, or | |
| // `ChainLockTransaction` held on this CPU. | |
| let _ = unsafe { current.set_cpu_affinity(old_affinity) }; | |
| }); | |
| // and `spin_fn` runs on CPU-B. | |
| // SAFETY: | |
| // - `t` is null, so `create_etc` allocates the `Thread` itself. | |
| // - `spin_fn` is a valid entry point whose `# Safety` preconditions are satisfied by | |
| // passing `&context` as `arg`: `&context` is non-null, aligned, points to a live, | |
| // initialized `Context` with no `&mut Context` alias, and `context` outlives `spin_fn`: | |
| // if `create_etc` fails no thread observes `arg`; otherwise there is no early return | |
| // before `thread.join`, and a failed join panics (see `assert!` below), so `context` is | |
| // never dropped while `spin_fn` may still run. | |
| // - `alt_trampoline` is `None`. | |
| // - Kernel unit tests may block and hold no `ChainLockTransaction`. | |
| let thread = unwrap_ok!(unsafe { | |
| create_etc( | |
| core::ptr::null_mut(), | |
| b"waiter", | |
| Some(spin_fn), | |
| core::ptr::from_ref(&context).cast_mut().cast(), | |
| &BaseProfile::new_fair(DEFAULT_PRIORITY), | |
| None, | |
| ) | |
| }); | |
| // SAFETY: `thread` was just created above and has not yet been resumed or joined, and no | |
| // locks or `ChainLockTransaction` are held. | |
| let _ = unsafe { thread.set_cpu_affinity(cpu_num_to_mask(cpu_b)) }; | |
| // SAFETY: `thread` is non-idle, non-detached, still in `Initial` state, and has not been | |
| // joined or destroyed; `num_spinlocks_held() == 0`; and no `ChainLockTransaction` is | |
| // active. | |
| unsafe { thread.resume() }; | |
| while !context.ready.load(Ordering::SeqCst) { | |
| libarch::r#yield(); | |
| } | |
| // SAFETY: `MpIpiTarget::Mask` does not require interrupts to be disabled on the calling | |
| // CPU. | |
| unsafe { | |
| mp::sync_exec(MpIpiTarget::Mask, cpu_num_to_mask(cpu_b), || { | |
| context.done.store(true, Ordering::SeqCst); | |
| }); | |
| } | |
| // SAFETY: `thread` was created above, is not the current thread, has not been detached or | |
| // joined, no `&Thread` reference is live, and blocking is permitted with no locks or | |
| // `ChainLockTransaction` held. | |
| let join_result = unsafe { thread.join(InstantMono::INFINITE) }; | |
| assert!(join_result.is_ok(), "thread.join failed: {join_result:?}"); | |
| } | |
| } |