[go: up one dir, main page]

saa 5.1.1

Word-sized low-level synchronization primitives providing both asynchronous and synchronous interfaces.
Documentation
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! [`Gate`] is a synchronization primitive that blocks tasks from entering a critical section until
//! they are allowed to do so.

#![deny(unsafe_code)]

use std::pin::{Pin, pin};
#[cfg(not(feature = "loom"))]
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::{self, AcqRel, Acquire, Relaxed};

#[cfg(feature = "loom")]
use loom::sync::atomic::AtomicUsize;

use crate::opcode::Opcode;
use crate::pager::SyncResult;
use crate::sync_primitive::SyncPrimitive;
use crate::wait_queue::{Entry, WaitQueue};
use crate::{Pager, pager};

/// [`Gate`] is a synchronization primitive that blocks tasks from entering a critical section until
/// they are allowed to do so.
#[derive(Debug, Default)]
pub struct Gate {
    /// [`Gate`] state.
    state: AtomicUsize,
}

/// The state of a [`Gate`].
///
/// [`Gate`] can be in one of three states.
///
/// * `Controlled` - The default state where tasks can enter the [`Gate`] if permitted.
/// * `Sealed` - The [`Gate`] is sealed and tasks immediately get rejected when they attempt to enter.
/// * `Open` - The [`Gate`] is open and tasks can immediately enter it.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
#[repr(u8)]
pub enum State {
    /// The default state where tasks can enter the [`Gate`] if permitted.
    Controlled = 0_u8,
    /// The [`Gate`] is sealed and tasks immediately get rejected when they attempt to enter it.
    Sealed = 1_u8,
    /// The [`Gate`] is open and tasks can immediately enter it.
    Open = 2_u8,
}

/// Errors that can occur when accessing a [`Gate`].
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
#[repr(u8)]
pub enum Error {
    /// The [`Gate`] rejected the task.
    Rejected = 4_u8,
    /// The [`Gate`] has been sealed.
    Sealed = 8_u8,
    /// Spurious failure to enter a [`Gate`] in a [`Controlled`](State::Controlled) state.
    ///
    /// This can happen if a task holding a [`Pager`] gets cancelled or drops the [`Pager`] before
    /// the [`Gate`] has permitted or rejected the task; the task causes all other waiting tasks
    /// of the [`Gate`] to get this error.
    SpuriousFailure = 12_u8,
    /// The [`Pager`] is not registered in any [`Gate`].
    NotRegistered = 16_u8,
    /// The wrong asynchronous/synchronous mode was used for a [`Pager`].
    WrongMode = 20_u8,
    /// The result is not ready.
    NotReady = 24_u8,
}

impl Gate {
    /// Mask to get the state value from `u8`.
    const STATE_MASK: u8 = 0b11;

    /// Returns the current state of the [`Gate`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::Ordering::Relaxed;
    ///
    /// use saa::Gate;
    /// use saa::gate::State;
    ///
    /// let gate = Gate::default();
    ///
    /// assert_eq!(gate.state(Relaxed), State::Controlled);
    /// ```
    #[inline]
    pub fn state(&self, mo: Ordering) -> State {
        State::from(self.state.load(mo) & WaitQueue::DATA_MASK)
    }

    /// Resets the [`Gate`] to its initial state if it is not in a [`Controlled`](State::Controlled)
    /// state.
    ///
    /// Returns the previous state of the [`Gate`].
    ///
    /// # Examples
    ///
    /// ```
    /// use saa::Gate;
    /// use saa::gate::State;
    ///
    /// let gate = Gate::default();
    ///
    /// assert_eq!(gate.reset(), None);
    ///
    /// gate.seal();
    ///
    /// assert_eq!(gate.reset(), Some(State::Sealed));
    /// ```
    #[inline]
    pub fn reset(&self) -> Option<State> {
        match self.state.fetch_update(Relaxed, Relaxed, |value| {
            let state = State::from(value & WaitQueue::DATA_MASK);
            if state == State::Controlled {
                None
            } else {
                debug_assert_eq!(value & WaitQueue::ADDR_MASK, 0);
                Some((value & WaitQueue::ADDR_MASK) | u8::from(state) as usize)
            }
        }) {
            Ok(state) => Some(State::from(state & WaitQueue::DATA_MASK)),
            Err(_) => None,
        }
    }

