]> git.lizzy.rs Git - rust.git/blob - src/sync.rs
Auto merge of #2061 - RalfJung:edition, r=RalfJung
[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     /// Create state for a new mutex.
213     fn mutex_create(&mut self) -> MutexId {
214         let this = self.eval_context_mut();
215         this.machine.threads.sync.mutexes.push(Default::default())
216     }
217
218     #[inline]
219     /// Get the id of the thread that currently owns this lock.
220     fn mutex_get_owner(&mut self, id: MutexId) -> ThreadId {
221         let this = self.eval_context_ref();
222         this.machine.threads.sync.mutexes[id].owner.unwrap()
223     }
224
225     #[inline]
226     /// Check if locked.
227     fn mutex_is_locked(&self, id: MutexId) -> bool {
228         let this = self.eval_context_ref();
229         this.machine.threads.sync.mutexes[id].owner.is_some()
230     }
231
232     /// Lock by setting the mutex owner and increasing the lock count.
233     fn mutex_lock(&mut self, id: MutexId, thread: ThreadId) {
234         let this = self.eval_context_mut();
235         let mutex = &mut this.machine.threads.sync.mutexes[id];
236         if let Some(current_owner) = mutex.owner {
237             assert_eq!(thread, current_owner, "mutex already locked by another thread");
238             assert!(
239                 mutex.lock_count > 0,
240                 "invariant violation: lock_count == 0 iff the thread is unlocked"
241             );
242         } else {
243             mutex.owner = Some(thread);
244         }
245         mutex.lock_count = mutex.lock_count.checked_add(1).unwrap();
246         if let Some(data_race) = &this.machine.data_race {
247             data_race.validate_lock_acquire(&mutex.data_race, thread);
248         }
249     }
250
251     /// Try unlocking by decreasing the lock count and returning the old lock
252     /// count. If the lock count reaches 0, release the lock and potentially
253     /// give to a new owner. If the lock was not locked by `expected_owner`,
254     /// return `None`.
255     fn mutex_unlock(&mut self, id: MutexId, expected_owner: ThreadId) -> Option<usize> {
256         let this = self.eval_context_mut();
257         let mutex = &mut this.machine.threads.sync.mutexes[id];
258         if let Some(current_owner) = mutex.owner {
259             // Mutex is locked.
260             if current_owner != expected_owner {
261                 // Only the owner can unlock the mutex.
262                 return None;
263             }
264             let old_lock_count = mutex.lock_count;
265             mutex.lock_count = old_lock_count
266                 .checked_sub(1)
267                 .expect("invariant violation: lock_count == 0 iff the thread is unlocked");
268             if mutex.lock_count == 0 {
269                 mutex.owner = None;
270                 // The mutex is completely unlocked. Try transfering ownership
271                 // to another thread.
272                 if let Some(data_race) = &this.machine.data_race {
273                     data_race.validate_lock_release(&mut mutex.data_race, current_owner);
274                 }
275                 this.mutex_dequeue_and_lock(id);
276             }
277             Some(old_lock_count)
278         } else {
279             // Mutex is not locked.
280             None
281         }
282     }
283
284     #[inline]
285     /// Put the thread into the queue waiting for the mutex.
286     fn mutex_enqueue_and_block(&mut self, id: MutexId, thread: ThreadId) {
287         let this = self.eval_context_mut();
288         assert!(this.mutex_is_locked(id), "queing on unlocked mutex");
289         this.machine.threads.sync.mutexes[id].queue.push_back(thread);
290         this.block_thread(thread);
291     }
292
293     #[inline]
294     /// Create state for a new read write lock.
295     fn rwlock_create(&mut self) -> RwLockId {
296         let this = self.eval_context_mut();
297         this.machine.threads.sync.rwlocks.push(Default::default())
298     }
299
300     #[inline]
301     /// Check if locked.
302     fn rwlock_is_locked(&self, id: RwLockId) -> bool {
303         let this = self.eval_context_ref();
304         let rwlock = &this.machine.threads.sync.rwlocks[id];
305         trace!(
306             "rwlock_is_locked: {:?} writer is {:?} and there are {} reader threads (some of which could hold multiple read locks)",
307             id,
308             rwlock.writer,
309             rwlock.readers.len(),
310         );
311         rwlock.writer.is_some() || rwlock.readers.is_empty().not()
312     }
313
314     #[inline]
315     /// Check if write locked.
316     fn rwlock_is_write_locked(&self, id: RwLockId) -> bool {
317         let this = self.eval_context_ref();
318         let rwlock = &this.machine.threads.sync.rwlocks[id];
319         trace!("rwlock_is_write_locked: {:?} writer is {:?}", id, rwlock.writer);
320         rwlock.writer.is_some()
321     }
322
323     /// Read-lock the lock by adding the `reader` the list of threads that own
324     /// this lock.
325     fn rwlock_reader_lock(&mut self, id: RwLockId, reader: ThreadId) {
326         let this = self.eval_context_mut();
327         assert!(!this.rwlock_is_write_locked(id), "the lock is write locked");
328         trace!("rwlock_reader_lock: {:?} now also held (one more time) by {:?}", id, reader);
329         let rwlock = &mut this.machine.threads.sync.rwlocks[id];
330         let count = rwlock.readers.entry(reader).or_insert(0);
331         *count = count.checked_add(1).expect("the reader counter overflowed");
332         if let Some(data_race) = &this.machine.data_race {
333             data_race.validate_lock_acquire(&rwlock.data_race, reader);
334         }
335     }
336
337     /// Try read-unlock the lock for `reader` and potentially give the lock to a new owner.
338     /// Returns `true` if succeeded, `false` if this `reader` did not hold the lock.
339     fn rwlock_reader_unlock(&mut self, id: RwLockId, reader: ThreadId) -> bool {
340         let this = self.eval_context_mut();
341         let rwlock = &mut this.machine.threads.sync.rwlocks[id];
342         match rwlock.readers.entry(reader) {
343             Entry::Occupied(mut entry) => {
344                 let count = entry.get_mut();
345                 assert!(*count > 0, "rwlock locked with count == 0");
346                 *count -= 1;
347                 if *count == 0 {
348                     trace!("rwlock_reader_unlock: {:?} no longer held by {:?}", id, reader);
349                     entry.remove();
350                 } else {
351                     trace!("rwlock_reader_unlock: {:?} held one less time by {:?}", id, reader);
352                 }
353             }
354             Entry::Vacant(_) => return false, // we did not even own this lock
355         }
356         if let Some(data_race) = &this.machine.data_race {
357             data_race.validate_lock_release_shared(&mut rwlock.data_race_reader, reader);
358         }
359
360         // The thread was a reader. If the lock is not held any more, give it to a writer.
361         if this.rwlock_is_locked(id).not() {
362             // All the readers are finished, so set the writer data-race handle to the value
363             //  of the union of all reader data race handles, since the set of readers
364             //  happen-before the writers
365             let rwlock = &mut this.machine.threads.sync.rwlocks[id];
366             rwlock.data_race.clone_from(&rwlock.data_race_reader);
367             this.rwlock_dequeue_and_lock_writer(id);
368         }
369         true
370     }
371
372     #[inline]
373     /// Put the reader in the queue waiting for the lock and block it.
374     fn rwlock_enqueue_and_block_reader(&mut self, id: RwLockId, reader: ThreadId) {
375         let this = self.eval_context_mut();
376         assert!(this.rwlock_is_write_locked(id), "read-queueing on not write locked rwlock");
377         this.machine.threads.sync.rwlocks[id].reader_queue.push_back(reader);
378         this.block_thread(reader);
379     }
380
381     #[inline]
382     /// Lock by setting the writer that owns the lock.
383     fn rwlock_writer_lock(&mut self, id: RwLockId, writer: ThreadId) {
384         let this = self.eval_context_mut();
385         assert!(!this.rwlock_is_locked(id), "the rwlock is already locked");
386         trace!("rwlock_writer_lock: {:?} now held by {:?}", id, writer);
387         let rwlock = &mut this.machine.threads.sync.rwlocks[id];
388         rwlock.writer = Some(writer);
389         if let Some(data_race) = &this.machine.data_race {
390             data_race.validate_lock_acquire(&rwlock.data_race, writer);
391         }
392     }
393
394     #[inline]
395     /// Try to unlock by removing the writer.
396     fn rwlock_writer_unlock(&mut self, id: RwLockId, expected_writer: ThreadId) -> bool {
397         let this = self.eval_context_mut();
398         let rwlock = &mut this.machine.threads.sync.rwlocks[id];
399         if let Some(current_writer) = rwlock.writer {
400             if current_writer != expected_writer {
401                 // Only the owner can unlock the rwlock.
402                 return false;
403             }
404             rwlock.writer = None;
405             trace!("rwlock_writer_unlock: {:?} unlocked by {:?}", id, expected_writer);
406             // Release memory to both reader and writer vector clocks
407             //  since this writer happens-before both the union of readers once they are finished
408             //  and the next writer
409             if let Some(data_race) = &this.machine.data_race {
410                 data_race.validate_lock_release(&mut rwlock.data_race, current_writer);
411                 data_race.validate_lock_release(&mut rwlock.data_race_reader, current_writer);
412             }
413             // The thread was a writer.
414             //
415             // We are prioritizing writers here against the readers. As a
416             // result, not only readers can starve writers, but also writers can
417             // starve readers.
418             if this.rwlock_dequeue_and_lock_writer(id) {
419                 // Someone got the write lock, nice.
420             } else {
421                 // Give the lock to all readers.
422                 while this.rwlock_dequeue_and_lock_reader(id) {
423                     // Rinse and repeat.
424                 }
425             }
426             true
427         } else {
428             false
429         }
430     }
431
432     #[inline]
433     /// Put the writer in the queue waiting for the lock.
434     fn rwlock_enqueue_and_block_writer(&mut self, id: RwLockId, writer: ThreadId) {
435         let this = self.eval_context_mut();
436         assert!(this.rwlock_is_locked(id), "write-queueing on unlocked rwlock");
437         this.machine.threads.sync.rwlocks[id].writer_queue.push_back(writer);
438         this.block_thread(writer);
439     }
440
441     #[inline]
442     /// Create state for a new conditional variable.
443     fn condvar_create(&mut self) -> CondvarId {
444         let this = self.eval_context_mut();
445         this.machine.threads.sync.condvars.push(Default::default())
446     }
447
448     #[inline]
449     /// Is the conditional variable awaited?
450     fn condvar_is_awaited(&mut self, id: CondvarId) -> bool {
451         let this = self.eval_context_mut();
452         !this.machine.threads.sync.condvars[id].waiters.is_empty()
453     }
454
455     /// Mark that the thread is waiting on the conditional variable.
456     fn condvar_wait(&mut self, id: CondvarId, thread: ThreadId, mutex: MutexId) {
457         let this = self.eval_context_mut();
458         let waiters = &mut this.machine.threads.sync.condvars[id].waiters;
459         assert!(waiters.iter().all(|waiter| waiter.thread != thread), "thread is already waiting");
460         waiters.push_back(CondvarWaiter { thread, mutex });
461     }
462
463     /// Wake up some thread (if there is any) sleeping on the conditional
464     /// variable.
465     fn condvar_signal(&mut self, id: CondvarId) -> Option<(ThreadId, MutexId)> {
466         let this = self.eval_context_mut();
467         let current_thread = this.get_active_thread();
468         let condvar = &mut this.machine.threads.sync.condvars[id];
469         let data_race = &this.machine.data_race;
470
471         // Each condvar signal happens-before the end of the condvar wake
472         if let Some(data_race) = data_race {
473             data_race.validate_lock_release(&mut condvar.data_race, current_thread);
474         }
475         condvar.waiters.pop_front().map(|waiter| {
476             if let Some(data_race) = data_race {
477                 data_race.validate_lock_acquire(&mut condvar.data_race, waiter.thread);
478             }
479             (waiter.thread, waiter.mutex)
480         })
481     }
482
483     #[inline]
484     /// Remove the thread from the queue of threads waiting on this conditional variable.
485     fn condvar_remove_waiter(&mut self, id: CondvarId, thread: ThreadId) {
486         let this = self.eval_context_mut();
487         this.machine.threads.sync.condvars[id].waiters.retain(|waiter| waiter.thread != thread);
488     }
489
490     fn futex_wait(&mut self, addr: u64, thread: ThreadId, bitset: u32) {
491         let this = self.eval_context_mut();
492         let futex = &mut this.machine.threads.sync.futexes.entry(addr).or_default();
493         let waiters = &mut futex.waiters;
494         assert!(waiters.iter().all(|waiter| waiter.thread != thread), "thread is already waiting");
495         waiters.push_back(FutexWaiter { thread, bitset });
496     }
497
498     fn futex_wake(&mut self, addr: u64, bitset: u32) -> Option<ThreadId> {
499         let this = self.eval_context_mut();
500         let current_thread = this.get_active_thread();
501         let futex = &mut this.machine.threads.sync.futexes.get_mut(&addr)?;
502         let data_race = &this.machine.data_race;
503
504         // Each futex-wake happens-before the end of the futex wait
505         if let Some(data_race) = data_race {
506             data_race.validate_lock_release(&mut futex.data_race, current_thread);
507         }
508
509         // Wake up the first thread in the queue that matches any of the bits in the bitset.
510         futex.waiters.iter().position(|w| w.bitset & bitset != 0).map(|i| {
511             let waiter = futex.waiters.remove(i).unwrap();
512             if let Some(data_race) = data_race {
513                 data_race.validate_lock_acquire(&futex.data_race, waiter.thread);
514             }
515             waiter.thread
516         })
517     }
518
519     fn futex_remove_waiter(&mut self, addr: u64, thread: ThreadId) {
520         let this = self.eval_context_mut();
521         if let Some(futex) = this.machine.threads.sync.futexes.get_mut(&addr) {
522             futex.waiters.retain(|waiter| waiter.thread != thread);
523         }
524     }
525 }