-
Notifications
You must be signed in to change notification settings - Fork 49
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
userlib: Add SpinLock Implementation
Add a simple SpinLock implementation to the user library to protect access to global state. At some point this needs to be replaces with a non-busy waiting locking implementation. Signed-off-by: Joerg Roedel <[email protected]>
- Loading branch information
1 parent
e3db7d3
commit a0b39e6
Showing
2 changed files
with
74 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
// SPDX-License-Identifier: MIT | ||
// | ||
// Copyright (c) 2024 SUSE LLC | ||
// | ||
// Author: Joerg Roedel <[email protected]> | ||
|
||
use core::cell::UnsafeCell; | ||
use core::ops::{Deref, DerefMut}; | ||
use core::sync::atomic::{AtomicU64, Ordering}; | ||
|
||
#[derive(Debug)] | ||
pub struct LockGuard<'a, T> { | ||
holder: &'a AtomicU64, | ||
data: &'a mut T, | ||
} | ||
|
||
impl<T> Drop for LockGuard<'_, T> { | ||
fn drop(&mut self) { | ||
self.holder.fetch_add(1, Ordering::Release); | ||
} | ||
} | ||
|
||
impl<T> Deref for LockGuard<'_, T> { | ||
type Target = T; | ||
fn deref(&self) -> &T { | ||
self.data | ||
} | ||
} | ||
|
||
impl<T> DerefMut for LockGuard<'_, T> { | ||
fn deref_mut(&mut self) -> &mut T { | ||
self.data | ||
} | ||
} | ||
|
||
#[derive(Debug)] | ||
pub struct SpinLock<T> { | ||
current: AtomicU64, | ||
holder: AtomicU64, | ||
data: UnsafeCell<T>, | ||
} | ||
|
||
// SAFETY: SpinLock guarantees mutually exclusive access to wrapped data. | ||
unsafe impl<T> Sync for SpinLock<T> {} | ||
|
||
impl<'a, T> SpinLock<T> { | ||
pub const fn new(data: T) -> Self { | ||
SpinLock { | ||
current: AtomicU64::new(0), | ||
holder: AtomicU64::new(0), | ||
data: UnsafeCell::new(data), | ||
} | ||
} | ||
|
||
pub fn lock(&'a self) -> LockGuard<'a, T> { | ||
let ticket = self.current.fetch_add(1, Ordering::Relaxed); | ||
loop { | ||
let h = self.holder.load(Ordering::Acquire); | ||
if h == ticket { | ||
break; | ||
} | ||
} | ||
|
||
LockGuard { | ||
holder: &self.holder, | ||
// SAFETY: Safe because at this point the lock is held and this is | ||
// guaranteed to be the only reference. | ||
data: unsafe { &mut *self.data.get() }, | ||
} | ||
} | ||
} |