Skip to content

Add enter_unprivileged() function #594

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions cortex-m/src/asm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,36 @@ pub unsafe fn semihosting_syscall(mut nr: u32, arg: u32) -> u32 {
nr
}

/// Switch to unprivileged mode.
///
/// Sets CONTROL.SPSEL (setting the program stack to be the active
/// stack) and CONTROL.nPRIV (setting unprivileged mode), updates the
/// program stack pointer to the address in `psp`, then jumps to the
/// address in `entry`.
///
/// # Safety
///
/// `psp` and `entry` must point to valid stack memory and executable
/// code, respectively.
#[cfg(cortex_m)]
#[inline(always)]
pub fn enter_unprivileged(psp: &u32, entry: fn() -> !) -> ! {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think PSP should be either a raw pointer, or a new type that requires appropriate alignment. Conceptually this is similar to https://docs.rs/rp2040-hal/latest/rp2040_hal/multicore/struct.Core.html#method.spawn and we could borrow the StackAllocation idea.

Unfortunately I don't immediately recall if PSP needs to be 4 or 8 byte aligned. We should check, and document.

The function also needs to be marked unsafe!

unsafe {
asm!(
"mrs {tmp}, CONTROL",
"orr {tmp}, #2",
"msr PSP, {psp}",
"msr CONTROL, {tmp}",
"isb",
"bx {ent}",
tmp = in(reg) 0,
psp = in(reg) psp,
ent = in(reg) entry,
options(noreturn, nomem, nostack)
);
}
}

/// Bootstrap.
///
/// Clears CONTROL.SPSEL (setting the main stack to be the active stack),
Expand Down