Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-kernel/src/scheduler.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-kernel / src / scheduler.rs` 395 lines ยท 14441 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! Host-testable CPU placement and fair run-queue policy. 17 //! 18 //! MADT efficiency classes use lower numbers for more efficient cores. This 19 //! module treats larger class numbers as faster cores and has no hardware 20 //! dependencies. A caller supplies the enabled CPU classes explicitly. 21 22 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] 23 pub enum TaskPriority { 24 Background, 25 Normal, 26 Latency, 27 } 28 29 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 30 pub struct Task { 31 pub id: u32, 32 pub priority: TaskPriority, 33 pub cpu: usize, 34 pub ticks: u64, 35 } 36 37 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 38 pub enum SchedulerError { 39 NoCpus, 40 Full, 41 DuplicateTask, 42 InvalidCpu, 43 UnknownTask, 44 } 45 46 /// Fixed-capacity scheduler. `CLASSES` maps CPU index to its MADT class. 47 /// Queue storage and task accounting are bounded by `TASKS`. 48 pub struct Scheduler { 49 classes: [u8; CPUS], 50 tasks: [Option; TASKS], 51 queues: [[Option; TASKS]; CPUS], 52 queue_len: [usize; CPUS], 53 background_wait_ticks: [usize; CPUS], 54 background_interval: usize, 55 cursor: usize, 56 } 57 58 impl Scheduler { 59 /// Create a scheduler that reserves one tick for waiting Background work 60 /// in every eight contested ticks. 61 pub const fn new(classes: [u8; CPUS]) -> Self { 62 Self::with_background_interval(classes, 8) 63 } 64 65 /// Set the maximum number of consecutive contested ticks before a 66 /// Background task receives a slot. Values below one are treated as one. 67 pub const fn with_background_interval(classes: [u8; CPUS], background_interval: usize) -> Self { 68 Self { 69 classes, 70 tasks: [None; TASKS], 71 queues: [[None; TASKS]; CPUS], 72 queue_len: [0; CPUS], 73 background_wait_ticks: [0; CPUS], 74 background_interval: if background_interval == 0 { 75 1 76 } else { 77 background_interval 78 }, 79 cursor: 0, 80 } 81 } 82 83 pub fn place(&self, priority: TaskPriority) -> Result { 84 if CPUS == 0 { 85 return Err(SchedulerError::NoCpus); 86 } 87 let best_class = match priority { 88 TaskPriority::Latency => *self.classes.iter().max().unwrap(), 89 TaskPriority::Background => *self.classes.iter().min().unwrap(), 90 TaskPriority::Normal => { 91 let start = self.cursor % CPUS; 92 return (0..CPUS) 93 .map(|offset| (start + offset) % CPUS) 94 .min_by_key(|cpu| self.queue_len[*cpu]) 95 .ok_or(SchedulerError::NoCpus); 96 } 97 }; 98 let start = self.cursor % CPUS; 99 for offset in 0..CPUS { 100 let cpu = (start + offset) % CPUS; 101 if self.classes[cpu] == best_class { 102 return Ok(cpu); 103 } 104 } 105 unreachable!() 106 } 107 108 pub fn enqueue(&mut self, id: u32, priority: TaskPriority) -> Result { 109 if self.tasks.iter().flatten().any(|task| task.id == id) { 110 return Err(SchedulerError::DuplicateTask); 111 } 112 let slot = self 113 .tasks 114 .iter() 115 .position(Option::is_none) 116 .ok_or(SchedulerError::Full)?; 117 let cpu = self.place(priority)?; 118 self.cursor = (cpu + 1) % CPUS; 119 let queue_slot = self.queue_len[cpu]; 120 self.queues[cpu][queue_slot] = Some(slot); 121 self.queue_len[cpu] += 1; 122 self.tasks[slot] = Some(Task { 123 id, 124 priority, 125 cpu, 126 ticks: 0, 127 }); 128 Ok(cpu) 129 } 130 131 /// Remove a task (e.g. a thread that has finished) from its run queue and 132 /// free its slot so the ID and slot can be reused. Searches every CPU's 133 /// queue because work stealing may have moved it. 134 pub fn remove(&mut self, id: u32) -> Result<(), SchedulerError> { 135 let slot = self 136 .tasks 137 .iter() 138 .position(|task| task.is_some_and(|t| t.id == id)) 139 .ok_or(SchedulerError::UnknownTask)?; 140 for cpu in 0..CPUS { 141 let len = self.queue_len[cpu]; 142 if let Some(at) = self.queues[cpu][..len] 143 .iter() 144 .position(|q| *q == Some(slot)) 145 { 146 for i in at..len - 1 { 147 self.queues[cpu][i] = self.queues[cpu][i + 1]; 148 } 149 self.queues[cpu][len - 1] = None; 150 self.queue_len[cpu] = len - 1; 151 break; 152 } 153 } 154 self.tasks[slot] = None; 155 Ok(()) 156 } 157 158 /// Account one tick on a CPU, choosing highest priority then least-served 159 /// task. Equal tasks therefore share service evenly over repeated ticks. 160 pub fn tick(&mut self, cpu: usize) -> Result, SchedulerError> { 161 if cpu >= CPUS { 162 return Err(SchedulerError::InvalidCpu); 163 } 164 if self.queue_len[cpu] == 0 && !self.steal(cpu)? { 165 return Ok(None); 166 } 167 let has_background = self.queues[cpu][..self.queue_len[cpu]] 168 .iter() 169 .flatten() 170 .any(|&slot| { 171 self.tasks[slot].expect("queued task exists").priority == TaskPriority::Background 172 }); 173 let has_higher_priority = self.queues[cpu][..self.queue_len[cpu]] 174 .iter() 175 .flatten() 176 .any(|&slot| { 177 self.tasks[slot].expect("queued task exists").priority > TaskPriority::Background 178 }); 179 let force_background = has_background && has_higher_priority && { 180 self.background_wait_ticks[cpu] = self.background_wait_ticks[cpu].saturating_add(1); 181 self.background_wait_ticks[cpu] >= self.background_interval 182 }; 183 if !has_background || !has_higher_priority { 184 self.background_wait_ticks[cpu] = 0; 185 } 186 187 let mut selected: Option = None; 188 for &slot in self.queues[cpu][..self.queue_len[cpu]].iter().flatten() { 189 let task = self.tasks[slot].expect("queued task exists"); 190 selected = match selected { 191 None => Some(slot), 192 Some(old) => { 193 let previous = self.tasks[old].expect("queued task exists"); 194 let task_wins = if force_background { 195 (task.priority == TaskPriority::Background 196 && previous.priority != TaskPriority::Background) 197 || (task.priority == previous.priority && task.ticks < previous.ticks) 198 } else { 199 task.priority > previous.priority 200 || (task.priority == previous.priority && task.ticks < previous.ticks) 201 }; 202 if task_wins { 203 Some(slot) 204 } else { 205 Some(old) 206 } 207 } 208 }; 209 } 210 if let Some(slot) = selected { 211 if self.tasks[slot].expect("queued task exists").priority == TaskPriority::Background { 212 self.background_wait_ticks[cpu] = 0; 213 } 214 let task = self.tasks[slot].as_mut().expect("queued task exists"); 215 task.ticks = task.ticks.saturating_add(1); 216 Ok(Some(task.id)) 217 } else { 218 Ok(None) 219 } 220 } 221 222 /// Move the most-served eligible task from the longest queue, leaving 223 /// high-priority work runnable there. Called automatically for idle CPUs. 224 pub fn steal(&mut self, idle_cpu: usize) -> Result { 225 if idle_cpu >= CPUS { 226 return Err(SchedulerError::InvalidCpu); 227 } 228 if self.queue_len[idle_cpu] != 0 { 229 return Ok(false); 230 } 231 let mut donor = None; 232 for cpu in 0..CPUS { 233 if cpu != idle_cpu 234 && self.queue_len[cpu] > 1 235 && donor.is_none_or(|old| self.queue_len[cpu] > self.queue_len[old]) 236 { 237 donor = Some(cpu); 238 } 239 } 240 let Some(donor) = donor else { return Ok(false) }; 241 let mut candidate = None; 242 for &slot in self.queues[donor][..self.queue_len[donor]].iter().flatten() { 243 let task = self.tasks[slot].expect("queued task exists"); 244 candidate = match candidate { 245 None => Some(slot), 246 Some(old) => { 247 let prev = self.tasks[old].expect("queued task exists"); 248 if task.priority < prev.priority 249 || (task.priority == prev.priority && task.ticks > prev.ticks) 250 { 251 Some(slot) 252 } else { 253 Some(old) 254 } 255 } 256 }; 257 } 258 let slot = candidate.expect("non-empty donor"); 259 let pos = self.queues[donor][..self.queue_len[donor]] 260 .iter() 261 .position(|v| *v == Some(slot)) 262 .unwrap(); 263 for i in pos..self.queue_len[donor] - 1 { 264 self.queues[donor][i] = self.queues[donor][i + 1]; 265 } 266 self.queue_len[donor] -= 1; 267 self.queues[idle_cpu][0] = Some(slot); 268 self.queue_len[idle_cpu] = 1; 269 self.tasks[slot].as_mut().expect("queued task exists").cpu = idle_cpu; 270 Ok(true) 271 } 272 273 pub fn task(&self, id: u32) -> Option { 274 self.tasks 275 .iter() 276 .flatten() 277 .find(|task| task.id == id) 278 .copied() 279 } 280 281 pub fn queue_len(&self, cpu: usize) -> Option { 282 self.queue_len.get(cpu).copied() 283 } 284 } 285 286 #[cfg(test)] 287 mod tests { 288 use super::*; 289 290 #[test] 291 fn placement_uses_fast_cores_for_latency_and_efficient_for_background() { 292 let mut s = Scheduler::<4, 8>::new([0, 0, 1, 1]); 293 assert!(matches!(s.enqueue(1, TaskPriority::Latency), Ok(2 | 3))); 294 assert!(matches!(s.enqueue(2, TaskPriority::Background), Ok(0 | 1))); 295 } 296 297 #[test] 298 fn equal_priority_tasks_share_n_ticks_fairly() { 299 let mut s = Scheduler::<1, 4>::new([0]); 300 s.enqueue(1, TaskPriority::Normal).unwrap(); 301 s.enqueue(2, TaskPriority::Normal).unwrap(); 302 for _ in 0..20 { 303 s.tick(0).unwrap(); 304 } 305 assert_eq!(s.task(1).unwrap().ticks, 10); 306 assert_eq!(s.task(2).unwrap().ticks, 10); 307 } 308 309 #[test] 310 fn priority_prevents_basic_inversion() { 311 let mut s = Scheduler::<1, 4>::new([0]); 312 s.enqueue(1, TaskPriority::Background).unwrap(); 313 s.enqueue(2, TaskPriority::Latency).unwrap(); 314 assert_eq!(s.tick(0), Ok(Some(2))); 315 } 316 317 #[test] 318 fn background_runs_within_configured_interval_under_latency_load() { 319 const INTERVAL: usize = 7; 320 let mut s = Scheduler::<1, 2>::with_background_interval([0], INTERVAL); 321 s.enqueue(1, TaskPriority::Background).unwrap(); 322 s.enqueue(2, TaskPriority::Latency).unwrap(); 323 324 let mut background_ran = false; 325 for _ in 0..INTERVAL { 326 background_ran |= s.tick(0).unwrap() == Some(1); 327 } 328 assert!(background_ran); 329 } 330 331 #[test] 332 fn latency_keeps_large_majority_of_ticks_with_background_budget() { 333 const INTERVAL: usize = 8; 334 const TICKS: usize = 80; 335 let mut s = Scheduler::<1, 2>::with_background_interval([0], INTERVAL); 336 s.enqueue(1, TaskPriority::Background).unwrap(); 337 s.enqueue(2, TaskPriority::Latency).unwrap(); 338 339 for _ in 0..TICKS { 340 s.tick(0).unwrap(); 341 } 342 let latency_ticks = s.task(2).unwrap().ticks; 343 let background_ticks = s.task(1).unwrap().ticks; 344 assert!(latency_ticks > TICKS as u64 * 3 / 4); 345 assert!(latency_ticks > background_ticks); 346 } 347 348 #[test] 349 fn idle_cpu_steals_and_runs_work() { 350 let mut s = Scheduler::<2, 4>::new([0, 1]); 351 s.enqueue(1, TaskPriority::Background).unwrap(); 352 s.enqueue(2, TaskPriority::Background).unwrap(); 353 assert!(s.steal(1).unwrap()); 354 assert!(s.task(1).unwrap().cpu == 1 || s.task(2).unwrap().cpu == 1); 355 assert!(s.tick(1).unwrap().is_some()); 356 } 357 358 #[test] 359 fn empty_queues_and_invalid_cpu_are_handled() { 360 let mut s = Scheduler::<2, 2>::new([0, 1]); 361 assert_eq!(s.tick(0), Ok(None)); 362 assert!(!s.steal(1).unwrap()); 363 assert_eq!(s.tick(2), Err(SchedulerError::InvalidCpu)); 364 } 365 366 #[test] 367 fn round_robin_placement_and_duplicate_rejection() { 368 let mut s = Scheduler::<2, 4>::new([0, 0]); 369 assert_eq!(s.enqueue(1, TaskPriority::Normal), Ok(0)); 370 assert_eq!(s.enqueue(2, TaskPriority::Normal), Ok(1)); 371 assert_eq!( 372 s.enqueue(1, TaskPriority::Normal), 373 Err(SchedulerError::DuplicateTask) 374 ); 375 } 376 #[test] 377 fn removed_tasks_free_their_slot_and_leave_the_queue() { 378 let mut s = Scheduler::<1, 2>::new([0]); 379 s.enqueue(1, TaskPriority::Normal).unwrap(); 380 s.enqueue(2, TaskPriority::Normal).unwrap(); 381 assert_eq!( 382 s.enqueue(3, TaskPriority::Normal), 383 Err(SchedulerError::Full) 384 ); 385 s.remove(1).unwrap(); 386 assert_eq!(s.queue_len(0), Some(1)); 387 assert!(s.task(1).is_none()); 388 // The freed slot is reusable, and only the remaining task is scheduled. 389 s.enqueue(3, TaskPriority::Normal).unwrap(); 390 for _ in 0..4 { 391 assert_ne!(s.tick(0).unwrap(), Some(1)); 392 } 393 assert_eq!(s.remove(1), Err(SchedulerError::UnknownTask)); 394 } 395 }