[<prev] [next>] [day] [month] [year] [list]
Message-Id: <20250131155940.305403-1-trintaeoitogc@gmail.com>
Date: Fri, 31 Jan 2025 12:59:39 -0300
From: Guilherme Giacomo Simoes <trintaeoitogc@...il.com>
To: peterz@...radead.org,
mingo@...hat.com,
will@...nel.org,
boqun.feng@...il.com,
longman@...hat.com,
ojeda@...nel.org,
alex.gaynor@...il.com,
gary@...yguo.net,
bjorn3_gh@...tonmail.com,
benno.lossin@...ton.me,
a.hindborg@...nel.org,
aliceryhl@...gle.com,
tmgross@...ch.edu
Cc: Guilherme Giacomo Simoes <trintaeoitogc@...il.com>,
linux-kernel@...r.kernel.org,
rust-for-linux@...r.kernel.org
Subject: [PATCH] rust: sync: lock: Add Lock::get_mut()
At initialization where we can guarantee that we do not have multiple
threads accessing the protected resource, blocking the resource in
addition to being redundant, can cause unnecessary overhead.
Add the Lock::get_mut() function for access the data without lock.
Receive a mutable instance of Lock, and return a mutable reference to
data because if the instance is mutable, the rust compiler guarantee the
access control.
Suggested-by: Björn Roy Baron <bjorn3_gh@...tonmail.com>
Signed-off-by: Guilherme Giacomo Simoes <trintaeoitogc@...il.com>
---
rust/kernel/sync/lock.rs | 37 +++++++++++++++++++++++++++++++++++++
1 file changed, 37 insertions(+)
diff --git a/rust/kernel/sync/lock.rs b/rust/kernel/sync/lock.rs
index eb80048e0110..f1e29820ce99 100644
--- a/rust/kernel/sync/lock.rs
+++ b/rust/kernel/sync/lock.rs
@@ -140,6 +140,43 @@ pub fn new(t: T, name: &'static CStr, key: &'static LockClassKey) -> impl PinIni
}),
})
}
+
+ /// Get a mutable reference to data
+ ///
+ /// ```
+ /// use kernel::sync::{new_mutex, Mutex};
+ ///
+ /// struct Inner {
+ /// a: u32,
+ /// }
+ ///
+ /// #[pin_data]
+ /// struct Example {
+ /// #[pin]
+ /// d: Mutex<Inner>,
+ /// }
+ ///
+ /// impl Example {
+ /// fn new() -> impl PinInit<Self> {
+ /// pin_init!(Self {
+ /// // This new_mutex! can be anothers locks like new_spinlock!()
+ /// d <- new_mutex!(Inner { a: 20 })
+ /// })
+ /// }
+ /// }
+ ///
+ /// let mut pin = KBox::pin_init(Example::new(), GFP_KERNEL)?;
+ /// let mut_pin = pin.as_mut();
+ ///
+ /// let data = unsafe { Pin::get_unchecked_mut(mut_pin).d.get_mut() };
+ /// assert_eq!(data.a, 20);
+ /// ```
+ pub fn get_mut(&mut self) -> &mut T {
+ // SAFETY: the UnsafeCell guarantee that the self.data is not null.
+ // The `&mut self` guarantees the exclusive access to the underlying data, therefore it's
+ // safe to reborrow the inner data.
+ unsafe { &mut *self.data.get() }
+ }
}
impl<B: Backend> Lock<(), B> {
--
2.34.1
Powered by blists - more mailing lists