blob: e11f08555827ea284781ebff419af70106537c29 [file]
// 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
/// Scheduler Run Queue tests
#[cfg(ktest)]
#[unittest::suite(name = "scheduler_run_queue")]
mod scheduler_run_queue_tests {
use core::ffi::{c_int, c_void};
use pin_init::stack_pin_init;
use unittest::{expect_eq, expect_false, expect_null, expect_true, unwrap_ok};
use crate::kernel::scheduler::{RunQueue, SchedTime, find_earliest_eligible_thread};
use crate::kernel::thread::{DEFAULT_PRIORITY, Thread, create_with_priority};
extern "C" fn noop_entry(_: *mut c_void) -> c_int {
0
}
/// Sets `start_time` and `finish_time` on an unstarted, unqueued thread.
///
/// # Safety
///
/// The caller must have exclusive access to `t`'s `queue_lock_`-guarded `SchedulerState`
/// fields (`start_time` and `finish_time`) for the duration of the call (e.g. `t` is
/// unstarted and not enqueued in any `RunQueue`), and no live reference may alias
/// `start_time` or `finish_time` for the duration of the call.
unsafe fn set_times(t: &Thread, start: SchedTime, finish: SchedTime) {
let state = t.scheduler_state_ptr();
// SAFETY:
// - By `Thread::scheduler_state_ptr`'s `# Safety-usable invariant`, `state` is non-null,
// aligned for `SchedulerState`, and points to `t`'s initialized `SchedulerState`
// storage for the duration of `&t`.
// - `SchedTime` is `Copy` (no uninitialized drop runs on assignment), and the caller
// guarantees exclusive access to `start_time` and `finish_time` with no aliasing
// references for the duration of this call; writing through raw-pointer field
// projections avoids forming `&mut SchedulerState`.
unsafe {
(*state).start_time = start;
(*state).finish_time = finish;
}
}
/// run_queue_basic
#[test]
fn test_run_queue_basic() {
// Create a RunQueue instance.
stack_pin_init!(let rq = RunQueue::new());
expect_true!(rq.is_empty(), "Queue should be empty initially");
expect_eq!(0usize, rq.len(), "Queue size should be 0 initially");
expect_false!(rq.front_cursor().is_valid(), "Queue front should be invalid initially");
expect_false!(rq.root_cursor().is_valid(), "Queue root should be invalid initially");
// Create three unstarted threads. Attach `zr::defer` guards during creation so
// partial OOM does not leak earlier threads on the global `thread_list`.
// SAFETY: `c"test_t1"` is a valid NUL-terminated string, `noop_entry` is safe to run,
// and this unit test runs in normal kernel-thread context where blocking is permitted with
// no active `ChainLockTransaction`.
let t1 = unwrap_ok!(unsafe {
create_with_priority(
c"test_t1".as_ptr(),
noop_entry,
core::ptr::null_mut(),
DEFAULT_PRIORITY,
)
});
let mut cleanup_t1 = zr::defer(|| {
// SAFETY: `t1` is valid, never started, not the current thread, not in any wait
// queue or `RunQueue`, and not used afterward.
unsafe { t1.forget() };
});
// SAFETY: `c"test_t2"` is a valid NUL-terminated string, `noop_entry` is safe to run,
// and this unit test runs in normal kernel-thread context where blocking is permitted with
// no active `ChainLockTransaction`.
let t2 = unwrap_ok!(unsafe {
create_with_priority(
c"test_t2".as_ptr(),
noop_entry,
core::ptr::null_mut(),
DEFAULT_PRIORITY,
)
});
let mut cleanup_t2 = zr::defer(|| {
// SAFETY: `t2` is valid, never started, not the current thread, not in any wait
// queue or `RunQueue`, and not used afterward.
unsafe { t2.forget() };
});
// SAFETY: `c"test_t3"` is a valid NUL-terminated string, `noop_entry` is safe to run,
// and this unit test runs in normal kernel-thread context where blocking is permitted with
// no active `ChainLockTransaction`.
let t3 = unwrap_ok!(unsafe {
create_with_priority(
c"test_t3".as_ptr(),
noop_entry,
core::ptr::null_mut(),
DEFAULT_PRIORITY,
)
});
// All three threads were created; explicit `forget()` handles cleanup after `erase_raw`.
cleanup_t1.cancel();
cleanup_t2.cancel();
// Set custom start/finish times to test order and eligibility.
// `create_with_priority(..., DEFAULT_PRIORITY)` already initializes `SchedulerState` with
// `BaseProfile::new_fair(DEFAULT_PRIORITY)` before publishing to `thread_list`.
// t1: start = 10, finish = 20
// t2: start = 20, finish = 30
// t3: start = 15, finish = 25
// SAFETY:
// - `ThreadPtr::as_ref`: `t1`, `t2`, and `t3` are valid `Thread`s kept alive until
// `forget()` at the end of this test.
// - `set_times`: each thread is unstarted and not enqueued in any `RunQueue`, so this test
// has exclusive access to its `queue_lock_`-guarded `start_time` and `finish_time`
// fields with no aliasing references for the duration of each call.
unsafe {
set_times(t1.as_ref(), SchedTime::from_raw(10), SchedTime::from_raw(20));
set_times(t2.as_ref(), SchedTime::from_raw(20), SchedTime::from_raw(30));
set_times(t3.as_ref(), SchedTime::from_raw(15), SchedTime::from_raw(25));
}
// Insert them into the run queue.
// SAFETY:
// - `t1.as_raw()`, `t2.as_raw()`, and `t3.as_raw()` are valid `Thread`s not currently in
// any container, and stay alive and pinned at their addresses while linked into `rq`
// (matching `rq`'s pinned stack lifetime), with no `&mut Thread` aliasing `rq`'s
// accesses.
// - `WavlTreeKeyable` (`Thread::get_key`) and `SubtreeInvariantTraits`: each thread is
// unstarted and `rq` is exclusively owned by this test, so `start_time`, `finish_time`,
// `subtree_invariants`, and `effective_profile.weight` are not concurrently mutated
// while the thread resides in `rq`.
unsafe {
rq.as_mut().insert_raw(t1.as_raw());
rq.as_mut().insert_raw(t2.as_raw());
rq.as_mut().insert_raw(t3.as_raw());
}
expect_false!(rq.is_empty(), "Queue should not be empty");
expect_eq!(3usize, rq.len(), "Queue size should be 3");
let front = rq.front_cursor();
expect_true!(front.is_valid(), "Queue front should be valid");
expect_eq!(t1.as_raw(), front.as_raw_ptr(), "Queue front should be t1");
expect_true!(rq.root_cursor().is_valid(), "Queue root should be valid");
// Predicate that always returns true.
let true_pred = |_: *mut Thread| true;
// Test case 1: eligible_time = 9.
// No thread is eligible because front (t1) start_time is 10.
{
// SAFETY: `rq` is an exclusively owned standalone `RunQueue` whose enqueued nodes
// (`t1`, `t2`, `t3`) are valid and not concurrently mutated in their `RunQueue` links
// or queue-locked `SchedulerState` fields.
let result =
unsafe { find_earliest_eligible_thread(&rq, SchedTime::from_raw(9), true_pred) };
expect_null!(result, "No thread should be eligible at time 9");
}
// Test case 2: eligible_time = 12.
// Only t1 is eligible.
{
// SAFETY: `rq` is an exclusively owned standalone `RunQueue` whose enqueued nodes
// (`t1`, `t2`, `t3`) are valid and not concurrently mutated in their `RunQueue` links
// or queue-locked `SchedulerState` fields.
let result =
unsafe { find_earliest_eligible_thread(&rq, SchedTime::from_raw(12), true_pred) };
expect_eq!(t1.as_raw(), result, "t1 should be the only eligible thread at time 12");
}
// Test case 3: eligible_time = 16.
// t1 (finish 20) and t3 (finish 25) are eligible.
// Should return t1 because it has the earliest finish time.
{
// SAFETY: `rq` is an exclusively owned standalone `RunQueue` whose enqueued nodes
// (`t1`, `t2`, `t3`) are valid and not concurrently mutated in their `RunQueue` links
// or queue-locked `SchedulerState` fields.
let result =
unsafe { find_earliest_eligible_thread(&rq, SchedTime::from_raw(16), true_pred) };
expect_eq!(
t1.as_raw(),
result,
"t1 should be preferred over t3 at time 16 due to earlier finish time"
);
}
// Test case 4: eligible_time = 16 with predicate excluding t1.
// `find_earliest_eligible_thread` does not backtrack, so if it decides to
// search a subtree (based on min_finish_time) and that subtree's best node
// is rejected by the predicate, it may fail (return null) even if there
// are other eligible and acceptable nodes.
{
let exclude_thread = t1.as_raw();
let exclude_pred = |t: *mut Thread| t != exclude_thread;
// SAFETY: `rq` is an exclusively owned standalone `RunQueue` whose enqueued nodes
// (`t1`, `t2`, `t3`) are valid and not concurrently mutated in their `RunQueue` links
// or queue-locked `SchedulerState` fields.
let result = unsafe {
find_earliest_eligible_thread(&rq, SchedTime::from_raw(16), exclude_pred)
};
expect_null!(result, "Should return null because algorithm does not backtrack");
}
// Test case 5: Erase t1 and try again at time 16.
// Should return t3 even without exclusion predicate.
// SAFETY:
// - `t1.as_raw()` is a valid `Thread` currently enqueued in `rq`, with no aliasing
// `&mut Thread`.
// - `rq` is exclusively owned by this test and all enqueued threads (`t1`, `t2`, `t3`)
// are unstarted, upholding the `WavlTreeKeyable` and `SubtreeInvariantTraits`
// synchronization preconditions (`start_time`, `finish_time`, `subtree_invariants`,
// and `effective_profile.weight` are not concurrently mutated).
let erased = unsafe { rq.as_mut().erase_raw(t1.as_raw()) }.unwrap_or(core::ptr::null_mut());
expect_eq!(t1.as_raw(), erased, "Erase should return t1");
// SAFETY: `rq` is an exclusively owned standalone `RunQueue` whose remaining nodes
// (`t2`, `t3`) are valid and not concurrently mutated in their `RunQueue` links or
// queue-locked `SchedulerState` fields.
let result =
unsafe { find_earliest_eligible_thread(&rq, SchedTime::from_raw(16), true_pred) };
expect_eq!(t3.as_raw(), result, "t3 should be chosen after t1 is erased");
// Test case 6: Iteration.
// Should visit t3, t2 in order (t1 was erased).
let mut cursor = rq.front_cursor();
expect_true!(cursor.is_valid(), "Cursor should be valid initially");
expect_eq!(t3.as_raw(), cursor.as_raw_ptr(), "First element should be t3");
cursor.move_next();
expect_true!(cursor.is_valid(), "Cursor should be valid after first move_next");
expect_eq!(t2.as_raw(), cursor.as_raw_ptr(), "Second element should be t2");
cursor.move_next();
expect_false!(cursor.is_valid(), "Cursor should be invalid after second move_next");
expect_true!(
fbl::is_sentinel_ptr(cursor.as_raw_ptr()),
"Element should be sentinel after end"
);
// Clean up threads. We must erase them from the queue first.
// SAFETY:
// - `t2.as_raw()` and `t3.as_raw()` are valid `Thread`s currently enqueued in `rq`, with
// no aliasing `&mut Thread`.
// - `rq` is exclusively owned by this test and all remaining enqueued threads are
// unstarted, upholding the `WavlTreeKeyable` and `SubtreeInvariantTraits` synchronization
// preconditions (`start_time`, `finish_time`, `subtree_invariants`, and
// `effective_profile.weight` are not concurrently mutated).
unsafe {
rq.as_mut().erase_raw(t2.as_raw());
rq.as_mut().erase_raw(t3.as_raw());
}
// SAFETY: `t1`, `t2`, and `t3` are valid `Thread`s that were never started, are not the
// current thread, are not in any wait queue or `RunQueue`, and are not used afterward.
unsafe {
t1.forget();
t2.forget();
t3.forget();
}
}
}