Debian Codegraph @

debian/rust-vendor/portable-atomic/src/imp/fallback/mod.rs

raw
1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2
3 /*
4 Fallback implementation using global locks.
5
6 This implementation uses seqlock for global locks.
7
8 This is basically based on global locks in crossbeam-utils's `AtomicCell`,
9 but seqlock is implemented in a way that does not depend on UB
10 (see comments in optimistic_read method in atomic! macro for details).
11
12 Note that we cannot use a lock per atomic type, since the in-memory representation of the atomic
13 type and the value type must be the same.
14 */
15
16 #![cfg_attr(
17 any(
18 all(
19 target_arch = "riscv32",
20 not(any(miri, portable_atomic_sanitize_thread)),
21 any(not(portable_atomic_no_asm), portable_atomic_unstable_asm),
22 not(portable_atomic_no_outline_atomics),
23 any(target_os = "linux", target_os = "android"),
24 ),
25 all(
26 target_arch = "arm",
27 not(any(miri, portable_atomic_sanitize_thread)),
28 any(not(portable_atomic_no_asm), portable_atomic_unstable_asm),
29 any(target_os = "linux", target_os = "android"),
30 any(test, not(any(target_feature = "v6", portable_atomic_target_feature = "v6"))),
31 not(portable_atomic_no_outline_atomics),
32 ),
33 ),
34 allow(dead_code)
35 )]
36
37 // This module requires CAS and this crate only provides atomics up to 128-bit.
38 // I don't believe there are any 16-bit multi-core systems with CAS, and
39 // at least no such architecture is currently supported in Rust.
40 // 128-bit targets that lack atomic usize CAS also do not reach this module.
41 #[cfg(target_pointer_width = "16")]
42 compile_error!(
43 "internal error: unreachable since atomics for 16-bit targets can always be provided by disable interrupts"
44 );
45 #[cfg(target_pointer_width = "128")]
46 compile_error!(
47 "internal error: unreachable since 128-bit target either has atomic CAS for the pointer width or does not have CAS"
48 );
49
50 mod utils;
51
52 // Use "wide" sequence lock if the pointer width <= 32 for preventing its counter against wrap
53 // around.
54 //
55 // Some 64-bit architectures have ABI with 32-bit pointer width (e.g., x86_64 X32 ABI,
56 // AArch64 ILP32 ABI, mips64 N32 ABI). On those targets, AtomicU64 is available and fast,
57 // so use it to implement normal sequence lock and reduce chunks of byte-wise atomic memcpy.
58 cfg_has_fast_atomic_64!({
59 mod seq_lock;
60 type AtomicChunk = core::sync::atomic::AtomicU64;
61 type Chunk = u64;
62 });
63 cfg_no_fast_atomic_64!({
64 #[path = "seq_lock_wide.rs"]
65 mod seq_lock;
66 type AtomicChunk = core::sync::atomic::AtomicU32;
67 type Chunk = u32;
68 });
69
70 use core::{cell::UnsafeCell, mem, sync::atomic::Ordering};
71
72 use self::{
73 seq_lock::{SeqLock, SeqLockWriteGuard},
74 utils::CachePadded,
75 };
76 #[cfg(portable_atomic_no_strict_provenance)]
77 use crate::utils::ptr::PtrExt as _;
78 use crate::utils::unlikely;
79
80 // Adapted from https://github.com/crossbeam-rs/crossbeam/blob/crossbeam-utils-0.8.21/crossbeam-utils/src/atomic/atomic_cell.rs#L970-L1010.
81 #[inline]
82 #[must_use]
83 fn lock(addr: usize) -> &'static SeqLock {
84 // The number of locks is a prime number because we want to make sure `addr % LEN` gets
85 // dispersed across all locks.
86 const LEN: usize = 67;
87 const L: CachePadded<SeqLock> = CachePadded::new(SeqLock::new());
88 static LOCKS: [CachePadded<SeqLock>; LEN] = [
89 L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L,
90 L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L,
91 L, L, L, L, L, L, L,
92 ];
93
94 // If the modulus is a constant number, the compiler will use crazy math to transform this into
95 // a sequence of cheap arithmetic operations rather than using the slow modulo instruction.
96 &LOCKS[addr % LEN]
97 }
98
99 // Emit SeqCst fence to ensure SeqCst semantics when ordering is SeqCst.
100 #[must_use]
101 struct ScFenceGuard;
102 impl ScFenceGuard {
103 #[inline]
104 fn new(emit_sc_fence: bool) -> Option<Self> {
105 if unlikely(emit_sc_fence) {
106 crate::fence(Ordering::SeqCst);
107 Some(ScFenceGuard)
108 } else {
109 None
110 }
111 }
112 }
113 impl Drop for ScFenceGuard {
114 #[inline]
115 fn drop(&mut self) {
116 crate::fence(Ordering::SeqCst);
117 }
118 }
119
120 macro_rules! atomic {
121 ($atomic_type:ident, $int_type:ident, $align:literal) => {
122 #[repr(C, align($align))]
123 pub(crate) struct $atomic_type {
124 v: UnsafeCell<$int_type>,
125 }
126
127 impl $atomic_type {
128 const LEN: usize = mem::size_of::<$int_type>() / mem::size_of::<Chunk>();
129
130 #[inline]
131 unsafe fn chunks(&self) -> &[AtomicChunk; Self::LEN] {
132 static_assert!($atomic_type::LEN > 1);
133 static_assert!(mem::size_of::<$int_type>() % mem::size_of::<Chunk>() == 0);
134
135 // SAFETY: the caller must uphold the safety contract for `chunks`.
136 unsafe { &*(self.v.get() as *const $int_type as *const [AtomicChunk; Self::LEN]) }
137 }
138
139 #[inline]
140 fn optimistic_read(&self) -> $int_type {
141 // Using `MaybeUninit<[usize; Self::LEN]>` here doesn't change codegen: https://godbolt.org/z/86f8s733M
142 let mut dst: [Chunk; Self::LEN] = [0; Self::LEN];
143 // SAFETY:
144 // - There are no threads that perform non-atomic concurrent write operations.
145 // - There is no writer that updates the value using atomic operations of different granularity.
146 //
147 // If the atomic operation is not used here, it will cause a data race
148 // when `write` performs concurrent write operation.
149 // Such a data race is sometimes considered virtually unproblematic
150 // in SeqLock implementations:
151 //
152 // - https://github.com/Amanieu/seqlock/issues/2
153 // - https://github.com/crossbeam-rs/crossbeam/blob/crossbeam-utils-0.8.21/crossbeam-utils/src/atomic/atomic_cell.rs#L1063-L1069
154 // - https://rust-lang.zulipchat.com/#narrow/stream/136281-t-lang.2Fwg-unsafe-code-guidelines/topic/avoiding.20UB.20due.20to.20races.20by.20discarding.20result.3F
155 //
156 // However, in our use case, the implementation that loads/stores value as
157 // chunks of usize is enough fast and sound, so we use that implementation.
158 //
159 // See also atomic-memcpy crate, a generic implementation of this pattern:
160 // https://github.com/taiki-e/atomic-memcpy
161 let chunks = unsafe { self.chunks() };
162 for i in 0..Self::LEN {
163 dst[i] = chunks[i].load(Ordering::Relaxed);
164 }
165 // SAFETY: integers are plain old data types so we can always transmute to them.
166 unsafe { mem::transmute::<[Chunk; Self::LEN], $int_type>(dst) }
167 }
168
169 #[inline]
170 fn read(&self, _guard: &SeqLockWriteGuard<'static>) -> $int_type {
171 // This calls optimistic_read that can return teared value, but the resulting value
172 // is guaranteed not to be teared because we hold the lock to write.
173 self.optimistic_read()
174 }
175
176 #[inline]
177 fn write(&self, val: $int_type, _guard: &SeqLockWriteGuard<'static>) {
178 // SAFETY: integers are plain old data types so we can always transmute them to arrays of integers.
179 let val = unsafe { mem::transmute::<$int_type, [Chunk; Self::LEN]>(val) };
180 // SAFETY:
181 // - The guard guarantees that we hold the lock to write.
182 // - There are no threads that perform non-atomic concurrent read or write operations.
183 //
184 // See optimistic_read for the reason that atomic operations are used here.
185 let chunks = unsafe { self.chunks() };
186 for i in 0..Self::LEN {
187 chunks[i].store(val[i], Ordering::Relaxed);
188 }
189 }
190 }
191
192 // Send is implicitly implemented.
193 // SAFETY: any data races are prevented by the lock and atomic operation.
194 unsafe impl Sync for $atomic_type {}
195
196 #[cfg(any(
197 test,
198 not(any(
199 all(
200 target_arch = "x86_64",
201 not(all(
202 any(miri, portable_atomic_sanitize_thread),
203 portable_atomic_no_cmpxchg16b_intrinsic,
204 )),
205 any(not(portable_atomic_no_asm), portable_atomic_unstable_asm),
206 not(portable_atomic_no_outline_atomics),
207 not(any(target_env = "sgx", miri)),
208 ),
209 all(
210 target_arch = "powerpc64",
211 not(portable_atomic_no_asm),
212 not(portable_atomic_no_outline_atomics),
213 any(
214 all(
215 target_os = "linux",
216 any(
217 all(
218 target_env = "gnu",
219 any(target_endian = "little", not(target_feature = "crt-static")),
220 ),
221 all(
222 target_env = "musl",
223 any(not(target_feature = "crt-static"), feature = "std"),
224 ),
225 target_env = "ohos",
226 all(target_env = "uclibc", not(target_feature = "crt-static")),
227 portable_atomic_outline_atomics,
228 ),
229 ),
230 target_os = "android",
231 all(
232 target_os = "freebsd",
233 any(
234 target_endian = "little",
235 not(target_feature = "crt-static"),
236 portable_atomic_outline_atomics,
237 ),
238 ),
239 target_os = "openbsd",
240 all(
241 target_os = "aix",
242 not(portable_atomic_pre_llvm_20),
243 portable_atomic_outline_atomics, // TODO(aix): currently disabled by default
244 ),
245 ),
246 not(any(miri, portable_atomic_sanitize_thread)),
247 ),
248 all(
249 target_arch = "riscv64",
250 not(any(miri, portable_atomic_sanitize_thread)),
251 any(not(portable_atomic_no_asm), portable_atomic_unstable_asm),
252 not(portable_atomic_no_outline_atomics),
253 any(target_os = "linux", target_os = "android"),
254 ),
255 )),
256 ))]
257 items!({
258 impl_default_no_fetch_ops!($atomic_type, $int_type);
259 impl_default_bit_opts!($atomic_type, $int_type);
260 impl $atomic_type {
261 #[inline]
262 pub(crate) const fn new(v: $int_type) -> Self {
263 Self { v: UnsafeCell::new(v) }
264 }
265
266 #[inline]
267 pub(crate) fn is_lock_free() -> bool {
268 Self::IS_ALWAYS_LOCK_FREE
269 }
270 pub(crate) const IS_ALWAYS_LOCK_FREE: bool = false;
271
272 #[inline]
273 #[cfg_attr(
274 all(debug_assertions, not(portable_atomic_no_track_caller)),
275 track_caller
276 )]
277 pub(crate) fn compare_exchange_weak(
278 &self,
279 current: $int_type,
280 new: $int_type,
281 success: Ordering,
282 failure: Ordering,
283 ) -> Result<$int_type, $int_type> {
284 self.compare_exchange(current, new, success, failure)
285 }
286
287 #[inline]
288 pub(crate) fn not(&self, order: Ordering) {
289 self.fetch_not(order);
290 }
291 #[inline]
292 pub(crate) fn neg(&self, order: Ordering) {
293 self.fetch_neg(order);
294 }
295
296 #[inline]
297 pub(crate) const fn as_ptr(&self) -> *mut $int_type {
298 self.v.get()
299 }
300 }
301 });
302 #[cfg_attr(
303 any(
304 all(
305 target_arch = "x86_64",
306 not(all(
307 any(miri, portable_atomic_sanitize_thread),
308 portable_atomic_no_cmpxchg16b_intrinsic,
309 )),
310 any(not(portable_atomic_no_asm), portable_atomic_unstable_asm),
311 not(portable_atomic_no_outline_atomics),
312 not(any(target_env = "sgx", miri)),
313 ),
314 all(
315 target_arch = "powerpc64",
316 not(portable_atomic_no_asm),
317 not(portable_atomic_no_outline_atomics),
318 any(
319 all(
320 target_os = "linux",
321 any(
322 all(
323 target_env = "gnu",
324 any(target_endian = "little", not(target_feature = "crt-static")),
325 ),
326 all(
327 target_env = "musl",
328 any(not(target_feature = "crt-static"), feature = "std"),
329 ),
330 target_env = "ohos",
331 all(target_env = "uclibc", not(target_feature = "crt-static")),
332 portable_atomic_outline_atomics,
333 ),
334 ),
335 target_os = "android",
336 all(
337 target_os = "freebsd",
338 any(
339 target_endian = "little",
340 not(target_feature = "crt-static"),
341 portable_atomic_outline_atomics,
342 ),
343 ),
344 target_os = "openbsd",
345 all(
346 target_os = "aix",
347 not(portable_atomic_pre_llvm_20),
348 portable_atomic_outline_atomics, // TODO(aix): currently disabled by default
349 ),
350 ),
351 not(any(miri, portable_atomic_sanitize_thread)),
352 ),
353 all(
354 target_arch = "riscv64",
355 not(any(miri, portable_atomic_sanitize_thread)),
356 any(not(portable_atomic_no_asm), portable_atomic_unstable_asm),
357 not(portable_atomic_no_outline_atomics),
358 any(target_os = "linux", target_os = "android"),
359 ),
360 ),
361 allow(dead_code)
362 )]
363 impl $atomic_type {
364 #[inline]
365 #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)]
366 pub(crate) fn load(&self, order: Ordering) -> $int_type {
367 crate::utils::assert_load_ordering(order);
368 let _sc_fence = ScFenceGuard::new(order == Ordering::SeqCst);
369 let lock = lock(self.v.get().addr());
370
371 // Try doing an optimistic read first.
372 if let Some(stamp) = lock.optimistic_read() {
373 let val = self.optimistic_read();
374
375 if lock.validate_read(stamp) {
376 return val;
377 }
378 }
379
380 // Grab a regular write lock so that writers don't starve this load.
381 let guard = lock.write();
382 let val = self.read(&guard);
383 // The value hasn't been changed. Drop the guard without incrementing the stamp.
384 guard.abort();
385 val
386 }
387
388 #[inline]
389 #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)]
390 pub(crate) fn store(&self, val: $int_type, order: Ordering) {
391 crate::utils::assert_store_ordering(order);
392 let _sc_fence = ScFenceGuard::new(order == Ordering::SeqCst);
393 let guard = lock(self.v.get().addr()).write();
394 self.write(val, &guard)
395 }
396
397 #[inline]
398 pub(crate) fn swap(&self, val: $int_type, order: Ordering) -> $int_type {
399 let _sc_fence = ScFenceGuard::new(order == Ordering::SeqCst);
400 let guard = lock(self.v.get().addr()).write();
401 let prev = self.read(&guard);
402 self.write(val, &guard);
403 prev
404 }
405
406 #[inline]
407 #[cfg_attr(all(debug_assertions, not(portable_atomic_no_track_caller)), track_caller)]
408 pub(crate) fn compare_exchange(
409 &self,
410 current: $int_type,
411 new: $int_type,
412 success: Ordering,
413 failure: Ordering,
414 ) -> Result<$int_type, $int_type> {
415 crate::utils::assert_compare_exchange_ordering(success, failure);
416 let _sc_fence = ScFenceGuard::new(
417 success == Ordering::SeqCst || failure == Ordering::SeqCst
418 );
419 let guard = lock(self.v.get().addr()).write();
420 let prev = self.read(&guard);
421 if prev == current {
422 self.write(new, &guard);
423 Ok(prev)
424 } else {
425 // The value hasn't been changed. Drop the guard without incrementing the stamp.
426 guard.abort();
427 Err(prev)
428 }
429 }
430
431 #[inline]
432 pub(crate) fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type {
433 let _sc_fence = ScFenceGuard::new(order == Ordering::SeqCst);
434 let guard = lock(self.v.get().addr()).write();
435 let prev = self.read(&guard);
436 self.write(prev.wrapping_add(val), &guard);
437 prev
438 }
439
440 #[inline]
441 pub(crate) fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type {
442 let _sc_fence = ScFenceGuard::new(order == Ordering::SeqCst);
443 let guard = lock(self.v.get().addr()).write();
444 let prev = self.read(&guard);
445 self.write(prev.wrapping_sub(val), &guard);
446 prev
447 }
448
449 #[inline]
450 pub(crate) fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type {
451 let _sc_fence = ScFenceGuard::new(order == Ordering::SeqCst);
452 let guard = lock(self.v.get().addr()).write();
453 let prev = self.read(&guard);
454 self.write(prev & val, &guard);
455 prev
456 }
457
458 #[inline]
459 pub(crate) fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type {
460 let _sc_fence = ScFenceGuard::new(order == Ordering::SeqCst);
461 let guard = lock(self.v.get().addr()).write();
462 let prev = self.read(&guard);
463 self.write(!(prev & val), &guard);
464 prev
465 }
466
467 #[inline]
468 pub(crate) fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type {
469 let _sc_fence = ScFenceGuard::new(order == Ordering::SeqCst);
470 let guard = lock(self.v.get().addr()).write();
471 let prev = self.read(&guard);
472 self.write(prev | val, &guard);
473 prev
474 }
475
476 #[inline]
477 pub(crate) fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type {
478 let _sc_fence = ScFenceGuard::new(order == Ordering::SeqCst);
479 let guard = lock(self.v.get().addr()).write();
480 let prev = self.read(&guard);
481 self.write(prev ^ val, &guard);
482 prev
483 }
484
485 #[inline]
486 pub(crate) fn fetch_not(&self, order: Ordering) -> $int_type {
487 let _sc_fence = ScFenceGuard::new(order == Ordering::SeqCst);
488 let guard = lock(self.v.get().addr()).write();
489 let prev = self.read(&guard);
490 self.write(!prev, &guard);
491 prev
492 }
493
494 #[inline]
495 pub(crate) fn fetch_neg(&self, order: Ordering) -> $int_type {
496 let _sc_fence = ScFenceGuard::new(order == Ordering::SeqCst);
497 let guard = lock(self.v.get().addr()).write();
498 let prev = self.read(&guard);
499 self.write(prev.wrapping_neg(), &guard);
500 prev
501 }
502 }
503 impl $atomic_type {
504 #[inline]
505 pub(crate) fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type {
506 let _sc_fence = ScFenceGuard::new(order == Ordering::SeqCst);
507 let guard = lock(self.v.get().addr()).write();
508 let prev = self.read(&guard);
509 self.write(core::cmp::max(prev, val), &guard);
510 prev
511 }
512
513 #[inline]
514 pub(crate) fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type {
515 let _sc_fence = ScFenceGuard::new(order == Ordering::SeqCst);
516 let guard = lock(self.v.get().addr()).write();
517 let prev = self.read(&guard);
518 self.write(core::cmp::min(prev, val), &guard);
519 prev
520 }
521 }
522 };
523 }
524
525 #[cfg_attr(
526 portable_atomic_no_cfg_target_has_atomic,
527 cfg(any(
528 test,
529 not(any(
530 not(portable_atomic_no_atomic_64),
531 all(
532 target_arch = "riscv32",
533 not(any(miri, portable_atomic_sanitize_thread)),
534 any(not(portable_atomic_no_asm), portable_atomic_unstable_asm),
535 any(target_feature = "zacas", portable_atomic_target_feature = "zacas"),
536 ),
537 ))
538 ))
539 )]
540 #[cfg_attr(
541 not(portable_atomic_no_cfg_target_has_atomic),
542 cfg(any(
543 test,
544 not(any(
545 target_has_atomic = "64",
546 all(
547 target_arch = "riscv32",
548 not(any(miri, portable_atomic_sanitize_thread)),
549 any(not(portable_atomic_no_asm), portable_atomic_unstable_asm),
550 any(target_feature = "zacas", portable_atomic_target_feature = "zacas"),
551 ),
552 ))
553 ))
554 )]
555 cfg_no_fast_atomic_64!({
556 atomic!(AtomicI64, i64, 8);
557 atomic!(AtomicU64, u64, 8);
558 });
559
560 atomic!(AtomicI128, i128, 16);
561 atomic!(AtomicU128, u128, 16);
562
563 #[cfg(test)]
564 mod tests {
565 use super::*;
566
567 cfg_no_fast_atomic_64!({
568 test_atomic_int!(i64);
569 test_atomic_int!(u64);
570 });
571 test_atomic_int!(i128);
572 test_atomic_int!(u128);
573
574 // load/store/swap implementation is not affected by signedness, so it is
575 // enough to test only unsigned types.
576 cfg_no_fast_atomic_64!({
577 stress_test!(u64);
578 });
579 stress_test!(u128);
580 }