Skip to main content

arch_rs/
lib.rs

1// Copyright 2026 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#![no_std]
6
7unsafe extern "C" {
8    fn cpp_ints_disabled() -> bool;
9    fn cpp_disable_ints();
10    fn cpp_enable_ints();
11    fn cpp_interrupt_save() -> InterruptSavedState;
12    fn cpp_interrupt_restore(state: InterruptSavedState);
13    fn cpp_curr_cpu_num() -> u32;
14    fn cpp_max_num_cpus() -> u32;
15}
16
17/// Returns true if interrupts are disabled on the current CPU.
18#[inline(always)]
19pub fn ints_disabled() -> bool {
20    unsafe { cpp_ints_disabled() }
21}
22
23/// Disable interrupts on the current CPU.
24#[inline(always)]
25pub fn disable_ints() {
26    unsafe { cpp_disable_ints() }
27}
28
29/// Enable interrupts on the current CPU.
30#[inline(always)]
31pub fn enable_ints() {
32    unsafe { cpp_enable_ints() }
33}
34
35/// The saved interrupt state, representing architecture-specific interrupt flags.
36#[cfg(target_arch = "x86_64")]
37#[repr(transparent)]
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub struct InterruptSavedState(usize);
40
41/// The saved interrupt state, representing architecture-specific interrupt flags.
42#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
43#[repr(transparent)]
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub struct InterruptSavedState(bool);
46
47/// Save the current interrupt state (specifically, whether interrupts are enabled)
48/// and disable interrupts on the current CPU.
49#[inline(always)]
50pub fn arch_interrupt_save() -> InterruptSavedState {
51    unsafe { cpp_interrupt_save() }
52}
53
54/// Restore the interrupt state on the current CPU to a previously saved state.
55#[inline(always)]
56pub fn arch_interrupt_restore(state: InterruptSavedState) {
57    unsafe { cpp_interrupt_restore(state) }
58}
59
60/// A guard that disables interrupts on the current CPU when created,
61/// and restores the previous interrupt state when dropped.
62pub struct InterruptDisableGuard {
63    state: InterruptSavedState,
64}
65
66impl InterruptDisableGuard {
67    #[inline(always)]
68    pub fn new() -> Self {
69        Self { state: arch_interrupt_save() }
70    }
71}
72
73impl Drop for InterruptDisableGuard {
74    #[inline(always)]
75    fn drop(&mut self) {
76        arch_interrupt_restore(self.state);
77    }
78}
79
80/// Returns the CPU number of the calling CPU.
81#[inline(always)]
82pub fn curr_cpu_num() -> u32 {
83    unsafe { cpp_curr_cpu_num() }
84}
85
86/// Returns the maximum number of CPUs in the system.
87#[inline(always)]
88pub fn max_num_cpus() -> u32 {
89    unsafe { cpp_max_num_cpus() }
90}