• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2 
3 /*
4 Adapted from https://github.com/rust-embedded/msp430.
5 
6 See also src/imp/msp430.rs.
7 
8 Refs: https://www.ti.com/lit/ug/slau208q/slau208q.pdf
9 */
10 
11 #[cfg(not(portable_atomic_no_asm))]
12 use core::arch::asm;
13 
14 pub(super) use super::super::msp430 as atomic;
15 
16 pub(super) type State = u16;
17 
18 /// Disables interrupts and returns the previous interrupt state.
19 #[inline(always)]
disable() -> State20 pub(super) fn disable() -> State {
21     let r: State;
22     // SAFETY: reading the status register and disabling interrupts are safe.
23     // (see module-level comments of interrupt/mod.rs on the safety of using privileged instructions)
24     unsafe {
25         // Do not use `nomem` and `readonly` because prevent subsequent memory accesses from being reordered before interrupts are disabled.
26         // Do not use `preserves_flags` because DINT modifies the GIE (global interrupt enable) bit of the status register.
27         #[cfg(not(portable_atomic_no_asm))]
28         asm!(
29             "mov R2, {0}",
30             "dint {{ nop",
31             out(reg) r,
32             options(nostack),
33         );
34         #[cfg(portable_atomic_no_asm)]
35         {
36             llvm_asm!("mov R2, $0" : "=r"(r) ::: "volatile");
37             llvm_asm!("dint { nop" ::: "memory" : "volatile");
38         }
39     }
40     r
41 }
42 
43 /// Restores the previous interrupt state.
44 ///
45 /// # Safety
46 ///
47 /// The state must be the one retrieved by the previous `disable`.
48 #[inline(always)]
restore(r: State)49 pub(super) unsafe fn restore(r: State) {
50     // SAFETY: the caller must guarantee that the state was retrieved by the previous `disable`,
51     unsafe {
52         // This clobbers the entire status register, but we never explicitly modify
53         // flags within a critical session, and the only flags that may be changed
54         // within a critical session are the arithmetic flags that are changed as
55         // a side effect of arithmetic operations, etc., which LLVM recognizes,
56         // so it is safe to clobber them here.
57         // See also the discussion at https://github.com/taiki-e/portable-atomic/pull/40.
58         //
59         // Do not use `nomem` and `readonly` because prevent preceding memory accesses from being reordered after interrupts are enabled.
60         // Do not use `preserves_flags` because MOV modifies the status register.
61         #[cfg(not(portable_atomic_no_asm))]
62         asm!("nop {{ mov {0}, R2 {{ nop", in(reg) r, options(nostack));
63         #[cfg(portable_atomic_no_asm)]
64         llvm_asm!("nop { mov $0, R2 { nop" :: "r"(r) : "memory" : "volatile");
65     }
66 }
67