1 /// A simple queue implementation for synchronization primitives.
3 /// This queue is used to implement condition variable and mutexes.
5 /// Users of this API are expected to use the `WaitVariable<T>` type. Since
6 /// that type is not `Sync`, it needs to be protected by e.g., a `SpinMutex` to
7 /// allow shared access.
9 /// Since userspace may send spurious wake-ups, the wakeup event state is
10 /// recorded in the enclave. The wakeup event state is protected by a spinlock.
11 /// The queue and associated wait state are stored in a `WaitVariable`.
13 use crate::ops::{Deref, DerefMut};
14 use crate::num::NonZeroUsize;
16 use fortanix_sgx_abi::{Tcs, EV_UNPARK, WAIT_INDEFINITE};
17 use super::abi::usercalls;
18 use super::abi::thread;
20 use self::unsafe_list::{UnsafeList, UnsafeListEntry};
21 pub use self::spin_mutex::{SpinMutex, SpinMutexGuard, try_lock_or_false};
23 /// An queue entry in a `WaitQueue`.
25 /// TCS address of the thread that is waiting
27 /// Whether this thread has been notified to be awoken
31 /// Data stored with a `WaitQueue` alongside it. This ensures accesses to the
32 /// queue and the data are synchronized, since the type itself is not `Sync`.
34 /// Consumers of this API should use a synchronization primitive for shared
35 /// access, such as `SpinMutex`.
37 pub struct WaitVariable<T> {
42 impl<T> WaitVariable<T> {
43 pub const fn new(var: T) -> Self {
45 queue: WaitQueue::new(),
50 pub fn queue_empty(&self) -> bool {
54 pub fn lock_var(&self) -> &T {
58 pub fn lock_var_mut(&mut self) -> &mut T {
63 #[derive(Copy, Clone)]
64 pub enum NotifiedTcs {
66 All { count: NonZeroUsize }
69 /// An RAII guard that will notify a set of target threads as well as unlock
71 pub struct WaitGuard<'a, T: 'a> {
72 mutex_guard: Option<SpinMutexGuard<'a, WaitVariable<T>>>,
73 notified_tcs: NotifiedTcs
76 /// A queue of threads that are waiting on some synchronization primitive.
78 /// `UnsafeList` entries are allocated on the waiting thread's stack. This
79 /// avoids any global locking that might happen in the heap allocator. This is
80 /// safe because the waiting thread will not return from that stack frame until
81 /// after it is notified. The notifying thread ensures to clean up any
82 /// references to the list entries before sending the wakeup event.
83 pub struct WaitQueue {
84 // We use an inner Mutex here to protect the data in the face of spurious
86 inner: UnsafeList<SpinMutex<WaitEntry>>,
88 unsafe impl Send for WaitQueue {}
90 impl Default for WaitQueue {
91 fn default() -> Self {
96 impl<'a, T> WaitGuard<'a, T> {
97 /// Returns which TCSes will be notified when this guard drops.
98 pub fn notified_tcs(&self) -> NotifiedTcs {
103 impl<'a, T> Deref for WaitGuard<'a, T> {
104 type Target = SpinMutexGuard<'a, WaitVariable<T>>;
106 fn deref(&self) -> &Self::Target {
107 self.mutex_guard.as_ref().unwrap()
111 impl<'a, T> DerefMut for WaitGuard<'a, T> {
112 fn deref_mut(&mut self) -> &mut Self::Target {
113 self.mutex_guard.as_mut().unwrap()
117 impl<'a, T> Drop for WaitGuard<'a, T> {
119 drop(self.mutex_guard.take());
120 let target_tcs = match self.notified_tcs {
121 NotifiedTcs::Single(tcs) => Some(tcs),
122 NotifiedTcs::All { .. } => None
124 rtunwrap!(Ok, usercalls::send(EV_UNPARK, target_tcs));
129 pub const fn new() -> Self {
131 inner: UnsafeList::new()
135 pub fn is_empty(&self) -> bool {
136 self.inner.is_empty()
139 /// Adds the calling thread to the `WaitVariable`'s wait queue, then wait
140 /// until a wakeup event.
142 /// This function does not return until this thread has been awoken.
143 pub fn wait<T>(mut guard: SpinMutexGuard<'_, WaitVariable<T>>) {
144 // very unsafe: check requirements of UnsafeList::push
146 let mut entry = UnsafeListEntry::new(SpinMutex::new(WaitEntry {
147 tcs: thread::current(),
150 let entry = guard.queue.inner.push(&mut entry);
152 while !entry.lock().wake {
153 // don't panic, this would invalidate `entry` during unwinding
154 let eventset = rtunwrap!(Ok, usercalls::wait(EV_UNPARK, WAIT_INDEFINITE));
155 rtassert!(eventset & EV_UNPARK == EV_UNPARK);
160 /// Either find the next waiter on the wait queue, or return the mutex
163 /// If a waiter is found, a `WaitGuard` is returned which will notify the
164 /// waiter when it is dropped.
165 pub fn notify_one<T>(mut guard: SpinMutexGuard<'_, WaitVariable<T>>)
166 -> Result<WaitGuard<'_, T>, SpinMutexGuard<'_, WaitVariable<T>>>
169 if let Some(entry) = guard.queue.inner.pop() {
170 let mut entry_guard = entry.lock();
171 let tcs = entry_guard.tcs;
172 entry_guard.wake = true;
175 mutex_guard: Some(guard),
176 notified_tcs: NotifiedTcs::Single(tcs)
184 /// Either find any and all waiters on the wait queue, or return the mutex
187 /// If at least one waiter is found, a `WaitGuard` is returned which will
188 /// notify all waiters when it is dropped.
189 pub fn notify_all<T>(mut guard: SpinMutexGuard<'_, WaitVariable<T>>)
190 -> Result<WaitGuard<'_, T>, SpinMutexGuard<'_, WaitVariable<T>>>
194 while let Some(entry) = guard.queue.inner.pop() {
196 let mut entry_guard = entry.lock();
197 entry_guard.wake = true;
199 if let Some(count) = NonZeroUsize::new(count) {
201 mutex_guard: Some(guard),
202 notified_tcs: NotifiedTcs::All { count }
211 /// A doubly-linked list where callers are in charge of memory allocation
212 /// of the nodes in the list.
214 use crate::ptr::NonNull;
217 pub struct UnsafeListEntry<T> {
218 next: NonNull<UnsafeListEntry<T>>,
219 prev: NonNull<UnsafeListEntry<T>>,
223 impl<T> UnsafeListEntry<T> {
226 next: NonNull::dangling(),
227 prev: NonNull::dangling(),
232 pub fn new(value: T) -> Self {
240 pub struct UnsafeList<T> {
241 head_tail: NonNull<UnsafeListEntry<T>>,
242 head_tail_entry: Option<UnsafeListEntry<T>>,
245 impl<T> UnsafeList<T> {
246 pub const fn new() -> Self {
249 head_tail: NonNull::new_unchecked(1 as _),
250 head_tail_entry: None
255 unsafe fn init(&mut self) {
256 if self.head_tail_entry.is_none() {
257 self.head_tail_entry = Some(UnsafeListEntry::dummy());
258 self.head_tail = NonNull::new_unchecked(self.head_tail_entry.as_mut().unwrap());
259 self.head_tail.as_mut().next = self.head_tail;
260 self.head_tail.as_mut().prev = self.head_tail;
264 pub fn is_empty(&self) -> bool {
266 if self.head_tail_entry.is_some() {
267 let first = self.head_tail.as_ref().next;
268 if first == self.head_tail {
269 // ,-------> /---------\ next ---,
271 // `--- prev \---------/ <-------`
272 rtassert!(self.head_tail.as_ref().prev == first);
283 /// Pushes an entry onto the back of the list.
287 /// The entry must remain allocated until the entry is removed from the
288 /// list AND the caller who popped is done using the entry. Special
289 /// care must be taken in the caller of `push` to ensure unwinding does
290 /// not destroy the stack frame containing the entry.
291 pub unsafe fn push<'a>(&mut self, entry: &'a mut UnsafeListEntry<T>) -> &'a T {
295 // /---------\ next ---> /---------\
296 // ... |prev_tail| |head_tail| ...
297 // \---------/ <--- prev \---------/
300 // /---------\ next ---> /-----\ next ---> /---------\
301 // ... |prev_tail| |entry| |head_tail| ...
302 // \---------/ <--- prev \-----/ <--- prev \---------/
303 let mut entry = NonNull::new_unchecked(entry);
304 let mut prev_tail = mem::replace(&mut self.head_tail.as_mut().prev, entry);
305 entry.as_mut().prev = prev_tail;
306 entry.as_mut().next = self.head_tail;
307 prev_tail.as_mut().next = entry;
308 // unwrap ok: always `Some` on non-dummy entries
309 (*entry.as_ptr()).value.as_ref().unwrap()
312 /// Pops an entry from the front of the list.
316 /// The caller must make sure to synchronize ending the borrow of the
317 /// return value and deallocation of the containing entry.
318 pub unsafe fn pop<'a>(&mut self) -> Option<&'a T> {
325 // /---------\ next ---> /-----\ next ---> /------\
326 // ... |head_tail| |first| |second| ...
327 // \---------/ <--- prev \-----/ <--- prev \------/
330 // /---------\ next ---> /------\
331 // ... |head_tail| |second| ...
332 // \---------/ <--- prev \------/
333 let mut first = self.head_tail.as_mut().next;
334 let mut second = first.as_mut().next;
335 self.head_tail.as_mut().next = second;
336 second.as_mut().prev = self.head_tail;
337 first.as_mut().next = NonNull::dangling();
338 first.as_mut().prev = NonNull::dangling();
339 // unwrap ok: always `Some` on non-dummy entries
340 Some((*first.as_ptr()).value.as_ref().unwrap())
348 use crate::cell::Cell;
350 unsafe fn assert_empty<T>(list: &mut UnsafeList<T>) {
351 assert!(list.pop().is_none(), "assertion failed: list is not empty");
357 assert_empty(&mut UnsafeList::<i32>::new());
364 let mut node = UnsafeListEntry::new(1234);
365 let mut list = UnsafeList::new();
366 assert_eq!(list.push(&mut node), &1234);
367 assert_eq!(list.pop().unwrap(), &1234);
368 assert_empty(&mut list);
373 fn complex_pushes_pops() {
375 let mut node1 = UnsafeListEntry::new(1234);
376 let mut node2 = UnsafeListEntry::new(4567);
377 let mut node3 = UnsafeListEntry::new(9999);
378 let mut node4 = UnsafeListEntry::new(8642);
379 let mut list = UnsafeList::new();
380 list.push(&mut node1);
381 list.push(&mut node2);
382 assert_eq!(list.pop().unwrap(), &1234);
383 list.push(&mut node3);
384 assert_eq!(list.pop().unwrap(), &4567);
385 assert_eq!(list.pop().unwrap(), &9999);
386 assert_empty(&mut list);
387 list.push(&mut node4);
388 assert_eq!(list.pop().unwrap(), &8642);
389 assert_empty(&mut list);
396 let mut node = UnsafeListEntry::new(Cell::new(0));
397 let mut list = UnsafeList::new();
398 let noderef = list.push(&mut node);
399 assert_eq!(noderef.get(), 0);
400 list.pop().unwrap().set(1);
401 assert_empty(&mut list);
402 assert_eq!(noderef.get(), 1);
408 /// Trivial spinlock-based implementation of `sync::Mutex`.
409 // FIXME: Perhaps use Intel TSX to avoid locking?
411 use crate::cell::UnsafeCell;
412 use crate::sync::atomic::{AtomicBool, Ordering, spin_loop_hint};
413 use crate::ops::{Deref, DerefMut};
416 pub struct SpinMutex<T> {
417 value: UnsafeCell<T>,
421 unsafe impl<T: Send> Send for SpinMutex<T> {}
422 unsafe impl<T: Send> Sync for SpinMutex<T> {}
424 pub struct SpinMutexGuard<'a, T: 'a> {
425 mutex: &'a SpinMutex<T>,
428 impl<'a, T> !Send for SpinMutexGuard<'a, T> {}
429 unsafe impl<'a, T: Sync> Sync for SpinMutexGuard<'a, T> {}
431 impl<T> SpinMutex<T> {
432 pub const fn new(value: T) -> Self {
434 value: UnsafeCell::new(value),
435 lock: AtomicBool::new(false)
440 pub fn lock(&self) -> SpinMutexGuard<'_, T> {
442 match self.try_lock() {
443 None => while self.lock.load(Ordering::Relaxed) {
446 Some(guard) => return guard
452 pub fn try_lock(&self) -> Option<SpinMutexGuard<'_, T>> {
453 if !self.lock.compare_and_swap(false, true, Ordering::Acquire) {
454 Some(SpinMutexGuard {
463 /// Lock the Mutex or return false.
464 pub macro try_lock_or_false {
466 if let Some(v) = $e.try_lock() {
474 impl<'a, T> Deref for SpinMutexGuard<'a, T> {
477 fn deref(&self) -> &T {
479 &*self.mutex.value.get()
484 impl<'a, T> DerefMut for SpinMutexGuard<'a, T> {
485 fn deref_mut(&mut self) -> &mut T {
487 &mut*self.mutex.value.get()
492 impl<'a, T> Drop for SpinMutexGuard<'a, T> {
494 self.mutex.lock.store(false, Ordering::Release)
500 #![allow(deprecated)]
503 use crate::sync::Arc;
505 use crate::time::{SystemTime, Duration};
509 let mutex = Arc::new(SpinMutex::<i32>::default());
510 let mutex2 = mutex.clone();
511 let guard = mutex.lock();
512 let t1 = thread::spawn(move || {
517 // FIXME: https://github.com/fortanix/rust-sgx/issues/31
518 let start = SystemTime::now();
519 let max = Duration::from_millis(50);
520 while start.elapsed().unwrap() < max {}
522 assert_eq!(*guard, 0);
525 assert_eq!(*mutex.lock(), 1);
533 use crate::sync::Arc;
538 let wq = Arc::new(SpinMutex::<WaitVariable<()>>::default());
539 let wq2 = wq.clone();
541 let locked = wq.lock();
543 let t1 = thread::spawn(move || {
544 // if we obtain the lock, the main thread should be waiting
545 assert!(WaitQueue::notify_one(wq2.lock()).is_ok());
548 WaitQueue::wait(locked);