Skip to content

Optimize critical_section: use MSR instruction #576

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

Merged
merged 6 commits into from
Jan 27, 2025
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion cortex-m/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ cm7 = []
cm7-r0p1 = ["cm7"]
linker-plugin-lto = []
std = []
critical-section-single-core = ["critical-section/restore-state-bool"]
critical-section-single-core = ["critical-section/restore-state-u32"]

[package.metadata.docs.rs]
targets = [
Expand Down
17 changes: 8 additions & 9 deletions cortex-m/src/critical_section.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,17 @@ set_impl!(SingleCoreCriticalSection);

unsafe impl Impl for SingleCoreCriticalSection {
unsafe fn acquire() -> RawRestoreState {
let was_active = primask::read().is_active();
// Backup previous state of PRIMASK register. We access the entire register directly as a
// u32 instead of using the primask::read() function to minimize the number of processor
// cycles during which interrupts are disabled.
let restore_state = primask::read_raw();
// NOTE: Fence guarantees are provided by interrupt::disable(), which performs a `compiler_fence(SeqCst)`.
interrupt::disable();
was_active
restore_state
}

unsafe fn release(was_active: RawRestoreState) {
// Only re-enable interrupts if they were enabled before the critical section.
if was_active {
// NOTE: Fence guarantees are provided by interrupt::enable(), which performs a
// `compiler_fence(SeqCst)`.
interrupt::enable()
}
unsafe fn release(restore_state: RawRestoreState) {
// NOTE: Fence guarantees are provided by primask::write_raw(), which performs a `compiler_fence(SeqCst)`.
primask::write_raw(restore_state);
}
}
11 changes: 5 additions & 6 deletions cortex-m/src/interrupt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,18 +66,17 @@ pub fn free<F, R>(f: F) -> R
where
F: FnOnce() -> R,
{
let primask = crate::register::primask::read();
// Backup previous state of PRIMASK register. We access the entire register directly as a
// u32 instead of using the primask::read() function to minimize the number of processor
// cycles during which interrupts are disabled.
let primask = crate::register::primask::read_raw();

// disable interrupts
disable();

let r = f();

// If the interrupts were active before our `disable` call, then re-enable
// them. Otherwise, keep them disabled
if primask.is_active() {
unsafe { enable() }
}
crate::register::primask::write_raw(primask);

r
}
Expand Down
30 changes: 26 additions & 4 deletions cortex-m/src/register/primask.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

#[cfg(cortex_m)]
use core::arch::asm;
#[cfg(cortex_m)]
use core::sync::atomic::{compiler_fence, Ordering};

/// All exceptions with configurable priority are ...
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
Expand All @@ -26,15 +28,35 @@ impl Primask {
}
}

/// Reads the CPU register
/// Reads the prioritizable interrupt mask
#[cfg(cortex_m)]
#[inline]
pub fn read() -> Primask {
let r: u32;
unsafe { asm!("mrs {}, PRIMASK", out(reg) r, options(nomem, nostack, preserves_flags)) };
if r & (1 << 0) == (1 << 0) {
if read_raw() & (1 << 0) == (1 << 0) {
Primask::Inactive
} else {
Primask::Active
}
}

/// Reads the entire PRIMASK register
/// Note that bits [31:1] are reserved and UNK (Unknown)
#[cfg(cortex_m)]
#[inline]
pub fn read_raw() -> u32 {
let r: u32;
unsafe { asm!("mrs {}, PRIMASK", out(reg) r, options(nomem, nostack, preserves_flags)) };
r
}

/// Writes the entire PRIMASK register
/// Note that bits [31:1] are reserved and SBZP (Should-Be-Zero-or-Preserved)
#[cfg(cortex_m)]
#[inline]
pub fn write_raw(r: u32) {
Copy link
Member

Choose a reason for hiding this comment

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

This needs to be unsafe because it can be used to enable interrupts, to match interrupt::enable(). If it was safe to call, user code could enable interrupts when other unsafe functions depend on them being disabled for memory safety, leading to UB.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fixed. Do you require safety comments for the unsafe blocks? That didn't look like it is a policy in this crate.

Copy link
Member

Choose a reason for hiding this comment

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

Not for the unsafe blocks inside functions, but we should add a # Safety note to the docs for that function. I suggest:

# Safety

This method is unsafe as other unsafe code may rely on interrupts remaining disabled, for example during a critical section, and being able to safely re-enable them would lead to undefined behaviour. Do not call this function in a context where interrupts are expected to remain disabled - for example, in the midst of a critical section or `interrupt::free()` call.

It's a bit vague and hard to comply with, but I think that's the nature of the problem. Happy to hear other suggestions.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That sounds good, I've added it.

// Ensure no preceeding memory accesses are reordered to after interrupts are possibly enabled.
compiler_fence(Ordering::SeqCst);
unsafe { asm!("msr PRIMASK, {}", in(reg) r, options(nomem, nostack, preserves_flags)) };
// Ensure no subsequent memory accesses are reordered to before interrupts are possibly disabled.
compiler_fence(Ordering::SeqCst);
}
35 changes: 35 additions & 0 deletions testsuite/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#![no_std]

extern crate cortex_m_rt;
use core::sync::atomic::{AtomicBool, Ordering};

#[cfg(target_env = "")] // appease clippy
#[panic_handler]
Expand All @@ -11,8 +12,16 @@ fn panic(info: &core::panic::PanicInfo) -> ! {
minitest::fail()
}

static EXCEPTION_FLAG: AtomicBool = AtomicBool::new(false);

#[cortex_m_rt::exception]
fn PendSV() {
EXCEPTION_FLAG.store(true, Ordering::SeqCst);
}

#[minitest::tests]
mod tests {
use crate::{Ordering, EXCEPTION_FLAG};
use minitest::log;

#[init]
Expand Down Expand Up @@ -51,4 +60,30 @@ mod tests {
assert!(!p.DWT.has_cycle_counter());
}
}

#[test]
fn critical_section_nesting() {
EXCEPTION_FLAG.store(false, Ordering::SeqCst);
critical_section::with(|_| {
critical_section::with(|_| {
cortex_m::peripheral::SCB::set_pendsv();
assert!(!EXCEPTION_FLAG.load(Ordering::SeqCst));
});
assert!(!EXCEPTION_FLAG.load(Ordering::SeqCst));
});
assert!(EXCEPTION_FLAG.load(Ordering::SeqCst));
}

#[test]
fn interrupt_free_nesting() {
EXCEPTION_FLAG.store(false, Ordering::SeqCst);
cortex_m::interrupt::free(|| {
cortex_m::interrupt::free(|| {
cortex_m::peripheral::SCB::set_pendsv();
assert!(!EXCEPTION_FLAG.load(Ordering::SeqCst));
});
assert!(!EXCEPTION_FLAG.load(Ordering::SeqCst));
});
assert!(EXCEPTION_FLAG.load(Ordering::SeqCst));
}
}
Loading