diff --git a/applications/tests/test_llft/Cargo.toml b/applications/tests/test_llft/Cargo.toml new file mode 100644 index 000000000..a5567b3e6 --- /dev/null +++ b/applications/tests/test_llft/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "test_llft" +version = "0.1.0" +edition = "2021" + +[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_llft/src/lib.rs b/applications/tests/test_llft/src/lib.rs new file mode 100644 index 000000000..7d3e79447 --- /dev/null +++ b/applications/tests/test_llft/src/lib.rs @@ -0,0 +1,164 @@ +#![no_std] + +extern crate alloc; + +use alloc::{borrow::Cow, vec}; +use awkernel_async_lib::{ + dag::{create_dag, finish_create_dags}, + scheduler::SchedulerType, + sleep, +}; +use awkernel_lib::cpu::{cpu_id, num_cpu, CpuSet}; +use core::{ + sync::atomic::{AtomicU8, Ordering}, + time::Duration, +}; + +// 0: warming up, 1: observing, 2: pass, 3: fail. +static PHASE: AtomicU8 = AtomicU8::new(0); +// 0: neither branch, 1: early branch, 2: early then late, 3: wrong order/CPU. +static ORDER: AtomicU8 = AtomicU8::new(0); + +fn record_branch(expected: u8, next: u8) { + if PHASE.load(Ordering::Acquire) != 1 { + return; + } + + if cpu_id() != 1 + || ORDER + .compare_exchange(expected, next, Ordering::AcqRel, Ordering::Acquire) + .is_err() + { + ORDER.store(3, Ordering::Release); + } +} + +/// Exercise LLFT on one worker and report success only after the sink runs. +/// +/// ```text +/// +--> llft_late (10 ms) --------------------------+ +/// source (1 ms) --+ +--> sink (10 ms) +/// +--> llft_early (10 ms) --> llft_tail (200 ms) --+ +/// ``` +/// +/// # Errors +/// +/// Returns an error if the DAG cannot be created or completed, its timing +/// estimates are unexpected, or the observed branch order or CPU is wrong. +pub async fn run() -> Result<(), Cow<'static, str>> { + if num_cpu() < 2 { + return Err("test_llft requires at least two CPUs".into()); + } + + let cpu = CpuSet::empty().with(1); + let llft = SchedulerType::LLFT(1_000_000, cpu); + let dag = create_dag(); + + dag.register_periodic_reactor::<_, (u8, u8)>( + "llft_source".into(), + || (0, 0), + vec!["llft_late_input".into(), "llft_early_input".into()], + llft, + Duration::from_secs(3), + Some(Duration::from_millis(1)), + ) + .await; + + dag.register_reactor::<_, (u8,), (u8,)>( + "llft_late".into(), + |(value,)| { + record_branch(1, 2); + (value,) + }, + vec!["llft_late_input".into()], + vec!["llft_late_output".into()], + llft, + Some(Duration::from_millis(10)), + ) + .await; + + dag.register_reactor::<_, (u8,), (u8,)>( + "llft_early".into(), + |(value,)| { + record_branch(0, 1); + (value,) + }, + vec!["llft_early_input".into()], + vec!["llft_early_output".into()], + llft, + Some(Duration::from_millis(10)), + ) + .await; + + dag.register_reactor::<_, (u8,), (u8,)>( + "llft_tail".into(), + |(value,)| (value,), + vec!["llft_early_output".into()], + vec!["llft_tail_output".into()], + llft, + Some(Duration::from_millis(200)), + ) + .await; + + dag.register_sink_reactor::<_, (u8, u8)>( + "llft_sink".into(), + |(_, _)| match PHASE.load(Ordering::Acquire) { + // The first complete job ensures both branches have received once + // and returned to their waiting state before the observed release. + 0 => PHASE.store(1, Ordering::Release), + 1 => { + let result = if cpu_id() == 1 && ORDER.load(Ordering::Acquire) == 2 { + 2 + } else { + 3 + }; + PHASE.store(result, Ordering::Release); + } + _ => {} + }, + vec!["llft_late_output".into(), "llft_tail_output".into()], + llft, + Duration::from_secs(1), + Some(Duration::from_millis(10)), + ) + .await; + + if let Err(errors) = finish_create_dags(core::slice::from_ref(&dag)).await { + for error in errors { + log::error!("test_llft: DAG creation failed: {error}"); + } + return Err("test_llft: DAG creation failed".into()); + } + + // Registration order fixes node IDs: source=0, late=1, early=2. + // With a 1000ms deadline, 10ms sink and 200ms early tail, + // latest finishes are 990ms (late) and 790ms (early). + let late = dag + .timing_info(1) + .map_err(|error| alloc::format!("test_llft: {error}"))?; + let early = dag + .timing_info(2) + .map_err(|error| alloc::format!("test_llft: {error}"))?; + if late.latest_finish() != Duration::from_millis(990) + || early.latest_finish() != Duration::from_millis(790) + { + return Err("test_llft: unexpected latest-finish estimates".into()); + } + + // Bounded wait is only a liveness timeout; the verdict comes from the + // recorded branch order and the second sink invocation, not elapsed time. + for _ in 0..100 { + match PHASE.load(Ordering::Acquire) { + 2 => { + log::info!("test_llft: early then late on CPU 1; DAG completed [OK]"); + return Ok(()); + } + 3 => return Err("test_llft: wrong branch order or CPU [FAIL]".into()), + _ => {} + } + // This sleep is owned and awaited here; no caller can cancel it. + sleep(Duration::from_millis(100)).await; + } + + Err("test_llft: timed out waiting for DAG completion [FAIL]".into()) +} diff --git a/awkernel_async_lib/src/dag.rs b/awkernel_async_lib/src/dag.rs index cf588d13c..fbb5c6be3 100644 --- a/awkernel_async_lib/src/dag.rs +++ b/awkernel_async_lib/src/dag.rs @@ -41,8 +41,8 @@ //! by DAG validation, which rejects estimates whose longest dependency path exceeds the sink's //! relative deadline. //! -//! WCET estimates are used for feasibility validation only. They do not change interval-tick job -//! release times or the DAG deadline assignment used by the EDF scheduler. +//! Validation also records [`TimingInfo`] for each node. These estimates do not change interval-tick +//! job release times or the DAG deadline assignment used by the EDF scheduler. //! //! # Example Usage //! @@ -141,6 +141,7 @@ impl_tuple_size!(T1, T2, T3); #[derive(Clone, Debug)] pub enum DagError { NodeNotFound(u32, usize), + MissingNodeTiming(u32, usize), MissingSinkDeadline(u32), InfeasibleWcet { dag_id: u32, @@ -168,6 +169,7 @@ impl core::fmt::Display for DagError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { DagError::NodeNotFound(dag_id, node_id) => write!(f, "DAG#{dag_id} Node#{node_id} not found"), + DagError::MissingNodeTiming(dag_id, node_id) => write!(f, "DAG#{dag_id} Node#{node_id} timing has not been analyzed"), DagError::MissingSinkDeadline(dag_id) => write!(f, "DAG#{dag_id} has no sink relative deadline"), DagError::InfeasibleWcet { dag_id, critical_path: Some(critical_path), deadline } => { write!(f, "DAG#{dag_id}: estimated critical path {critical_path:?} exceeds sink relative deadline {deadline:?}") @@ -221,6 +223,15 @@ pub(crate) struct JobInfo { } impl DagGraph { + /// Whenever the relative deadlines of nodes are updated, clear the cached timing information. + fn clear_timing(&mut self) { + for idx in self.node_indices() { + if let Some(info) = self.node_weight_mut(idx) { + info.timing = None; + } + } + } + #[inline] fn get_sink_relative_deadline(&self) -> Option { let sink_node_index = self.externals(Direction::Outgoing).next()?; @@ -232,6 +243,7 @@ impl DagGraph { match self.node_weight_mut(node_idx) { Some(info) => { info.relative_deadline = Some(deadline); + self.clear_timing(); true } None => false, @@ -285,6 +297,19 @@ impl Dag { .ok_or(DagError::MissingSinkDeadline(self.id)) } + /// Returns the estimates computed during DAG validation for a node ID from [`DagInfo`]. + /// Analysis is invalidated when the graph or its sink deadline changes. + pub fn timing_info(&self, node_id: u32) -> Result { + let mut node = MCSNode::new(); + let graph = self.graph.lock(&mut node); + let index = to_node_index(node_id); + graph + .node_weight(index) + .ok_or(DagError::NodeNotFound(self.id, index.index()))? + .timing + .ok_or(DagError::MissingNodeTiming(self.id, index.index())) + } + fn set_relative_deadline( &self, node_idx: NodeIndex, @@ -310,12 +335,14 @@ impl Dag { publish_topic_names: publish_topic_names.to_vec(), relative_deadline: None, wcet, + timing: None, num_finished: 0, deadline_job: None, }; let mut node = MCSNode::new(); let mut graph = self.graph.lock(&mut node); + graph.clear_timing(); let add_node_idx = graph.add_node(add_node_info); let subscribe_topic_set: BTreeSet<_> = subscribe_topic_names.iter().collect(); @@ -706,12 +733,69 @@ impl PendingTask { } } +/// WCET-based estimates relative to the DAG job release, not timing requirements. +/// A missing WCET is retained as zero for the estimates. +/// +/// This struct is useful for analyzing the timing characteristics of nodes within a DAG, +/// as well as for defining alternative scheduling strategies based on timing estimates. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TimingInfo { + estimated_wcet: Duration, + earliest_start: Duration, + latest_finish: Duration, + is_in_critical_path: bool, +} + +impl TimingInfo { + /// WCET used in the analysis. + #[inline] + pub const fn estimated_wcet(&self) -> Duration { + self.estimated_wcet + } + + /// Longest estimated execution path leading up to the node. + #[inline] + pub const fn earliest_start(&self) -> Duration { + self.earliest_start + } + + /// Earliest start plus the node's estimated WCET. + #[inline] + pub fn earliest_finish(&self) -> Duration { + self.earliest_start + self.estimated_wcet() + } + + /// Latest finish minus the node's estimated WCET. + #[inline] + pub fn latest_start(&self) -> Duration { + self.latest_finish - self.estimated_wcet() + } + + /// Latest finish compatible with the sink deadline and successor WCETs. + pub const fn latest_finish(&self) -> Duration { + self.latest_finish + } + + /// Latest finish minus earliest finish; this is static, not runtime laxity. + #[inline] + pub fn slack(&self) -> Duration { + self.latest_finish - self.earliest_finish() + } + + /// True for every node on any longest estimated WCET path. + #[inline] + pub fn is_in_critical_path(&self) -> bool { + self.is_in_critical_path + } +} + struct NodeInfo { task_id: u32, subscribe_topic_names: Vec>, publish_topic_names: Vec>, relative_deadline: Option, wcet: Option, + timing: Option, num_finished: u64, // Number of DAG jobs that this node finished. deadline_job: Option, // Job whose deadline the last wake of this node got. } @@ -823,6 +907,39 @@ pub(crate) fn calculate_and_update_dag_deadline( ) } +/// Return the latest-finish ordering time for an already released job. +/// +/// The caller must first use `calculate_and_update_dag_deadline` so the same +/// source-release and deadline bookkeeping as EDF takes place. No job is released here. +/// Missing job/timing means the scheduler falls back to the real deadline. +fn released_job_latest_finish(dag_info: &DagInfo) -> Option { + let dag = get_dag(dag_info.dag_id)?; + let job = dag.get_or_release_job(to_node_index(dag_info.node_id), false)?; + match dag.timing_info(dag_info.node_id) { + Ok(timing) => { + let offset = timing.latest_finish().as_micros() as u64; + Some(job.release_time + offset) + } + Err(_) => None, + } +} + +/// Keep the real deadline separate from the latest-finish ordering key. +/// If the job or timing is unavailable, or the key overflows, order by the +/// real deadline until explicit error reporting is supported. +pub(crate) fn calculate_dag_latest_finish_priority( + dag_info: &DagInfo, + wake_time: u64, + state: State, +) -> (u64, u64) { + let deadline = calculate_and_update_dag_deadline(dag_info, wake_time, state); + let ordering_time = match released_job_latest_finish(dag_info) { + Some(latest_finish) => latest_finish, + None => deadline, + }; + (deadline, ordering_time) +} + pub async fn finish_create_dags(dags: &[Arc]) -> Result<(), Vec> { match validate_all_rules(dags) { Ok(()) => { @@ -966,15 +1083,17 @@ fn validate_dag(dag: &Dag) -> Result<(), DagError> { Ok(()) } -/// Checks whether the longest declared WCET path fits within the sink's relative deadline. +/// Checks feasibility and calculates node timing estimates. /// This runs during DAG setup, not in the scheduler or reactor execution paths. /// /// A forward pass computes `EF(v) = max(EF(p)) + C(v)` over predecessors, including the /// sink's own WCET. +/// +/// A fn compute_timing(dag: &Dag) -> Result<(), DagError> { let dag_id = dag.id; let mut node = MCSNode::new(); - let graph = dag.graph.lock(&mut node); + let mut graph = dag.graph.lock(&mut node); let sink_deadline = graph .get_sink_relative_deadline() .ok_or(DagError::MissingSinkDeadline(dag_id))?; @@ -988,11 +1107,12 @@ fn compute_timing(dag: &Dag) -> Result<(), DagError> { DfsEvent::BackEdge(_, _) => Err(DagError::ContainsCycle(dag_id)), _ => Ok(()), })?; + + // Forward pass to compute earliest finish and critical path length let mut earliest_finish: Vec = graph .node_references() .map(|(_, info)| info.wcet.unwrap_or(Duration::ZERO)) .collect(); - let mut critical_path = Duration::ZERO; for &idx in order.iter().rev() { let mut start = Duration::ZERO; @@ -1008,11 +1128,40 @@ fn compute_timing(dag: &Dag) -> Result<(), DagError> { })?; critical_path = critical_path.max(*finish); } + + let invalid_path = || DagError::InfeasibleWcet { + dag_id, + critical_path: Some(critical_path), + deadline: sink_deadline, + }; + if critical_path > sink_deadline { - return Err(DagError::InfeasibleWcet { - dag_id, - critical_path: Some(critical_path), - deadline: sink_deadline, + return Err(invalid_path()); + } + let critical_slack = sink_deadline - critical_path; + + // Backward pass to compute latest start times and timing estimates for each node + // No overflow or node ID checks needed, as forward pass already ensures times are feasible + let mut latest_start: Vec = graph.node_references().map(|_| sink_deadline).collect(); + for idx in order { + let mut latest_finish = sink_deadline; + for successor in graph.neighbors_directed(idx, Direction::Outgoing) { + let start = latest_start[successor.index()]; + latest_finish = latest_finish.min(start); + } + let info = graph.node_weight_mut(idx).unwrap(); + + let estimated_wcet = info.wcet.unwrap_or(Duration::ZERO); + let earliest_finish = earliest_finish[idx.index()]; + let earliest_start = earliest_finish - estimated_wcet; + let slack = latest_finish - earliest_finish; + + latest_start[idx.index()] = latest_finish - estimated_wcet; + info.timing = Some(TimingInfo { + estimated_wcet, + earliest_start, + latest_finish, + is_in_critical_path: slack == critical_slack, }); } @@ -1729,6 +1878,61 @@ mod tests { (dag, [source, middle, sink]) } + #[test] + fn latest_finish_priority_tracks_each_released_job_and_keeps_real_deadline() { + let ms = Duration::from_millis; + let (dag, [source, middle, sink]) = + timing_chain([Some(ms(10)), Some(ms(20)), Some(ms(30))]); + compute_timing(&dag).unwrap(); + let info = |index: NodeIndex| DagInfo { + dag_id: dag.id, + node_id: u32::try_from(index.index()).unwrap(), + }; + let source_info = info(source); + let middle_info = info(middle); + let sink_info = info(sink); + + // Before release, the real deadline also supplies the ordering key. + assert_eq!( + calculate_dag_latest_finish_priority(&middle_info, 5, State::Waiting), + (100_005, 100_005) + ); + dag.set_next_release_time(Instant::zero() + Duration::from_micros(1_000)); + assert_eq!( + calculate_dag_latest_finish_priority(&source_info, 1_100, State::Waiting), + (101_000, 51_000) + ); + assert_eq!( + calculate_dag_latest_finish_priority(&middle_info, 1_200, State::Waiting), + (101_000, 71_000) + ); + assert_eq!( + calculate_dag_latest_finish_priority(&sink_info, 1_300, State::Waiting), + (101_000, 101_000) + ); + assert_eq!( + calculate_dag_latest_finish_priority(&source_info, 1_400, State::Preempted), + (101_000, 51_000) + ); + + dag.finish_job(source); + dag.set_next_release_time(Instant::zero() + Duration::from_micros(2_000)); + assert_eq!( + calculate_dag_latest_finish_priority(&source_info, 2_100, State::Waiting), + (102_000, 52_000) + ); + // The middle node is still processing the earlier job. + assert_eq!( + calculate_dag_latest_finish_priority(&middle_info, 2_200, State::Waiting), + (101_000, 71_000) + ); + dag.set_relative_deadline(sink, ms(120)).unwrap(); + assert_eq!( + calculate_dag_latest_finish_priority(&middle_info, 2_300, State::Waiting), + (101_000, 101_000) + ); + } + fn timing_diamond(wcets: [Option; 4]) -> (Arc, [NodeIndex; 4]) { let dag = create_dag(); let source_to_a: Cow<'static, str> = alloc::format!("timing_{}_source_a", dag.id).into(); @@ -1778,16 +1982,25 @@ mod tests { &[], Some(Duration::from_millis(30)), ); - dag.add_node_with_topic_edges( + let middle = dag.add_node_with_topic_edges( core::slice::from_ref(&source_topic), core::slice::from_ref(&sink_topic), Some(Duration::from_millis(20)), ); - dag.add_node_with_topic_edges(&[], &[source_topic], Some(Duration::from_millis(10))); + let source = + dag.add_node_with_topic_edges(&[], &[source_topic], Some(Duration::from_millis(10))); dag.set_relative_deadline(sink, Duration::from_millis(60)) .unwrap(); compute_timing(&dag).unwrap(); + let timing = |idx: NodeIndex| { + dag.timing_info(u32::try_from(idx.index()).unwrap()) + .unwrap() + }; + assert_eq!(timing(source).earliest_start(), Duration::ZERO); + assert_eq!(timing(middle).earliest_finish(), Duration::from_millis(30)); + assert_eq!(timing(middle).latest_finish(), Duration::from_millis(30)); + assert_eq!(timing(sink).latest_finish(), Duration::from_millis(60)); dag.set_relative_deadline(sink, Duration::from_millis(59)) .unwrap(); @@ -2023,4 +2236,72 @@ mod tests { assert_eq!(graph.node_weight(absent).unwrap().wcet, None); assert_eq!(graph.node_weight(zero).unwrap().wcet, Some(Duration::ZERO)); } + + #[test] + fn timing_estimates_identify_critical_and_short_branches() { + let ms = Duration::from_millis; + let (dag, [source, long, short, sink]) = + timing_diamond([Some(ms(10)), Some(ms(60)), Some(ms(30)), Some(ms(20))]); + compute_timing(&dag).unwrap(); + let info = |idx: NodeIndex| { + dag.timing_info(u32::try_from(idx.index()).unwrap()) + .unwrap() + }; + + let long = info(long); + assert_eq!( + (long.earliest_start(), long.earliest_finish()), + (ms(10), ms(70)) + ); + assert_eq!( + (long.latest_start(), long.latest_finish()), + (ms(20), ms(80)) + ); + assert_eq!(long.slack(), ms(10)); + assert!(long.is_in_critical_path()); + + let short = info(short); + assert_eq!( + (short.earliest_start(), short.earliest_finish()), + (ms(10), ms(40)) + ); + assert_eq!( + (short.latest_start(), short.latest_finish()), + (ms(50), ms(80)) + ); + assert_eq!(short.slack(), ms(40)); + assert!(!short.is_in_critical_path()); + assert!(info(source).is_in_critical_path()); + assert!(info(sink).is_in_critical_path()); + } + + #[test] + fn equal_critical_paths_and_missing_wcet_are_preserved() { + let ms = Duration::from_millis; + let (dag, [_, a, b, sink]) = + timing_diamond([None, Some(ms(20)), Some(ms(20)), Some(Duration::ZERO)]); + compute_timing(&dag).unwrap(); + let info = |idx: NodeIndex| { + dag.timing_info(u32::try_from(idx.index()).unwrap()) + .unwrap() + }; + assert!(info(a).is_in_critical_path()); + assert!(info(b).is_in_critical_path()); + assert_eq!(info(sink).estimated_wcet(), Duration::ZERO); + let source = dag.get_source_nodes()[0]; + assert_eq!(info(source).estimated_wcet(), Duration::ZERO); + assert_eq!(info(source).estimated_wcet(), Duration::ZERO); + assert_eq!(info(source).earliest_finish(), Duration::ZERO); + } + + #[test] + fn changed_deadline_invalidates_previously_computed_timing() { + let (dag, [source, _, sink]) = timing_chain([None, None, None]); + compute_timing(&dag).unwrap(); + dag.set_relative_deadline(sink, Duration::ZERO).unwrap(); + assert!(matches!( + dag.timing_info(u32::try_from(source.index()).unwrap()), + Err(DagError::MissingNodeTiming(_, _)) + )); + } } diff --git a/awkernel_async_lib/src/scheduler.rs b/awkernel_async_lib/src/scheduler.rs index 112e73dd2..74237fdf4 100644 --- a/awkernel_async_lib/src/scheduler.rs +++ b/awkernel_async_lib/src/scheduler.rs @@ -22,6 +22,7 @@ use alloc::boxed::Box; mod clustered; mod edf; +mod llft; pub(super) mod panicked; mod prioritized_fifo; mod prioritized_rr; @@ -76,7 +77,7 @@ pub fn move_preemption_pending(cpu_id: usize) -> Option>> { /// 0 is the lowest priority and 31 is the highest priority. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SchedulerType { - /// EDF: `(relative_deadline, cpu_set)`. + /// Earliest Deadline First (EDF): `(relative_deadline, cpu_set)`. /// /// `cpu_set` is the set of cores the task may run on. It is normalized at /// spawn time: CPU 0 (the primary core) and any out-of-range bits are @@ -88,6 +89,12 @@ pub enum SchedulerType { /// `CpuSet::all()` gives global EDF, and a one-core set gives /// partitioned EDF. EDF(u64, CpuSet), + /// Least Latest Finish Time (LLFT): `(relative_deadline, cpu_set)`. + /// + /// DAG tasks are ordered by their estimated latest finish; standalone + /// tasks use their relative deadline in microseconds. Affinity is + /// normalized in the same way as for EDF. + LLFT(u64, CpuSet), PrioritizedFIFO(u8), PrioritizedRR(u8), Panicked, @@ -98,6 +105,7 @@ impl SchedulerType { matches!( (self, other), (SchedulerType::EDF(_, _), SchedulerType::EDF(_, _)) + | (SchedulerType::LLFT(_, _), SchedulerType::LLFT(_, _)) | ( SchedulerType::PrioritizedFIFO(_), SchedulerType::PrioritizedFIFO(_) @@ -110,13 +118,13 @@ impl SchedulerType { ) } - /// Return the CPU affinity set if this is a [`SchedulerType::EDF`] scheduler. + /// Return the CPU affinity set for a clustered scheduler. /// /// Returns `Some(set)` where `set` is the set of CPU cores (`1..num_cpu()`) the task /// may run on. Returns `None` for all other scheduler variants. pub const fn cpu_set(&self) -> Option { match self { - SchedulerType::EDF(_, set) => Some(*set), + SchedulerType::EDF(_, set) | SchedulerType::LLFT(_, set) => Some(*set), _ => None, } } @@ -126,7 +134,7 @@ impl SchedulerType { /// scheduler; it is the single source of truth for the clustered prefix /// of `PRIORITY_LIST`. pub const fn is_clustered(&self) -> bool { - matches!(self, SchedulerType::EDF(_, _)) + matches!(self, SchedulerType::EDF(_, _) | SchedulerType::LLFT(_, _)) } } @@ -137,13 +145,16 @@ impl SchedulerType { /// - The highest priority. /// - EDF scheduler. /// - The second highest priority. -/// - Prioritized FIFO scheduler. +/// - LLFT scheduler. /// - The third highest priority. +/// - Prioritized FIFO scheduler. +/// - The fourth highest priority. /// - Prioritized Round-Robin scheduler. /// - The lowest priority. /// - Panicked scheduler. -static PRIORITY_LIST: [SchedulerType; 4] = [ +static PRIORITY_LIST: [SchedulerType; 5] = [ SchedulerType::EDF(0, CpuSet::empty()), + SchedulerType::LLFT(0, CpuSet::empty()), SchedulerType::PrioritizedFIFO(0), SchedulerType::PrioritizedRR(0), SchedulerType::Panicked, @@ -374,6 +385,7 @@ pub(crate) fn get_scheduler(sched_type: &SchedulerType) -> &'static dyn Schedule SchedulerType::PrioritizedFIFO(_) => &prioritized_fifo::SCHEDULER, SchedulerType::PrioritizedRR(_) => &prioritized_rr::SCHEDULER, SchedulerType::EDF(_, _) => &edf::SCHEDULER, + SchedulerType::LLFT(_, _) => &llft::SCHEDULER, SchedulerType::Panicked => &panicked::SCHEDULER, } } diff --git a/awkernel_async_lib/src/scheduler/llft.rs b/awkernel_async_lib/src/scheduler/llft.rs new file mode 100644 index 000000000..6df050b1c --- /dev/null +++ b/awkernel_async_lib/src/scheduler/llft.rs @@ -0,0 +1,66 @@ +//! Least latest finish time first, distinct from the real job deadline. + +use super::{ + clustered::{ClusteredOrdering, ClusteredScheduler}, + SchedulerType, +}; +use crate::{dag::calculate_dag_latest_finish_priority, task::TaskInfo}; +use awkernel_lib::cpu::CpuSet; + +pub(super) struct LeastLatestFinish; + +pub(super) static SCHEDULER: ClusteredScheduler = ClusteredScheduler::new(); + +impl ClusteredOrdering for LeastLatestFinish { + const KIND: SchedulerType = SchedulerType::LLFT(0, CpuSet::empty()); + + fn ready_priority(info: &TaskInfo, wake_time: u64) -> (u64, u64) { + let SchedulerType::LLFT(relative_deadline, _) = info.scheduler_type else { + unreachable!("non-LLFT task routed to LLFT"); + }; + match &info.dag_info { + Some(dag_info) => calculate_dag_latest_finish_priority(dag_info, wake_time, info.state), + None => { + let deadline = wake_time + relative_deadline; + (deadline, deadline) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::scheduler::get_priority; + use affinity_btree_queue::{AffinityBTreeQueue, DEFAULT_MIN_DEGREE}; + use awkernel_lib::cpu::CPU_SET_WORDS; + + #[test] + fn clustered_policy_is_distinct_and_below_edf() { + let edf = SchedulerType::EDF(10, CpuSet::all()); + let latest = SchedulerType::LLFT(10, CpuSet::all()); + assert!(!latest.equals(&edf)); + assert!(latest.equals(&SchedulerType::LLFT(20, CpuSet::empty()))); + assert!(latest.is_clustered()); + assert_eq!(latest.cpu_set(), Some(CpuSet::all())); + assert!(get_priority(&edf) > get_priority(&latest)); + assert!(get_priority(&latest) > get_priority(&SchedulerType::PrioritizedFIFO(0))); + } + + #[test] + fn affinity_queue_orders_latest_finish_then_wake_time() { + let mut queue = + AffinityBTreeQueue::<(u64, u64), &str, DEFAULT_MIN_DEGREE, CPU_SET_WORDS>::new(3); + let worker_one = CpuSet::empty().with(1); + let worker_two = CpuSet::empty().with(2); + queue.push((50, 20), worker_one, "later wake").unwrap(); + queue.push((70, 5), worker_one, "later finish").unwrap(); + queue.push((50, 10), worker_one, "earlier wake").unwrap(); + queue.push((40, 1), worker_two, "other CPU").unwrap(); + + assert_eq!(queue.pop_for_cpu(1).unwrap().2, "earlier wake"); + assert_eq!(queue.pop_for_cpu(1).unwrap().2, "later wake"); + assert_eq!(queue.pop_for_cpu(1).unwrap().2, "later finish"); + assert_eq!(queue.pop_for_cpu(2).unwrap().2, "other CPU"); + } +} diff --git a/awkernel_async_lib/src/task.rs b/awkernel_async_lib/src/task.rs index 7b9a926ff..60e19a395 100644 --- a/awkernel_async_lib/src/task.rs +++ b/awkernel_async_lib/src/task.rs @@ -300,7 +300,7 @@ impl Tasks { if let btree_map::Entry::Vacant(e) = self.id_to_task.entry(id) { // Validate and normalise the CPU set before creating TaskInfo so that // info.scheduler_type and task.cpu_set stay in sync. - let cpu_set = if let SchedulerType::EDF(deadline, set) = scheduler_type { + let cpu_set = if let Some(set) = scheduler_type.cpu_set() { // CPU 0 is the primary core and cannot run clustered tasks. let masked = masked_workers(set, num_cpu()); let normalized = if masked.is_empty() { @@ -315,7 +315,13 @@ impl Tasks { } else { masked }; - scheduler_type = SchedulerType::EDF(deadline, normalized); + scheduler_type = match scheduler_type { + SchedulerType::EDF(deadline, _) => SchedulerType::EDF(deadline, normalized), + SchedulerType::LLFT(deadline, _) => { + SchedulerType::LLFT(deadline, normalized) + } + other => other, + }; Some(normalized) } else { None diff --git a/mdbook/src/internal/scheduler.md b/mdbook/src/internal/scheduler.md index 29125ccb5..d349fd859 100644 --- a/mdbook/src/internal/scheduler.md +++ b/mdbook/src/internal/scheduler.md @@ -31,6 +31,7 @@ There are several functions regarding the scheduler in [awkernel_async_lib/src/s ```rust pub enum SchedulerType { EDF(u64, CpuSet), // relative deadline and CPU affinity set + LLFT(u64, CpuSet), // relative deadline and CPU affinity set PrioritizedFIFO(u8), PrioritizedRR(u8), Panicked, @@ -62,7 +63,7 @@ Some schedulers are implemented under the folder [awkernel_async_lib/src/schedul ```shell $ ls awkernel_async_lib/src/scheduler -> clustered.rs edf.rs panicked.rs prioritized_fifo.rs prioritized_rr.rs +> clustered.rs llft.rs edf.rs panicked.rs prioritized_fifo.rs prioritized_rr.rs ``` A scheduler can be implemented by implementing `Scheduler` Trait. @@ -88,6 +89,23 @@ Bookkeeping for sleeping workers uses two pieces of state. A single global count A new clustered scheduler should use `ClusteredScheduler` for the affinity-aware queue, `ClusteredTask` queue accounting, and `queued_cpu_mask()` implementation, and implement `ClusteredOrdering` to provide its scheduler type and ready-task ordering. It must still be placed in the clustered prefix of `PRIORITY_LIST` and matched by `SchedulerType::is_clustered()`; the prefix requirement is enforced at compile time. +### Least Latest Finish Time (LLFT) Scheduler + +`SchedulerType::LLFT(relative_deadline, cpu_set)` schedules the **earliest** estimated +latest finish first. It shares EDF's clustered queue, affinity normalization, wake-time +tie-breaker and preemption mechanism. EDF has higher scheduler priority; it wins when +both policies have runnable work on the same worker. + +For a released DAG job, the ordering key is its source tick target plus the node's +validated `TimingInfo::latest_finish()` offset, converted to microseconds by truncation. +The real job deadline is still stored in task information and remains the source release +plus the sink deadline, as in EDF. Overlapping jobs use the release of the job that the +node is processing. Standalone tasks use wake time plus their configured relative +deadline for both ordering and the real deadline. + +A DAG wake without a released job or valid timing, or whose latest-finish key cannot be +represented, falls back to its real deadline as the ordering key. + ### PrioritizedFIFO Scheduler The PrioritizedFIFO scheduler is implemented in [prioritized_fifo.rs](https://github.com/tier4/awkernel/blob/main/awkernel_async_lib/src/scheduler/prioritized_fifo.rs). This scheduler provides fixed-priority scheduling where tasks are executed in First-In-First-Out order within each priority level. diff --git a/userland/Cargo.toml b/userland/Cargo.toml index 98eb2af89..8c94cc223 100644 --- a/userland/Cargo.toml +++ b/userland/Cargo.toml @@ -90,6 +90,10 @@ optional = true path = "../applications/tests/test_edf" optional = true +[dependencies.test_llft] +path = "../applications/tests/test_llft" +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_llft = ["dep:test_llft"] diff --git a/userland/src/lib.rs b/userland/src/lib.rs index e376f8ded..029baeb0f 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_llft")] + test_llft::run().await?; + Ok(()) }