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