[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <20241101060237.1185533-7-boqun.feng@gmail.com>
Date: Thu, 31 Oct 2024 23:02:29 -0700
From: Boqun Feng <boqun.feng@...il.com>
To: rust-for-linux@...r.kernel.org,
rcu@...r.kernel.org,
linux-kernel@...r.kernel.org,
linux-arch@...r.kernel.org,
llvm@...ts.linux.dev,
lkmm@...ts.linux.dev
Cc: Miguel Ojeda <ojeda@...nel.org>, Alex Gaynor <alex.gaynor@...il.com>,
Wedson Almeida Filho <wedsonaf@...il.com>,
Boqun Feng <boqun.feng@...il.com>, Gary Guo <gary@...yguo.net>,
Björn Roy Baron <bjorn3_gh@...tonmail.com>,
Benno Lossin <benno.lossin@...ton.me>,
Andreas Hindborg <a.hindborg@...sung.com>,
Alice Ryhl <aliceryhl@...gle.com>,
Alan Stern <stern@...land.harvard.edu>,
Andrea Parri <parri.andrea@...il.com>, Will Deacon <will@...nel.org>,
Peter Zijlstra <peterz@...radead.org>,
Nicholas Piggin <npiggin@...il.com>, David Howells <dhowells@...hat.com>,
Jade Alglave <j.alglave@....ac.uk>, Luc Maranget <luc.maranget@...ia.fr>,
"Paul E. McKenney" <paulmck@...nel.org>,
Akira Yokosawa <akiyks@...il.com>, Daniel Lustig <dlustig@...dia.com>,
Joel Fernandes <joel@...lfernandes.org>,
Nathan Chancellor <nathan@...nel.org>,
Nick Desaulniers <ndesaulniers@...gle.com>, kent.overstreet@...il.com,
Greg Kroah-Hartman <gregkh@...uxfoundation.org>, elver@...gle.com,
Mark Rutland <mark.rutland@....com>,
Thomas Gleixner <tglx@...utronix.de>, Ingo Molnar <mingo@...hat.com>,
Borislav Petkov <bp@...en8.de>,
Dave Hansen <dave.hansen@...ux.intel.com>, x86@...nel.org,
"H. Peter Anvin" <hpa@...or.com>,
Catalin Marinas <catalin.marinas@....com>, torvalds@...ux-foundation.org,
linux-arm-kernel@...ts.infradead.org, linux-fsdevel@...r.kernel.org,
Trevor Gross <tmgross@...ch.edu>, dakr@...hat.com,
Frederic Weisbecker <frederic@...nel.org>,
Neeraj Upadhyay <neeraj.upadhyay@...nel.org>,
Josh Triplett <josh@...htriplett.org>,
Uladzislau Rezki <urezki@...il.com>,
Steven Rostedt <rostedt@...dmis.org>,
Mathieu Desnoyers <mathieu.desnoyers@...icios.com>,
Lai Jiangshan <jiangshanlai@...il.com>,
Zqiang <qiang.zhang1211@...il.com>,
Paul Walmsley <paul.walmsley@...ive.com>,
Palmer Dabbelt <palmer@...belt.com>, Albert Ou <aou@...s.berkeley.edu>,
linux-riscv@...ts.infradead.org
Subject: [RFC v2 06/13] rust: sync: atomic: Add the framework of arithmetic operations
One important set of atomic operations is the arithmetic operations,
i.e. add(), sub(), fetch_add(), add_return(), etc. However it may not
make senses for all the types that `AllowAtomic` to have arithmetic
operations, for example a `Foo(u32)` may not have a reasonable add() or
sub(), plus subword types (`u8` and `u16`) currently don't have
atomic arithmetic operations even on C side and might not have them in
the future in Rust (because they are usually suboptimal on a few
architecures). Therefore add a subtrait of `AllowAtomic` describing
which types have and can do atomic arithemtic operations.
A few things about this `AllowAtomicArithmetic` trait:
* It has an associate type `Delta` instead of using
`AllowAllowAtomic::Repr` because, a `Bar(u32)` (whose `Repr` is `i32`)
may not wants an `add(&self, i32)`, but an `add(&self, u32)`.
* `AtomicImpl` types already implement an `AtomicHasArithmeticOps`
trait, so add blanket implementation for them. In the future, `i8` and
`i16` may impl `AtomicImpl` but not `AtomicHasArithmeticOps` if
arithemtic operations are not available.
Only add() and fetch_add() are added. The rest will be added in the
future.
Signed-off-by: Boqun Feng <boqun.feng@...il.com>
---
rust/kernel/sync/atomic/generic.rs | 102 +++++++++++++++++++++++++++++
1 file changed, 102 insertions(+)
diff --git a/rust/kernel/sync/atomic/generic.rs b/rust/kernel/sync/atomic/generic.rs
index bfccc4336c75..a75c3e9f4c89 100644
--- a/rust/kernel/sync/atomic/generic.rs
+++ b/rust/kernel/sync/atomic/generic.rs
@@ -3,6 +3,7 @@
//! Generic atomic primitives.
use super::ops::*;
+use super::ordering;
use super::ordering::*;
use crate::types::Opaque;
@@ -54,6 +55,23 @@ fn from_repr(repr: Self::Repr) -> Self {
}
}
+/// Atomics that allows arithmetic operations with an integer type.
+pub trait AllowAtomicArithmetic: AllowAtomic {
+ /// The delta types for arithmetic operations.
+ type Delta;
+
+ /// Converts [`Self::Delta`] into the representation of the atomic type.
+ fn delta_into_repr(d: Self::Delta) -> Self::Repr;
+}
+
+impl<T: AtomicImpl + AtomicHasArithmeticOps> AllowAtomicArithmetic for T {
+ type Delta = Self;
+
+ fn delta_into_repr(d: Self::Delta) -> Self::Repr {
+ d
+ }
+}
+
impl<T: AllowAtomic> Atomic<T> {
/// Creates a new atomic.
pub const fn new(v: T) -> Self {
@@ -402,3 +420,87 @@ pub fn compare_exchange<Ordering: All>(&self, mut old: T, new: T, o: Ordering) -
}
}
}
+
+impl<T: AllowAtomicArithmetic> Atomic<T>
+where
+ T::Repr: AtomicHasArithmeticOps,
+{
+ /// Atomic add.
+ ///
+ /// The addition is a wrapping addition.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use kernel::sync::atomic::{Atomic, Relaxed};
+ ///
+ /// let x = Atomic::new(42);
+ ///
+ /// assert_eq!(42, x.load(Relaxed));
+ ///
+ /// x.add(12, Relaxed);
+ ///
+ /// assert_eq!(54, x.load(Relaxed));
+ /// ```
+ #[inline(always)]
+ pub fn add<Ordering: RelaxedOnly>(&self, v: T::Delta, _: Ordering) {
+ let v = T::delta_into_repr(v);
+ let a = self.as_ptr().cast::<T::Repr>();
+
+ // SAFETY:
+ // - For calling the atomic_add() function:
+ // - `self.as_ptr()` is a valid pointer, and per the safety requirement of `AllocAtomic`,
+ // a `*mut T` is a valid `*mut T::Repr`. Therefore `a` is a valid pointer,
+ // - per the type invariants, the following atomic operation won't cause data races.
+ // - For extra safety requirement of usage on pointers returned by `self.as_ptr():
+ // - atomic operations are used here.
+ unsafe {
+ T::Repr::atomic_add(a, v);
+ }
+ }
+
+ /// Atomic fetch and add.
+ ///
+ /// The addition is a wrapping addition.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use kernel::sync::atomic::{Atomic, Acquire, Full, Relaxed};
+ ///
+ /// let x = Atomic::new(42);
+ ///
+ /// assert_eq!(42, x.load(Relaxed));
+ ///
+ /// assert_eq!(54, { x.fetch_add(12, Acquire); x.load(Relaxed) });
+ ///
+ /// let x = Atomic::new(42);
+ ///
+ /// assert_eq!(42, x.load(Relaxed));
+ ///
+ /// assert_eq!(54, { x.fetch_add(12, Full); x.load(Relaxed) } );
+ /// ```
+ #[inline(always)]
+ pub fn fetch_add<Ordering: All>(&self, v: T::Delta, _: Ordering) -> T {
+ let v = T::delta_into_repr(v);
+ let a = self.as_ptr().cast::<T::Repr>();
+
+ // SAFETY:
+ // - For calling the atomic_fetch_add*() function:
+ // - `self.as_ptr()` is a valid pointer, and per the safety requirement of `AllocAtomic`,
+ // a `*mut T` is a valid `*mut T::Repr`. Therefore `a` is a valid pointer,
+ // - per the type invariants, the following atomic operation won't cause data races.
+ // - For extra safety requirement of usage on pointers returned by `self.as_ptr():
+ // - atomic operations are used here.
+ let ret = unsafe {
+ match Ordering::ORDER {
+ ordering::OrderingDesc::Full => T::Repr::atomic_fetch_add(a, v),
+ ordering::OrderingDesc::Acquire => T::Repr::atomic_fetch_add_acquire(a, v),
+ ordering::OrderingDesc::Release => T::Repr::atomic_fetch_add_release(a, v),
+ ordering::OrderingDesc::Relaxed => T::Repr::atomic_fetch_add_relaxed(a, v),
+ }
+ };
+
+ T::from_repr(ret)
+ }
+}
--
2.45.2
Powered by blists - more mailing lists