    /// Permits waiting tasks to enter the [`Gate`] if the [`Gate`] is in a
    /// [`Controlled`](State::Controlled) state.
    ///
    /// Returns the number of permitted tasks.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if the [`Gate`] is not in a [`Controlled`](State::Controlled) state.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::thread;
    ///
    /// use saa::Gate;
    /// use saa::gate::State;
    ///
    /// let gate = Arc::new(Gate::default());
    ///
    /// let gate_clone = gate.clone();
    ///
    /// let thread = thread::spawn(move || {
    ///     assert_eq!(gate_clone.enter_sync(), Ok(State::Controlled));
    /// });
    ///
    /// loop {
    ///     if gate.permit() == Ok(1) {
    ///         break;
    ///     }
    /// }
    ///
    /// thread.join().unwrap();
    /// ```
    #[inline]
    pub fn permit(&self) -> Result<usize, State> {
        let (state, count) = self.wake_all(None, None);
        if state == State::Controlled {
            Ok(count)
        } else {
            debug_assert_eq!(count, 0);
            Err(state)
        }
    }

    /// Rejects waiting tasks from entering the [`Gate`] if the [`Gate`] is in a
    /// [`Controlled`](State::Controlled) state.
    ///
    /// Returns the number of rejected tasks.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if the [`Gate`] is not in a [`Controlled`](State::Controlled) state.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::thread;
    ///
    /// use saa::Gate;
    /// use saa::gate::Error;
    ///
    /// let gate = Arc::new(Gate::default());
    ///
    /// let gate_clone = gate.clone();
    ///
    /// let thread = thread::spawn(move || {
    ///     assert_eq!(gate_clone.enter_sync(), Err(Error::Rejected));
    /// });
    ///
    /// loop {
    ///     if gate.reject() == Ok(1) {
    ///         break;
    ///     }
    /// }
    ///
    /// thread.join().unwrap();
    /// ```
    #[inline]
    pub fn reject(&self) -> Result<usize, State> {
        let (state, count) = self.wake_all(None, Some(Error::Rejected));
        if state == State::Controlled {
            Ok(count)
        } else {
            debug_assert_eq!(count, 0);
            Err(state)
        }
    }

    /// Opens the [`Gate`] to allow any tasks to enter it.
    ///
    /// Returns the number of tasks that were waiting to enter it.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::Ordering::Relaxed;
    ///
    /// use saa::Gate;
    /// use saa::gate::State;
    ///
    /// let gate = Gate::default();
    /// assert_eq!(gate.state(Relaxed), State::Controlled);
    ///
    /// let (prev_state, count) = gate.open();
    ///
    /// assert_eq!(prev_state, State::Controlled);
    /// assert_eq!(count, 0);
    /// assert_eq!(gate.state(Relaxed), State::Open);
    /// ```
    #[inline]
    pub fn open(&self) -> (State, usize) {
        self.wake_all(Some(State::Open), None)
    }

    /// Seals the [`Gate`] to disallow tasks from entering.
    ///
    /// Returns the previous state of the [`Gate`] and the number of tasks that were waiting to
    /// enter the Gate.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::Ordering::Relaxed;
    ///
    /// use saa::Gate;
    /// use saa::gate::State;
    ///
    /// let gate = Gate::default();
    ///
    /// let (prev_state, count) = gate.seal();
    ///
    /// assert_eq!(prev_state, State::Controlled);
    /// assert_eq!(count, 0);
    /// assert_eq!(gate.state(Relaxed), State::Sealed);
    /// ```
    #[inline]
    pub fn seal(&self) -> (State, usize) {
        self.wake_all(Some(State::Sealed), Some(Error::Sealed))
    }

    /// Enters the [`Gate`] asynchronously.
    ///
    /// Returns the current state of the [`Gate`].
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if it failed to enter the [`Gate`].
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::future;
    /// use saa::Gate;
    ///
    /// let gate = Gate::default();
    ///
    /// let a = async {
    ///     assert!(gate.enter_async().await.is_ok());
    /// };
    /// let b = async {
    ///     gate.permit();
    /// };
    /// future::join(a, b);
    /// ```
    #[inline]
    pub async fn enter_async(&self) -> Result<State, Error> {
        let mut pinned_pager = pin!(Pager::default());
        pinned_pager
            .wait_queue()
            .construct(self, Opcode::Wait(0), false);
        self.push_wait_queue_entry(&mut pinned_pager, || {});
        pinned_pager.poll_async().await
    }

    /// Enters the [`Gate`] asynchronously with a wait callback.
    ///
    /// Returns the current state of the [`Gate`]. The callback is invoked when the task starts
    /// waiting.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if it failed to enter the [`Gate`].
    ///
    /// # Examples
    ///
    /// ```
    /// use futures::future;
    /// use saa::Gate;
    ///
    /// let gate = Gate::default();
    ///
    /// let a = async {
    ///     let mut wait = false;
    ///     assert!(gate.enter_async_with(|| wait = true).await.is_ok());
    /// };
    /// let b = async {
    ///    gate.permit();
    /// };
    /// future::join(a, b);
    /// ```
    #[inline]
    pub async fn enter_async_with<F: FnOnce()>(&self, begin_wait: F) -> Result<State, Error> {
        let mut pinned_pager = pin!(Pager::default());
        pinned_pager
            .wait_queue()
            .construct(self, Opcode::Wait(0), false);
        self.push_wait_queue_entry(&mut pinned_pager, begin_wait);
        pinned_pager.poll_async().await
    }

