1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2
3 /*
4 Adapted from https://github.com/Rahix/avr-device.
5
6 Refs:
7 - AVR Instruction Set Manual https://ww1.microchip.com/downloads/en/DeviceDoc/AVR-InstructionSet-Manual-DS40002198.pdf
8 */
9
10 #[cfg(not(portable_atomic_no_asm))]
11 use core::arch::asm;
12
13 pub(super) type State = u8;
14
15 /// Disables interrupts and returns the previous interrupt state.
16 #[inline(always)]
disable() -> State17 pub(super) fn disable() -> State {
18 let sreg: State;
19 // SAFETY: reading the status register (SREG) and disabling interrupts are safe.
20 // (see module-level comments of interrupt/mod.rs on the safety of using privileged instructions)
21 unsafe {
22 // Do not use `nomem` and `readonly` because prevent subsequent memory accesses from being reordered before interrupts are disabled.
23 // Do not use `preserves_flags` because CLI modifies the I bit of the status register (SREG).
24 // Refs: https://ww1.microchip.com/downloads/en/DeviceDoc/AVR-InstructionSet-Manual-DS40002198.pdf#page=58
25 #[cfg(not(portable_atomic_no_asm))]
26 asm!(
27 "in {0}, 0x3F",
28 "cli",
29 out(reg) sreg,
30 options(nostack),
31 );
32 #[cfg(portable_atomic_no_asm)]
33 {
34 llvm_asm!("in $0, 0x3F" : "=r"(sreg) ::: "volatile");
35 llvm_asm!("cli" ::: "memory" : "volatile");
36 }
37 }
38 sreg
39 }
40
41 /// Restores the previous interrupt state.
42 ///
43 /// # Safety
44 ///
45 /// The state must be the one retrieved by the previous `disable`.
46 #[inline(always)]
restore(sreg: State)47 pub(super) unsafe fn restore(sreg: State) {
48 // SAFETY: the caller must guarantee that the state was retrieved by the previous `disable`,
49 unsafe {
50 // This clobbers the entire status register. See msp430.rs to safety on this.
51 //
52 // Do not use `nomem` and `readonly` because prevent preceding memory accesses from being reordered after interrupts are enabled.
53 // Do not use `preserves_flags` because OUT modifies the status register (SREG).
54 #[cfg(not(portable_atomic_no_asm))]
55 asm!("out 0x3F, {0}", in(reg) sreg, options(nostack));
56 #[cfg(portable_atomic_no_asm)]
57 llvm_asm!("out 0x3F, $0" :: "r"(sreg) : "memory" : "volatile");
58 }
59 }
60