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