    /// Enters the [`Gate`] synchronously.
    ///
    /// Returns the current state of the [`Gate`].
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if it failed to enter the [`Gate`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::thread;
    ///
    /// use saa::Gate;
    /// use saa::gate::State;
    ///
    /// let gate = Arc::new(Gate::default());
    ///
    /// let gate_clone = gate.clone();
    /// let thread_1 = thread::spawn(move || {
    ///     assert_eq!(gate_clone.enter_sync(), Ok(State::Controlled));
    /// });
    ///
    /// let gate_clone = gate.clone();
    /// let thread_2 = thread::spawn(move || {
    ///     assert_eq!(gate_clone.enter_sync(), Ok(State::Controlled));
    /// });
    ///
    /// let mut count = 0;
    /// while count != 2 {
    ///     if let Ok(n) = gate.permit() {
    ///         count += n;
    ///     }
    /// }
    ///
    /// thread_1.join().unwrap();
    /// thread_2.join().unwrap();
    /// ```
    #[inline]
    pub fn enter_sync(&self) -> Result<State, Error> {
        self.enter_sync_with(|| ())
    }

    /// Enters the [`Gate`] synchronously with a wait callback.
    ///
    /// Returns the current state of the [`Gate`]. The callback is invoked when the task starts
    /// waiting.
    /// # Errors
    ///
    /// Returns an [`Error`] if it failed to enter the [`Gate`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    /// use std::thread;
    ///
    /// use saa::Gate;
    /// use saa::gate::State;
    ///
    /// let gate = Arc::new(Gate::default());
    ///
    /// let gate_clone = gate.clone();
    /// let thread_1 = thread::spawn(move || {
    ///     let mut wait = false;
    ///     assert_eq!(gate_clone.enter_sync_with(|| wait = true), Ok(State::Controlled));
    /// });
    ///
    /// let gate_clone = gate.clone();
    /// let thread_2 = thread::spawn(move || {
    ///     let mut wait = false;
    ///     assert_eq!(gate_clone.enter_sync_with(|| wait = true), Ok(State::Controlled));
    /// });
    ///
    /// let mut count = 0;
    /// while count != 2 {
    ///     if let Ok(n) = gate.permit() {
    ///         count += n;
    ///     }
    /// }
    ///
    /// thread_1.join().unwrap();
    /// thread_2.join().unwrap();
    /// ```
    #[inline]
    pub fn enter_sync_with<F: FnOnce()>(&self, begin_wait: F) -> Result<State, Error> {
        let mut pinned_pager = pin!(Pager::default());
        pinned_pager
            .wait_queue()
            .construct(self, Opcode::Wait(0), true);
        self.push_wait_queue_entry(&mut pinned_pager, begin_wait);
        pinned_pager.poll_sync()
    }

    /// Registers a [`Pager`] to allow it to get a permit to enter the [`Gate`] remotely.
    ///
    /// `is_sync` indicates whether the [`Pager`] will be polled asynchronously (`false`) or
    /// synchronously (`true`).
    ///
    /// Returns `false` if the [`Pager`] was already registered.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::pin::pin;
    /// use std::sync::Arc;
    /// use std::thread;
    ///
    /// use saa::{Gate, Pager};
    /// use saa::gate::State;
    ///
    /// let gate = Arc::new(Gate::default());
    ///
    /// let mut pinned_pager = pin!(Pager::default());
    ///
    /// assert!(gate.register_pager(&mut pinned_pager, true));
    /// assert!(!gate.register_pager(&mut pinned_pager, true));
    ///
    /// let gate_clone = gate.clone();
    /// let thread = thread::spawn(move || {
    ///     assert_eq!(gate_clone.permit(), Ok(1));
    /// });
    ///
    /// thread.join().unwrap();
    ///
    /// assert_eq!(pinned_pager.poll_sync(), Ok(State::Controlled));
    /// ```
    #[inline]
    pub fn register_pager<'g>(
        &'g self,
        pager: &mut Pin<&mut Pager<'g, Self>>,
        is_sync: bool,
    ) -> bool {
        if pager.is_registered() {
            return false;
        }
        pager.wait_queue().construct(self, Opcode::Wait(0), is_sync);
        self.push_wait_queue_entry(pager, || ());
        true
    }

