Debian Codegraph @

third_party/rust/cache-padded/src/lib.rs

raw
1 //! Prevent false sharing by padding and aligning to the length of a cache line.
2 //!
3 //! In concurrent programming, sometimes it is desirable to make sure commonly accessed shared data
4 //! is not all placed into the same cache line. Updating an atomic value invalidates the whole cache
5 //! line it belongs to, which makes the next access to the same cache line slower for other CPU
6 //! cores. Use [`CachePadded`] to ensure updating one piece of data doesn't invalidate other cached
7 //! data.
8 //!
9 //! # Size and alignment
10 //!
11 //! Cache lines are assumed to be N bytes long, depending on the architecture:
12 //!
13 //! * On x86-64, aarch64, and powerpc64, N = 128.
14 //! * On arm, mips, mips64, and riscv64, N = 32.
15 //! * On s390x, N = 256.
16 //!
17 //! Note that N is just a reasonable guess and is not guaranteed to match the actual cache line
18 //! length of the machine the program is running on.
19 //!
20 //! The size of `CachePadded<T>` is the smallest multiple of N bytes large enough to accommodate
21 //! a value of type `T`.
22 //!
23 //! The alignment of `CachePadded<T>` is the maximum of N bytes and the alignment of `T`.
24 //!
25 //! # Examples
26 //!
27 //! Alignment and padding:
28 //!
29 //! ```
30 //! use cache_padded::CachePadded;
31 //!
32 //! let array = [CachePadded::new(1i8), CachePadded::new(2i8)];
33 //! let addr1 = &*array[0] as *const i8 as usize;
34 //! let addr2 = &*array[1] as *const i8 as usize;
35 //!
36 //! assert!(addr2 - addr1 >= 64);
37 //! assert_eq!(addr1 % 64, 0);
38 //! assert_eq!(addr2 % 64, 0);
39 //! ```
40 //!
41 //! When building a concurrent queue with a head and a tail index, it is wise to place indices in
42 //! different cache lines so that concurrent threads pushing and popping elements don't invalidate
43 //! each other's cache lines:
44 //!
45 //! ```
46 //! use cache_padded::CachePadded;
47 //! use std::sync::atomic::AtomicUsize;
48 //!
49 //! struct Queue<T> {
50 //! head: CachePadded<AtomicUsize>,
51 //! tail: CachePadded<AtomicUsize>,
52 //! buffer: *mut T,
53 //! }
54 //! ```
55
56 #![no_std]
57 #![forbid(unsafe_code)]
58 #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
59
60 use core::fmt;
61 use core::ops::{Deref, DerefMut};
62
63 /// Pads and aligns data to the length of a cache line.
64 // Starting from Intel's Sandy Bridge, spatial prefetcher is now pulling pairs of 64-byte cache
65 // lines at a time, so we have to align to 128 bytes rather than 64.
66 //
67 // Sources:
68 // - https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf
69 // - https://github.com/facebook/folly/blob/1b5288e6eea6df074758f877c849b6e73bbb9fbb/folly/lang/Align.h#L107
70 //
71 // ARM's big.LITTLE architecture has asymmetric cores and "big" cores have 128-byte cache line size.
72 //
73 // Sources:
74 // - https://www.mono-project.com/news/2016/09/12/arm64-icache/
75 //
76 // powerpc64 has 128-byte cache line size.
77 //
78 // Sources:
79 // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_ppc64x.go#L9
80 #[cfg_attr(
81 any(
82 target_arch = "x86_64",
83 target_arch = "aarch64",
84 target_arch = "powerpc64",
85 ),
86 repr(align(128))
87 )]
88 // arm, mips, mips64, and riscv64 have 32-byte cache line size.
89 //
90 // Sources:
91 // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_arm.go#L7
92 // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips.go#L7
93 // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mipsle.go#L7
94 // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips64x.go#L9
95 // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_riscv64.go#L7
96 #[cfg_attr(
97 any(
98 target_arch = "arm",
99 target_arch = "mips",
100 target_arch = "mips64",
101 target_arch = "riscv64",
102 ),
103 repr(align(32))
104 )]
105 // s390x has 256-byte cache line size.
106 //
107 // Sources:
108 // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_s390x.go#L7
109 #[cfg_attr(target_arch = "s390x", repr(align(256)))]
110 // x86 and wasm have 64-byte cache line size.
111 //
112 // Sources:
113 // - https://github.com/golang/go/blob/dda2991c2ea0c5914714469c4defc2562a907230/src/internal/cpu/cpu_x86.go#L9
114 // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_wasm.go#L7
115 //
116 // All others are assumed to have 64-byte cache line size.
117 #[cfg_attr(
118 not(any(
119 target_arch = "x86_64",
120 target_arch = "aarch64",
121 target_arch = "powerpc64",
122 target_arch = "arm",
123 target_arch = "mips",
124 target_arch = "mips64",
125 target_arch = "riscv64",
126 target_arch = "s390x",
127 )),
128 repr(align(64))
129 )]
130 #[derive(Clone, Copy, Default, Hash, PartialEq, Eq)]
131 pub struct CachePadded<T>(T);
132
133 impl<T> CachePadded<T> {
134 /// Pads and aligns a piece of data to the length of a cache line.
135 ///
136 /// # Examples
137 ///
138 /// ```
139 /// use cache_padded::CachePadded;
140 ///
141 /// let padded = CachePadded::new(1);
142 /// ```
143 pub const fn new(t: T) -> CachePadded<T> {
144 CachePadded(t)
145 }
146
147 /// Returns the inner data.
148 ///
149 /// # Examples
150 ///
151 /// ```
152 /// use cache_padded::CachePadded;
153 ///
154 /// let padded = CachePadded::new(7);
155 /// let data = padded.into_inner();
156 /// assert_eq!(data, 7);
157 /// ```
158 pub fn into_inner(self) -> T {
159 self.0
160 }
161 }
162
163 impl<T> Deref for CachePadded<T> {
164 type Target = T;
165
166 fn deref(&self) -> &T {
167 &self.0
168 }
169 }
170
171 impl<T> DerefMut for CachePadded<T> {
172 fn deref_mut(&mut self) -> &mut T {
173 &mut self.0
174 }
175 }
176
177 impl<T: fmt::Debug> fmt::Debug for CachePadded<T> {
178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179 f.debug_tuple("CachePadded").field(&self.0).finish()
180 }
181 }
182
183 impl<T> From<T> for CachePadded<T> {
184 fn from(t: T) -> Self {
185 CachePadded::new(t)
186 }
187 }