orengine_utils/cache_padded.rs
1//! Provides cache-padded atomic types.
2//!
3//! # Example
4//!
5//! ```
6//! use orengine_utils::cache_padded::{CachePadded, CachePaddedAtomicUsize};
7//! use core::sync::atomic::{AtomicUsize, Ordering};
8//!
9//! // Using CachePaddedAtomicUsize type alias
10//! let counter = CachePaddedAtomicUsize::new(0);
11//!
12//! counter.fetch_add(1, Ordering::Relaxed);
13//!
14//! assert_eq!(counter.load(Ordering::Relaxed), 1);
15//!
16//! // Using CachePadded with a custom type
17//! let padded_value = CachePadded::new(42);
18//! assert_eq!(*padded_value, 42);
19//! ```
20// This code is forked from crossbeam: https://github.com/crossbeam-rs/crossbeam/blob/master/crossbeam-utils/src/cache_padded.rs
21use core::fmt;
22use core::ops::{Deref, DerefMut};
23use core::sync::atomic::{
24 AtomicBool, AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicPtr, AtomicU16,
25 AtomicU32, AtomicU64, AtomicU8, AtomicUsize,
26};
27
28/// Pads and aligns a value to the length of a cache line.
29///
30/// In concurrent programming, sometimes it is desirable to make sure commonly accessed pieces of
31/// data are not placed into the same cache line. Updating an atomic value invalidates the whole
32/// cache line it belongs to, which makes the next access to the same cache line slower for other
33/// CPU cores. Use `CachePadded` to ensure updating one piece of data doesn't invalidate other
34/// cached data.
35///
36/// # Size and alignment
37///
38/// Cache lines are assumed to be N bytes long, depending on the architecture:
39///
40/// * On x86-64, aarch64, and powerpc64, N = 128.
41/// * On arm, mips, mips64, sparc, and hexagon, N = 32.
42/// * On m68k, N = 16.
43/// * On s390x, N = 256.
44/// * On all others, N = 64.
45///
46/// Note that N is just a reasonable guess and is not guaranteed to match the actual cache line
47/// length of the machine the program is running on. On modern Intel architectures, spatial
48/// prefetcher is pulling pairs of 64-byte cache lines at a time, so we pessimistically assume that
49/// cache lines are 128 bytes long.
50///
51/// The size of `CachePadded<T>` is the smallest multiple of N bytes large enough to accommodate
52/// a value of type `T`.
53///
54/// The alignment of `CachePadded<T>` is the maximum of N bytes and the alignment of `T`.
55///
56/// # Examples
57///
58/// Alignment and padding:
59///
60/// ```
61/// use orengine_utils::cache_padded::CachePadded;
62///
63/// let array = [CachePadded::new(1i8), CachePadded::new(2i8)];
64/// let addr1 = &*array[0] as *const i8 as usize;
65/// let addr2 = &*array[1] as *const i8 as usize;
66///
67/// assert!(addr2 - addr1 >= 32);
68/// assert_eq!(addr1 % 32, 0);
69/// assert_eq!(addr2 % 32, 0);
70/// ```
71///
72/// When building a concurrent queue with a head and a tail index, it is wise to place them in
73/// different cache lines so that concurrent threads pushing and popping elements don't invalidate
74/// each other's cache lines:
75///
76/// ```
77/// use orengine_utils::cache_padded::CachePadded;
78/// use core::sync::atomic::AtomicUsize;
79///
80/// struct Queue<T> {
81/// head: CachePadded<AtomicUsize>,
82/// tail: CachePadded<AtomicUsize>,
83/// buffer: *mut T,
84/// }
85/// ```
86#[derive(Clone, Copy, Default, Hash, PartialEq, Eq)]
87// Starting from Intel's Sandy Bridge, spatial prefetcher is now pulling pairs of 64-byte cache
88// lines at a time, so we have to align to 128 bytes rather than 64.
89//
90// Sources:
91// - https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf
92// - https://github.com/facebook/folly/blob/1b5288e6eea6df074758f877c849b6e73bbb9fbb/folly/lang/Align.h#L107
93//
94// aarch64/arm64ec's big.LITTLE architecture has asymmetric cores and "big" cores have 128-byte cache line size.
95//
96// Sources:
97// - https://www.mono-project.com/news/2016/09/12/arm64-icache/
98//
99// powerpc64 has 128-byte cache line size.
100//
101// Sources:
102// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_ppc64x.go#L9
103// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/powerpc/include/asm/cache.h#L26
104#[cfg_attr(
105 any(
106 target_arch = "x86_64",
107 target_arch = "aarch64",
108 target_arch = "arm64ec",
109 target_arch = "powerpc64",
110 ),
111 repr(align(128))
112)]
113// arm, mips, mips64, sparc, and hexagon have 32-byte cache line size.
114//
115// Sources:
116// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_arm.go#L7
117// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips.go#L7
118// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mipsle.go#L7
119// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips64x.go#L9
120// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/sparc/include/asm/cache.h#L17
121// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/hexagon/include/asm/cache.h#L12
122#[cfg_attr(
123 any(
124 target_arch = "arm",
125 target_arch = "mips",
126 target_arch = "mips32r6",
127 target_arch = "mips64",
128 target_arch = "mips64r6",
129 target_arch = "sparc",
130 target_arch = "hexagon",
131 ),
132 repr(align(32))
133)]
134// m68k has a 16-byte cache line size.
135//
136// Sources:
137// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/m68k/include/asm/cache.h#L9
138#[cfg_attr(target_arch = "m68k", repr(align(16)))]
139// s390x has 256-byte cache line size.
140//
141// Sources:
142// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_s390x.go#L7
143// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/s390/include/asm/cache.h#L13
144#[cfg_attr(target_arch = "s390x", repr(align(256)))]
145// x86, wasm, riscv, and sparc64 have 64-byte cache line size.
146//
147// Sources:
148// - https://github.com/golang/go/blob/dda2991c2ea0c5914714469c4defc2562a907230/src/internal/cpu/cpu_x86.go#L9
149// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_wasm.go#L7
150// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/riscv/include/asm/cache.h#L10
151// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/sparc/include/asm/cache.h#L19
152//
153// All others are assumed to have 64-byte cache line size.
154#[cfg_attr(
155 not(any(
156 target_arch = "x86_64",
157 target_arch = "aarch64",
158 target_arch = "arm64ec",
159 target_arch = "powerpc64",
160 target_arch = "arm",
161 target_arch = "mips",
162 target_arch = "mips32r6",
163 target_arch = "mips64",
164 target_arch = "mips64r6",
165 target_arch = "sparc",
166 target_arch = "hexagon",
167 target_arch = "m68k",
168 target_arch = "s390x",
169 )),
170 repr(align(64))
171)]
172pub struct CachePadded<T> {
173 value: T,
174}
175
176unsafe impl<T: Send> Send for CachePadded<T> {}
177unsafe impl<T: Sync> Sync for CachePadded<T> {}
178
179impl<T> CachePadded<T> {
180 /// Pads and aligns a value to the length of a cache line.
181 ///
182 /// # Examples
183 ///
184 /// ```
185 /// use orengine_utils::cache_padded::CachePadded;
186 ///
187 /// let padded_value = CachePadded::new(1);
188 /// ```
189 pub const fn new(t: T) -> Self {
190 Self { value: t }
191 }
192
193 /// Returns the inner value.
194 ///
195 /// # Examples
196 ///
197 /// ```
198 /// use orengine_utils::cache_padded::CachePadded;
199 ///
200 /// let padded_value = CachePadded::new(7);
201 /// let value = padded_value.into_inner();
202 ///
203 /// assert_eq!(value, 7);
204 /// ```
205 pub fn into_inner(self) -> T {
206 self.value
207 }
208}
209
210impl<T> Deref for CachePadded<T> {
211 type Target = T;
212
213 fn deref(&self) -> &T {
214 &self.value
215 }
216}
217
218impl<T> DerefMut for CachePadded<T> {
219 fn deref_mut(&mut self) -> &mut T {
220 &mut self.value
221 }
222}
223
224impl<T: fmt::Debug> fmt::Debug for CachePadded<T> {
225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226 f.debug_struct("CachePadded")
227 .field("value", &self.value)
228 .finish()
229 }
230}
231
232impl<T> From<T> for CachePadded<T> {
233 fn from(t: T) -> Self {
234 Self::new(t)
235 }
236}
237
238impl<T: fmt::Display> fmt::Display for CachePadded<T> {
239 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240 fmt::Display::fmt(&self.value, f)
241 }
242}
243
244macro_rules! cache_padded_atomic_number {
245 ($name:ident, $atomic_type:ident, $number_type:ident) => {
246 #[allow(
247 rustdoc::redundant_explicit_links,
248 reason = "It is needed for right IDE doc formating"
249 )]
250 #[doc = concat!(
251 "Alias to [`CachePadded`](CachePadded)`<`[`", stringify!($atomic_type), "`]`>`."
252 )]
253 pub struct $name(CachePadded<$atomic_type>);
254
255 impl $name {
256 #[doc = concat!(
257 "Creates a new [`CachePadded`](CachePadded)`<`[`", stringify!($atomic_type), "`]`>`."
258 )]
259 #[inline(always)]
260 pub const fn new(t: $number_type) -> Self {
261 Self($crate::cache_padded::CachePadded::new($atomic_type::new(t)))
262 }
263 }
264
265 impl core::ops::Deref for $name {
266 type Target = $atomic_type;
267
268 fn deref(&self) -> &$atomic_type {
269 &self.0
270 }
271 }
272
273 impl core::ops::DerefMut for $name {
274 fn deref_mut(&mut self) -> &mut $atomic_type {
275 &mut self.0
276 }
277 }
278
279 impl Default for $name {
280 fn default() -> Self {
281 Self::new($number_type::default())
282 }
283 }
284 };
285}
286
287cache_padded_atomic_number!(CachePaddedAtomicU8, AtomicU8, u8);
288cache_padded_atomic_number!(CachePaddedAtomicU16, AtomicU16, u16);
289cache_padded_atomic_number!(CachePaddedAtomicU32, AtomicU32, u32);
290cache_padded_atomic_number!(CachePaddedAtomicU64, AtomicU64, u64);
291cache_padded_atomic_number!(CachePaddedAtomicUsize, AtomicUsize, usize);
292
293cache_padded_atomic_number!(CachePaddedAtomicI8, AtomicI8, i8);
294cache_padded_atomic_number!(CachePaddedAtomicI16, AtomicI16, i16);
295cache_padded_atomic_number!(CachePaddedAtomicI32, AtomicI32, i32);
296cache_padded_atomic_number!(CachePaddedAtomicI64, AtomicI64, i64);
297cache_padded_atomic_number!(CachePaddedAtomicIsize, AtomicIsize, isize);
298
299cache_padded_atomic_number!(CachePaddedAtomicBool, AtomicBool, bool);
300
301#[allow(
302 rustdoc::redundant_explicit_links,
303 reason = "It is needed for right IDE doc formating"
304)]
305#[allow(
306 clippy::doc_markdown,
307 reason = "It is needed for right IDE doc formating"
308)]
309/// Alias to <code>[CachePadded](CachePadded)<[AtomicPtr](AtomicPtr)`<T>`></code>.
310pub struct CachePaddedAtomicPtr<T>(CachePadded<AtomicPtr<T>>);
311
312impl<T> CachePaddedAtomicPtr<T> {
313 #[allow(
314 clippy::doc_markdown,
315 reason = "It is needed for right IDE doc formating"
316 )]
317 /// Creates a new <code>[CachePadded](CachePadded)<[AtomicPtr](AtomicPtr)`<T>`></code>.
318 #[inline(always)]
319 pub const fn new(ptr: *mut T) -> Self {
320 Self(CachePadded::new(AtomicPtr::new(ptr)))
321 }
322}
323
324impl<T> Deref for CachePaddedAtomicPtr<T> {
325 type Target = AtomicPtr<T>;
326
327 fn deref(&self) -> &Self::Target {
328 &self.0
329 }
330}
331
332impl<T> DerefMut for CachePaddedAtomicPtr<T> {
333 fn deref_mut(&mut self) -> &mut Self::Target {
334 &mut self.0
335 }
336}