mbarrier/
lib.rs

1/*!
2# mbarrier - Cross-platform Memory Barriers for Rust
3
4This crate provides memory barrier implementations inspired by the Linux kernel,
5offering cross-platform support for various CPU architectures.
6
7Memory barriers are synchronization primitives that prevent certain types of
8memory reordering performed by CPUs and compilers.
9
10## Example
11
12```rust
13use mbarrier::*;
14
15// Read memory barrier
16rmb();
17
18// Write memory barrier
19wmb();
20
21// General memory barrier
22mb();
23
24// SMP-aware barriers
25smp_rmb();
26smp_wmb();
27smp_mb();
28```
29*/
30
31#![no_std]
32#![deny(missing_docs)]
33
34/// Architecture-specific barrier implementations
35mod arch;
36
37pub use arch::*;
38
39/// Read memory barrier.
40///
41/// Ensures that all memory reads issued before this barrier are completed
42/// before any memory reads issued after this barrier.
43#[inline(always)]
44pub fn rmb() {
45    arch::rmb_impl()
46}
47
48/// Write memory barrier.
49///
50/// Ensures that all memory writes issued before this barrier are completed
51/// before any memory writes issued after this barrier.
52#[inline(always)]
53pub fn wmb() {
54    arch::wmb_impl()
55}
56
57/// General memory barrier.
58///
59/// Ensures that all memory operations (reads and writes) issued before this
60/// barrier are completed before any memory operations issued after this barrier.
61#[inline(always)]
62pub fn mb() {
63    arch::mb_impl()
64}
65
66/// SMP read memory barrier.
67///
68/// On SMP systems, acts as rmb(). On UP systems, acts as a compiler barrier only.
69#[inline(always)]
70pub fn smp_rmb() {
71    #[cfg(feature = "smp")]
72    {
73        rmb()
74    }
75    #[cfg(not(feature = "smp"))]
76    {
77        use core::sync::atomic::{Ordering, compiler_fence};
78        compiler_fence(Ordering::Acquire)
79    }
80}
81
82/// SMP write memory barrier.
83///
84/// On SMP systems, acts as wmb(). On UP systems, acts as a compiler barrier only.
85#[inline(always)]
86pub fn smp_wmb() {
87    #[cfg(feature = "smp")]
88    {
89        wmb()
90    }
91    #[cfg(not(feature = "smp"))]
92    {
93        use core::sync::atomic::{Ordering, compiler_fence};
94        compiler_fence(Ordering::Release)
95    }
96}
97
98/// SMP general memory barrier.
99///
100/// On SMP systems, acts as mb(). On UP systems, acts as a compiler barrier only.
101#[inline(always)]
102pub fn smp_mb() {
103    #[cfg(feature = "smp")]
104    {
105        mb()
106    }
107    #[cfg(not(feature = "smp"))]
108    {
109        use core::sync::atomic::{Ordering, compiler_fence};
110        compiler_fence(Ordering::SeqCst)
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    #[test]
119    fn test_barriers_compile() {
120        // These tests just ensure the barriers compile and don't panic
121        rmb();
122        wmb();
123        mb();
124        smp_rmb();
125        smp_wmb();
126        smp_mb();
127    }
128}