]> git.lizzy.rs Git - rust.git/blob - src/sync.rs
Fully support FUTEX_*_BITSET.
[rust.git] / src / sync.rs
1 use std::collections::{hash_map::Entry, HashMap, VecDeque};
2 use std::convert::TryFrom;
3 use std::num::NonZeroU32;
4 use std::ops::Not;
5
6 use log::trace;
7
8 use rustc_index::vec::{Idx, IndexVec};
9
10 use crate::*;
11
12 /// We cannot use the `newtype_index!` macro because we have to use 0 as a
13 /// sentinel value meaning that the identifier is not assigned. This is because
14 /// the pthreads static initializers initialize memory with zeros (see the
15 /// `src/shims/sync.rs` file).
16 macro_rules! declare_id {
17     ($name: ident) => {
18         /// 0 is used to indicate that the id was not yet assigned and,
19         /// therefore, is not a valid identifier.
20         #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
21         pub struct $name(NonZeroU32);
22
23         impl $name {
24             // Panics if `id == 0`.
25             pub fn from_u32(id: u32) -> Self {
26                 Self(NonZeroU32::new(id).unwrap())
27             }
28         }
29
30         impl Idx for $name {
31             fn new(idx: usize) -> Self {
32                 // We use 0 as a sentinel value (see the comment above) and,
33                 // therefore, need to shift by one when converting from an index
34                 // into a vector.
35                 let shifted_idx = u32::try_from(idx).unwrap().checked_add(1).unwrap();
36                 $name(NonZeroU32::new(shifted_idx).unwrap())
37             }
38             fn index(self) -> usize {
39                 // See the comment in `Self::new`.
40                 // (This cannot underflow because self is NonZeroU32.)
41                 usize::try_from(self.0.get() - 1).unwrap()
42             }
43         }
44
45         impl $name {
46             pub fn to_u32_scalar<'tcx>(&self) -> Scalar<Tag> {
47                 Scalar::from_u32(self.0.get())
48             }
49         }
50     };
51 }
52
53 declare_id!(MutexId);
54
55 /// The mutex state.
56 #[derive(Default, Debug)]
57 struct Mutex {
58     /// The thread that currently owns the lock.
59     owner: Option<ThreadId>,
60     /// How many times the mutex was locked by the owner.
61     lock_count: usize,
62     /// The queue of threads waiting for this mutex.
63     queue: VecDeque<ThreadId>,
64     /// Data race handle, this tracks the happens-before
65     /// relationship between each mutex access. It is
66     /// released to during unlock and acquired from during
67     /// locking, and therefore stores the clock of the last
68     /// thread to release this mutex.
69     data_race: VClock,
70 }
71
72 declare_id!(RwLockId);
73
74 /// The read-write lock state.
75 #[derive(Default, Debug)]
76 struct RwLock {
77     /// The writer thread that currently owns the lock.
78     writer: Option<ThreadId>,
79     /// The readers that currently own the lock and how many times they acquired
80     /// the lock.
81     readers: HashMap<ThreadId, usize>,
82     /// The queue of writer threads waiting for this lock.
83     writer_queue: VecDeque<ThreadId>,
84     /// The queue of reader threads waiting for this lock.
85     reader_queue: VecDeque<ThreadId>,
86     /// Data race handle for writers, tracks the happens-before
87     /// ordering between each write access to a rwlock and is updated
88     /// after a sequence of concurrent readers to track the happens-
89     /// before ordering between the set of previous readers and
90     /// the current writer.
91     /// Contains the clock of the last thread to release a writer
92     /// lock or the joined clock of the set of last threads to release
93     /// shared reader locks.
94     data_race: VClock,
95     /// Data race handle for readers, this is temporary storage
96     /// for the combined happens-before ordering for between all
97     /// concurrent readers and the next writer, and the value
98     /// is stored to the main data_race variable once all
99     /// readers are finished.
100     /// Has to be stored separately since reader lock acquires
101     /// must load the clock of the last write and must not
102     /// add happens-before orderings between shared reader
103     /// locks.
104     data_race_reader: VClock,
105 }
106
107 declare_id!(CondvarId);
108
109 /// A thread waiting on a conditional variable.
110 #[derive(Debug)]
111 struct CondvarWaiter {
112     /// The thread that is waiting on this variable.
113     thread: ThreadId,
114     /// The mutex on which the thread is waiting.
115     mutex: MutexId,
116 }
117
118 /// The conditional variable state.
119 #[derive(Default, Debug)]
120 struct Condvar {
121     waiters: VecDeque<CondvarWaiter>,
122     /// Tracks the happens-before relationship
123     /// between a cond-var signal and a cond-var
124     /// wait during a non-suprious signal event.
125     /// Contains the clock of the last thread to
126     /// perform a futex-signal.
127     data_race: VClock,
128 }
129
130 /// The futex state.
131 #[derive(Default, Debug)]
132 struct Futex {
133     waiters: VecDeque<FutexWaiter>,
134     /// Tracks the happens-before relationship
135     /// between a futex-wake and a futex-wait
136     /// during a non-spurious wake event.
137     /// Contains the clock of the last thread to
138     /// perform a futex-wake.
139     data_race: VClock,
140 }
141
142 /// A thread waiting on a futex.
143 #[derive(Debug)]
144 struct FutexWaiter {
145     /// The thread that is waiting on this futex.
146     thread: ThreadId,
147     /// The bitset used by FUTEX_*_BITSET, or u32::MAX for other operations.
148     bitset: u32,
149 }
150
151 /// The state of all synchronization variables.
152 #[derive(Default, Debug)]
153 pub(super) struct SynchronizationState {
154     mutexes: IndexVec<MutexId, Mutex>,
155     rwlocks: IndexVec<RwLockId, RwLock>,
156     condvars: IndexVec<CondvarId, Condvar>,
157     futexes: HashMap<u64, Futex>,
158 }
159
160 // Private extension trait for local helper methods
161 impl<'mir, 'tcx: 'mir> EvalContextExtPriv<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
162 trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
163     /// Take a reader out of the queue waiting for the lock.
164     /// Returns `true` if some thread got the rwlock.
165     #[inline]
166     fn rwlock_dequeue_and_lock_reader(&mut self, id: RwLockId) -> bool {
167         let this = self.eval_context_mut();
168         if let Some(reader) = this.machine.threads.sync.rwlocks[id].reader_queue.pop_front() {
169             this.unblock_thread(reader);
170             this.rwlock_reader_lock(id, reader);
171             true
172         } else {
173             false
174         }
175     }
176
177     /// Take the writer out of the queue waiting for the lock.
178     /// Returns `true` if some thread got the rwlock.
179     #[inline]
180     fn rwlock_dequeue_and_lock_writer(&mut self, id: RwLockId) -> bool {
181         let this = self.eval_context_mut();
182         if let Some(writer) = this.machine.threads.sync.rwlocks[id].writer_queue.pop_front() {
183             this.unblock_thread(writer);
184             this.rwlock_writer_lock(id, writer);
185             true
186         } else {
187             false
188         }
189     }
190
191     /// Take a thread out of the queue waiting for the mutex, and lock
192     /// the mutex for it. Returns `true` if some thread has the mutex now.
193     #[inline]
194     fn mutex_dequeue_and_lock(&mut self, id: MutexId) -> bool {
195         let this = self.eval_context_mut();
196         if let Some(thread) = this.machine.threads.sync.mutexes[id].queue.pop_front() {
197             this.unblock_thread(thread);
198             this.mutex_lock(id, thread);
199             true
200         } else {
201             false
202         }
203     }
204 }
205
206 // Public interface to synchronization primitives. Please note that in most
207 // cases, the function calls are infallible and it is the client's (shim
208 // implementation's) responsibility to detect and deal with erroneous
209 // situations.
210 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
211 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
212     #[inline]
213     /// Create state for a new mutex.
214     fn mutex_create(&mut self) -> MutexId {
215         let this = self.eval_context_mut();
216         this.machine.threads.sync.mutexes.push(Default::default())
217     }
218
219     #[inline]
220     /// Get the id of the thread that currently owns this lock.
221     fn mutex_get_owner(&mut self, id: MutexId) -> ThreadId {
222         let this = self.eval_context_ref();
223         this.machine.threads.sync.mutexes[id].owner.unwrap()
224     }
225
226     #[inline]
227     /// Check if locked.
228     fn mutex_is_locked(&self, id: MutexId) -> bool {
229         let this = self.eval_context_ref();
230         this.machine.threads.sync.mutexes[id].owner.is_some()
231     }
232
233     /// Lock by setting the mutex owner and increasing the lock count.
234     fn mutex_lock(&mut self, id: MutexId, thread: ThreadId) {
235         let this = self.eval_context_mut();
236         let mutex = &mut this.machine.threads.sync.mutexes[id];
237         if let Some(current_owner) = mutex.owner {
238             assert_eq!(thread, current_owner, "mutex already locked by another thread");
239             assert!(
240                 mutex.lock_count > 0,
241                 "invariant violation: lock_count == 0 iff the thread is unlocked"
242             );
243         } else {
244             mutex.owner = Some(thread);
245         }
246         mutex.lock_count = mutex.lock_count.checked_add(1).unwrap();
247         if let Some(data_race) = &this.machine.data_race {
248             data_race.validate_lock_acquire(&mutex.data_race, thread);
249         }
250     }
251
252     /// Try unlocking by decreasing the lock count and returning the old lock
253     /// count. If the lock count reaches 0, release the lock and potentially
254     /// give to a new owner. If the lock was not locked by `expected_owner`,
255     /// return `None`.
256     fn mutex_unlock(&mut self, id: MutexId, expected_owner: ThreadId) -> Option<usize> {
257         let this = self.eval_context_mut();
258         let mutex = &mut this.machine.threads.sync.mutexes[id];
259         if let Some(current_owner) = mutex.owner {
260             // Mutex is locked.
261             if current_owner != expected_owner {
262                 // Only the owner can unlock the mutex.
263                 return None;
264             }
265             let old_lock_count = mutex.lock_count;
266             mutex.lock_count = old_lock_count
267                 .checked_sub(1)
268                 .expect("invariant violation: lock_count == 0 iff the thread is unlocked");
269             if mutex.lock_count == 0 {
270                 mutex.owner = None;
271                 // The mutex is completely unlocked. Try transfering ownership
272                 // to another thread.
273                 if let Some(data_race) = &this.machine.data_race {
274                     data_race.validate_lock_release(&mut mutex.data_race, current_owner);
275                 }
276                 this.mutex_dequeue_and_lock(id);
277             }
278             Some(old_lock_count)
279         } else {
280             // Mutex is not locked.
281             None
282         }
283     }
284
285     #[inline]
286     /// Put the thread into the queue waiting for the mutex.
287     fn mutex_enqueue_and_block(&mut self, id: MutexId, thread: ThreadId) {
288         let this = self.eval_context_mut();
289         assert!(this.mutex_is_locked(id), "queing on unlocked mutex");
290         this.machine.threads.sync.mutexes[id].queue.push_back(thread);
291         this.block_thread(thread);
292     }
293
294     #[inline]
295     /// Create state for a new read write lock.
296     fn rwlock_create(&mut self) -> RwLockId {
297         let this = self.eval_context_mut();
298         this.machine.threads.sync.rwlocks.push(Default::default())
299     }
300
301     #[inline]
302     /// Check if locked.
303     fn rwlock_is_locked(&self, id: RwLockId) -> bool {
304         let this = self.eval_context_ref();
305         let rwlock = &this.machine.threads.sync.rwlocks[id];
306         trace!(
307             "rwlock_is_locked: {:?} writer is {:?} and there are {} reader threads (some of which could hold multiple read locks)",
308             id,
309             rwlock.writer,
310             rwlock.readers.len(),
311         );
312         rwlock.writer.is_some() || rwlock.readers.is_empty().not()
313     }
314
315     #[inline]
316     /// Check if write locked.
317     fn rwlock_is_write_locked(&self, id: RwLockId) -> bool {
318         let this = self.eval_context_ref();
319         let rwlock = &this.machine.threads.sync.rwlocks[id];
320         trace!("rwlock_is_write_locked: {:?} writer is {:?}", id, rwlock.writer);
321         rwlock.writer.is_some()
322     }
323
324     /// Read-lock the lock by adding the `reader` the list of threads that own
325     /// this lock.
326     fn rwlock_reader_lock(&mut self, id: RwLockId, reader: ThreadId) {
327         let this = self.eval_context_mut();
328         assert!(!this.rwlock_is_write_locked(id), "the lock is write locked");
329         trace!("rwlock_reader_lock: {:?} now also held (one more time) by {:?}", id, reader);
330         let rwlock = &mut this.machine.threads.sync.rwlocks[id];
331         let count = rwlock.readers.entry(reader).or_insert(0);
332         *count = count.checked_add(1).expect("the reader counter overflowed");
333         if let Some(data_race) = &this.machine.data_race {
334             data_race.validate_lock_acquire(&rwlock.data_race, reader);
335         }
336     }
337
338     /// Try read-unlock the lock for `reader` and potentially give the lock to a new owner.
339     /// Returns `true` if succeeded, `false` if this `reader` did not hold the lock.
340     fn rwlock_reader_unlock(&mut self, id: RwLockId, reader: ThreadId) -> bool {
341         let this = self.eval_context_mut();
342         let rwlock = &mut this.machine.threads.sync.rwlocks[id];
343         match rwlock.readers.entry(reader) {
344             Entry::Occupied(mut entry) => {
345                 let count = entry.get_mut();
346                 assert!(*count > 0, "rwlock locked with count == 0");
347                 *count -= 1;
348                 if *count == 0 {
349                     trace!("rwlock_reader_unlock: {:?} no longer held by {:?}", id, reader);
350                     entry.remove();
351                 } else {
352                     trace!("rwlock_reader_unlock: {:?} held one less time by {:?}", id, reader);
353                 }
354             }
355             Entry::Vacant(_) => return false, // we did not even own this lock
356         }
357         if let Some(data_race) = &this.machine.data_race {
358             data_race.validate_lock_release_shared(&mut rwlock.data_race_reader, reader);
359         }
360
361         // The thread was a reader. If the lock is not held any more, give it to a writer.
362         if this.rwlock_is_locked(id).not() {
363             // All the readers are finished, so set the writer data-race handle to the value
364             //  of the union of all reader data race handles, since the set of readers
365             //  happen-before the writers
366             let rwlock = &mut this.machine.threads.sync.rwlocks[id];
367             rwlock.data_race.clone_from(&rwlock.data_race_reader);
368             this.rwlock_dequeue_and_lock_writer(id);
369         }
370         true
371     }
372
373     #[inline]
374     /// Put the reader in the queue waiting for the lock and block it.
375     fn rwlock_enqueue_and_block_reader(&mut self, id: RwLockId, reader: ThreadId) {
376         let this = self.eval_context_mut();
377         assert!(this.rwlock_is_write_locked(id), "read-queueing on not write locked rwlock");
378         this.machine.threads.sync.rwlocks[id].reader_queue.push_back(reader);
379         this.block_thread(reader);
380     }
381
382     #[inline]
383     /// Lock by setting the writer that owns the lock.
384     fn rwlock_writer_lock(&mut self, id: RwLockId, writer: ThreadId) {
385         let this = self.eval_context_mut();
386         assert!(!this.rwlock_is_locked(id), "the rwlock is already locked");
387         trace!("rwlock_writer_lock: {:?} now held by {:?}", id, writer);
388         let rwlock = &mut this.machine.threads.sync.rwlocks[id];
389         rwlock.writer = Some(writer);
390         if let Some(data_race) = &this.machine.data_race {
391             data_race.validate_lock_acquire(&rwlock.data_race, writer);
392         }
393     }
394
395     #[inline]
396     /// Try to unlock by removing the writer.
397     fn rwlock_writer_unlock(&mut self, id: RwLockId, expected_writer: ThreadId) -> bool {
398         let this = self.eval_context_mut();
399         let rwlock = &mut this.machine.threads.sync.rwlocks[id];
400         if let Some(current_writer) = rwlock.writer {
401             if current_writer != expected_writer {
402                 // Only the owner can unlock the rwlock.
403                 return false;
404             }
405             rwlock.writer = None;
406             trace!("rwlock_writer_unlock: {:?} unlocked by {:?}", id, expected_writer);
407             // Release memory to both reader and writer vector clocks
408             //  since this writer happens-before both the union of readers once they are finished
409             //  and the next writer
410             if let Some(data_race) = &this.machine.data_race {
411                 data_race.validate_lock_release(&mut rwlock.data_race, current_writer);
412                 data_race.validate_lock_release(&mut rwlock.data_race_reader, current_writer);
413             }
414             // The thread was a writer.
415             //
416             // We are prioritizing writers here against the readers. As a
417             // result, not only readers can starve writers, but also writers can
418             // starve readers.
419             if this.rwlock_dequeue_and_lock_writer(id) {
420                 // Someone got the write lock, nice.
421             } else {
422                 // Give the lock to all readers.
423                 while this.rwlock_dequeue_and_lock_reader(id) {
424                     // Rinse and repeat.
425                 }
426             }
427             true
428         } else {
429             false
430         }
431     }
432
433     #[inline]
434     /// Put the writer in the queue waiting for the lock.
435     fn rwlock_enqueue_and_block_writer(&mut self, id: RwLockId, writer: ThreadId) {
436         let this = self.eval_context_mut();
437         assert!(this.rwlock_is_locked(id), "write-queueing on unlocked rwlock");
438         this.machine.threads.sync.rwlocks[id].writer_queue.push_back(writer);
439         this.block_thread(writer);
440     }
441
442     #[inline]
443     /// Create state for a new conditional variable.
444     fn condvar_create(&mut self) -> CondvarId {
445         let this = self.eval_context_mut();
446         this.machine.threads.sync.condvars.push(Default::default())
447     }
448
449     #[inline]
450     /// Is the conditional variable awaited?
451     fn condvar_is_awaited(&mut self, id: CondvarId) -> bool {
452         let this = self.eval_context_mut();
453         !this.machine.threads.sync.condvars[id].waiters.is_empty()
454     }
455
456     /// Mark that the thread is waiting on the conditional variable.
457     fn condvar_wait(&mut self, id: CondvarId, thread: ThreadId, mutex: MutexId) {
458         let this = self.eval_context_mut();
459         let waiters = &mut this.machine.threads.sync.condvars[id].waiters;
460         assert!(waiters.iter().all(|waiter| waiter.thread != thread), "thread is already waiting");
461         waiters.push_back(CondvarWaiter { thread, mutex });
462     }
463
464     /// Wake up some thread (if there is any) sleeping on the conditional
465     /// variable.
466     fn condvar_signal(&mut self, id: CondvarId) -> Option<(ThreadId, MutexId)> {
467         let this = self.eval_context_mut();
468         let current_thread = this.get_active_thread();
469         let condvar = &mut this.machine.threads.sync.condvars[id];
470         let data_race = &this.machine.data_race;
471
472         // Each condvar signal happens-before the end of the condvar wake
473         if let Some(data_race) = data_race {
474             data_race.validate_lock_release(&mut condvar.data_race, current_thread);
475         }
476         condvar.waiters.pop_front().map(|waiter| {
477             if let Some(data_race) = data_race {
478                 data_race.validate_lock_acquire(&mut condvar.data_race, waiter.thread);
479             }
480             (waiter.thread, waiter.mutex)
481         })
482     }
483
484     #[inline]
485     /// Remove the thread from the queue of threads waiting on this conditional variable.
486     fn condvar_remove_waiter(&mut self, id: CondvarId, thread: ThreadId) {
487         let this = self.eval_context_mut();
488         this.machine.threads.sync.condvars[id].waiters.retain(|waiter| waiter.thread != thread);
489     }
490
491     fn futex_wait(&mut self, addr: u64, thread: ThreadId, bitset: u32) {
492         let this = self.eval_context_mut();
493         let futex = &mut this.machine.threads.sync.futexes.entry(addr).or_default();
494         let waiters = &mut futex.waiters;
495         assert!(waiters.iter().all(|waiter| waiter.thread != thread), "thread is already waiting");
496         waiters.push_back(FutexWaiter { thread, bitset });
497     }
498
499     fn futex_wake(&mut self, addr: u64, bitset: u32) -> Option<ThreadId> {
500         let this = self.eval_context_mut();
501         let current_thread = this.get_active_thread();
502         let futex = &mut this.machine.threads.sync.futexes.get_mut(&addr)?;
503         let data_race = &this.machine.data_race;
504
505         // Each futex-wake happens-before the end of the futex wait
506         if let Some(data_race) = data_race {
507             data_race.validate_lock_release(&mut futex.data_race, current_thread);
508         }
509
510         // Wake up the first thread in the queue that matches any of the bits in the bitset.
511         futex.waiters.iter().position(|w| w.bitset & bitset != 0).map(|i| {
512             let waiter = futex.waiters.remove(i).unwrap();
513             if let Some(data_race) = data_race {
514                 data_race.validate_lock_acquire(&futex.data_race, waiter.thread);
515             }
516             waiter.thread
517         })
518     }
519
520     fn futex_remove_waiter(&mut self, addr: u64, thread: ThreadId) {
521         let this = self.eval_context_mut();
522         if let Some(futex) = this.machine.threads.sync.futexes.get_mut(&addr) {
523             futex.waiters.retain(|waiter| waiter.thread != thread);
524         }
525     }
526 }