Debian Codegraph @

debian/missing-sources/parking_lot_core/src/thread_parker/sgx.rs

raw
1 // Copyright 2016 Amanieu d'Antras
2 //
3 // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4 // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5 // http://opensource.org/licenses/MIT>, at your option. This file may not be
6 // copied, modified, or distributed except according to those terms.
7
8 use core::sync::atomic::{AtomicBool, Ordering};
9 use std::io::ErrorKind;
10 use std::time::Instant;
11 use std::{
12 io,
13 os::fortanix_sgx::{
14 thread::current as current_tcs,
15 usercalls::{
16 self,
17 raw::{Tcs, EV_UNPARK, WAIT_INDEFINITE},
18 },
19 },
20 thread,
21 };
22
23 // Helper type for putting a thread to sleep until some other thread wakes it up
24 pub struct ThreadParker {
25 parked: AtomicBool,
26 tcs: Tcs,
27 }
28
29 impl super::ThreadParkerT for ThreadParker {
30 type UnparkHandle = UnparkHandle;
31
32 const IS_CHEAP_TO_CONSTRUCT: bool = true;
33
34 #[inline]
35 fn new() -> ThreadParker {
36 ThreadParker {
37 parked: AtomicBool::new(false),
38 tcs: current_tcs(),
39 }
40 }
41
42 #[inline]
43 unsafe fn prepare_park(&self) {
44 self.parked.store(true, Ordering::Relaxed);
45 }
46
47 #[inline]
48 unsafe fn timed_out(&self) -> bool {
49 self.parked.load(Ordering::Relaxed)
50 }
51
52 #[inline]
53 unsafe fn park(&self) {
54 while self.parked.load(Ordering::Acquire) {
55 let result = usercalls::wait(EV_UNPARK, WAIT_INDEFINITE);
56 debug_assert_eq!(result.expect("wait returned error") & EV_UNPARK, EV_UNPARK);
57 }
58 }
59
60 #[inline]
61 unsafe fn park_until(&self, timeout: Instant) -> bool {
62 while self.parked.load(Ordering::Acquire) {
63 let remaining = match timeout.checked_duration_since(Instant::now()) {
64 Some(remaining) => remaining,
65 None => {
66 return false;
67 }
68 };
69 let remaining_nanos = u128::min(remaining.as_nanos(), WAIT_INDEFINITE as u128 - 1) as u64;
70
71 if let Err(e) = usercalls::wait(EV_UNPARK, remaining_nanos) {
72 if e.kind() == ErrorKind::TimedOut || e.kind() == ErrorKind::WouldBlock {
73 return false;
74 }
75 }
76 }
77 true
78 }
79
80 #[inline]
81 unsafe fn unpark_lock(&self) -> UnparkHandle {
82 // We don't need to lock anything, just clear the state
83 self.parked.store(false, Ordering::Release);
84 UnparkHandle(self.tcs)
85 }
86 }
87
88 pub struct UnparkHandle(Tcs);
89
90 impl super::UnparkHandleT for UnparkHandle {
91 #[inline]
92 unsafe fn unpark(self) {
93 let result = usercalls::send(EV_UNPARK, Some(self.0));
94 if cfg!(debug_assertions) {
95 if let Err(error) = result {
96 // `InvalidInput` may be returned if the thread we send to has
97 // already been unparked and exited.
98 if error.kind() != io::ErrorKind::InvalidInput {
99 panic!("send returned an unexpected error: {:?}", error);
100 }
101 }
102 }
103 }
104 }
105
106 #[inline]
107 pub fn thread_yield() {
108 thread::yield_now();
109 }