diff --git a/applications/tests/test_dvfs_task/Cargo.toml b/applications/tests/test_dvfs_task/Cargo.toml new file mode 100644 index 000000000..797d49532 --- /dev/null +++ b/applications/tests/test_dvfs_task/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "test_dvfs_task" +version = "0.1.0" +edition = "2024" + +[dependencies] +log = "0.4" + +[dependencies.awkernel_async_lib] +path = "../../../awkernel_async_lib" +default-features = false + +[dependencies.awkernel_lib] +path = "../../../awkernel_lib" +default-features = false diff --git a/applications/tests/test_dvfs_task/src/lib.rs b/applications/tests/test_dvfs_task/src/lib.rs new file mode 100644 index 000000000..efc32861c --- /dev/null +++ b/applications/tests/test_dvfs_task/src/lib.rs @@ -0,0 +1,115 @@ +#![no_std] + +extern crate alloc; + +use alloc::vec::Vec; +use core::{ + sync::atomic::{AtomicUsize, Ordering}, + time::Duration, +}; + +use awkernel_async_lib::{ + scheduler::SchedulerType, + task::{self, TaskResult}, +}; +use awkernel_lib::{ + cpu::{CpuSet, num_cpu}, + dvfs::{get_curr_cpu_freq, get_max_cpu_freq}, + time::Instant, +}; + +const NUM_LOOP: usize = 100_000_000; +const NUM_ROUND: usize = 10; +const NUM_TASKS: usize = 3; + +/// Number of finished `busy_loop` tasks. +static FINISHED: AtomicUsize = AtomicUsize::new(0); + +pub async fn run() { + if num_cpu() < 7 { + log::error!("need at least 7 CPUs"); + return; + } + + let max = match get_max_cpu_freq() { + Ok(f) => f, + Err(e) => { + log::error!("get_max_cpu_freq failed: {e:?}"); + return; + } + }; + + task::spawn( + "dvfs_task_none".into(), + busy_loop(1, None), + SchedulerType::EDF(1_000_000, CpuSet::empty().with(2)), + ); + + task::spawn_with_freq( + "dvfs_task_half".into(), + busy_loop(2, Some(max / 2)), + SchedulerType::EDF(1_000_000, CpuSet::empty().with(4)), + max / 2, + ); + + task::spawn_with_freq( + "dvfs_task_max".into(), + busy_loop(3, Some(max)), + SchedulerType::EDF(1_000_000, CpuSet::empty().with(6)), + max, + ); + + // Wait for all tasks to finish. + while FINISHED.load(Ordering::Relaxed) < NUM_TASKS { + awkernel_async_lib::sleep(Duration::from_millis(100)).await; + } + + // Check that each worker CPU (CPU#0 runs no task) requested the minimum + // frequency when idle. Read the scheduler's records instead of running a + // task on each CPU, which would change its frequency. Read them all before + // logging, because the logger task resets the record of the CPU it runs on. + let self_cpu = awkernel_lib::cpu::cpu_id(); + let requested: Vec = (1..num_cpu()) + .map(task::is_idle_min_freq_requested) + .collect(); + + for (core, requested) in (1..num_cpu()).zip(requested) { + if core == self_cpu { + log::info!("after all tasks: CPU#{core} is running this test, skipped"); + } else if requested { + log::info!("after all tasks: CPU#{core} requested the minimum frequency when idle"); + } else { + log::error!( + "after all tasks: CPU#{core} did not request the minimum frequency when idle" + ); + } + } +} + +async fn busy_loop(label: u32, expected: Option) -> TaskResult { + for _ in 0..NUM_ROUND { + // Measure while keeping interrupts (and thus preemption) disabled. + let int_guard = awkernel_lib::interrupt::InterruptGuard::new(); + let cpuid = awkernel_lib::cpu::cpu_id(); + let start = Instant::now(); + for _ in 0..NUM_LOOP { + core::hint::black_box(()); + } + let t = start.elapsed(); + let current = get_curr_cpu_freq(); + drop(int_guard); + + // Log outside the guard. + match current { + Ok(current) => log::info!( + "dvfs_task {label}: CPU#{cpuid}, current = {current}, expected = {expected:?}, time = {t:?}" + ), + Err(e) => log::warn!("dvfs_task {label}: get_curr_cpu_freq failed: {e:?}"), + } + + awkernel_async_lib::r#yield().await; + } + log::info!("dvfs_task {label} finished"); + FINISHED.fetch_add(1, Ordering::Relaxed); + Ok(()) +} diff --git a/awkernel_async_lib/Cargo.toml b/awkernel_async_lib/Cargo.toml index 323bc58d0..c0cd0cdcc 100644 --- a/awkernel_async_lib/Cargo.toml +++ b/awkernel_async_lib/Cargo.toml @@ -44,3 +44,4 @@ spinlock = ["awkernel_lib/spinlock"] clippy = [] perf = [] period-index-propagation = ["perf"] +dvfs = [] diff --git a/awkernel_async_lib/src/task.rs b/awkernel_async_lib/src/task.rs index 7ac806ba5..2ea86196f 100644 --- a/awkernel_async_lib/src/task.rs +++ b/awkernel_async_lib/src/task.rs @@ -65,6 +65,11 @@ pub(crate) static NUM_CLUSTERED_TASKS_IN_QUEUE: AtomicU32 = AtomicU32::new(0); static PREEMPTION_REQUEST: [AtomicBool; NUM_MAX_CPU] = array![_ => AtomicBool::new(false); NUM_MAX_CPU]; +/// Per-CPU record of the idle-time frequency request. See `is_idle_min_freq_requested()`. +#[cfg(feature = "dvfs")] +static IDLE_MIN_FREQ_REQUESTED: [AtomicBool; NUM_MAX_CPU] = + array![_ => AtomicBool::new(false); NUM_MAX_CPU]; + /// Task has ID, future, information, and a reference to a scheduler. pub struct Task { pub id: u32, @@ -186,6 +191,9 @@ pub struct TaskInfo { panicked: bool, pub(crate) dag_info: Option, + #[cfg(feature = "dvfs")] + freq: Option, + #[cfg(not(feature = "no_preempt"))] thread: Option, } @@ -252,6 +260,18 @@ impl TaskInfo { pub fn get_dag_info(&self) -> Option { self.dag_info.clone() } + + #[inline(always)] + #[cfg(feature = "dvfs")] + pub fn update_freq(&mut self, freq: u64) { + self.freq = Some(freq); + } + + #[inline(always)] + #[cfg(feature = "dvfs")] + pub fn get_freq(&self) -> Option { + self.freq + } } /// State of task. @@ -294,6 +314,7 @@ impl Tasks { scheduler: &'static dyn Scheduler, mut scheduler_type: SchedulerType, dag_info: Option, + #[cfg(feature = "dvfs")] freq: Option, ) -> u32 { let mut id = self.candidate_id; loop { @@ -337,6 +358,9 @@ impl Tasks { panicked: false, dag_info, + #[cfg(feature = "dvfs")] + freq, + #[cfg(not(feature = "no_preempt"))] thread: None, }); @@ -403,7 +427,14 @@ pub fn spawn( future: impl Future + 'static + Send, sched_type: SchedulerType, ) -> u32 { - inner_spawn(name, future, sched_type, None) + inner_spawn( + name, + future, + sched_type, + None, + #[cfg(feature = "dvfs")] + None, + ) } /// Spawn a detached task with DAG information. @@ -433,7 +464,24 @@ pub fn spawn_with_dag_info( sched_type: SchedulerType, dag_info: DagInfo, ) -> u32 { - inner_spawn(name, future, sched_type, Some(dag_info)) + inner_spawn( + name, + future, + sched_type, + Some(dag_info), + #[cfg(feature = "dvfs")] + None, + ) +} + +#[cfg(feature = "dvfs")] +pub fn spawn_with_freq( + name: Cow<'static, str>, + future: impl Future + 'static + Send, + sched_type: SchedulerType, + freq: u64, +) -> u32 { + inner_spawn(name, future, sched_type, None, Some(freq)) } pub fn inner_spawn( @@ -441,6 +489,7 @@ pub fn inner_spawn( future: impl Future + 'static + Send, sched_type: SchedulerType, dag_info: Option, + #[cfg(feature = "dvfs")] freq: Option, ) -> u32 { if let SchedulerType::PrioritizedFIFO(p) | SchedulerType::PrioritizedRR(p) = sched_type { if p > HIGHEST_PRIORITY { @@ -456,7 +505,15 @@ pub fn inner_spawn( let mut node = MCSNode::new(); let mut tasks = TASKS.lock(&mut node); - let id = tasks.spawn(name, future.fuse(), scheduler, sched_type, dag_info); + let id = tasks.spawn( + name, + future.fuse(), + scheduler, + sched_type, + dag_info, + #[cfg(feature = "dvfs")] + freq, + ); let task = tasks.id_to_task.get(&id).cloned(); drop(tasks); @@ -1234,6 +1291,34 @@ pub mod perf { } } +/// Return `true` if `cpu_id` succeeded in requesting the minimum frequency +/// when it last went idle and has not run a task since then. +#[cfg(feature = "dvfs")] +pub fn is_idle_min_freq_requested(cpu_id: usize) -> bool { + IDLE_MIN_FREQ_REQUESTED[cpu_id].load(Ordering::Relaxed) +} + +/// Set the CPU frequency requested by the task to run next. +/// A task without an explicit request runs at the maximum frequency. +/// This also resets the record of the idle-time request of this CPU. +#[cfg(feature = "dvfs")] +fn apply_task_freq(cpu_id: usize, freq: Option) { + IDLE_MIN_FREQ_REQUESTED[cpu_id].store(false, Ordering::Relaxed); + + match freq { + Some(f) => { + if let Err(e) = awkernel_lib::dvfs::set_cpu_freq_clamped(f) { + log::error!("CPU#{cpu_id}: failed to set the frequency to {f} Hz: {e}"); + } + } + None => { + if let Err(e) = awkernel_lib::dvfs::set_max_cpu_freq() { + log::error!("CPU#{cpu_id}: failed to set the frequency to max: {e}"); + } + } + } +} + pub fn run_main() { loop { #[cfg(feature = "perf")] @@ -1266,8 +1351,15 @@ pub fn run_main() { perf::start_context_switch_main(); info.update_last_executed(); + + #[cfg(feature = "dvfs")] + let freq = info.get_freq(); + drop(info); + #[cfg(feature = "dvfs")] + apply_task_freq(cpu_id, freq); + unsafe { preempt::yield_and_pool(ctx) }; #[cfg(feature = "perf")] @@ -1297,6 +1389,9 @@ pub fn run_main() { continue; } + #[cfg(feature = "dvfs")] + let freq; + { let mut node = MCSNode::new(); let mut info = task.info.lock(&mut node); @@ -1307,8 +1402,16 @@ pub fn run_main() { } info.update_last_executed(); + + #[cfg(feature = "dvfs")] + { + freq = info.get_freq(); + } } + #[cfg(feature = "dvfs")] + apply_task_freq(cpu_id, freq); + // Use the primary memory allocator. #[cfg(not(feature = "std"))] unsafe { @@ -1415,6 +1518,17 @@ pub fn run_main() { #[cfg(feature = "perf")] perf::start_idle(); + // No runnable task. Lower the frequency to the minimum while idle, + // and record the result. + #[cfg(feature = "dvfs")] + { + let result = awkernel_lib::dvfs::set_min_cpu_freq(); + if let Err(e) = &result { + log::error!("CPU#{cpu_id}: failed to set the frequency to min: {e}"); + } + IDLE_MIN_FREQ_REQUESTED[cpu_id].store(result.is_ok(), Ordering::Relaxed); + } + awkernel_lib::cpu::sleep_cpu(None); } } diff --git a/awkernel_async_lib/src/task/preempt.rs b/awkernel_async_lib/src/task/preempt.rs index df30685fc..2641c2317 100644 --- a/awkernel_async_lib/src/task/preempt.rs +++ b/awkernel_async_lib/src/task/preempt.rs @@ -203,11 +203,23 @@ unsafe fn do_preemption() { current_task.clone() }; + #[cfg(feature = "dvfs")] + let freq; + if let Some(next_thread) = { let mut node = MCSNode::new(); let mut task_info = next.info.lock(&mut node); + + #[cfg(feature = "dvfs")] + { + freq = task_info.get_freq(); + } + task_info.take_preempt_context() } { + #[cfg(feature = "dvfs")] + super::apply_task_freq(cpu_id, freq); + // If the next task is a preempted task, yield to it. yield_preempted_and_wake_task(current_task, next_thread); } else { diff --git a/awkernel_lib/src/dvfs.rs b/awkernel_lib/src/dvfs.rs index e1e5e8e38..6914d3d28 100644 --- a/awkernel_lib/src/dvfs.rs +++ b/awkernel_lib/src/dvfs.rs @@ -118,6 +118,9 @@ unsafe extern "Rust" { unsafe fn __awkernel_cpu_init(cpu_id: usize) -> Result<()>; unsafe fn __awkernel_set_cpu_freq(freq: u64) -> Result<()>; unsafe fn __awkernel_set_global_freq(freq: u64) -> Result<()>; + unsafe fn __awkernel_set_cpu_freq_clamped(freq: u64) -> Result<()>; + unsafe fn __awkernel_set_max_cpu_freq() -> Result<()>; + unsafe fn __awkernel_set_min_cpu_freq() -> Result<()>; unsafe fn __awkernel_get_max_cpu_freq() -> Result; unsafe fn __awkernel_get_min_cpu_freq() -> Result; unsafe fn __awkernel_get_curr_cpu_freq() -> Result; @@ -149,6 +152,24 @@ pub unsafe fn set_global_freq(freq: u64) -> Result<()> { unsafe { __awkernel_set_global_freq(freq) } } +/// Set the frequency of the current CPU in Hz, clamped to the min and max frequencies of the CPU. +#[inline(always)] +pub fn set_cpu_freq_clamped(freq: u64) -> Result<()> { + unsafe { __awkernel_set_cpu_freq_clamped(freq) } +} + +/// Set the frequency of the current CPU to its maximum. +#[inline(always)] +pub fn set_max_cpu_freq() -> Result<()> { + unsafe { __awkernel_set_max_cpu_freq() } +} + +/// Set the frequency of the current CPU to its minimum. +#[inline(always)] +pub fn set_min_cpu_freq() -> Result<()> { + unsafe { __awkernel_set_min_cpu_freq() } +} + /// Get the maximum frequency of the current CPU in Hz. #[inline(always)] pub fn get_max_cpu_freq() -> Result { @@ -185,6 +206,24 @@ unsafe extern "Rust" fn default_set_global_freq(freq: u64) -> Result<()> { crate::arch::ArchImpl::set_global_freq(freq) } +#[linkage = "weak"] +#[export_name = "__awkernel_set_cpu_freq_clamped"] +extern "Rust" fn default_set_cpu_freq_clamped(freq: u64) -> Result<()> { + crate::arch::ArchImpl::set_cpu_freq_clamped(freq) +} + +#[linkage = "weak"] +#[export_name = "__awkernel_set_max_cpu_freq"] +extern "Rust" fn default_set_max_cpu_freq() -> Result<()> { + crate::arch::ArchImpl::set_max_cpu_freq() +} + +#[linkage = "weak"] +#[export_name = "__awkernel_set_min_cpu_freq"] +extern "Rust" fn default_set_min_cpu_freq() -> Result<()> { + crate::arch::ArchImpl::set_min_cpu_freq() +} + #[linkage = "weak"] #[export_name = "__awkernel_get_max_cpu_freq"] extern "Rust" fn default_get_max_cpu_freq() -> Result { @@ -226,6 +265,23 @@ macro_rules! impl_dvfs { unsafe { <$ty as $crate::dvfs::Dvfs>::set_global_freq(freq) } } + #[export_name = "__awkernel_set_cpu_freq_clamped"] + extern "Rust" fn __awkernel_bsp_set_cpu_freq_clamped( + freq: u64, + ) -> $crate::dvfs::Result<()> { + <$ty as $crate::dvfs::Dvfs>::set_cpu_freq_clamped(freq) + } + + #[export_name = "__awkernel_set_max_cpu_freq"] + extern "Rust" fn __awkernel_bsp_set_max_cpu_freq() -> $crate::dvfs::Result<()> { + <$ty as $crate::dvfs::Dvfs>::set_max_cpu_freq() + } + + #[export_name = "__awkernel_set_min_cpu_freq"] + extern "Rust" fn __awkernel_bsp_set_min_cpu_freq() -> $crate::dvfs::Result<()> { + <$ty as $crate::dvfs::Dvfs>::set_min_cpu_freq() + } + #[export_name = "__awkernel_get_max_cpu_freq"] extern "Rust" fn __awkernel_bsp_get_max_cpu_freq() -> $crate::dvfs::Result { <$ty as $crate::dvfs::Dvfs>::get_max_cpu_freq() diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml index 0b11ba533..51bd8937b 100644 --- a/kernel/Cargo.toml +++ b/kernel/Cargo.toml @@ -142,4 +142,4 @@ aarch64_virt = [ ] spinlock = ["awkernel_lib/spinlock"] linux = [] -dvfs = [] +dvfs = ["awkernel_async_lib/dvfs"] diff --git a/userland/Cargo.toml b/userland/Cargo.toml index 98eb2af89..8c5d574fd 100644 --- a/userland/Cargo.toml +++ b/userland/Cargo.toml @@ -90,6 +90,10 @@ optional = true path = "../applications/tests/test_edf" optional = true +[dependencies.test_dvfs_task] +path = "../applications/tests/test_dvfs_task" +optional = true + [features] default = [] perf = ["awkernel/perf", "awkernel_services/perf"] @@ -129,3 +133,4 @@ test_dvfs = ["dep:test_dvfs", "awkernel/dvfs"] test_raspi_dvfs = ["dep:test_raspi_dvfs"] test_voluntary_preemption = ["dep:test_voluntary_preemption"] test_edf = ["dep:test_edf"] +test_dvfs_task = ["dep:test_dvfs_task", "awkernel/dvfs"] diff --git a/userland/src/lib.rs b/userland/src/lib.rs index a21a1450c..1b43acf94 100644 --- a/userland/src/lib.rs +++ b/userland/src/lib.rs @@ -59,5 +59,8 @@ pub async fn run() -> Result<(), Cow<'static, str>> { #[cfg(feature = "test_edf")] test_edf::run().await; // test for EDF scheduler + #[cfg(feature = "test_dvfs_task")] + test_dvfs_task::run().await; // test for per-task frequency + Ok(()) }