1 use core::{ 2 hint::spin_loop, 3 sync::atomic::{AtomicBool, Ordering}, 4 }; 5 6 use alloc::{ 7 boxed::Box, 8 collections::LinkedList, 9 string::{String, ToString}, 10 sync::{Arc, Weak}, 11 }; 12 use atomic_enum::atomic_enum; 13 14 use crate::{ 15 arch::{sched::sched, CurrentIrqArch}, 16 exception::InterruptArch, 17 kdebug, kinfo, 18 libs::{once::Once, spinlock::SpinLock}, 19 process::{ProcessManager, ProcessState}, 20 syscall::SystemError, 21 }; 22 23 use super::{ 24 fork::CloneFlags, init::initial_kernel_thread, Pid, ProcessControlBlock, ProcessFlags, 25 }; 26 27 /// 内核线程的创建任务列表 28 static KTHREAD_CREATE_LIST: SpinLock<LinkedList<Arc<KernelThreadCreateInfo>>> = 29 SpinLock::new(LinkedList::new()); 30 31 static mut KTHREAD_DAEMON_PCB: Option<Arc<ProcessControlBlock>> = None; 32 33 #[derive(Debug)] 34 pub enum WorkerPrivate { 35 KernelThread(KernelThreadPcbPrivate), 36 } 37 38 #[allow(dead_code)] 39 impl WorkerPrivate { 40 pub fn kernel_thread(&self) -> Option<&KernelThreadPcbPrivate> { 41 match self { 42 Self::KernelThread(x) => Some(x), 43 } 44 } 45 46 pub fn kernel_thread_mut(&mut self) -> Option<&mut KernelThreadPcbPrivate> { 47 match self { 48 Self::KernelThread(x) => Some(x), 49 } 50 } 51 } 52 53 bitflags! { 54 pub struct KernelThreadFlags: u32 { 55 const IS_PER_CPU = 1 << 0; 56 const SHOULD_STOP = 1 << 1; 57 const SHOULD_PARK = 1 << 2; 58 } 59 } 60 61 #[derive(Debug)] 62 pub struct KernelThreadPcbPrivate { 63 flags: KernelThreadFlags, 64 } 65 66 #[allow(dead_code)] 67 impl KernelThreadPcbPrivate { 68 pub fn new() -> Self { 69 Self { 70 flags: KernelThreadFlags::empty(), 71 } 72 } 73 74 pub fn flags(&self) -> &KernelThreadFlags { 75 &self.flags 76 } 77 78 pub fn flags_mut(&mut self) -> &mut KernelThreadFlags { 79 &mut self.flags 80 } 81 } 82 83 /// 内核线程的闭包,参数必须与闭包的参数一致,返回值必须是i32 84 /// 85 /// 元组的第一个元素是闭包,第二个元素是闭包的参数对象 86 /// 87 /// 对于非原始类型的参数,需要使用Box包装 88 #[allow(dead_code)] 89 pub enum KernelThreadClosure { 90 UsizeClosure((Box<dyn Fn(usize) -> i32 + Send + Sync>, usize)), 91 EmptyClosure((Box<dyn Fn() -> i32 + Send + Sync>, ())), 92 // 添加其他类型入参的闭包,返回值必须是i32 93 } 94 95 impl KernelThreadClosure { 96 pub fn run(self) -> i32 { 97 match self { 98 Self::UsizeClosure((func, arg)) => func(arg), 99 Self::EmptyClosure((func, _arg)) => func(), 100 } 101 } 102 } 103 104 pub struct KernelThreadCreateInfo { 105 /// 内核线程的入口函数、传入参数 106 closure: SpinLock<Option<Box<KernelThreadClosure>>>, 107 /// 内核线程的名字 108 name: String, 109 /// 是否已经完成创建 todo:使用comletion机制优化这里 110 created: AtomicKernelThreadCreateStatus, 111 result_pcb: SpinLock<Option<Arc<ProcessControlBlock>>>, 112 /// 不安全的Arc引用计数,当内核线程创建失败时,需要减少这个计数 113 has_unsafe_arc_instance: AtomicBool, 114 self_ref: Weak<Self>, 115 /// 如果该值为true在进入bootstrap stage2之后,就会进入睡眠状态 116 to_mark_sleep: AtomicBool, 117 } 118 119 #[atomic_enum] 120 #[derive(PartialEq)] 121 pub enum KernelThreadCreateStatus { 122 Created, 123 NotCreated, 124 ErrorOccured, 125 } 126 127 #[allow(dead_code)] 128 impl KernelThreadCreateInfo { 129 pub fn new(func: KernelThreadClosure, name: String) -> Arc<Self> { 130 let result = Arc::new(Self { 131 closure: SpinLock::new(Some(Box::new(func))), 132 name, 133 created: AtomicKernelThreadCreateStatus::new(KernelThreadCreateStatus::NotCreated), 134 result_pcb: SpinLock::new(None), 135 has_unsafe_arc_instance: AtomicBool::new(false), 136 self_ref: Weak::new(), 137 to_mark_sleep: AtomicBool::new(true), 138 }); 139 let tmp = result.clone(); 140 unsafe { 141 let tmp = Arc::into_raw(tmp) as *mut Self; 142 (*tmp).self_ref = Arc::downgrade(&result); 143 Arc::from_raw(tmp); 144 } 145 146 return result; 147 } 148 149 /// 创建者调用这函数,等待创建完成后,获取创建结果 150 /// 151 /// ## 返回值 152 /// 153 /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB 154 /// - None 创建失败 155 pub fn poll_result(&self) -> Option<Arc<ProcessControlBlock>> { 156 loop { 157 match self.created.load(Ordering::SeqCst) { 158 KernelThreadCreateStatus::Created => { 159 return self.result_pcb.lock().take(); 160 } 161 KernelThreadCreateStatus::NotCreated => { 162 spin_loop(); 163 } 164 KernelThreadCreateStatus::ErrorOccured => { 165 // 创建失败,减少不安全的Arc引用计数 166 let to_delete = self.has_unsafe_arc_instance.swap(false, Ordering::SeqCst); 167 if to_delete { 168 let self_ref = self.self_ref.upgrade().unwrap(); 169 unsafe { Arc::decrement_strong_count(&self_ref) }; 170 } 171 return None; 172 } 173 } 174 } 175 } 176 177 pub fn take_closure(&self) -> Option<Box<KernelThreadClosure>> { 178 return self.closure.lock().take(); 179 } 180 181 pub fn name(&self) -> &String { 182 &self.name 183 } 184 185 pub unsafe fn set_create_ok(&self, pcb: Arc<ProcessControlBlock>) { 186 // todo: 使用completion机制优化这里 187 self.result_pcb.lock().replace(pcb); 188 self.created 189 .store(KernelThreadCreateStatus::Created, Ordering::SeqCst); 190 } 191 192 /// 生成一个不安全的Arc指针(用于创建内核线程时传递参数) 193 pub fn generate_unsafe_arc_ptr(self: Arc<Self>) -> *const Self { 194 assert!( 195 self.has_unsafe_arc_instance 196 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) 197 .is_ok(), 198 "Cannot generate unsafe arc ptr when there is already one." 199 ); 200 let ptr = Arc::into_raw(self); 201 return ptr; 202 } 203 204 pub unsafe fn parse_unsafe_arc_ptr(ptr: *const Self) -> Arc<Self> { 205 let arc = Arc::from_raw(ptr); 206 assert!( 207 arc.has_unsafe_arc_instance 208 .compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst) 209 .is_ok(), 210 "Cannot parse unsafe arc ptr when there is no one." 211 ); 212 assert!(Arc::strong_count(&arc) > 0); 213 return arc; 214 } 215 216 /// 设置是否在进入bootstrap stage2之后,就进入睡眠状态 217 /// 218 /// ## 参数 219 /// 220 /// - to_mark_sleep: 是否在进入bootstrap stage2之后,就进入睡眠状态 221 /// 222 /// ## 返回值 223 /// 如果已经创建完成,返回EINVAL 224 pub fn set_to_mark_sleep(&self, to_mark_sleep: bool) -> Result<(), SystemError> { 225 let result_guard = self.result_pcb.lock(); 226 if result_guard.is_some() { 227 // 已经创建完成,不需要设置 228 return Err(SystemError::EINVAL); 229 } 230 self.to_mark_sleep.store(to_mark_sleep, Ordering::SeqCst); 231 return Ok(()); 232 } 233 234 pub fn to_mark_sleep(&self) -> bool { 235 self.to_mark_sleep.load(Ordering::SeqCst) 236 } 237 } 238 239 pub struct KernelThreadMechanism; 240 241 impl KernelThreadMechanism { 242 pub fn init_stage1() { 243 assert!(ProcessManager::current_pcb().pid() == Pid::new(0)); 244 kinfo!("Initializing kernel thread mechanism stage1..."); 245 246 // 初始化第一个内核线程 247 248 let create_info = KernelThreadCreateInfo::new( 249 KernelThreadClosure::EmptyClosure((Box::new(initial_kernel_thread), ())), 250 "init".to_string(), 251 ); 252 let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; 253 // 由于当前是pid=0的idle进程,而__inner_create要求当前是kthread,所以先临时设置为kthread 254 ProcessManager::current_pcb() 255 .flags 256 .lock() 257 .insert(ProcessFlags::KTHREAD); 258 create_info 259 .set_to_mark_sleep(false) 260 .expect("Failed to set to_mark_sleep"); 261 KernelThreadMechanism::__inner_create( 262 &create_info, 263 CloneFlags::CLONE_VM | CloneFlags::CLONE_SIGNAL, 264 ) 265 .unwrap_or_else(|e| panic!("Failed to create initial kernel thread, error: {:?}", e)); 266 267 ProcessManager::current_pcb() 268 .flags 269 .lock() 270 .remove(ProcessFlags::KTHREAD); 271 drop(irq_guard); 272 kinfo!("Initializing kernel thread mechanism stage1 complete"); 273 } 274 275 pub fn init_stage2() { 276 assert!(ProcessManager::current_pcb() 277 .flags() 278 .contains(ProcessFlags::KTHREAD)); 279 static INIT: Once = Once::new(); 280 INIT.call_once(|| { 281 kinfo!("Initializing kernel thread mechanism stage2..."); 282 // 初始化kthreadd 283 let closure = KernelThreadClosure::EmptyClosure((Box::new(Self::kthread_daemon), ())); 284 let info = KernelThreadCreateInfo::new(closure, "kthreadd".to_string()); 285 let kthreadd_pid: Pid = Self::__inner_create( 286 &info, 287 CloneFlags::CLONE_VM | CloneFlags::CLONE_FS | CloneFlags::CLONE_SIGNAL, 288 ) 289 .expect("Failed to create kthread daemon"); 290 291 let pcb = ProcessManager::find(kthreadd_pid).unwrap(); 292 ProcessManager::wakeup(&pcb).expect("Failed to wakeup kthread daemon"); 293 unsafe { 294 KTHREAD_DAEMON_PCB.replace(pcb); 295 } 296 kinfo!("Initializing kernel thread mechanism stage2 complete"); 297 }); 298 } 299 300 /// 创建一个新的内核线程 301 /// 302 /// ## 参数 303 /// 304 /// - func: 内核线程的入口函数、传入参数 305 /// - name: 内核线程的名字 306 /// 307 /// ## 返回值 308 /// 309 /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB 310 #[allow(dead_code)] 311 pub fn create(func: KernelThreadClosure, name: String) -> Option<Arc<ProcessControlBlock>> { 312 let info = KernelThreadCreateInfo::new(func, name); 313 while unsafe { KTHREAD_DAEMON_PCB.is_none() } { 314 // 等待kthreadd启动 315 spin_loop() 316 } 317 KTHREAD_CREATE_LIST.lock().push_back(info.clone()); 318 ProcessManager::wakeup(unsafe { KTHREAD_DAEMON_PCB.as_ref().unwrap() }) 319 .expect("Failed to wakeup kthread daemon"); 320 return info.poll_result(); 321 } 322 323 /// 创建并运行一个新的内核线程 324 /// 325 /// ## 参数 326 /// 327 /// - func: 内核线程的入口函数、传入参数 328 /// - name: 内核线程的名字 329 /// 330 /// ## 返回值 331 /// 332 /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB 333 #[allow(dead_code)] 334 pub fn create_and_run( 335 func: KernelThreadClosure, 336 name: String, 337 ) -> Option<Arc<ProcessControlBlock>> { 338 let pcb = Self::create(func, name)?; 339 ProcessManager::wakeup(&pcb) 340 .expect(format!("Failed to wakeup kthread: {:?}", pcb.pid()).as_str()); 341 return Some(pcb); 342 } 343 344 /// 停止一个内核线程 345 /// 346 /// 如果目标内核线程的数据检查失败,会panic 347 /// 348 /// ## 返回值 349 /// 350 /// - Ok(i32) 目标内核线程的退出码 351 #[allow(dead_code)] 352 pub fn stop(pcb: &Arc<ProcessControlBlock>) -> Result<usize, SystemError> { 353 if !pcb.flags().contains(ProcessFlags::KTHREAD) { 354 panic!("Cannt stop a non-kthread process"); 355 } 356 357 let mut worker_private = pcb.worker_private(); 358 assert!( 359 worker_private.is_some(), 360 "kthread stop: worker_private is none, pid: {:?}", 361 pcb.pid() 362 ); 363 worker_private 364 .as_mut() 365 .unwrap() 366 .kernel_thread_mut() 367 .expect("Error type of worker private") 368 .flags 369 .insert(KernelThreadFlags::SHOULD_STOP); 370 371 drop(worker_private); 372 373 ProcessManager::wakeup(pcb).ok(); 374 375 // 忙等目标内核线程退出 376 // todo: 使用completion机制优化这里 377 loop { 378 if let ProcessState::Exited(code) = pcb.sched_info().state() { 379 return Ok(code); 380 } 381 spin_loop(); 382 } 383 } 384 385 /// 判断一个内核线程是否应当停止 386 /// 387 /// ## 参数 388 /// 389 /// - pcb: 目标内核线程的PCB 390 /// 391 /// ## 返回值 392 /// 393 /// - bool 是否应当停止. true表示应当停止,false表示不应当停止. 如果目标进程不是内核线程,返回false 394 /// 395 /// ## Panic 396 /// 397 /// 如果目标内核线程的数据检查失败,会panic 398 #[allow(dead_code)] 399 pub fn should_stop(pcb: &Arc<ProcessControlBlock>) -> bool { 400 if !pcb.flags().contains(ProcessFlags::KTHREAD) { 401 return false; 402 } 403 404 let worker_private = pcb.worker_private(); 405 assert!( 406 worker_private.is_some(), 407 "kthread should_stop: worker_private is none, pid: {:?}", 408 pcb.pid() 409 ); 410 return worker_private 411 .as_ref() 412 .unwrap() 413 .kernel_thread() 414 .expect("Error type of worker private") 415 .flags 416 .contains(KernelThreadFlags::SHOULD_STOP); 417 } 418 419 /// A daemon thread which creates other kernel threads 420 fn kthread_daemon() -> i32 { 421 let current_pcb = ProcessManager::current_pcb(); 422 kdebug!("kthread_daemon: pid: {:?}", current_pcb.pid()); 423 { 424 // 初始化worker_private 425 let mut worker_private_guard = current_pcb.worker_private(); 426 let worker_private = WorkerPrivate::KernelThread(KernelThreadPcbPrivate::new()); 427 *worker_private_guard = Some(worker_private); 428 } 429 // 设置为kthread 430 current_pcb.flags().insert(ProcessFlags::KTHREAD); 431 drop(current_pcb); 432 433 loop { 434 let mut list = KTHREAD_CREATE_LIST.lock(); 435 while let Some(info) = list.pop_front() { 436 drop(list); 437 438 // create a new kernel thread 439 let result: Result<Pid, SystemError> = 440 Self::__inner_create(&info, CloneFlags::CLONE_FS | CloneFlags::CLONE_SIGNAL); 441 442 if result.is_err() { 443 // 创建失败 444 info.created 445 .store(KernelThreadCreateStatus::ErrorOccured, Ordering::SeqCst); 446 }; 447 list = KTHREAD_CREATE_LIST.lock(); 448 } 449 drop(list); 450 451 let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; 452 ProcessManager::mark_sleep(true).ok(); 453 drop(irq_guard); 454 sched(); 455 } 456 } 457 } 458 459 /// 内核线程启动的第二阶段 460 /// 461 /// 该函数只能被`kernel_thread_bootstrap_stage1`调用(jmp到该函数) 462 /// 463 /// ## 参数 464 /// 465 /// - ptr: 传入的参数,是一个指向`Arc<KernelThreadCreateInfo>`的指针 466 pub unsafe extern "C" fn kernel_thread_bootstrap_stage2(ptr: *const KernelThreadCreateInfo) -> ! { 467 let info = KernelThreadCreateInfo::parse_unsafe_arc_ptr(ptr); 468 469 let closure: Box<KernelThreadClosure> = info.take_closure().unwrap(); 470 info.set_create_ok(ProcessManager::current_pcb()); 471 let to_mark_sleep = info.to_mark_sleep(); 472 drop(info); 473 474 if to_mark_sleep { 475 // 进入睡眠状态 476 let irq_guard = CurrentIrqArch::save_and_disable_irq(); 477 ProcessManager::mark_sleep(true).expect("Failed to mark sleep"); 478 drop(irq_guard); 479 sched(); 480 } 481 482 let mut retval = SystemError::EINTR.to_posix_errno(); 483 484 if !KernelThreadMechanism::should_stop(&ProcessManager::current_pcb()) { 485 retval = closure.run(); 486 } 487 488 ProcessManager::exit(retval as usize); 489 } 490 491 pub fn kthread_init() { 492 static INIT: Once = Once::new(); 493 INIT.call_once(|| { 494 KernelThreadMechanism::init_stage1(); 495 }); 496 } 497