12387fb2aSBoqun Feng // SPDX-License-Identifier: GPL-2.0
22387fb2aSBoqun Feng
32387fb2aSBoqun Feng //! Atomic primitives.
42387fb2aSBoqun Feng //!
52387fb2aSBoqun Feng //! These primitives have the same semantics as their C counterparts: and the precise definitions of
62387fb2aSBoqun Feng //! semantics can be found at [`LKMM`]. Note that Linux Kernel Memory (Consistency) Model is the
72387fb2aSBoqun Feng //! only model for Rust code in kernel, and Rust's own atomics should be avoided.
82387fb2aSBoqun Feng //!
92387fb2aSBoqun Feng //! # Data races
102387fb2aSBoqun Feng //!
112387fb2aSBoqun Feng //! [`LKMM`] atomics have different rules regarding data races:
122387fb2aSBoqun Feng //!
132387fb2aSBoqun Feng //! - A normal write from C side is treated as an atomic write if
142387fb2aSBoqun Feng //! CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC=y.
152387fb2aSBoqun Feng //! - Mixed-size atomic accesses don't cause data races.
162387fb2aSBoqun Feng //!
172387fb2aSBoqun Feng //! [`LKMM`]: srctree/tools/memory-model/
182387fb2aSBoqun Feng
192387fb2aSBoqun Feng mod internal;
20b638c9bcSBoqun Feng pub mod ordering;
2129c32c40SBoqun Feng mod predefine;
222387fb2aSBoqun Feng
232387fb2aSBoqun Feng pub use internal::AtomicImpl;
24b638c9bcSBoqun Feng pub use ordering::{Acquire, Full, Relaxed, Release};
2529c32c40SBoqun Feng
2629c32c40SBoqun Feng use crate::build_error;
27*d1320543SBoqun Feng use internal::{AtomicArithmeticOps, AtomicBasicOps, AtomicExchangeOps, AtomicRepr};
2829c32c40SBoqun Feng use ordering::OrderingType;
2929c32c40SBoqun Feng
3029c32c40SBoqun Feng /// A memory location which can be safely modified from multiple execution contexts.
3129c32c40SBoqun Feng ///
3229c32c40SBoqun Feng /// This has the same size, alignment and bit validity as the underlying type `T`. And it disables
3329c32c40SBoqun Feng /// niche optimization for the same reason as [`UnsafeCell`].
3429c32c40SBoqun Feng ///
3529c32c40SBoqun Feng /// The atomic operations are implemented in a way that is fully compatible with the [Linux Kernel
3629c32c40SBoqun Feng /// Memory (Consistency) Model][LKMM], hence they should be modeled as the corresponding
3729c32c40SBoqun Feng /// [`LKMM`][LKMM] atomic primitives. With the help of [`Atomic::from_ptr()`] and
3829c32c40SBoqun Feng /// [`Atomic::as_ptr()`], this provides a way to interact with [C-side atomic operations]
3929c32c40SBoqun Feng /// (including those without the `atomic` prefix, e.g. `READ_ONCE()`, `WRITE_ONCE()`,
4029c32c40SBoqun Feng /// `smp_load_acquire()` and `smp_store_release()`).
4129c32c40SBoqun Feng ///
4229c32c40SBoqun Feng /// # Invariants
4329c32c40SBoqun Feng ///
4429c32c40SBoqun Feng /// `self.0` is a valid `T`.
4529c32c40SBoqun Feng ///
4629c32c40SBoqun Feng /// [`UnsafeCell`]: core::cell::UnsafeCell
4729c32c40SBoqun Feng /// [LKMM]: srctree/tools/memory-model/
4829c32c40SBoqun Feng /// [C-side atomic operations]: srctree/Documentation/atomic_t.txt
4929c32c40SBoqun Feng #[repr(transparent)]
5029c32c40SBoqun Feng pub struct Atomic<T: AtomicType>(AtomicRepr<T::Repr>);
5129c32c40SBoqun Feng
5229c32c40SBoqun Feng // SAFETY: `Atomic<T>` is safe to share among execution contexts because all accesses are atomic.
5329c32c40SBoqun Feng unsafe impl<T: AtomicType> Sync for Atomic<T> {}
5429c32c40SBoqun Feng
5529c32c40SBoqun Feng /// Types that support basic atomic operations.
5629c32c40SBoqun Feng ///
5729c32c40SBoqun Feng /// # Round-trip transmutability
5829c32c40SBoqun Feng ///
5929c32c40SBoqun Feng /// `T` is round-trip transmutable to `U` if and only if both of these properties hold:
6029c32c40SBoqun Feng ///
6129c32c40SBoqun Feng /// - Any valid bit pattern for `T` is also a valid bit pattern for `U`.
6229c32c40SBoqun Feng /// - Transmuting (e.g. using [`transmute()`]) a value of type `T` to `U` and then to `T` again
6329c32c40SBoqun Feng /// yields a value that is in all aspects equivalent to the original value.
6429c32c40SBoqun Feng ///
6529c32c40SBoqun Feng /// # Safety
6629c32c40SBoqun Feng ///
6729c32c40SBoqun Feng /// - [`Self`] must have the same size and alignment as [`Self::Repr`].
6829c32c40SBoqun Feng /// - [`Self`] must be [round-trip transmutable] to [`Self::Repr`].
6929c32c40SBoqun Feng ///
7029c32c40SBoqun Feng /// Note that this is more relaxed than requiring the bi-directional transmutability (i.e.
7129c32c40SBoqun Feng /// [`transmute()`] is always sound between `U` and `T`) because of the support for atomic
7229c32c40SBoqun Feng /// variables over unit-only enums, see [Examples].
7329c32c40SBoqun Feng ///
7429c32c40SBoqun Feng /// # Limitations
7529c32c40SBoqun Feng ///
7629c32c40SBoqun Feng /// Because C primitives are used to implement the atomic operations, and a C function requires a
7729c32c40SBoqun Feng /// valid object of a type to operate on (i.e. no `MaybeUninit<_>`), hence at the Rust <-> C
7829c32c40SBoqun Feng /// surface, only types with all the bits initialized can be passed. As a result, types like `(u8,
7929c32c40SBoqun Feng /// u16)` (padding bytes are uninitialized) are currently not supported.
8029c32c40SBoqun Feng ///
8129c32c40SBoqun Feng /// # Examples
8229c32c40SBoqun Feng ///
8329c32c40SBoqun Feng /// A unit-only enum that implements [`AtomicType`]:
8429c32c40SBoqun Feng ///
8529c32c40SBoqun Feng /// ```
8629c32c40SBoqun Feng /// use kernel::sync::atomic::{AtomicType, Atomic, Relaxed};
8729c32c40SBoqun Feng ///
8829c32c40SBoqun Feng /// #[derive(Clone, Copy, PartialEq, Eq)]
8929c32c40SBoqun Feng /// #[repr(i32)]
9029c32c40SBoqun Feng /// enum State {
9129c32c40SBoqun Feng /// Uninit = 0,
9229c32c40SBoqun Feng /// Working = 1,
9329c32c40SBoqun Feng /// Done = 2,
9429c32c40SBoqun Feng /// };
9529c32c40SBoqun Feng ///
9629c32c40SBoqun Feng /// // SAFETY: `State` and `i32` has the same size and alignment, and it's round-trip
9729c32c40SBoqun Feng /// // transmutable to `i32`.
9829c32c40SBoqun Feng /// unsafe impl AtomicType for State {
9929c32c40SBoqun Feng /// type Repr = i32;
10029c32c40SBoqun Feng /// }
10129c32c40SBoqun Feng ///
10229c32c40SBoqun Feng /// let s = Atomic::new(State::Uninit);
10329c32c40SBoqun Feng ///
10429c32c40SBoqun Feng /// assert_eq!(State::Uninit, s.load(Relaxed));
10529c32c40SBoqun Feng /// ```
10629c32c40SBoqun Feng /// [`transmute()`]: core::mem::transmute
10729c32c40SBoqun Feng /// [round-trip transmutable]: AtomicType#round-trip-transmutability
10829c32c40SBoqun Feng /// [Examples]: AtomicType#examples
10929c32c40SBoqun Feng pub unsafe trait AtomicType: Sized + Send + Copy {
11029c32c40SBoqun Feng /// The backing atomic implementation type.
11129c32c40SBoqun Feng type Repr: AtomicImpl;
11229c32c40SBoqun Feng }
11329c32c40SBoqun Feng
114*d1320543SBoqun Feng /// Types that support atomic add operations.
115*d1320543SBoqun Feng ///
116*d1320543SBoqun Feng /// # Safety
117*d1320543SBoqun Feng ///
118*d1320543SBoqun Feng // TODO: Properly defines `wrapping_add` in the following comment.
119*d1320543SBoqun Feng /// `wrapping_add` any value of type `Self::Repr::Delta` obtained by [`Self::rhs_into_delta()`] to
120*d1320543SBoqun Feng /// any value of type `Self::Repr` obtained through transmuting a value of type `Self` to must
121*d1320543SBoqun Feng /// yield a value with a bit pattern also valid for `Self`.
122*d1320543SBoqun Feng pub unsafe trait AtomicAdd<Rhs = Self>: AtomicType {
123*d1320543SBoqun Feng /// Converts `Rhs` into the `Delta` type of the atomic implementation.
rhs_into_delta(rhs: Rhs) -> <Self::Repr as AtomicImpl>::Delta124*d1320543SBoqun Feng fn rhs_into_delta(rhs: Rhs) -> <Self::Repr as AtomicImpl>::Delta;
125*d1320543SBoqun Feng }
126*d1320543SBoqun Feng
12729c32c40SBoqun Feng #[inline(always)]
into_repr<T: AtomicType>(v: T) -> T::Repr12829c32c40SBoqun Feng const fn into_repr<T: AtomicType>(v: T) -> T::Repr {
12929c32c40SBoqun Feng // SAFETY: Per the safety requirement of `AtomicType`, `T` is round-trip transmutable to
13029c32c40SBoqun Feng // `T::Repr`, therefore the transmute operation is sound.
13129c32c40SBoqun Feng unsafe { core::mem::transmute_copy(&v) }
13229c32c40SBoqun Feng }
13329c32c40SBoqun Feng
13429c32c40SBoqun Feng /// # Safety
13529c32c40SBoqun Feng ///
13629c32c40SBoqun Feng /// `r` must be a valid bit pattern of `T`.
13729c32c40SBoqun Feng #[inline(always)]
from_repr<T: AtomicType>(r: T::Repr) -> T13829c32c40SBoqun Feng const unsafe fn from_repr<T: AtomicType>(r: T::Repr) -> T {
13929c32c40SBoqun Feng // SAFETY: Per the safety requirement of the function, the transmute operation is sound.
14029c32c40SBoqun Feng unsafe { core::mem::transmute_copy(&r) }
14129c32c40SBoqun Feng }
14229c32c40SBoqun Feng
14329c32c40SBoqun Feng impl<T: AtomicType> Atomic<T> {
14429c32c40SBoqun Feng /// Creates a new atomic `T`.
new(v: T) -> Self14529c32c40SBoqun Feng pub const fn new(v: T) -> Self {
14629c32c40SBoqun Feng // INVARIANT: Per the safety requirement of `AtomicType`, `into_repr(v)` is a valid `T`.
14729c32c40SBoqun Feng Self(AtomicRepr::new(into_repr(v)))
14829c32c40SBoqun Feng }
14929c32c40SBoqun Feng
15029c32c40SBoqun Feng /// Creates a reference to an atomic `T` from a pointer of `T`.
15129c32c40SBoqun Feng ///
15229c32c40SBoqun Feng /// This usually is used when communicating with C side or manipulating a C struct, see
15329c32c40SBoqun Feng /// examples below.
15429c32c40SBoqun Feng ///
15529c32c40SBoqun Feng /// # Safety
15629c32c40SBoqun Feng ///
15729c32c40SBoqun Feng /// - `ptr` is aligned to `align_of::<T>()`.
15829c32c40SBoqun Feng /// - `ptr` is valid for reads and writes for `'a`.
15929c32c40SBoqun Feng /// - For the duration of `'a`, other accesses to `*ptr` must not cause data races (defined
16029c32c40SBoqun Feng /// by [`LKMM`]) against atomic operations on the returned reference. Note that if all other
16129c32c40SBoqun Feng /// accesses are atomic, then this safety requirement is trivially fulfilled.
16229c32c40SBoqun Feng ///
16329c32c40SBoqun Feng /// [`LKMM`]: srctree/tools/memory-model
16429c32c40SBoqun Feng ///
16529c32c40SBoqun Feng /// # Examples
16629c32c40SBoqun Feng ///
16729c32c40SBoqun Feng /// Using [`Atomic::from_ptr()`] combined with [`Atomic::load()`] or [`Atomic::store()`] can
16829c32c40SBoqun Feng /// achieve the same functionality as `READ_ONCE()`/`smp_load_acquire()` or
16929c32c40SBoqun Feng /// `WRITE_ONCE()`/`smp_store_release()` in C side:
17029c32c40SBoqun Feng ///
17129c32c40SBoqun Feng /// ```
17229c32c40SBoqun Feng /// # use kernel::types::Opaque;
17329c32c40SBoqun Feng /// use kernel::sync::atomic::{Atomic, Relaxed, Release};
17429c32c40SBoqun Feng ///
17529c32c40SBoqun Feng /// // Assume there is a C struct `foo`.
17629c32c40SBoqun Feng /// mod cbindings {
17729c32c40SBoqun Feng /// #[repr(C)]
17829c32c40SBoqun Feng /// pub(crate) struct foo {
17929c32c40SBoqun Feng /// pub(crate) a: i32,
18029c32c40SBoqun Feng /// pub(crate) b: i32
18129c32c40SBoqun Feng /// }
18229c32c40SBoqun Feng /// }
18329c32c40SBoqun Feng ///
18429c32c40SBoqun Feng /// let tmp = Opaque::new(cbindings::foo { a: 1, b: 2 });
18529c32c40SBoqun Feng ///
18629c32c40SBoqun Feng /// // struct foo *foo_ptr = ..;
18729c32c40SBoqun Feng /// let foo_ptr = tmp.get();
18829c32c40SBoqun Feng ///
18929c32c40SBoqun Feng /// // SAFETY: `foo_ptr` is valid, and `.a` is in bounds.
19029c32c40SBoqun Feng /// let foo_a_ptr = unsafe { &raw mut (*foo_ptr).a };
19129c32c40SBoqun Feng ///
19229c32c40SBoqun Feng /// // a = READ_ONCE(foo_ptr->a);
19329c32c40SBoqun Feng /// //
19429c32c40SBoqun Feng /// // SAFETY: `foo_a_ptr` is valid for read, and all other accesses on it is atomic, so no
19529c32c40SBoqun Feng /// // data race.
19629c32c40SBoqun Feng /// let a = unsafe { Atomic::from_ptr(foo_a_ptr) }.load(Relaxed);
19729c32c40SBoqun Feng /// # assert_eq!(a, 1);
19829c32c40SBoqun Feng ///
19929c32c40SBoqun Feng /// // smp_store_release(&foo_ptr->a, 2);
20029c32c40SBoqun Feng /// //
20129c32c40SBoqun Feng /// // SAFETY: `foo_a_ptr` is valid for writes, and all other accesses on it is atomic, so
20229c32c40SBoqun Feng /// // no data race.
20329c32c40SBoqun Feng /// unsafe { Atomic::from_ptr(foo_a_ptr) }.store(2, Release);
20429c32c40SBoqun Feng /// ```
from_ptr<'a>(ptr: *mut T) -> &'a Self where T: Sync,20529c32c40SBoqun Feng pub unsafe fn from_ptr<'a>(ptr: *mut T) -> &'a Self
20629c32c40SBoqun Feng where
20729c32c40SBoqun Feng T: Sync,
20829c32c40SBoqun Feng {
20929c32c40SBoqun Feng // CAST: `T` and `Atomic<T>` have the same size, alignment and bit validity.
21029c32c40SBoqun Feng // SAFETY: Per function safety requirement, `ptr` is a valid pointer and the object will
21129c32c40SBoqun Feng // live long enough. It's safe to return a `&Atomic<T>` because function safety requirement
21229c32c40SBoqun Feng // guarantees other accesses won't cause data races.
21329c32c40SBoqun Feng unsafe { &*ptr.cast::<Self>() }
21429c32c40SBoqun Feng }
21529c32c40SBoqun Feng
21629c32c40SBoqun Feng /// Returns a pointer to the underlying atomic `T`.
21729c32c40SBoqun Feng ///
21829c32c40SBoqun Feng /// Note that use of the return pointer must not cause data races defined by [`LKMM`].
21929c32c40SBoqun Feng ///
22029c32c40SBoqun Feng /// # Guarantees
22129c32c40SBoqun Feng ///
22229c32c40SBoqun Feng /// The returned pointer is valid and properly aligned (i.e. aligned to [`align_of::<T>()`]).
22329c32c40SBoqun Feng ///
22429c32c40SBoqun Feng /// [`LKMM`]: srctree/tools/memory-model
22529c32c40SBoqun Feng /// [`align_of::<T>()`]: core::mem::align_of
as_ptr(&self) -> *mut T22629c32c40SBoqun Feng pub const fn as_ptr(&self) -> *mut T {
22729c32c40SBoqun Feng // GUARANTEE: Per the function guarantee of `AtomicRepr::as_ptr()`, the `self.0.as_ptr()`
22829c32c40SBoqun Feng // must be a valid and properly aligned pointer for `T::Repr`, and per the safety guarantee
22929c32c40SBoqun Feng // of `AtomicType`, it's a valid and properly aligned pointer of `T`.
23029c32c40SBoqun Feng self.0.as_ptr().cast()
23129c32c40SBoqun Feng }
23229c32c40SBoqun Feng
23329c32c40SBoqun Feng /// Returns a mutable reference to the underlying atomic `T`.
23429c32c40SBoqun Feng ///
23529c32c40SBoqun Feng /// This is safe because the mutable reference of the atomic `T` guarantees exclusive access.
get_mut(&mut self) -> &mut T23629c32c40SBoqun Feng pub fn get_mut(&mut self) -> &mut T {
23729c32c40SBoqun Feng // CAST: `T` and `T::Repr` has the same size and alignment per the safety requirement of
23829c32c40SBoqun Feng // `AtomicType`, and per the type invariants `self.0` is a valid `T`, therefore the casting
23929c32c40SBoqun Feng // result is a valid pointer of `T`.
24029c32c40SBoqun Feng // SAFETY: The pointer is valid per the CAST comment above, and the mutable reference
24129c32c40SBoqun Feng // guarantees exclusive access.
24229c32c40SBoqun Feng unsafe { &mut *self.0.as_ptr().cast() }
24329c32c40SBoqun Feng }
24429c32c40SBoqun Feng }
24529c32c40SBoqun Feng
24629c32c40SBoqun Feng impl<T: AtomicType> Atomic<T>
24729c32c40SBoqun Feng where
24829c32c40SBoqun Feng T::Repr: AtomicBasicOps,
24929c32c40SBoqun Feng {
25029c32c40SBoqun Feng /// Loads the value from the atomic `T`.
25129c32c40SBoqun Feng ///
25229c32c40SBoqun Feng /// # Examples
25329c32c40SBoqun Feng ///
25429c32c40SBoqun Feng /// ```
25529c32c40SBoqun Feng /// use kernel::sync::atomic::{Atomic, Relaxed};
25629c32c40SBoqun Feng ///
25729c32c40SBoqun Feng /// let x = Atomic::new(42i32);
25829c32c40SBoqun Feng ///
25929c32c40SBoqun Feng /// assert_eq!(42, x.load(Relaxed));
26029c32c40SBoqun Feng ///
26129c32c40SBoqun Feng /// let x = Atomic::new(42i64);
26229c32c40SBoqun Feng ///
26329c32c40SBoqun Feng /// assert_eq!(42, x.load(Relaxed));
26429c32c40SBoqun Feng /// ```
26529c32c40SBoqun Feng #[doc(alias("atomic_read", "atomic64_read"))]
26629c32c40SBoqun Feng #[inline(always)]
load<Ordering: ordering::AcquireOrRelaxed>(&self, _: Ordering) -> T26729c32c40SBoqun Feng pub fn load<Ordering: ordering::AcquireOrRelaxed>(&self, _: Ordering) -> T {
26829c32c40SBoqun Feng let v = {
26929c32c40SBoqun Feng match Ordering::TYPE {
27029c32c40SBoqun Feng OrderingType::Relaxed => T::Repr::atomic_read(&self.0),
27129c32c40SBoqun Feng OrderingType::Acquire => T::Repr::atomic_read_acquire(&self.0),
27229c32c40SBoqun Feng _ => build_error!("Wrong ordering"),
27329c32c40SBoqun Feng }
27429c32c40SBoqun Feng };
27529c32c40SBoqun Feng
27629c32c40SBoqun Feng // SAFETY: `v` comes from reading `self.0`, which is a valid `T` per the type invariants.
27729c32c40SBoqun Feng unsafe { from_repr(v) }
27829c32c40SBoqun Feng }
27929c32c40SBoqun Feng
28029c32c40SBoqun Feng /// Stores a value to the atomic `T`.
28129c32c40SBoqun Feng ///
28229c32c40SBoqun Feng /// # Examples
28329c32c40SBoqun Feng ///
28429c32c40SBoqun Feng /// ```
28529c32c40SBoqun Feng /// use kernel::sync::atomic::{Atomic, Relaxed};
28629c32c40SBoqun Feng ///
28729c32c40SBoqun Feng /// let x = Atomic::new(42i32);
28829c32c40SBoqun Feng ///
28929c32c40SBoqun Feng /// assert_eq!(42, x.load(Relaxed));
29029c32c40SBoqun Feng ///
29129c32c40SBoqun Feng /// x.store(43, Relaxed);
29229c32c40SBoqun Feng ///
29329c32c40SBoqun Feng /// assert_eq!(43, x.load(Relaxed));
29429c32c40SBoqun Feng /// ```
29529c32c40SBoqun Feng #[doc(alias("atomic_set", "atomic64_set"))]
29629c32c40SBoqun Feng #[inline(always)]
store<Ordering: ordering::ReleaseOrRelaxed>(&self, v: T, _: Ordering)29729c32c40SBoqun Feng pub fn store<Ordering: ordering::ReleaseOrRelaxed>(&self, v: T, _: Ordering) {
29829c32c40SBoqun Feng let v = into_repr(v);
29929c32c40SBoqun Feng
30029c32c40SBoqun Feng // INVARIANT: `v` is a valid `T`, and is stored to `self.0` by `atomic_set*()`.
30129c32c40SBoqun Feng match Ordering::TYPE {
30229c32c40SBoqun Feng OrderingType::Relaxed => T::Repr::atomic_set(&self.0, v),
30329c32c40SBoqun Feng OrderingType::Release => T::Repr::atomic_set_release(&self.0, v),
30429c32c40SBoqun Feng _ => build_error!("Wrong ordering"),
30529c32c40SBoqun Feng }
30629c32c40SBoqun Feng }
30729c32c40SBoqun Feng }
308b606a532SBoqun Feng
309b606a532SBoqun Feng impl<T: AtomicType> Atomic<T>
310b606a532SBoqun Feng where
311b606a532SBoqun Feng T::Repr: AtomicExchangeOps,
312b606a532SBoqun Feng {
313b606a532SBoqun Feng /// Atomic exchange.
314b606a532SBoqun Feng ///
315b606a532SBoqun Feng /// Atomically updates `*self` to `v` and returns the old value of `*self`.
316b606a532SBoqun Feng ///
317b606a532SBoqun Feng /// # Examples
318b606a532SBoqun Feng ///
319b606a532SBoqun Feng /// ```
320b606a532SBoqun Feng /// use kernel::sync::atomic::{Atomic, Acquire, Relaxed};
321b606a532SBoqun Feng ///
322b606a532SBoqun Feng /// let x = Atomic::new(42);
323b606a532SBoqun Feng ///
324b606a532SBoqun Feng /// assert_eq!(42, x.xchg(52, Acquire));
325b606a532SBoqun Feng /// assert_eq!(52, x.load(Relaxed));
326b606a532SBoqun Feng /// ```
327b606a532SBoqun Feng #[doc(alias("atomic_xchg", "atomic64_xchg", "swap"))]
328b606a532SBoqun Feng #[inline(always)]
xchg<Ordering: ordering::Ordering>(&self, v: T, _: Ordering) -> T329b606a532SBoqun Feng pub fn xchg<Ordering: ordering::Ordering>(&self, v: T, _: Ordering) -> T {
330b606a532SBoqun Feng let v = into_repr(v);
331b606a532SBoqun Feng
332b606a532SBoqun Feng // INVARIANT: `self.0` is a valid `T` after `atomic_xchg*()` because `v` is transmutable to
333b606a532SBoqun Feng // `T`.
334b606a532SBoqun Feng let ret = {
335b606a532SBoqun Feng match Ordering::TYPE {
336b606a532SBoqun Feng OrderingType::Full => T::Repr::atomic_xchg(&self.0, v),
337b606a532SBoqun Feng OrderingType::Acquire => T::Repr::atomic_xchg_acquire(&self.0, v),
338b606a532SBoqun Feng OrderingType::Release => T::Repr::atomic_xchg_release(&self.0, v),
339b606a532SBoqun Feng OrderingType::Relaxed => T::Repr::atomic_xchg_relaxed(&self.0, v),
340b606a532SBoqun Feng }
341b606a532SBoqun Feng };
342b606a532SBoqun Feng
343b606a532SBoqun Feng // SAFETY: `ret` comes from reading `*self`, which is a valid `T` per type invariants.
344b606a532SBoqun Feng unsafe { from_repr(ret) }
345b606a532SBoqun Feng }
346b606a532SBoqun Feng
347b606a532SBoqun Feng /// Atomic compare and exchange.
348b606a532SBoqun Feng ///
349b606a532SBoqun Feng /// If `*self` == `old`, atomically updates `*self` to `new`. Otherwise, `*self` is not
350b606a532SBoqun Feng /// modified.
351b606a532SBoqun Feng ///
352b606a532SBoqun Feng /// Compare: The comparison is done via the byte level comparison between `*self` and `old`.
353b606a532SBoqun Feng ///
354b606a532SBoqun Feng /// Ordering: When succeeds, provides the corresponding ordering as the `Ordering` type
355b606a532SBoqun Feng /// parameter indicates, and a failed one doesn't provide any ordering, the load part of a
356b606a532SBoqun Feng /// failed cmpxchg is a [`Relaxed`] load.
357b606a532SBoqun Feng ///
358b606a532SBoqun Feng /// Returns `Ok(value)` if cmpxchg succeeds, and `value` is guaranteed to be equal to `old`,
359b606a532SBoqun Feng /// otherwise returns `Err(value)`, and `value` is the current value of `*self`.
360b606a532SBoqun Feng ///
361b606a532SBoqun Feng /// # Examples
362b606a532SBoqun Feng ///
363b606a532SBoqun Feng /// ```
364b606a532SBoqun Feng /// use kernel::sync::atomic::{Atomic, Full, Relaxed};
365b606a532SBoqun Feng ///
366b606a532SBoqun Feng /// let x = Atomic::new(42);
367b606a532SBoqun Feng ///
368b606a532SBoqun Feng /// // Checks whether cmpxchg succeeded.
369b606a532SBoqun Feng /// let success = x.cmpxchg(52, 64, Relaxed).is_ok();
370b606a532SBoqun Feng /// # assert!(!success);
371b606a532SBoqun Feng ///
372b606a532SBoqun Feng /// // Checks whether cmpxchg failed.
373b606a532SBoqun Feng /// let failure = x.cmpxchg(52, 64, Relaxed).is_err();
374b606a532SBoqun Feng /// # assert!(failure);
375b606a532SBoqun Feng ///
376b606a532SBoqun Feng /// // Uses the old value if failed, probably re-try cmpxchg.
377b606a532SBoqun Feng /// match x.cmpxchg(52, 64, Relaxed) {
378b606a532SBoqun Feng /// Ok(_) => { },
379b606a532SBoqun Feng /// Err(old) => {
380b606a532SBoqun Feng /// // do something with `old`.
381b606a532SBoqun Feng /// # assert_eq!(old, 42);
382b606a532SBoqun Feng /// }
383b606a532SBoqun Feng /// }
384b606a532SBoqun Feng ///
385b606a532SBoqun Feng /// // Uses the latest value regardlessly, same as atomic_cmpxchg() in C.
386b606a532SBoqun Feng /// let latest = x.cmpxchg(42, 64, Full).unwrap_or_else(|old| old);
387b606a532SBoqun Feng /// # assert_eq!(42, latest);
388b606a532SBoqun Feng /// assert_eq!(64, x.load(Relaxed));
389b606a532SBoqun Feng /// ```
390b606a532SBoqun Feng ///
391b606a532SBoqun Feng /// [`Relaxed`]: ordering::Relaxed
392b606a532SBoqun Feng #[doc(alias(
393b606a532SBoqun Feng "atomic_cmpxchg",
394b606a532SBoqun Feng "atomic64_cmpxchg",
395b606a532SBoqun Feng "atomic_try_cmpxchg",
396b606a532SBoqun Feng "atomic64_try_cmpxchg",
397b606a532SBoqun Feng "compare_exchange"
398b606a532SBoqun Feng ))]
399b606a532SBoqun Feng #[inline(always)]
cmpxchg<Ordering: ordering::Ordering>( &self, mut old: T, new: T, o: Ordering, ) -> Result<T, T>400b606a532SBoqun Feng pub fn cmpxchg<Ordering: ordering::Ordering>(
401b606a532SBoqun Feng &self,
402b606a532SBoqun Feng mut old: T,
403b606a532SBoqun Feng new: T,
404b606a532SBoqun Feng o: Ordering,
405b606a532SBoqun Feng ) -> Result<T, T> {
406b606a532SBoqun Feng // Note on code generation:
407b606a532SBoqun Feng //
408b606a532SBoqun Feng // try_cmpxchg() is used to implement cmpxchg(), and if the helper functions are inlined,
409b606a532SBoqun Feng // the compiler is able to figure out that branch is not needed if the users don't care
410b606a532SBoqun Feng // about whether the operation succeeds or not. One exception is on x86, due to commit
411b606a532SBoqun Feng // 44fe84459faf ("locking/atomic: Fix atomic_try_cmpxchg() semantics"), the
412b606a532SBoqun Feng // atomic_try_cmpxchg() on x86 has a branch even if the caller doesn't care about the
413b606a532SBoqun Feng // success of cmpxchg and only wants to use the old value. For example, for code like:
414b606a532SBoqun Feng //
415b606a532SBoqun Feng // let latest = x.cmpxchg(42, 64, Full).unwrap_or_else(|old| old);
416b606a532SBoqun Feng //
417b606a532SBoqun Feng // It will still generate code:
418b606a532SBoqun Feng //
419b606a532SBoqun Feng // movl $0x40, %ecx
420b606a532SBoqun Feng // movl $0x34, %eax
421b606a532SBoqun Feng // lock
422b606a532SBoqun Feng // cmpxchgl %ecx, 0x4(%rsp)
423b606a532SBoqun Feng // jne 1f
424b606a532SBoqun Feng // 2:
425b606a532SBoqun Feng // ...
426b606a532SBoqun Feng // 1: movl %eax, %ecx
427b606a532SBoqun Feng // jmp 2b
428b606a532SBoqun Feng //
429b606a532SBoqun Feng // This might be "fixed" by introducing a try_cmpxchg_exclusive() that knows the "*old"
430b606a532SBoqun Feng // location in the C function is always safe to write.
431b606a532SBoqun Feng if self.try_cmpxchg(&mut old, new, o) {
432b606a532SBoqun Feng Ok(old)
433b606a532SBoqun Feng } else {
434b606a532SBoqun Feng Err(old)
435b606a532SBoqun Feng }
436b606a532SBoqun Feng }
437b606a532SBoqun Feng
438b606a532SBoqun Feng /// Atomic compare and exchange and returns whether the operation succeeds.
439b606a532SBoqun Feng ///
440b606a532SBoqun Feng /// If `*self` == `old`, atomically updates `*self` to `new`. Otherwise, `*self` is not
441b606a532SBoqun Feng /// modified, `*old` is updated to the current value of `*self`.
442b606a532SBoqun Feng ///
443b606a532SBoqun Feng /// "Compare" and "Ordering" part are the same as [`Atomic::cmpxchg()`].
444b606a532SBoqun Feng ///
445b606a532SBoqun Feng /// Returns `true` means the cmpxchg succeeds otherwise returns `false`.
446b606a532SBoqun Feng #[inline(always)]
try_cmpxchg<Ordering: ordering::Ordering>(&self, old: &mut T, new: T, _: Ordering) -> bool447b606a532SBoqun Feng fn try_cmpxchg<Ordering: ordering::Ordering>(&self, old: &mut T, new: T, _: Ordering) -> bool {
448b606a532SBoqun Feng let mut tmp = into_repr(*old);
449b606a532SBoqun Feng let new = into_repr(new);
450b606a532SBoqun Feng
451b606a532SBoqun Feng // INVARIANT: `self.0` is a valid `T` after `atomic_try_cmpxchg*()` because `new` is
452b606a532SBoqun Feng // transmutable to `T`.
453b606a532SBoqun Feng let ret = {
454b606a532SBoqun Feng match Ordering::TYPE {
455b606a532SBoqun Feng OrderingType::Full => T::Repr::atomic_try_cmpxchg(&self.0, &mut tmp, new),
456b606a532SBoqun Feng OrderingType::Acquire => {
457b606a532SBoqun Feng T::Repr::atomic_try_cmpxchg_acquire(&self.0, &mut tmp, new)
458b606a532SBoqun Feng }
459b606a532SBoqun Feng OrderingType::Release => {
460b606a532SBoqun Feng T::Repr::atomic_try_cmpxchg_release(&self.0, &mut tmp, new)
461b606a532SBoqun Feng }
462b606a532SBoqun Feng OrderingType::Relaxed => {
463b606a532SBoqun Feng T::Repr::atomic_try_cmpxchg_relaxed(&self.0, &mut tmp, new)
464b606a532SBoqun Feng }
465b606a532SBoqun Feng }
466b606a532SBoqun Feng };
467b606a532SBoqun Feng
468b606a532SBoqun Feng // SAFETY: `tmp` comes from reading `*self`, which is a valid `T` per type invariants.
469b606a532SBoqun Feng *old = unsafe { from_repr(tmp) };
470b606a532SBoqun Feng
471b606a532SBoqun Feng ret
472b606a532SBoqun Feng }
473b606a532SBoqun Feng }
474*d1320543SBoqun Feng
475*d1320543SBoqun Feng impl<T: AtomicType> Atomic<T>
476*d1320543SBoqun Feng where
477*d1320543SBoqun Feng T::Repr: AtomicArithmeticOps,
478*d1320543SBoqun Feng {
479*d1320543SBoqun Feng /// Atomic add.
480*d1320543SBoqun Feng ///
481*d1320543SBoqun Feng /// Atomically updates `*self` to `(*self).wrapping_add(v)`.
482*d1320543SBoqun Feng ///
483*d1320543SBoqun Feng /// # Examples
484*d1320543SBoqun Feng ///
485*d1320543SBoqun Feng /// ```
486*d1320543SBoqun Feng /// use kernel::sync::atomic::{Atomic, Relaxed};
487*d1320543SBoqun Feng ///
488*d1320543SBoqun Feng /// let x = Atomic::new(42);
489*d1320543SBoqun Feng ///
490*d1320543SBoqun Feng /// assert_eq!(42, x.load(Relaxed));
491*d1320543SBoqun Feng ///
492*d1320543SBoqun Feng /// x.add(12, Relaxed);
493*d1320543SBoqun Feng ///
494*d1320543SBoqun Feng /// assert_eq!(54, x.load(Relaxed));
495*d1320543SBoqun Feng /// ```
496*d1320543SBoqun Feng #[inline(always)]
add<Rhs>(&self, v: Rhs, _: ordering::Relaxed) where T: AtomicAdd<Rhs>,497*d1320543SBoqun Feng pub fn add<Rhs>(&self, v: Rhs, _: ordering::Relaxed)
498*d1320543SBoqun Feng where
499*d1320543SBoqun Feng T: AtomicAdd<Rhs>,
500*d1320543SBoqun Feng {
501*d1320543SBoqun Feng let v = T::rhs_into_delta(v);
502*d1320543SBoqun Feng
503*d1320543SBoqun Feng // INVARIANT: `self.0` is a valid `T` after `atomic_add()` due to safety requirement of
504*d1320543SBoqun Feng // `AtomicAdd`.
505*d1320543SBoqun Feng T::Repr::atomic_add(&self.0, v);
506*d1320543SBoqun Feng }
507*d1320543SBoqun Feng
508*d1320543SBoqun Feng /// Atomic fetch and add.
509*d1320543SBoqun Feng ///
510*d1320543SBoqun Feng /// Atomically updates `*self` to `(*self).wrapping_add(v)`, and returns the value of `*self`
511*d1320543SBoqun Feng /// before the update.
512*d1320543SBoqun Feng ///
513*d1320543SBoqun Feng /// # Examples
514*d1320543SBoqun Feng ///
515*d1320543SBoqun Feng /// ```
516*d1320543SBoqun Feng /// use kernel::sync::atomic::{Atomic, Acquire, Full, Relaxed};
517*d1320543SBoqun Feng ///
518*d1320543SBoqun Feng /// let x = Atomic::new(42);
519*d1320543SBoqun Feng ///
520*d1320543SBoqun Feng /// assert_eq!(42, x.load(Relaxed));
521*d1320543SBoqun Feng ///
522*d1320543SBoqun Feng /// assert_eq!(54, { x.fetch_add(12, Acquire); x.load(Relaxed) });
523*d1320543SBoqun Feng ///
524*d1320543SBoqun Feng /// let x = Atomic::new(42);
525*d1320543SBoqun Feng ///
526*d1320543SBoqun Feng /// assert_eq!(42, x.load(Relaxed));
527*d1320543SBoqun Feng ///
528*d1320543SBoqun Feng /// assert_eq!(54, { x.fetch_add(12, Full); x.load(Relaxed) } );
529*d1320543SBoqun Feng /// ```
530*d1320543SBoqun Feng #[inline(always)]
fetch_add<Rhs, Ordering: ordering::Ordering>(&self, v: Rhs, _: Ordering) -> T where T: AtomicAdd<Rhs>,531*d1320543SBoqun Feng pub fn fetch_add<Rhs, Ordering: ordering::Ordering>(&self, v: Rhs, _: Ordering) -> T
532*d1320543SBoqun Feng where
533*d1320543SBoqun Feng T: AtomicAdd<Rhs>,
534*d1320543SBoqun Feng {
535*d1320543SBoqun Feng let v = T::rhs_into_delta(v);
536*d1320543SBoqun Feng
537*d1320543SBoqun Feng // INVARIANT: `self.0` is a valid `T` after `atomic_fetch_add*()` due to safety requirement
538*d1320543SBoqun Feng // of `AtomicAdd`.
539*d1320543SBoqun Feng let ret = {
540*d1320543SBoqun Feng match Ordering::TYPE {
541*d1320543SBoqun Feng OrderingType::Full => T::Repr::atomic_fetch_add(&self.0, v),
542*d1320543SBoqun Feng OrderingType::Acquire => T::Repr::atomic_fetch_add_acquire(&self.0, v),
543*d1320543SBoqun Feng OrderingType::Release => T::Repr::atomic_fetch_add_release(&self.0, v),
544*d1320543SBoqun Feng OrderingType::Relaxed => T::Repr::atomic_fetch_add_relaxed(&self.0, v),
545*d1320543SBoqun Feng }
546*d1320543SBoqun Feng };
547*d1320543SBoqun Feng
548*d1320543SBoqun Feng // SAFETY: `ret` comes from reading `self.0`, which is a valid `T` per type invariants.
549*d1320543SBoqun Feng unsafe { from_repr(ret) }
550*d1320543SBoqun Feng }
551*d1320543SBoqun Feng }
552