Skip to main content

ax_cpu/arch/aarch64/
context.rs

1#[cfg(feature = "context")]
2use core::arch::naked_asm;
3use core::fmt;
4#[cfg(feature = "context")]
5use core::mem::{align_of, offset_of, size_of};
6
7#[cfg(feature = "context")]
8use ax_memory_addr::VirtAddr;
9
10#[cfg(feature = "fp-simd")]
11use super::fp::FpState;
12#[cfg(feature = "context")]
13use crate::{KernelTlsBase, TaskLocalState, context::TaskAnchor};
14
15/// Saved registers when a trap (exception) occurs.
16#[repr(C)]
17#[derive(Default, Clone, Copy)]
18pub struct TrapFrame {
19    /// General-purpose registers (X0..X30).
20    pub x: super::registers::GeneralRegisters,
21    /// Exception Link Register (ELR_EL1).
22    pub elr: u64,
23    /// Saved Process Status Register (SPSR_EL1).
24    pub spsr: u64,
25
26    /// Stack pointer at the time of the exception.
27    /// Populated by SAVE_REGS as `sp_before_sub = sp_after_sub + trapframe_size`.
28    ///
29    /// Note: This field is read-only (saved by SAVE_REGS for inspection only).
30    /// The actual SP is restored by RESTORE_REGS via `add sp, sp, #trapframe_size`,
31    /// not from this field. Modifying this value will NOT affect the actual SP
32    /// after exception return.
33    pub sp: u64,
34}
35
36impl fmt::Debug for TrapFrame {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        writeln!(f, "TrapFrame: {{")?;
39        for (i, &reg) in self.x.iter().enumerate() {
40            writeln!(f, "    x{i}: {reg:#x},")?;
41        }
42        writeln!(f, "    elr: {:#x},", self.elr)?;
43        writeln!(f, "    spsr: {:#x},", self.spsr)?;
44        writeln!(f, "    sp: {:#x},", self.sp)?;
45        write!(f, "}}")?;
46        Ok(())
47    }
48}
49
50impl TrapFrame {
51    /// Copies IRQ sampling values from this saved machine image.
52    pub fn interrupted_context(&self) -> crate::trap::InterruptedContext {
53        use crate::trap::{InterruptedContext, InterruptedPrivilege};
54        InterruptedContext {
55            pc: self.ip(),
56            sp: self.sp as usize,
57            fp: self.x[29] as usize,
58            privilege: match self.origin() {
59                crate::trap::TrapOrigin::Kernel => InterruptedPrivilege::Kernel,
60                crate::trap::TrapOrigin::User => InterruptedPrivilege::User,
61            },
62        }
63    }
64
65    /// Returns the privilege domain represented by this register image.
66    pub const fn origin(&self) -> crate::TrapOrigin {
67        if self.spsr & 0b1_1111 == 0 {
68            crate::TrapOrigin::User
69        } else {
70            crate::TrapOrigin::Kernel
71        }
72    }
73
74    /// Gets the 0th syscall argument.
75    pub const fn arg0(&self) -> usize {
76        self.x[0] as _
77    }
78
79    /// Sets the 0th syscall argument.
80    pub const fn set_arg0(&mut self, a0: usize) {
81        self.x[0] = a0 as _;
82    }
83
84    /// Gets the 1st syscall argument.
85    pub const fn arg1(&self) -> usize {
86        self.x[1] as _
87    }
88
89    /// Sets the 1st syscall argument.
90    pub const fn set_arg1(&mut self, a1: usize) {
91        self.x[1] = a1 as _;
92    }
93
94    /// Gets the 2nd syscall argument.
95    pub const fn arg2(&self) -> usize {
96        self.x[2] as _
97    }
98
99    /// Sets the 2nd syscall argument.
100    pub const fn set_arg2(&mut self, a2: usize) {
101        self.x[2] = a2 as _;
102    }
103
104    /// Gets the 3rd syscall argument.
105    pub const fn arg3(&self) -> usize {
106        self.x[3] as _
107    }
108
109    /// Sets the 3rd syscall argument.
110    pub const fn set_arg3(&mut self, a3: usize) {
111        self.x[3] = a3 as _;
112    }
113
114    /// Gets the 4th syscall argument.
115    pub const fn arg4(&self) -> usize {
116        self.x[4] as _
117    }
118
119    /// Sets the 4th syscall argument.
120    pub const fn set_arg4(&mut self, a4: usize) {
121        self.x[4] = a4 as _;
122    }
123
124    /// Gets the 5th syscall argument.
125    pub const fn arg5(&self) -> usize {
126        self.x[5] as _
127    }
128
129    /// Sets the 5th syscall argument.
130    pub const fn set_arg5(&mut self, a5: usize) {
131        self.x[5] = a5 as _;
132    }
133
134    /// Gets the instruction pointer.
135    pub const fn ip(&self) -> usize {
136        self.elr as _
137    }
138
139    /// Sets the instruction pointer.
140    pub const fn set_ip(&mut self, pc: usize) {
141        self.elr = pc as _;
142    }
143
144    /// Get the syscall number.
145    pub const fn sysno(&self) -> usize {
146        self.x[8] as usize
147    }
148
149    /// Sets the syscall number.
150    pub const fn set_sysno(&mut self, sysno: usize) {
151        self.x[8] = sysno as _;
152    }
153
154    /// Gets the return value register.
155    pub const fn retval(&self) -> usize {
156        self.x[0] as _
157    }
158
159    /// Sets the return value register.
160    pub const fn set_retval(&mut self, r0: usize) {
161        self.x[0] = r0 as _;
162    }
163
164    /// Sets the return address.
165    pub const fn set_ra(&mut self, lr: usize) {
166        self.x[30] = lr as _;
167    }
168
169    /// Copies the machine registers needed by a runtime stack unwinder.
170    pub fn backtrace_registers(&self) -> crate::trap::BacktraceRegisters {
171        crate::trap::BacktraceRegisters::new(self.x[29] as _, self.elr as _, self.x[30] as _)
172    }
173}
174
175/// Saved hardware states of a task.
176///
177/// The context usually includes:
178///
179/// - Callee-saved registers
180/// - Stack pointer register
181/// - Thread pointer register (for kernel-space thread-local storage)
182/// - FP/SIMD registers
183///
184/// On context switch, current task saves its context from CPU to memory,
185/// and the next task restores its context from memory to CPU.
186#[allow(missing_docs)]
187#[repr(C)]
188#[derive(Debug, Default)]
189#[cfg(feature = "context")]
190pub struct TaskContext {
191    sp: u64,
192    r19: u64,
193    r20: u64,
194    r21: u64,
195    r22: u64,
196    r23: u64,
197    r24: u64,
198    r25: u64,
199    r26: u64,
200    r27: u64,
201    r28: u64,
202    r29: u64,
203    lr: u64, // r30
204    /// Architecture-neutral current-header and kernel-TLS switch state.
205    task_local: TaskLocalState,
206    #[cfg(feature = "fp-simd")]
207    fp_state: FpState,
208}
209
210// `stp`/`ldp` address only the first member of each pair. Prove the paired
211// fields are adjacent and that the task TLS newtype has the register width.
212#[cfg(feature = "context")]
213const _: () = {
214    assert!(size_of::<KernelTlsBase>() == size_of::<usize>());
215    assert!(align_of::<KernelTlsBase>() == align_of::<usize>());
216    assert!(offset_of!(TaskContext, sp) == 0);
217    assert!(offset_of!(TaskContext, r20) == offset_of!(TaskContext, r19) + size_of::<u64>());
218    assert!(offset_of!(TaskContext, r22) == offset_of!(TaskContext, r21) + size_of::<u64>());
219    assert!(offset_of!(TaskContext, r24) == offset_of!(TaskContext, r23) + size_of::<u64>());
220    assert!(offset_of!(TaskContext, r26) == offset_of!(TaskContext, r25) + size_of::<u64>());
221    assert!(offset_of!(TaskContext, r28) == offset_of!(TaskContext, r27) + size_of::<u64>());
222    assert!(offset_of!(TaskContext, lr) == offset_of!(TaskContext, r29) + size_of::<u64>());
223    assert!(offset_of!(TaskContext, task_local) == offset_of!(TaskContext, lr) + size_of::<u64>());
224};
225
226#[cfg(feature = "context")]
227impl TaskContext {
228    /// Creates a dummy context for a new task.
229    ///
230    /// Note the context is not initialized, it will be filled by
231    /// [`switch_to`](Self::switch_to) (for initial tasks) and [`init`]
232    /// (for regular tasks) methods.
233    ///
234    /// [`init`]: TaskContext::init
235    pub fn new() -> Self {
236        Self::default()
237    }
238
239    /// Initializes the context for a new task, with the given entry point and
240    /// kernel stack.
241    pub fn init(&mut self, entry: usize, kstack_top: VirtAddr, kernel_tls: KernelTlsBase) {
242        self.sp = kstack_top.as_usize() as u64;
243        self.lr = entry as u64;
244        self.task_local.set_kernel_tls(kernel_tls);
245    }
246
247    /// Sets the pinned task-owned runtime task anchor.
248    pub fn set_task_anchor(&mut self, header: TaskAnchor) {
249        self.task_local.set_task_anchor(header);
250    }
251
252    /// Returns the configured task-owned runtime task anchor.
253    pub const fn task_anchor(&self) -> Option<TaskAnchor> {
254        self.task_local.task_anchor()
255    }
256
257    /// Saves the running parent's hardware FP image into an unpublished child.
258    ///
259    /// The runtime must pin the parent CPU while calling this method. Kernel
260    /// code uses the soft-float ABI; eager task switching keeps the parent's
261    /// user register image live across kernel entry and preemption.
262    #[cfg(all(feature = "fp-simd", feature = "uspace"))]
263    pub fn clone_user_fp_state_into(&self, child: &mut Self) {
264        assert!(
265            self.task_anchor().is_some(),
266            "FP clone parent must be bound"
267        );
268        assert!(
269            child.task_anchor().is_none(),
270            "FP clone child must be unpublished"
271        );
272        child.fp_state.save();
273    }
274
275    /// Completes FP/SIMD work before current-context publication.
276    pub fn prepare_switch_to(&mut self, _next_ctx: &Self) {
277        #[cfg(feature = "fp-simd")]
278        {
279            self.fp_state.save();
280            _next_ctx.fp_state.restore();
281        }
282    }
283
284    /// Performs only the final GPR/current/TLS transfer.
285    ///
286    /// # Safety
287    ///
288    /// Scheduling must be serialized, FP state prepared, and the next current
289    /// anchor published. Both contexts and their anchors must remain pinned and
290    /// alive. IRQs must remain disabled from publication through this call,
291    /// with no intervening fallible or ownership-sensitive work.
292    #[inline(always)]
293    pub unsafe fn switch_to(&mut self, next_ctx: &Self) {
294        unsafe { context_switch_raw(self, next_ctx) }
295    }
296}
297
298#[cfg(kernel_tls)]
299#[unsafe(naked)]
300#[cfg(feature = "context")]
301unsafe extern "C" fn context_switch_raw(_current_task: &mut TaskContext, _next_task: &TaskContext) {
302    naked_asm!(
303        "
304        // save old context (callee-saved registers)
305        stp     x29, x30, [x0, {r29_offset}]
306        stp     x27, x28, [x0, {r27_offset}]
307        stp     x25, x26, [x0, {r25_offset}]
308        stp     x23, x24, [x0, {r23_offset}]
309        stp     x21, x22, [x0, {r21_offset}]
310        stp     x19, x20, [x0, {r19_offset}]
311        mov     x19, sp
312        str     x19, [x0, {sp_offset}]
313        mrs     x9, tpidr_el0
314        str     x9, [x0, {kernel_tls_offset}]
315
316        // restore new context
317        ldr     x9, [x1, {kernel_tls_offset}]
318        msr     tpidr_el0, x9
319        ldr     x19, [x1, {sp_offset}]
320        mov     sp, x19
321        ldp     x19, x20, [x1, {r19_offset}]
322        ldp     x21, x22, [x1, {r21_offset}]
323        ldp     x23, x24, [x1, {r23_offset}]
324        ldp     x25, x26, [x1, {r25_offset}]
325        ldp     x27, x28, [x1, {r27_offset}]
326        ldp     x29, x30, [x1, {r29_offset}]
327        ldr     x9, [x1, {context_header_offset}]
328        msr     sp_el0, x9
329
330        ret",
331        sp_offset = const offset_of!(TaskContext, sp),
332        r19_offset = const offset_of!(TaskContext, r19),
333        r21_offset = const offset_of!(TaskContext, r21),
334        r23_offset = const offset_of!(TaskContext, r23),
335        r25_offset = const offset_of!(TaskContext, r25),
336        r27_offset = const offset_of!(TaskContext, r27),
337        r29_offset = const offset_of!(TaskContext, r29),
338        context_header_offset = const offset_of!(TaskContext, task_local)
339            + offset_of!(TaskLocalState, context_header),
340        kernel_tls_offset = const offset_of!(TaskContext, task_local)
341            + offset_of!(TaskLocalState, kernel_tls),
342    )
343}
344
345#[cfg(not(kernel_tls))]
346#[unsafe(naked)]
347#[cfg(feature = "context")]
348unsafe extern "C" fn context_switch_raw(_current_task: &mut TaskContext, _next_task: &TaskContext) {
349    naked_asm!(
350        "
351        // save old context (callee-saved registers)
352        stp     x29, x30, [x0, {r29_offset}]
353        stp     x27, x28, [x0, {r27_offset}]
354        stp     x25, x26, [x0, {r25_offset}]
355        stp     x23, x24, [x0, {r23_offset}]
356        stp     x21, x22, [x0, {r21_offset}]
357        stp     x19, x20, [x0, {r19_offset}]
358        mov     x19, sp
359        str     x19, [x0, {sp_offset}]
360
361        // LinuxCurrent keeps task identity in SP_EL0. TPIDR_EL0 remains
362        // userspace-owned and is never part of a kernel task switch.
363        ldr     x19, [x1, {sp_offset}]
364        mov     sp, x19
365        ldp     x19, x20, [x1, {r19_offset}]
366        ldp     x21, x22, [x1, {r21_offset}]
367        ldp     x23, x24, [x1, {r23_offset}]
368        ldp     x25, x26, [x1, {r25_offset}]
369        ldp     x27, x28, [x1, {r27_offset}]
370        ldp     x29, x30, [x1, {r29_offset}]
371        ldr     x9, [x1, {context_header_offset}]
372        msr     sp_el0, x9
373        ret",
374        sp_offset = const offset_of!(TaskContext, sp),
375        r19_offset = const offset_of!(TaskContext, r19),
376        r21_offset = const offset_of!(TaskContext, r21),
377        r23_offset = const offset_of!(TaskContext, r23),
378        r25_offset = const offset_of!(TaskContext, r25),
379        r27_offset = const offset_of!(TaskContext, r27),
380        r29_offset = const offset_of!(TaskContext, r29),
381        context_header_offset = const offset_of!(TaskContext, task_local)
382            + offset_of!(TaskLocalState, context_header),
383    )
384}