]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/itron/condvar.rs
Rollup merge of #101445 - TaKO8Ki:suggest-introducing-explicit-lifetime, r=oli-obk
[rust.git] / library / std / src / sys / itron / condvar.rs
1 //! POSIX conditional variable implementation based on user-space wait queues.
2 use super::{abi, error::expect_success_aborting, spin::SpinMutex, task, time::with_tmos_strong};
3 use crate::{mem::replace, ptr::NonNull, sys::locks::Mutex, time::Duration};
4
5 // The implementation is inspired by the queue-based implementation shown in
6 // Andrew D. Birrell's paper "Implementing Condition Variables with Semaphores"
7
8 pub struct Condvar {
9     waiters: SpinMutex<waiter_queue::WaiterQueue>,
10 }
11
12 unsafe impl Send for Condvar {}
13 unsafe impl Sync for Condvar {}
14
15 pub type MovableCondvar = Condvar;
16
17 impl Condvar {
18     #[inline]
19     pub const fn new() -> Condvar {
20         Condvar { waiters: SpinMutex::new(waiter_queue::WaiterQueue::new()) }
21     }
22
23     #[inline]
24     pub unsafe fn init(&mut self) {}
25
26     pub unsafe fn notify_one(&self) {
27         self.waiters.with_locked(|waiters| {
28             if let Some(task) = waiters.pop_front() {
29                 // Unpark the task
30                 match unsafe { abi::wup_tsk(task) } {
31                     // The task already has a token.
32                     abi::E_QOVR => {}
33                     // Can't undo the effect; abort the program on failure
34                     er => {
35                         expect_success_aborting(er, &"wup_tsk");
36                     }
37                 }
38             }
39         });
40     }
41
42     pub unsafe fn notify_all(&self) {
43         self.waiters.with_locked(|waiters| {
44             while let Some(task) = waiters.pop_front() {
45                 // Unpark the task
46                 match unsafe { abi::wup_tsk(task) } {
47                     // The task already has a token.
48                     abi::E_QOVR => {}
49                     // Can't undo the effect; abort the program on failure
50                     er => {
51                         expect_success_aborting(er, &"wup_tsk");
52                     }
53                 }
54             }
55         });
56     }
57
58     pub unsafe fn wait(&self, mutex: &Mutex) {
59         // Construct `Waiter`.
60         let mut waiter = waiter_queue::Waiter::new();
61         let waiter = NonNull::from(&mut waiter);
62
63         self.waiters.with_locked(|waiters| unsafe {
64             waiters.insert(waiter);
65         });
66
67         unsafe { mutex.unlock() };
68
69         // Wait until `waiter` is removed from the queue
70         loop {
71             // Park the current task
72             expect_success_aborting(unsafe { abi::slp_tsk() }, &"slp_tsk");
73
74             if !self.waiters.with_locked(|waiters| unsafe { waiters.is_queued(waiter) }) {
75                 break;
76             }
77         }
78
79         unsafe { mutex.lock() };
80     }
81
82     pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
83         // Construct and pin `Waiter`
84         let mut waiter = waiter_queue::Waiter::new();
85         let waiter = NonNull::from(&mut waiter);
86
87         self.waiters.with_locked(|waiters| unsafe {
88             waiters.insert(waiter);
89         });
90
91         unsafe { mutex.unlock() };
92
93         // Park the current task and do not wake up until the timeout elapses
94         // or the task gets woken up by `notify_*`
95         match with_tmos_strong(dur, |tmo| {
96             let er = unsafe { abi::tslp_tsk(tmo) };
97             if er == 0 {
98                 // We were unparked. Are we really dequeued?
99                 if self.waiters.with_locked(|waiters| unsafe { waiters.is_queued(waiter) }) {
100                     // No we are not. Continue waiting.
101                     return abi::E_TMOUT;
102                 }
103             }
104             er
105         }) {
106             abi::E_TMOUT => {}
107             er => {
108                 expect_success_aborting(er, &"tslp_tsk");
109             }
110         }
111
112         // Remove `waiter` from `self.waiters`. If `waiter` is still in
113         // `waiters`, it means we woke up because of a timeout. Otherwise,
114         // we woke up because of `notify_*`.
115         let success = self.waiters.with_locked(|waiters| unsafe { !waiters.remove(waiter) });
116
117         unsafe { mutex.lock() };
118         success
119     }
120 }
121
122 mod waiter_queue {
123     use super::*;
124
125     pub struct WaiterQueue {
126         head: Option<ListHead>,
127     }
128
129     #[derive(Copy, Clone)]
130     struct ListHead {
131         first: NonNull<Waiter>,
132         last: NonNull<Waiter>,
133     }
134
135     unsafe impl Send for ListHead {}
136     unsafe impl Sync for ListHead {}
137
138     pub struct Waiter {
139         // These fields are only accessed through `&[mut] WaiterQueue`.
140         /// The waiting task's ID. Will be zeroed when the task is woken up
141         /// and removed from a queue.
142         task: abi::ID,
143         priority: abi::PRI,
144         prev: Option<NonNull<Waiter>>,
145         next: Option<NonNull<Waiter>>,
146     }
147
148     unsafe impl Send for Waiter {}
149     unsafe impl Sync for Waiter {}
150
151     impl Waiter {
152         #[inline]
153         pub fn new() -> Self {
154             let task = task::current_task_id();
155             let priority = task::task_priority(abi::TSK_SELF);
156
157             // Zeroness of `Waiter::task` indicates whether the `Waiter` is
158             // linked to a queue or not. This invariant is important for
159             // the correctness.
160             debug_assert_ne!(task, 0);
161
162             Self { task, priority, prev: None, next: None }
163         }
164     }
165
166     impl WaiterQueue {
167         #[inline]
168         pub const fn new() -> Self {
169             Self { head: None }
170         }
171
172         /// # Safety
173         ///
174         ///  - The caller must own `*waiter_ptr`. The caller will lose the
175         ///    ownership until `*waiter_ptr` is removed from `self`.
176         ///
177         ///  - `*waiter_ptr` must be valid until it's removed from the queue.
178         ///
179         ///  - `*waiter_ptr` must not have been previously inserted to a `WaiterQueue`.
180         ///
181         pub unsafe fn insert(&mut self, mut waiter_ptr: NonNull<Waiter>) {
182             unsafe {
183                 let waiter = waiter_ptr.as_mut();
184
185                 debug_assert!(waiter.prev.is_none());
186                 debug_assert!(waiter.next.is_none());
187
188                 if let Some(head) = &mut self.head {
189                     // Find the insertion position and insert `waiter`
190                     let insert_after = {
191                         let mut cursor = head.last;
192                         loop {
193                             if waiter.priority >= cursor.as_ref().priority {
194                                 // `cursor` and all previous waiters have the same or higher
195                                 // priority than `current_task_priority`. Insert the new
196                                 // waiter right after `cursor`.
197                                 break Some(cursor);
198                             }
199                             cursor = if let Some(prev) = cursor.as_ref().prev {
200                                 prev
201                             } else {
202                                 break None;
203                             };
204                         }
205                     };
206
207                     if let Some(mut insert_after) = insert_after {
208                         // Insert `waiter` after `insert_after`
209                         let insert_before = insert_after.as_ref().next;
210
211                         waiter.prev = Some(insert_after);
212                         insert_after.as_mut().next = Some(waiter_ptr);
213
214                         waiter.next = insert_before;
215                         if let Some(mut insert_before) = insert_before {
216                             insert_before.as_mut().prev = Some(waiter_ptr);
217                         } else {
218                             head.last = waiter_ptr;
219                         }
220                     } else {
221                         // Insert `waiter` to the front
222                         waiter.next = Some(head.first);
223                         head.first.as_mut().prev = Some(waiter_ptr);
224                         head.first = waiter_ptr;
225                     }
226                 } else {
227                     // `waiter` is the only element
228                     self.head = Some(ListHead { first: waiter_ptr, last: waiter_ptr });
229                 }
230             }
231         }
232
233         /// Given a `Waiter` that was previously inserted to `self`, remove
234         /// it from `self` if it's still there.
235         #[inline]
236         pub unsafe fn remove(&mut self, mut waiter_ptr: NonNull<Waiter>) -> bool {
237             unsafe {
238                 let waiter = waiter_ptr.as_mut();
239                 if waiter.task != 0 {
240                     let head = self.head.as_mut().unwrap();
241
242                     match (waiter.prev, waiter.next) {
243                         (Some(mut prev), Some(mut next)) => {
244                             prev.as_mut().next = Some(next);
245                             next.as_mut().prev = Some(prev);
246                         }
247                         (None, Some(mut next)) => {
248                             head.first = next;
249                             next.as_mut().prev = None;
250                         }
251                         (Some(mut prev), None) => {
252                             prev.as_mut().next = None;
253                             head.last = prev;
254                         }
255                         (None, None) => {
256                             self.head = None;
257                         }
258                     }
259
260                     waiter.task = 0;
261
262                     true
263                 } else {
264                     false
265                 }
266             }
267         }
268
269         /// Given a `Waiter` that was previously inserted to `self`, return a
270         /// flag indicating whether it's still in `self`.
271         #[inline]
272         pub unsafe fn is_queued(&self, waiter: NonNull<Waiter>) -> bool {
273             unsafe { waiter.as_ref().task != 0 }
274         }
275
276         #[inline]
277         pub fn pop_front(&mut self) -> Option<abi::ID> {
278             unsafe {
279                 let head = self.head.as_mut()?;
280                 let waiter = head.first.as_mut();
281
282                 // Get the ID
283                 let id = replace(&mut waiter.task, 0);
284
285                 // Unlink the waiter
286                 if let Some(mut next) = waiter.next {
287                     head.first = next;
288                     next.as_mut().prev = None;
289                 } else {
290                     self.head = None;
291                 }
292
293                 Some(id)
294             }
295         }
296     }
297 }