#![allow(dead_code)]
use alloc::sync::Arc;
use core::{
cell::UnsafeCell,
fmt,
ops::{Deref, DerefMut},
sync::atomic::{
AtomicUsize,
Ordering::{AcqRel, Acquire, Relaxed, Release},
},
};
use crate::{
task::{disable_preempt, DisabledPreemptGuard},
trap::{disable_local, DisabledLocalIrqGuard},
};
pub struct RwLock<T: ?Sized> {
lock: AtomicUsize,
val: UnsafeCell<T>,
}
const READER: usize = 1;
const WRITER: usize = 1 << (usize::BITS - 1);
const UPGRADEABLE_READER: usize = 1 << (usize::BITS - 2);
const BEING_UPGRADED: usize = 1 << (usize::BITS - 3);
const MAX_READER: usize = 1 << (usize::BITS - 4);
impl<T> RwLock<T> {
pub const fn new(val: T) -> Self {
Self {
val: UnsafeCell::new(val),
lock: AtomicUsize::new(0),
}
}
}
impl<T: ?Sized> RwLock<T> {
pub fn read_irq_disabled(&self) -> RwLockReadGuard<T> {
loop {
if let Some(readguard) = self.try_read_irq_disabled() {
return readguard;
} else {
core::hint::spin_loop();
}
}
}
pub fn write_irq_disabled(&self) -> RwLockWriteGuard<T> {
loop {
if let Some(writeguard) = self.try_write_irq_disabled() {
return writeguard;
} else {
core::hint::spin_loop();
}
}
}
pub fn upread_irq_disabled(&self) -> RwLockUpgradeableGuard<T> {
loop {
if let Some(guard) = self.try_upread_irq_disabled() {
return guard;
} else {
core::hint::spin_loop();
}
}
}
pub fn try_read_irq_disabled(&self) -> Option<RwLockReadGuard<T>> {
let irq_guard = disable_local();
let lock = self.lock.fetch_add(READER, Acquire);
if lock & (WRITER | MAX_READER | BEING_UPGRADED) == 0 {
Some(RwLockReadGuard {
inner: self,
inner_guard: InnerGuard::IrqGuard(irq_guard),
})
} else {
self.lock.fetch_sub(READER, Release);
None
}
}
pub fn try_write_irq_disabled(&self) -> Option<RwLockWriteGuard<T>> {
let irq_guard = disable_local();
if self
.lock
.compare_exchange(0, WRITER, Acquire, Relaxed)
.is_ok()
{
Some(RwLockWriteGuard {
inner: self,
inner_guard: InnerGuard::IrqGuard(irq_guard),
})
} else {
None
}
}
pub fn try_upread_irq_disabled(&self) -> Option<RwLockUpgradeableGuard<T>> {
let irq_guard = disable_local();
let lock = self.lock.fetch_or(UPGRADEABLE_READER, Acquire) & (WRITER | UPGRADEABLE_READER);
if lock == 0 {
return Some(RwLockUpgradeableGuard {
inner: self,
inner_guard: InnerGuard::IrqGuard(irq_guard),
});
} else if lock == WRITER {
self.lock.fetch_sub(UPGRADEABLE_READER, Release);
}
None
}
pub fn read(&self) -> RwLockReadGuard<T> {
loop {
if let Some(readguard) = self.try_read() {
return readguard;
} else {
core::hint::spin_loop();
}
}
}
pub fn read_arc(self: &Arc<Self>) -> ArcRwLockReadGuard<T> {
loop {
if let Some(readguard) = self.try_read_arc() {
return readguard;
} else {
core::hint::spin_loop();
}
}
}
pub fn write(&self) -> RwLockWriteGuard<T> {
loop {
if let Some(writeguard) = self.try_write() {
return writeguard;
} else {
core::hint::spin_loop();
}
}
}
pub fn write_arc(self: &Arc<Self>) -> ArcRwLockWriteGuard<T> {
loop {
if let Some(writeguard) = self.try_write_arc() {
return writeguard;
} else {
core::hint::spin_loop();
}
}
}
pub fn upread(&self) -> RwLockUpgradeableGuard<T> {
loop {
if let Some(guard) = self.try_upread() {
return guard;
} else {
core::hint::spin_loop();
}
}
}
pub fn upread_arc(self: &Arc<Self>) -> ArcRwLockUpgradeableGuard<T> {
loop {
if let Some(guard) = self.try_upread_arc() {
return guard;
} else {
core::hint::spin_loop();
}
}
}
pub fn try_read(&self) -> Option<RwLockReadGuard<T>> {
let guard = disable_preempt();
let lock = self.lock.fetch_add(READER, Acquire);
if lock & (WRITER | MAX_READER | BEING_UPGRADED) == 0 {
Some(RwLockReadGuard {
inner: self,
inner_guard: InnerGuard::PreemptGuard(guard),
})
} else {
self.lock.fetch_sub(READER, Release);
None
}
}
pub fn try_read_arc(self: &Arc<Self>) -> Option<ArcRwLockReadGuard<T>> {
let guard = disable_preempt();
let lock = self.lock.fetch_add(READER, Acquire);
if lock & (WRITER | MAX_READER | BEING_UPGRADED) == 0 {
Some(ArcRwLockReadGuard {
inner: self.clone(),
inner_guard: InnerGuard::PreemptGuard(guard),
})
} else {
self.lock.fetch_sub(READER, Release);
None
}
}
pub fn try_write(&self) -> Option<RwLockWriteGuard<T>> {
let guard = disable_preempt();
if self
.lock
.compare_exchange(0, WRITER, Acquire, Relaxed)
.is_ok()
{
Some(RwLockWriteGuard {
inner: self,
inner_guard: InnerGuard::PreemptGuard(guard),
})
} else {
None
}
}
fn try_write_arc(self: &Arc<Self>) -> Option<ArcRwLockWriteGuard<T>> {
let guard = disable_preempt();
if self
.lock
.compare_exchange(0, WRITER, Acquire, Relaxed)
.is_ok()
{
Some(ArcRwLockWriteGuard {
inner: self.clone(),
inner_guard: InnerGuard::PreemptGuard(guard),
})
} else {
None
}
}
pub fn try_upread(&self) -> Option<RwLockUpgradeableGuard<T>> {
let guard = disable_preempt();
let lock = self.lock.fetch_or(UPGRADEABLE_READER, Acquire) & (WRITER | UPGRADEABLE_READER);
if lock == 0 {
return Some(RwLockUpgradeableGuard {
inner: self,
inner_guard: InnerGuard::PreemptGuard(guard),
});
} else if lock == WRITER {
self.lock.fetch_sub(UPGRADEABLE_READER, Release);
}
None
}
pub fn try_upread_arc(self: &Arc<Self>) -> Option<ArcRwLockUpgradeableGuard<T>> {
let guard = disable_preempt();
let lock = self.lock.fetch_or(UPGRADEABLE_READER, Acquire) & (WRITER | UPGRADEABLE_READER);
if lock == 0 {
return Some(ArcRwLockUpgradeableGuard {
inner: self.clone(),
inner_guard: InnerGuard::PreemptGuard(guard),
});
} else if lock == WRITER {
self.lock.fetch_sub(UPGRADEABLE_READER, Release);
}
None
}
}
impl<T: ?Sized + fmt::Debug> fmt::Debug for RwLock<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.val, f)
}
}
unsafe impl<T: ?Sized + Send> Send for RwLock<T> {}
unsafe impl<T: ?Sized + Send + Sync> Sync for RwLock<T> {}
impl<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> !Send for RwLockWriteGuard_<T, R> {}
unsafe impl<T: ?Sized + Sync, R: Deref<Target = RwLock<T>> + Clone + Sync> Sync
for RwLockWriteGuard_<T, R>
{
}
impl<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> !Send for RwLockReadGuard_<T, R> {}
unsafe impl<T: ?Sized + Sync, R: Deref<Target = RwLock<T>> + Clone + Sync> Sync
for RwLockReadGuard_<T, R>
{
}
impl<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> !Send for RwLockUpgradeableGuard_<T, R> {}
unsafe impl<T: ?Sized + Sync, R: Deref<Target = RwLock<T>> + Clone + Sync> Sync
for RwLockUpgradeableGuard_<T, R>
{
}
enum InnerGuard {
IrqGuard(DisabledLocalIrqGuard),
PreemptGuard(DisabledPreemptGuard),
}
impl InnerGuard {
fn transfer_to(&mut self) -> Self {
match self {
InnerGuard::IrqGuard(irq_guard) => InnerGuard::IrqGuard(irq_guard.transfer_to()),
InnerGuard::PreemptGuard(preempt_guard) => {
InnerGuard::PreemptGuard(preempt_guard.transfer_to())
}
}
}
}
#[clippy::has_significant_drop]
#[must_use]
pub struct RwLockReadGuard_<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> {
inner_guard: InnerGuard,
inner: R,
}
pub type RwLockReadGuard<'a, T> = RwLockReadGuard_<T, &'a RwLock<T>>;
pub type ArcRwLockReadGuard<T> = RwLockReadGuard_<T, Arc<RwLock<T>>>;
impl<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> Deref for RwLockReadGuard_<T, R> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.inner.val.get() }
}
}
impl<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> Drop for RwLockReadGuard_<T, R> {
fn drop(&mut self) {
self.inner.lock.fetch_sub(READER, Release);
}
}
impl<T: ?Sized + fmt::Debug, R: Deref<Target = RwLock<T>> + Clone> fmt::Debug
for RwLockReadGuard_<T, R>
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
pub struct RwLockWriteGuard_<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> {
inner_guard: InnerGuard,
inner: R,
}
pub type RwLockWriteGuard<'a, T> = RwLockWriteGuard_<T, &'a RwLock<T>>;
pub type ArcRwLockWriteGuard<T> = RwLockWriteGuard_<T, Arc<RwLock<T>>>;
impl<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> Deref for RwLockWriteGuard_<T, R> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.inner.val.get() }
}
}
impl<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> RwLockWriteGuard_<T, R> {
pub fn downgrade(mut self) -> RwLockUpgradeableGuard_<T, R> {
loop {
self = match self.try_downgrade() {
Ok(guard) => return guard,
Err(e) => e,
};
}
}
fn try_downgrade(mut self) -> Result<RwLockUpgradeableGuard_<T, R>, Self> {
let inner = self.inner.clone();
let res = self
.inner
.lock
.compare_exchange(WRITER, UPGRADEABLE_READER, AcqRel, Relaxed);
if res.is_ok() {
let inner_guard = self.inner_guard.transfer_to();
drop(self);
Ok(RwLockUpgradeableGuard_ { inner, inner_guard })
} else {
Err(self)
}
}
}
impl<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> DerefMut for RwLockWriteGuard_<T, R> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *self.inner.val.get() }
}
}
impl<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> Drop for RwLockWriteGuard_<T, R> {
fn drop(&mut self) {
self.inner.lock.fetch_and(!WRITER, Release);
}
}
impl<T: ?Sized + fmt::Debug, R: Deref<Target = RwLock<T>> + Clone> fmt::Debug
for RwLockWriteGuard_<T, R>
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
pub struct RwLockUpgradeableGuard_<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> {
inner_guard: InnerGuard,
inner: R,
}
pub type RwLockUpgradeableGuard<'a, T> = RwLockUpgradeableGuard_<T, &'a RwLock<T>>;
pub type ArcRwLockUpgradeableGuard<T> = RwLockUpgradeableGuard_<T, Arc<RwLock<T>>>;
impl<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> RwLockUpgradeableGuard_<T, R> {
pub fn upgrade(mut self) -> RwLockWriteGuard_<T, R> {
self.inner.lock.fetch_or(BEING_UPGRADED, Acquire);
loop {
self = match self.try_upgrade() {
Ok(guard) => return guard,
Err(e) => e,
};
}
}
pub fn try_upgrade(mut self) -> Result<RwLockWriteGuard_<T, R>, Self> {
let res = self.inner.lock.compare_exchange(
UPGRADEABLE_READER | BEING_UPGRADED,
WRITER | UPGRADEABLE_READER,
AcqRel,
Relaxed,
);
if res.is_ok() {
let inner = self.inner.clone();
let inner_guard = self.inner_guard.transfer_to();
drop(self);
Ok(RwLockWriteGuard_ { inner, inner_guard })
} else {
Err(self)
}
}
}
impl<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> Deref for RwLockUpgradeableGuard_<T, R> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.inner.val.get() }
}
}
impl<T: ?Sized, R: Deref<Target = RwLock<T>> + Clone> Drop for RwLockUpgradeableGuard_<T, R> {
fn drop(&mut self) {
self.inner.lock.fetch_sub(UPGRADEABLE_READER, Release);
}
}
impl<T: ?Sized + fmt::Debug, R: Deref<Target = RwLock<T>> + Clone> fmt::Debug
for RwLockUpgradeableGuard_<T, R>
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}