1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
use crate::as_mut; use crate::alloc::MemPool; use crate::cell::VCell; use crate::ptr::Ptr; use crate::stm::{Journal, Log, Notifier, Logger}; use crate::{PSafe, RootObj, TxInSafe, TxOutSafe}; use std::cell::UnsafeCell; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use std::panic::{RefUnwindSafe, UnwindSafe}; use std::sync::{TryLockError, TryLockResult}; #[allow(unused_imports)] use std::{fmt, intrinsics}; /// A transaction-wide recursive mutual exclusion primitive useful for /// protecting shared data while transaction is open. Further locking in the /// same thread is non-blocking. Any access to data is serialized. Borrow rules /// are checked dynamically to prevent multiple mutable dereferencing. /// /// This mutex will block threads/transactions waiting for the lock to become /// available. The difference between `Mutex` and [`std`]`::`[`sync`]`::`[`Mutex`] /// is that it will hold the lock until the transaction commits. For example, /// consider the following code snippet in which a shared object is protected /// with [`std`]`::`[`sync`]`::`[`Mutex`]. In this case, data might be lost. /// /// ```no_compile /// use corundum::default::*; /// use std::sync::Mutex; /// /// type P = BuddyAlloc; /// /// let obj = P::open::<Parc<Mutex<i32>>>("foo.pool", O_CF).unwrap(); /// // ^ std::sync::Mutex is not PSafe /// /// transaction(|j| { /// { /// let obj = obj.lock().unwrap(); /// // Some statements ... /// } // <-- release the lock here /// /// // Another thread can work with obj /// /// { /// let obj = obj.lock().unwrap(); /// // Some statements ... /// } // <-- release the lock here /// /// // A crash may happen here after another thread has used updated data /// // which leads to an inconsistent state /// }); /// ``` /// /// The safest way to have a shared object protected from both data-race and /// data-loss is to wrap it with a transaction-wide `Mutex` as in the following /// example: /// /// ``` /// use corundum::default::*; /// /// type P = BuddyAlloc; /// /// // PMutex<T> = corundum::sync::Mutex<T,P> /// let obj = P::open::<Parc<PMutex<i32>>>("foo.pool", O_CF).unwrap(); /// /// transaction(|j| { /// { /// let obj = obj.lock(j); /// // Some statements ... /// } /// /// // data is still locked. /// /// { /// let obj = obj.lock(j); // <-- does not block the current thread /// // Some statements ... /// } /// /// }); // <-- release the lock here after committing or rolling back the transaction /// ``` /// /// [`new`]: #method.new /// [`lock`]: #method.lock /// [`Mutex`]: std::sync::Mutex /// [`sync`]: std::sync /// [`std`]: std /// pub struct Mutex<T, A: MemPool> { heap: PhantomData<A>, inner: VCell<MutexInner, A>, data: UnsafeCell<(u8, T)>, } struct MutexInner { borrowed: bool, #[cfg(feature = "pthread")] lock: (bool, libc::pthread_mutex_t, libc::pthread_mutexattr_t), #[cfg(not(feature = "pthread"))] lock: (bool, u64) } impl Default for MutexInner { #[cfg(feature = "pthread")] fn default() -> Self { use std::mem::MaybeUninit; let mut attr = MaybeUninit::<libc::pthread_mutexattr_t>::uninit(); let mut lock = libc::PTHREAD_MUTEX_INITIALIZER; unsafe { init_lock(&mut lock, attr.as_mut_ptr()); } MutexInner { borrowed: false, lock: (false, lock, unsafe { attr.assume_init() }) } } #[cfg(not(feature = "pthread"))] fn default() -> Self { MutexInner { borrowed: false, lock: (false, 0) } } } impl MutexInner { fn acquire(&self) -> bool { if self.borrowed { false } else { as_mut(self).borrowed = true; true } } fn release(&self) { as_mut(self).borrowed = false; } } impl<T: ?Sized, A: MemPool> !TxOutSafe for Mutex<T, A> {} impl<T, A: MemPool> UnwindSafe for Mutex<T, A> {} impl<T, A: MemPool> RefUnwindSafe for Mutex<T, A> {} unsafe impl<T, A: MemPool> TxInSafe for Mutex<T, A> {} unsafe impl<T, A: MemPool> PSafe for Mutex<T, A> {} unsafe impl<T: Send, A: MemPool> Send for Mutex<T, A> {} unsafe impl<T: Send, A: MemPool> Sync for Mutex<T, A> {} impl<T, A: MemPool> Mutex<T, A> { /// Creates a new `Mutex` /// /// # Examples /// /// ``` /// # use corundum::alloc::*; /// use corundum::sync::{Parc,Mutex}; /// /// Heap::transaction(|j| { /// let p = Parc::new(Mutex::new(10, j), j); /// }).unwrap(); /// ``` pub fn new(data: T, _journal: &Journal<A>) -> Mutex<T, A> { Mutex { heap: PhantomData, inner: VCell::new(MutexInner::default()), data: UnsafeCell::new((0, data)), } } } impl<T: PSafe, A: MemPool> Mutex<T, A> { #[inline] #[allow(clippy::mut_from_ref)] /// Takes a log and returns a `&mut T` for interior mutability pub(crate) fn get_mut(&self, journal: &Journal<A>) -> &mut T { unsafe { let inner = &mut *self.data.get(); if inner.0 == 0 { inner.1.take_log(journal, Notifier::NonAtomic(Ptr::from_ref(&inner.0))); } &mut inner.1 } } #[inline] #[allow(clippy::mut_from_ref)] fn self_mut(&self) -> &mut Self { unsafe { let ptr: *const Self = self; &mut *(ptr as *mut Self) } } } impl<T, A: MemPool> Mutex<T, A> { #[inline] fn raw_lock(&self, journal: &Journal<A>) { unsafe { // Log::unlock_on_failure(self.inner.get(), journal); let lock = &self.inner.lock.1 as *const _ as *mut _; #[cfg(feature = "pthread")] { libc::pthread_mutex_lock(lock); } #[cfg(not(feature = "pthread"))] { let tid = std::thread::current().id().as_u64().get(); while intrinsics::atomic_cxchg_acqrel(lock, 0, tid).0 != tid {} } if self.inner.acquire() { Log::unlock_on_commit(&self.inner.lock as *const _ as u64, journal); } else { #[cfg(feature = "pthread")] libc::pthread_mutex_unlock(lock); #[cfg(not(feature = "pthread"))] intrinsics::atomic_store_rel(lock, 0); panic!("Cannot have multiple instances of MutexGuard"); } } } /// Acquires a mutex, blocking the current thread until it is able to do so. /// /// This function will block the local thread until it is available to /// acquire the mutex. Upon returning, the thread is the only thread with /// the lock held. An RAII guard is returned to keep track of borrowing /// data. It creates an [`UnlockOnCommit`] log to unlock the mutex when /// transaction is done. /// /// If the local thread already holds the lock, `lock()` does not block it. /// The mutex remains locked until the transaction is committed. /// Alternatively, [`PMutex`] can be used as a compact form of `Mutex`. /// /// # Examples /// /// ``` /// use corundum::default::*; /// use corundum::sync::{Parc,Mutex}; /// use std::thread; /// /// type P = BuddyAlloc; /// /// let obj = P::open::<Parc<Mutex<i32,P>,P>>("foo.pool", O_CF).unwrap(); /// /// // Using short forms in the pool module, there is no need to specify the /// // pool type, as follows: /// // let obj = P::open::<Parc<PMutex<i32>>>("foo.pool", O_CF).unwrap(); /// /// let obj = Parc::volatile(&obj); /// thread::spawn(move || { /// transaction(move |j| { /// if let Some(obj) = obj.upgrade(j) { /// *obj.lock(j) += 1; /// } /// }).unwrap(); /// }).join().expect("thread::spawn failed"); /// ``` /// /// [`PMutex`]: ../default/type.PMutex.html /// [`UnlockOnCommit`]: ../stm/enum.LogEnum.html#variant.UnlockOnCommit /// pub fn lock<'a>(&'a self, journal: &'a Journal<A>) -> MutexGuard<'a, T, A> { self.raw_lock(journal); unsafe { MutexGuard::new(self, journal) } } #[inline] fn raw_trylock(&self, journal: &Journal<A>) -> bool { unsafe { let lock = &self.inner.lock.1 as *const _ as *mut _; #[cfg(feature = "pthread")] let result = libc::pthread_mutex_trylock(lock) == 0; #[cfg(not(feature = "pthread"))] let result = { let tid = std::thread::current().id().as_u64().get(); intrinsics::atomic_cxchg_acqrel(lock, 0, tid).0 == tid }; if result { if self.inner.acquire() { Log::unlock_on_commit(&self.inner.lock as *const _ as u64, journal); true } else { #[cfg(feature = "pthread")] libc::pthread_mutex_unlock(lock); #[cfg(not(feature = "pthread"))] intrinsics::atomic_store_rel(lock, 0); panic!("Cannot have multiple instances of MutexGuard"); } } else { false } } } /// Attempts to acquire this lock. /// /// If the lock could not be acquired at this time, then [`Err`] is returned. /// Otherwise, an RAII guard is returned. The lock will be unlocked when the /// owner transaction ends. /// /// This function does not block. /// /// # Errors /// /// If another user of this mutex holds a guard, then this call will return /// failure if the mutex would otherwise be acquired. /// /// # Examples /// /// ``` /// use corundum::default::*; /// use std::thread; /// /// type P = BuddyAlloc; /// /// let obj = P::open::<Parc<PMutex<i32>>>("foo.pool", O_CF).unwrap(); /// /// let a = Parc::volatile(&obj); /// thread::spawn(move || { /// transaction(|j| { /// if let Some(obj) = a.upgrade(j) { /// let mut lock = obj.try_lock(j); /// if let Ok(ref mut mutex) = lock { /// **mutex = 10; /// } else { /// println!("try_lock failed"); /// } /// } /// }).unwrap(); /// }).join().expect("thread::spawn failed"); /// /// transaction(|j| { /// assert_eq!(*obj.lock(j), 10); /// }).unwrap(); /// ``` /// /// [`PMutex`]: ../default/type.PMutex.html pub fn try_lock<'a>(&'a self, journal: &'a Journal<A>) -> TryLockResult<MutexGuard<'a, T, A>> { if self.raw_trylock(journal) { unsafe { Ok(MutexGuard::new(self, journal)) } } else { Err(TryLockError::WouldBlock) } } } impl<T: RootObj<A>, A: MemPool> RootObj<A> for Mutex<T, A> { fn init(journal: &Journal<A>) -> Self { Mutex::new(T::init(journal), journal) } } impl<T: fmt::Debug, A: MemPool> fmt::Debug for Mutex<T, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.data.fmt(f) } } pub struct MutexGuard<'a, T: 'a, A: MemPool> { lock: &'a Mutex<T, A>, journal: *const Journal<A>, } impl<T: ?Sized, A: MemPool> !TxOutSafe for MutexGuard<'_, T, A> {} impl<T: ?Sized, A: MemPool> !Send for MutexGuard<'_, T, A> {} unsafe impl<T: Sync, A: MemPool> Sync for MutexGuard<'_, T, A> {} impl<T: fmt::Debug, A: MemPool> fmt::Debug for MutexGuard<'_, T, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } impl<T: fmt::Display, A: MemPool> fmt::Display for MutexGuard<'_, T, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { (**self).fmt(f) } } impl<'mutex, T, A: MemPool> MutexGuard<'mutex, T, A> { unsafe fn new( lock: &'mutex Mutex<T, A>, journal: &'mutex Journal<A>, ) -> MutexGuard<'mutex, T, A> { MutexGuard { lock, journal } } } impl<T, A: MemPool> Deref for MutexGuard<'_, T, A> { type Target = T; fn deref(&self) -> &T { unsafe { &(*self.lock.data.get()).1 } } } impl<T: PSafe, A: MemPool> DerefMut for MutexGuard<'_, T, A> { fn deref_mut(&mut self) -> &mut T { unsafe { self.lock.get_mut(&*self.journal) } } } impl<T, A: MemPool> Drop for MutexGuard<'_, T, A> { fn drop(&mut self) { self.lock.inner.release() } } #[cfg(feature = "pthread")] pub unsafe fn init_lock(mutex: *mut libc::pthread_mutex_t, attr: *mut libc::pthread_mutexattr_t) { *mutex = libc::PTHREAD_MUTEX_INITIALIZER; let result = libc::pthread_mutexattr_init(attr); debug_assert_eq!(result, 0); let result = libc::pthread_mutexattr_settype(attr, libc::PTHREAD_MUTEX_RECURSIVE); debug_assert_eq!(result, 0); let result = libc::pthread_mutex_init(mutex, attr); debug_assert_eq!(result, 0); let result = libc::pthread_mutexattr_destroy(attr); debug_assert_eq!(result, 0); }