    /// Wakes up all waiting tasks and updates the state.
    ///
    /// Returns `(prev_state, count)` where `prev_state` is the previous state of the Gate and
    /// `count` is the number of tasks that were woken up.
    fn wake_all(&self, next_state: Option<State>, error: Option<Error>) -> (State, usize) {
        match self.state.fetch_update(AcqRel, Acquire, |value| {
            if let Some(new_value) = next_state {
                Some(u8::from(new_value) as usize)
            } else {
                Some(value & WaitQueue::DATA_MASK)
            }
        }) {
            Ok(value) | Err(value) => {
                let mut count = 0;
                let prev_state = State::from(value & WaitQueue::DATA_MASK);
                let next_state = next_state.unwrap_or(prev_state);
                let result = Self::into_u8(next_state, error);
                let anchor_ptr = WaitQueue::to_anchor_ptr(value);
                if !anchor_ptr.is_null() {
                    let tail_entry_ptr = WaitQueue::to_entry_ptr(anchor_ptr);
                    Entry::iter_forward(tail_entry_ptr, false, |entry, _| {
                        entry.set_result(result);
                        count += 1;
                        false
                    });
                }
                (prev_state, count)
            }
        }
    }

    /// Pushes the wait queue entry.
    #[inline]
    fn push_wait_queue_entry<F: FnOnce()>(
        &self,
        pager: &mut Pin<&mut Pager<Self>>,
        mut begin_wait: F,
    ) {
        loop {
            let state = self.state.load(Acquire);
            match State::from(state & WaitQueue::DATA_MASK) {
                State::Controlled => {
                    if let Some(returned) =
                        self.try_push_wait_queue_entry(pager.wait_queue(), state, begin_wait)
                    {
                        begin_wait = returned;
                        continue;
                    }
                }
                State::Sealed => {
                    pager
                        .wait_queue()
                        .entry()
                        .set_result(Self::into_u8(State::Sealed, Some(Error::Sealed)));
                }
                State::Open => {
                    pager
                        .wait_queue()
                        .entry()
                        .set_result(Self::into_u8(State::Open, None));
                }
            }
            break;
        }
    }

    /// Converts `(State, Error)` into `u8`.
    #[inline]
    fn into_u8(state: State, error: Option<Error>) -> u8 {
        u8::from(state) | error.map_or(0_u8, u8::from)
    }
}

impl Drop for Gate {
    #[inline]
    fn drop(&mut self) {
        if self.state.load(Relaxed) & WaitQueue::ADDR_MASK == 0 {
            return;
        }
        self.seal();
    }
}

impl SyncPrimitive for Gate {
    #[inline]
    fn state(&self) -> &AtomicUsize {
        &self.state
    }

    #[inline]
    fn max_shared_owners() -> usize {
        usize::MAX
    }

    #[inline]
    fn drop_wait_queue_entry(entry: &Entry) {
        if entry.try_consume_result().is_none() {
            let this: &Self = entry.sync_primitive_ref();
            this.wake_all(None, Some(Error::SpuriousFailure));
            entry.acknowledge_result_sync();
        }
    }
}

impl SyncResult for Gate {
    type Result = Result<State, Error>;

    #[inline]
    fn to_result(value: u8, pager_error: Option<pager::Error>) -> Self::Result {
        if let Some(pager_error) = pager_error {
            match pager_error {
                pager::Error::NotRegistered => Err(Error::NotRegistered),
                pager::Error::WrongMode => Err(Error::WrongMode),
                pager::Error::NotReady => Err(Error::NotReady),
            }
        } else {
            let state = State::from(value & Self::STATE_MASK);
            let error = value & !(Self::STATE_MASK);
            if error != 0 {
                Err(Error::from(error))
            } else {
                Ok(state)
            }
        }
    }
}

impl From<State> for u8 {
    #[inline]
    fn from(value: State) -> Self {
        match value {
            State::Controlled => 0_u8,
            State::Sealed => 1_u8,
            State::Open => 2_u8,
        }
    }
}

impl From<u8> for State {
    #[inline]
    fn from(value: u8) -> Self {
        State::from(value as usize)
    }
}

impl From<usize> for State {
    #[inline]
    fn from(value: usize) -> Self {
        match value {
            0 => State::Controlled,
            1 => State::Sealed,
            _ => State::Open,
        }
    }
}

impl From<Error> for u8 {
    #[inline]
    fn from(value: Error) -> Self {
        match value {
            Error::Rejected => 4_u8,
            Error::Sealed => 8_u8,
            Error::SpuriousFailure => 12_u8,
            Error::NotRegistered => 16_u8,
            Error::WrongMode => 20_u8,
            Error::NotReady => 24_u8,
        }
    }
}

impl From<u8> for Error {
    #[inline]
    fn from(value: u8) -> Self {
        Error::from(value as usize)
    }
}

impl From<usize> for Error {
    #[inline]
    fn from(value: usize) -> Self {
        match value {
            4 => Error::Rejected,
            8 => Error::Sealed,
            12 => Error::SpuriousFailure,
            16 => Error::NotRegistered,
            20 => Error::WrongMode,
            _ => Error::NotReady,
        }
    }
}