11496ba7bSLoGin use core::{ 21496ba7bSLoGin arch::asm, 31496ba7bSLoGin intrinsics::unlikely, 41496ba7bSLoGin mem::ManuallyDrop, 51496ba7bSLoGin sync::atomic::{compiler_fence, Ordering}, 61496ba7bSLoGin }; 71496ba7bSLoGin 8*971462beSGnoCiYeH use alloc::{ 9*971462beSGnoCiYeH string::String, 10*971462beSGnoCiYeH sync::{Arc, Weak}, 11*971462beSGnoCiYeH vec::Vec, 12*971462beSGnoCiYeH }; 131496ba7bSLoGin 141496ba7bSLoGin use memoffset::offset_of; 151496ba7bSLoGin use x86::{controlregs::Cr4, segmentation::SegmentSelector}; 161496ba7bSLoGin 171496ba7bSLoGin use crate::{ 181496ba7bSLoGin arch::process::table::TSSManager, 191496ba7bSLoGin exception::InterruptArch, 203c82aa56SChiichen kwarn, 211496ba7bSLoGin libs::spinlock::SpinLockGuard, 221496ba7bSLoGin mm::{ 231496ba7bSLoGin percpu::{PerCpu, PerCpuVar}, 241496ba7bSLoGin VirtAddr, 251496ba7bSLoGin }, 261496ba7bSLoGin process::{ 27*971462beSGnoCiYeH fork::{CloneFlags, KernelCloneArgs}, 28*971462beSGnoCiYeH KernelStack, ProcessControlBlock, ProcessFlags, ProcessManager, SwitchResult, 29*971462beSGnoCiYeH SWITCH_RESULT, 301496ba7bSLoGin }, 311496ba7bSLoGin syscall::{Syscall, SystemError}, 321496ba7bSLoGin }; 331496ba7bSLoGin 341496ba7bSLoGin use self::{ 351496ba7bSLoGin kthread::kernel_thread_bootstrap_stage1, 36*971462beSGnoCiYeH syscall::ARCH_SET_FS, 371496ba7bSLoGin table::{switch_fs_and_gs, KERNEL_DS, USER_DS}, 381496ba7bSLoGin }; 391496ba7bSLoGin 401496ba7bSLoGin use super::{fpu::FpState, interrupt::TrapFrame, CurrentIrqArch}; 411496ba7bSLoGin 421496ba7bSLoGin mod c_adapter; 431496ba7bSLoGin pub mod kthread; 441496ba7bSLoGin pub mod syscall; 451496ba7bSLoGin pub mod table; 461496ba7bSLoGin 47*971462beSGnoCiYeH pub const IA32_FS_BASE: u32 = 0xC000_0100; 48*971462beSGnoCiYeH pub const IA32_GS_BASE: u32 = 0xC000_0101; 49*971462beSGnoCiYeH 501496ba7bSLoGin extern "C" { 511496ba7bSLoGin /// 从中断返回 521496ba7bSLoGin fn ret_from_intr(); 531496ba7bSLoGin } 541496ba7bSLoGin 55de71ec25SLoGin #[allow(dead_code)] 56de71ec25SLoGin #[repr(align(32768))] 57de71ec25SLoGin union InitProcUnion { 58de71ec25SLoGin /// 用于存放idle进程的内核栈 59de71ec25SLoGin idle_stack: [u8; 32768], 60de71ec25SLoGin } 61de71ec25SLoGin 62de71ec25SLoGin #[link_section = ".data.init_proc_union"] 63de71ec25SLoGin #[no_mangle] 64de71ec25SLoGin static BSP_IDLE_STACK_SPACE: InitProcUnion = InitProcUnion { 65de71ec25SLoGin idle_stack: [0; 32768], 66de71ec25SLoGin }; 67de71ec25SLoGin 681496ba7bSLoGin /// PCB中与架构相关的信息 691496ba7bSLoGin #[derive(Debug, Clone)] 701496ba7bSLoGin #[allow(dead_code)] 711496ba7bSLoGin pub struct ArchPCBInfo { 721496ba7bSLoGin rflags: usize, 731496ba7bSLoGin rbx: usize, 741496ba7bSLoGin r12: usize, 751496ba7bSLoGin r13: usize, 761496ba7bSLoGin r14: usize, 771496ba7bSLoGin r15: usize, 781496ba7bSLoGin rbp: usize, 791496ba7bSLoGin rsp: usize, 801496ba7bSLoGin rip: usize, 811496ba7bSLoGin cr2: usize, 821496ba7bSLoGin fsbase: usize, 831496ba7bSLoGin gsbase: usize, 841496ba7bSLoGin fs: u16, 851496ba7bSLoGin gs: u16, 861496ba7bSLoGin 871496ba7bSLoGin /// 浮点寄存器的状态 881496ba7bSLoGin fp_state: Option<FpState>, 891496ba7bSLoGin } 901496ba7bSLoGin 911496ba7bSLoGin #[allow(dead_code)] 921496ba7bSLoGin impl ArchPCBInfo { 931496ba7bSLoGin /// 创建一个新的ArchPCBInfo 941496ba7bSLoGin /// 951496ba7bSLoGin /// ## 参数 961496ba7bSLoGin /// 971496ba7bSLoGin /// - `kstack`:内核栈的引用,如果为None,则不会设置rsp和rbp。如果为Some,则会设置rsp和rbp为内核栈的最高地址。 981496ba7bSLoGin /// 991496ba7bSLoGin /// ## 返回值 1001496ba7bSLoGin /// 1011496ba7bSLoGin /// 返回一个新的ArchPCBInfo 1021496ba7bSLoGin pub fn new(kstack: Option<&KernelStack>) -> Self { 1031496ba7bSLoGin let mut r = Self { 1041496ba7bSLoGin rflags: 0, 1051496ba7bSLoGin rbx: 0, 1061496ba7bSLoGin r12: 0, 1071496ba7bSLoGin r13: 0, 1081496ba7bSLoGin r14: 0, 1091496ba7bSLoGin r15: 0, 1101496ba7bSLoGin rbp: 0, 1111496ba7bSLoGin rsp: 0, 1121496ba7bSLoGin rip: 0, 1131496ba7bSLoGin cr2: 0, 1141496ba7bSLoGin fsbase: 0, 1151496ba7bSLoGin gsbase: 0, 1161496ba7bSLoGin fs: KERNEL_DS.bits(), 1171496ba7bSLoGin gs: KERNEL_DS.bits(), 1181496ba7bSLoGin fp_state: None, 1191496ba7bSLoGin }; 1201496ba7bSLoGin 1211496ba7bSLoGin if kstack.is_some() { 1221496ba7bSLoGin let kstack = kstack.unwrap(); 1231496ba7bSLoGin r.rsp = kstack.stack_max_address().data(); 1241496ba7bSLoGin r.rbp = kstack.stack_max_address().data(); 1251496ba7bSLoGin } 1261496ba7bSLoGin 1271496ba7bSLoGin return r; 1281496ba7bSLoGin } 1291496ba7bSLoGin 1301496ba7bSLoGin pub fn set_stack(&mut self, stack: VirtAddr) { 1311496ba7bSLoGin self.rsp = stack.data(); 1321496ba7bSLoGin } 1331496ba7bSLoGin 1341496ba7bSLoGin pub fn set_stack_base(&mut self, stack_base: VirtAddr) { 1351496ba7bSLoGin self.rbp = stack_base.data(); 1361496ba7bSLoGin } 1371496ba7bSLoGin 1381496ba7bSLoGin pub fn rbp(&self) -> usize { 1391496ba7bSLoGin self.rbp 1401496ba7bSLoGin } 1411496ba7bSLoGin 1421496ba7bSLoGin pub unsafe fn push_to_stack(&mut self, value: usize) { 1431496ba7bSLoGin self.rsp -= core::mem::size_of::<usize>(); 1441496ba7bSLoGin *(self.rsp as *mut usize) = value; 1451496ba7bSLoGin } 1461496ba7bSLoGin 1471496ba7bSLoGin pub unsafe fn pop_from_stack(&mut self) -> usize { 1481496ba7bSLoGin let value = *(self.rsp as *const usize); 1491496ba7bSLoGin self.rsp += core::mem::size_of::<usize>(); 1501496ba7bSLoGin value 1511496ba7bSLoGin } 1521496ba7bSLoGin 1531496ba7bSLoGin pub fn save_fp_state(&mut self) { 1541496ba7bSLoGin if self.fp_state.is_none() { 1551496ba7bSLoGin self.fp_state = Some(FpState::new()); 1561496ba7bSLoGin } 1571496ba7bSLoGin 1581496ba7bSLoGin self.fp_state.as_mut().unwrap().save(); 1591496ba7bSLoGin } 1601496ba7bSLoGin 1611496ba7bSLoGin pub fn restore_fp_state(&mut self) { 1621496ba7bSLoGin if unlikely(self.fp_state.is_none()) { 1631496ba7bSLoGin return; 1641496ba7bSLoGin } 1651496ba7bSLoGin 1661496ba7bSLoGin self.fp_state.as_mut().unwrap().restore(); 1671496ba7bSLoGin } 1681496ba7bSLoGin 1693c82aa56SChiichen /// 返回浮点寄存器结构体的副本 1703c82aa56SChiichen pub fn fp_state(&self) -> &Option<FpState> { 1713c82aa56SChiichen &self.fp_state 1723c82aa56SChiichen } 1733c82aa56SChiichen 1743c82aa56SChiichen // 清空浮点寄存器 1753c82aa56SChiichen pub fn clear_fp_state(&mut self) { 1763c82aa56SChiichen if unlikely(self.fp_state.is_none()) { 1773c82aa56SChiichen kwarn!("fp_state is none"); 1783c82aa56SChiichen return; 1793c82aa56SChiichen } 1803c82aa56SChiichen 1813c82aa56SChiichen self.fp_state.as_mut().unwrap().clear(); 1823c82aa56SChiichen } 1831496ba7bSLoGin pub unsafe fn save_fsbase(&mut self) { 1841496ba7bSLoGin if x86::controlregs::cr4().contains(Cr4::CR4_ENABLE_FSGSBASE) { 1851496ba7bSLoGin self.fsbase = x86::current::segmentation::rdfsbase() as usize; 1861496ba7bSLoGin } else { 187*971462beSGnoCiYeH self.fsbase = x86::msr::rdmsr(IA32_FS_BASE) as usize; 1881496ba7bSLoGin } 1891496ba7bSLoGin } 1901496ba7bSLoGin 1911496ba7bSLoGin pub unsafe fn save_gsbase(&mut self) { 1921496ba7bSLoGin if x86::controlregs::cr4().contains(Cr4::CR4_ENABLE_FSGSBASE) { 1931496ba7bSLoGin self.gsbase = x86::current::segmentation::rdgsbase() as usize; 1941496ba7bSLoGin } else { 195*971462beSGnoCiYeH self.gsbase = x86::msr::rdmsr(IA32_GS_BASE) as usize; 1961496ba7bSLoGin } 1971496ba7bSLoGin } 1981496ba7bSLoGin 1991496ba7bSLoGin pub unsafe fn restore_fsbase(&mut self) { 2001496ba7bSLoGin if x86::controlregs::cr4().contains(Cr4::CR4_ENABLE_FSGSBASE) { 2011496ba7bSLoGin x86::current::segmentation::wrfsbase(self.fsbase as u64); 202*971462beSGnoCiYeH } else { 203*971462beSGnoCiYeH x86::msr::wrmsr(IA32_FS_BASE, self.fsbase as u64); 2041496ba7bSLoGin } 2051496ba7bSLoGin } 2061496ba7bSLoGin 2071496ba7bSLoGin pub unsafe fn restore_gsbase(&mut self) { 2081496ba7bSLoGin if x86::controlregs::cr4().contains(Cr4::CR4_ENABLE_FSGSBASE) { 2091496ba7bSLoGin x86::current::segmentation::wrgsbase(self.gsbase as u64); 210*971462beSGnoCiYeH } else { 211*971462beSGnoCiYeH x86::msr::wrmsr(IA32_GS_BASE, self.gsbase as u64); 2121496ba7bSLoGin } 2131496ba7bSLoGin } 2141496ba7bSLoGin 2151496ba7bSLoGin pub fn fsbase(&self) -> usize { 2161496ba7bSLoGin self.fsbase 2171496ba7bSLoGin } 2181496ba7bSLoGin 2191496ba7bSLoGin pub fn gsbase(&self) -> usize { 2201496ba7bSLoGin self.gsbase 2211496ba7bSLoGin } 2223c82aa56SChiichen 2233c82aa56SChiichen pub fn cr2_mut(&mut self) -> &mut usize { 2243c82aa56SChiichen &mut self.cr2 2253c82aa56SChiichen } 2263c82aa56SChiichen 2273c82aa56SChiichen pub fn fp_state_mut(&mut self) -> &mut Option<FpState> { 2283c82aa56SChiichen &mut self.fp_state 2293c82aa56SChiichen } 2301496ba7bSLoGin } 2311496ba7bSLoGin 2321496ba7bSLoGin impl ProcessControlBlock { 2331496ba7bSLoGin /// 获取当前进程的pcb 2341496ba7bSLoGin pub fn arch_current_pcb() -> Arc<Self> { 2351496ba7bSLoGin // 获取栈指针 2361496ba7bSLoGin let ptr = VirtAddr::new(x86::current::registers::rsp() as usize); 2371496ba7bSLoGin let stack_base = VirtAddr::new(ptr.data() & (!(KernelStack::ALIGN - 1))); 2381496ba7bSLoGin // 从内核栈的最低地址处取出pcb的地址 2391496ba7bSLoGin let p = stack_base.data() as *const *const ProcessControlBlock; 2401496ba7bSLoGin if unlikely((unsafe { *p }).is_null()) { 2411496ba7bSLoGin panic!("current_pcb is null"); 2421496ba7bSLoGin } 2431496ba7bSLoGin unsafe { 244*971462beSGnoCiYeH // 为了防止内核栈的pcb weak 指针被释放,这里需要将其包装一下 245*971462beSGnoCiYeH let weak_wrapper: ManuallyDrop<Weak<ProcessControlBlock>> = 246*971462beSGnoCiYeH ManuallyDrop::new(Weak::from_raw(*p)); 2471496ba7bSLoGin 248*971462beSGnoCiYeH let new_arc: Arc<ProcessControlBlock> = weak_wrapper.upgrade().unwrap(); 2491496ba7bSLoGin return new_arc; 2501496ba7bSLoGin } 2511496ba7bSLoGin } 2521496ba7bSLoGin } 2531496ba7bSLoGin 2541496ba7bSLoGin impl ProcessManager { 2551496ba7bSLoGin pub fn arch_init() { 2561496ba7bSLoGin { 2571496ba7bSLoGin // 初始化进程切换结果 per cpu变量 2581496ba7bSLoGin let mut switch_res_vec: Vec<SwitchResult> = Vec::new(); 2591496ba7bSLoGin for _ in 0..PerCpu::MAX_CPU_NUM { 2601496ba7bSLoGin switch_res_vec.push(SwitchResult::new()); 2611496ba7bSLoGin } 2621496ba7bSLoGin unsafe { 2631496ba7bSLoGin SWITCH_RESULT = Some(PerCpuVar::new(switch_res_vec).unwrap()); 2641496ba7bSLoGin } 2651496ba7bSLoGin } 2661496ba7bSLoGin } 2671496ba7bSLoGin /// fork的过程中复制线程 2681496ba7bSLoGin /// 2691496ba7bSLoGin /// 由于这个过程与具体的架构相关,所以放在这里 2701496ba7bSLoGin pub fn copy_thread( 2711496ba7bSLoGin current_pcb: &Arc<ProcessControlBlock>, 2721496ba7bSLoGin new_pcb: &Arc<ProcessControlBlock>, 273*971462beSGnoCiYeH clone_args: KernelCloneArgs, 2741496ba7bSLoGin current_trapframe: &TrapFrame, 2751496ba7bSLoGin ) -> Result<(), SystemError> { 276*971462beSGnoCiYeH let clone_flags = clone_args.flags; 2771496ba7bSLoGin let mut child_trapframe = current_trapframe.clone(); 2781496ba7bSLoGin 2791496ba7bSLoGin // 子进程的返回值为0 2801496ba7bSLoGin child_trapframe.set_return_value(0); 2811496ba7bSLoGin 2821496ba7bSLoGin // 设置子进程的栈基址(开始执行中断返回流程时的栈基址) 2831496ba7bSLoGin let mut new_arch_guard = new_pcb.arch_info(); 2841496ba7bSLoGin let kernel_stack_guard = new_pcb.kernel_stack(); 2851496ba7bSLoGin 2861496ba7bSLoGin // 设置子进程在内核态开始执行时的rsp、rbp 2871496ba7bSLoGin new_arch_guard.set_stack_base(kernel_stack_guard.stack_max_address()); 2881496ba7bSLoGin 2891496ba7bSLoGin let trap_frame_vaddr: VirtAddr = 2901496ba7bSLoGin kernel_stack_guard.stack_max_address() - core::mem::size_of::<TrapFrame>(); 2911496ba7bSLoGin new_arch_guard.set_stack(trap_frame_vaddr); 2921496ba7bSLoGin 2931496ba7bSLoGin // 拷贝栈帧 2941496ba7bSLoGin unsafe { 295*971462beSGnoCiYeH let usp = clone_args.stack; 296*971462beSGnoCiYeH if usp != 0 { 297*971462beSGnoCiYeH child_trapframe.rsp = usp as u64; 298*971462beSGnoCiYeH } 2991496ba7bSLoGin let trap_frame_ptr = trap_frame_vaddr.data() as *mut TrapFrame; 3001496ba7bSLoGin *trap_frame_ptr = child_trapframe; 3011496ba7bSLoGin } 3021496ba7bSLoGin 3031496ba7bSLoGin let current_arch_guard = current_pcb.arch_info_irqsave(); 3041496ba7bSLoGin new_arch_guard.fsbase = current_arch_guard.fsbase; 3051496ba7bSLoGin new_arch_guard.gsbase = current_arch_guard.gsbase; 3061496ba7bSLoGin new_arch_guard.fs = current_arch_guard.fs; 3071496ba7bSLoGin new_arch_guard.gs = current_arch_guard.gs; 3081496ba7bSLoGin new_arch_guard.fp_state = current_arch_guard.fp_state.clone(); 3091496ba7bSLoGin 3101496ba7bSLoGin // 拷贝浮点寄存器的状态 3111496ba7bSLoGin if let Some(fp_state) = current_arch_guard.fp_state.as_ref() { 3121496ba7bSLoGin new_arch_guard.fp_state = Some(*fp_state); 3131496ba7bSLoGin } 3141496ba7bSLoGin drop(current_arch_guard); 3151496ba7bSLoGin 3161496ba7bSLoGin // 设置返回地址(子进程开始执行的指令地址) 3171496ba7bSLoGin if new_pcb.flags().contains(ProcessFlags::KTHREAD) { 3181496ba7bSLoGin let kthread_bootstrap_stage1_func_addr = kernel_thread_bootstrap_stage1 as usize; 3191496ba7bSLoGin new_arch_guard.rip = kthread_bootstrap_stage1_func_addr; 3201496ba7bSLoGin } else { 3211496ba7bSLoGin new_arch_guard.rip = ret_from_intr as usize; 3221496ba7bSLoGin } 3231496ba7bSLoGin 324*971462beSGnoCiYeH // 设置tls 325*971462beSGnoCiYeH if clone_flags.contains(CloneFlags::CLONE_SETTLS) { 326*971462beSGnoCiYeH drop(new_arch_guard); 327*971462beSGnoCiYeH Syscall::do_arch_prctl_64(new_pcb, ARCH_SET_FS, clone_args.tls, true)?; 328*971462beSGnoCiYeH } 329*971462beSGnoCiYeH 3301496ba7bSLoGin return Ok(()); 3311496ba7bSLoGin } 3321496ba7bSLoGin 3331496ba7bSLoGin /// 切换进程 3341496ba7bSLoGin /// 3351496ba7bSLoGin /// ## 参数 3361496ba7bSLoGin /// 3371496ba7bSLoGin /// - `prev`:上一个进程的pcb 3381496ba7bSLoGin /// - `next`:下一个进程的pcb 3391496ba7bSLoGin pub unsafe fn switch_process(prev: Arc<ProcessControlBlock>, next: Arc<ProcessControlBlock>) { 3401496ba7bSLoGin assert!(CurrentIrqArch::is_irq_enabled() == false); 3411496ba7bSLoGin 3421496ba7bSLoGin // 保存浮点寄存器 3431496ba7bSLoGin prev.arch_info().save_fp_state(); 3441496ba7bSLoGin // 切换浮点寄存器 3451496ba7bSLoGin next.arch_info().restore_fp_state(); 3461496ba7bSLoGin 3471496ba7bSLoGin // 切换fsbase 3481496ba7bSLoGin prev.arch_info().save_fsbase(); 3491496ba7bSLoGin next.arch_info().restore_fsbase(); 3501496ba7bSLoGin 3511496ba7bSLoGin // 切换gsbase 3521496ba7bSLoGin prev.arch_info().save_gsbase(); 3531496ba7bSLoGin next.arch_info().restore_gsbase(); 3541496ba7bSLoGin 3551496ba7bSLoGin // 切换地址空间 3561496ba7bSLoGin let next_addr_space = next.basic().user_vm().as_ref().unwrap().clone(); 3571496ba7bSLoGin compiler_fence(Ordering::SeqCst); 3581496ba7bSLoGin 3591496ba7bSLoGin next_addr_space.read().user_mapper.utable.make_current(); 360*971462beSGnoCiYeH drop(next_addr_space); 3611496ba7bSLoGin compiler_fence(Ordering::SeqCst); 3621496ba7bSLoGin // 切换内核栈 3631496ba7bSLoGin 3641496ba7bSLoGin // 获取arch info的锁,并强制泄露其守卫(切换上下文后,在switch_finish_hook中会释放锁) 365*971462beSGnoCiYeH let next_arch = SpinLockGuard::leak(next.arch_info()) as *mut ArchPCBInfo; 366*971462beSGnoCiYeH let prev_arch = SpinLockGuard::leak(prev.arch_info()) as *mut ArchPCBInfo; 3671496ba7bSLoGin 368*971462beSGnoCiYeH (*prev_arch).rip = switch_back as usize; 3691496ba7bSLoGin 3701496ba7bSLoGin // 恢复当前的 preempt count*2 3711496ba7bSLoGin ProcessManager::current_pcb().preempt_enable(); 3721496ba7bSLoGin ProcessManager::current_pcb().preempt_enable(); 3731496ba7bSLoGin 3741496ba7bSLoGin // 切换tss 3751496ba7bSLoGin TSSManager::current_tss().set_rsp( 3761496ba7bSLoGin x86::Ring::Ring0, 3771496ba7bSLoGin next.kernel_stack().stack_max_address().data() as u64, 3781496ba7bSLoGin ); 379*971462beSGnoCiYeH SWITCH_RESULT.as_mut().unwrap().get_mut().prev_pcb = Some(prev); 380*971462beSGnoCiYeH SWITCH_RESULT.as_mut().unwrap().get_mut().next_pcb = Some(next); 3811496ba7bSLoGin // kdebug!("switch tss ok"); 382de71ec25SLoGin compiler_fence(Ordering::SeqCst); 3831496ba7bSLoGin // 正式切换上下文 3841496ba7bSLoGin switch_to_inner(prev_arch, next_arch); 3851496ba7bSLoGin } 3861496ba7bSLoGin } 3871496ba7bSLoGin 3881496ba7bSLoGin /// 保存上下文,然后切换进程,接着jmp到`switch_finish_hook`钩子函数 3891496ba7bSLoGin #[naked] 390*971462beSGnoCiYeH unsafe extern "sysv64" fn switch_to_inner(prev: *mut ArchPCBInfo, next: *mut ArchPCBInfo) { 3911496ba7bSLoGin asm!( 3921496ba7bSLoGin // As a quick reminder for those who are unfamiliar with the System V ABI (extern "C"): 3931496ba7bSLoGin // 3941496ba7bSLoGin // - the current parameters are passed in the registers `rdi`, `rsi`, 3951496ba7bSLoGin // - we can modify scratch registers, e.g. rax 3961496ba7bSLoGin // - we cannot change callee-preserved registers arbitrarily, e.g. rbx, which is why we 3971496ba7bSLoGin // store them here in the first place. 3981496ba7bSLoGin concat!(" 3991496ba7bSLoGin // Save old registers, and load new ones 4001496ba7bSLoGin mov [rdi + {off_rbx}], rbx 4011496ba7bSLoGin mov rbx, [rsi + {off_rbx}] 4021496ba7bSLoGin 4031496ba7bSLoGin mov [rdi + {off_r12}], r12 4041496ba7bSLoGin mov r12, [rsi + {off_r12}] 4051496ba7bSLoGin 4061496ba7bSLoGin mov [rdi + {off_r13}], r13 4071496ba7bSLoGin mov r13, [rsi + {off_r13}] 4081496ba7bSLoGin 4091496ba7bSLoGin mov [rdi + {off_r14}], r14 4101496ba7bSLoGin mov r14, [rsi + {off_r14}] 4111496ba7bSLoGin 4121496ba7bSLoGin mov [rdi + {off_r15}], r15 4131496ba7bSLoGin mov r15, [rsi + {off_r15}] 4141496ba7bSLoGin 4151496ba7bSLoGin // switch segment registers (这些寄存器只能通过接下来的switch_hook的return来切换) 4161496ba7bSLoGin mov [rdi + {off_fs}], fs 4171496ba7bSLoGin mov [rdi + {off_gs}], gs 4181496ba7bSLoGin 419*971462beSGnoCiYeH // mov fs, [rsi + {off_fs}] 420*971462beSGnoCiYeH // mov gs, [rsi + {off_gs}] 421*971462beSGnoCiYeH 4221496ba7bSLoGin push rbp 4231496ba7bSLoGin push rax 4241496ba7bSLoGin 4251496ba7bSLoGin mov [rdi + {off_rbp}], rbp 4261496ba7bSLoGin mov rbp, [rsi + {off_rbp}] 4271496ba7bSLoGin 4281496ba7bSLoGin mov [rdi + {off_rsp}], rsp 4291496ba7bSLoGin mov rsp, [rsi + {off_rsp}] 4301496ba7bSLoGin 4311496ba7bSLoGin // // push RFLAGS (can only be modified via stack) 4321496ba7bSLoGin pushfq 4331496ba7bSLoGin // // pop RFLAGS into `self.rflags` 4341496ba7bSLoGin pop QWORD PTR [rdi + {off_rflags}] 4351496ba7bSLoGin 4361496ba7bSLoGin // // push `next.rflags` 4371496ba7bSLoGin push QWORD PTR [rsi + {off_rflags}] 4381496ba7bSLoGin // // pop into RFLAGS 4391496ba7bSLoGin popfq 4401496ba7bSLoGin 4411496ba7bSLoGin // push next rip to stack 4421496ba7bSLoGin push QWORD PTR [rsi + {off_rip}] 4431496ba7bSLoGin 4441496ba7bSLoGin 4451496ba7bSLoGin // When we return, we cannot even guarantee that the return address on the stack, points to 4461496ba7bSLoGin // the calling function. Thus, we have to execute this Rust hook by 4471496ba7bSLoGin // ourselves, which will unlock the contexts before the later switch. 4481496ba7bSLoGin 4491496ba7bSLoGin // Note that switch_finish_hook will be responsible for executing `ret`. 4501496ba7bSLoGin jmp {switch_hook} 4511496ba7bSLoGin "), 4521496ba7bSLoGin 4531496ba7bSLoGin off_rflags = const(offset_of!(ArchPCBInfo, rflags)), 4541496ba7bSLoGin 4551496ba7bSLoGin off_rbx = const(offset_of!(ArchPCBInfo, rbx)), 4561496ba7bSLoGin off_r12 = const(offset_of!(ArchPCBInfo, r12)), 4571496ba7bSLoGin off_r13 = const(offset_of!(ArchPCBInfo, r13)), 4581496ba7bSLoGin off_r14 = const(offset_of!(ArchPCBInfo, r14)), 4591496ba7bSLoGin off_rbp = const(offset_of!(ArchPCBInfo, rbp)), 4601496ba7bSLoGin off_rsp = const(offset_of!(ArchPCBInfo, rsp)), 4611496ba7bSLoGin off_r15 = const(offset_of!(ArchPCBInfo, r15)), 4621496ba7bSLoGin off_rip = const(offset_of!(ArchPCBInfo, rip)), 4631496ba7bSLoGin off_fs = const(offset_of!(ArchPCBInfo, fs)), 4641496ba7bSLoGin off_gs = const(offset_of!(ArchPCBInfo, gs)), 4651496ba7bSLoGin 4661496ba7bSLoGin switch_hook = sym crate::process::switch_finish_hook, 4671496ba7bSLoGin options(noreturn), 4681496ba7bSLoGin ); 4691496ba7bSLoGin } 4701496ba7bSLoGin 4711496ba7bSLoGin /// 从`switch_to_inner`返回后,执行这个函数 4721496ba7bSLoGin /// 4731496ba7bSLoGin /// 也就是说,当进程再次被调度时,会从这里开始执行 4741496ba7bSLoGin #[inline(never)] 4751496ba7bSLoGin unsafe extern "sysv64" fn switch_back() { 4761496ba7bSLoGin asm!(concat!( 4771496ba7bSLoGin " 4781496ba7bSLoGin pop rax 4791496ba7bSLoGin pop rbp 4801496ba7bSLoGin " 4811496ba7bSLoGin )) 4821496ba7bSLoGin } 4831496ba7bSLoGin 4841496ba7bSLoGin pub unsafe fn arch_switch_to_user(path: String, argv: Vec<String>, envp: Vec<String>) -> ! { 4851496ba7bSLoGin // 以下代码不能发生中断 4861496ba7bSLoGin CurrentIrqArch::interrupt_disable(); 4871496ba7bSLoGin 4881496ba7bSLoGin let current_pcb = ProcessManager::current_pcb(); 4891496ba7bSLoGin let trap_frame_vaddr = VirtAddr::new( 4901496ba7bSLoGin current_pcb.kernel_stack().stack_max_address().data() - core::mem::size_of::<TrapFrame>(), 4911496ba7bSLoGin ); 4921496ba7bSLoGin // kdebug!("trap_frame_vaddr: {:?}", trap_frame_vaddr); 4931496ba7bSLoGin let new_rip = VirtAddr::new(ret_from_intr as usize); 4941496ba7bSLoGin 4951496ba7bSLoGin assert!( 4961496ba7bSLoGin (x86::current::registers::rsp() as usize) < trap_frame_vaddr.data(), 4971496ba7bSLoGin "arch_switch_to_user(): current_rsp >= fake trap 4981496ba7bSLoGin frame vaddr, this may cause some illegal access to memory! 4991496ba7bSLoGin rsp: {:#x}, trap_frame_vaddr: {:#x}", 5001496ba7bSLoGin x86::current::registers::rsp() as usize, 5011496ba7bSLoGin trap_frame_vaddr.data() 5021496ba7bSLoGin ); 5031496ba7bSLoGin 5041496ba7bSLoGin let mut arch_guard = current_pcb.arch_info_irqsave(); 5051496ba7bSLoGin arch_guard.rsp = trap_frame_vaddr.data(); 5061496ba7bSLoGin 5071496ba7bSLoGin arch_guard.fs = USER_DS.bits(); 5081496ba7bSLoGin arch_guard.gs = USER_DS.bits(); 5091496ba7bSLoGin 5101496ba7bSLoGin switch_fs_and_gs( 5111496ba7bSLoGin SegmentSelector::from_bits_truncate(arch_guard.fs), 5121496ba7bSLoGin SegmentSelector::from_bits_truncate(arch_guard.gs), 5131496ba7bSLoGin ); 5141496ba7bSLoGin arch_guard.rip = new_rip.data(); 5151496ba7bSLoGin 5161496ba7bSLoGin drop(arch_guard); 5171496ba7bSLoGin 5181496ba7bSLoGin // 删除kthread的标志 5191496ba7bSLoGin current_pcb.flags().remove(ProcessFlags::KTHREAD); 5201496ba7bSLoGin current_pcb.worker_private().take(); 5211496ba7bSLoGin 5221496ba7bSLoGin let mut trap_frame = TrapFrame::new(); 5231496ba7bSLoGin 5241496ba7bSLoGin compiler_fence(Ordering::SeqCst); 5251496ba7bSLoGin Syscall::do_execve(path, argv, envp, &mut trap_frame).unwrap_or_else(|e| { 5261496ba7bSLoGin panic!( 5271496ba7bSLoGin "arch_switch_to_user(): pid: {pid:?}, Failed to execve: , error: {e:?}", 5281496ba7bSLoGin pid = current_pcb.pid(), 5291496ba7bSLoGin e = e 5301496ba7bSLoGin ); 5311496ba7bSLoGin }); 5321496ba7bSLoGin compiler_fence(Ordering::SeqCst); 5331496ba7bSLoGin 5341496ba7bSLoGin // 重要!在这里之后,一定要保证上面的引用计数变量、动态申请的变量、锁的守卫都被drop了,否则可能导致内存安全问题! 5351496ba7bSLoGin 5361496ba7bSLoGin drop(current_pcb); 5371496ba7bSLoGin 5381496ba7bSLoGin compiler_fence(Ordering::SeqCst); 5391496ba7bSLoGin ready_to_switch_to_user(trap_frame, trap_frame_vaddr.data(), new_rip.data()); 5401496ba7bSLoGin } 5411496ba7bSLoGin 5421496ba7bSLoGin /// 由于需要依赖ret来切换到用户态,所以不能inline 5431496ba7bSLoGin #[inline(never)] 5441496ba7bSLoGin unsafe extern "sysv64" fn ready_to_switch_to_user( 5451496ba7bSLoGin trap_frame: TrapFrame, 5461496ba7bSLoGin trapframe_vaddr: usize, 5471496ba7bSLoGin new_rip: usize, 5481496ba7bSLoGin ) -> ! { 5491496ba7bSLoGin *(trapframe_vaddr as *mut TrapFrame) = trap_frame; 5501496ba7bSLoGin asm!( 5511496ba7bSLoGin "mov rsp, {trapframe_vaddr}", 5521496ba7bSLoGin "push {new_rip}", 5531496ba7bSLoGin "ret", 5541496ba7bSLoGin trapframe_vaddr = in(reg) trapframe_vaddr, 5551496ba7bSLoGin new_rip = in(reg) new_rip 5561496ba7bSLoGin ); 5571496ba7bSLoGin unreachable!() 5581496ba7bSLoGin } 559