fast_trap/
fast.rs

1use crate::{EntireHandler, FlowContext, TrapHandler};
2use core::{mem::MaybeUninit, ptr::NonNull};
3
4/// 快速路径函数。
5pub type FastHandler = extern "C" fn(
6    ctx: FastContext,
7    a1: usize,
8    a2: usize,
9    a3: usize,
10    a4: usize,
11    a5: usize,
12    a6: usize,
13    a7: usize,
14) -> FastResult;
15
16/// 快速路径上下文。
17///
18/// 将陷入处理器上下文中在快速路径中可安全操作的部分暴露给快速路径函数。
19#[repr(transparent)]
20pub struct FastContext(&'static mut TrapHandler);
21
22impl FastContext {
23    /// 访问陷入上下文的 a0 寄存器。
24    ///
25    /// 由于 a0 寄存器在快速路径中用于传递上下文指针,
26    /// 将陷入上下文的 a0 暂存到陷入处理器上下文中。
27    #[inline]
28    pub fn a0(&self) -> usize {
29        self.0.scratch
30    }
31
32    /// 获取控制流上下文。
33    #[inline]
34    pub fn regs(&mut self) -> &mut FlowContext {
35        unsafe { self.0.context.as_mut() }
36    }
37
38    /// 交换上下文指针。
39    #[inline]
40    pub fn swap_context(&mut self, new: NonNull<FlowContext>) -> NonNull<FlowContext> {
41        core::mem::replace(&mut self.0.context, new)
42    }
43
44    /// 启动一个带有 `argc` 个参数的新上下文。
45    #[inline]
46    pub fn call(self, argc: usize) -> FastResult {
47        unsafe { self.0.context.as_ref().load_others() };
48        if argc <= 2 {
49            FastResult::FastCall
50        } else {
51            FastResult::Call
52        }
53    }
54
55    /// 从快速路径恢复。
56    ///
57    /// > **NOTICE** 必须先手工调用 `save_args`,或通过其他方式设置参数寄存器。
58    #[inline]
59    pub fn restore(self) -> FastResult {
60        FastResult::Restore
61    }
62
63    /// 丢弃当前上下文,并直接切换到另一个上下文。
64    #[inline]
65    pub fn switch_to(self, others: NonNull<FlowContext>) -> FastResult {
66        unsafe { others.as_ref().load_others() };
67        self.0.context = others;
68        FastResult::Switch
69    }
70
71    /// 向完整路径 `f` 传递对象 `t`。
72    ///
73    /// > **NOTICE** 必须先手工调用 `save_args`,或通过其他方式设置参数寄存器。
74    #[inline]
75    pub fn continue_with<T: 'static>(self, f: EntireHandler<T>, t: T) -> FastResult {
76        // TODO 检查栈溢出
77        unsafe { *self.0.locate_fast_mail() = MaybeUninit::new(t) };
78        self.0.scratch = f as _;
79        FastResult::Continue
80    }
81}
82
83/// 快速路径处理结果。
84#[repr(usize)]
85pub enum FastResult {
86    /// 调用新上下文,只需设置 2 个或更少参数。
87    FastCall = 0,
88    /// 调用新上下文,需要设置超过 2 个参数。
89    Call = 1,
90    /// 从快速路径直接返回。
91    Restore = 2,
92    /// 直接切换到另一个上下文。
93    Switch = 3,
94    /// 调用完整路径函数。
95    Continue = 4,
96}