2 * monitor.c: Monitor locking functions
5 * Dick Porter (dick@ximian.com)
7 * (C) 2003 Ximian, Inc.
13 #include <mono/metadata/monitor.h>
14 #include <mono/metadata/threads-types.h>
15 #include <mono/metadata/exception.h>
16 #include <mono/metadata/threads.h>
17 #include <mono/io-layer/io-layer.h>
18 #include <mono/metadata/object-internals.h>
19 #include <mono/metadata/gc-internal.h>
21 /*#define LOCK_DEBUG(a) do { a; } while (0)*/
25 * The monitor implementation here is based on
26 * http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf and
27 * http://www.research.ibm.com/people/d/dfb/papers/Bacon98Thin.ps
29 * The Dice paper describes a technique for saving lock record space
30 * by returning records to a free list when they become unused. That
31 * sounds like unnecessary complexity to me, though if it becomes
32 * clear that unused lock records are taking up lots of space or we
33 * need to shave more time off by avoiding a malloc then we can always
34 * implement the free list idea later. The timeout parameter to
35 * try_enter voids some of the assumptions about the reference count
36 * field in Dice's implementation too. In his version, the thread
37 * attempting to lock a contended object will block until it succeeds,
38 * so the reference count will never be decremented while an object is
41 * Bacon's thin locks have a fast path that doesn't need a lock record
42 * for the common case of locking an unlocked or shallow-nested
43 * object, but the technique relies on encoding the thread ID in 15
44 * bits (to avoid too much per-object space overhead.) Unfortunately
45 * I don't think it's possible to reliably encode a pthread_t into 15
46 * bits. (The JVM implementation used seems to have a 15-bit
47 * per-thread identifier available.)
49 * This implementation then combines Dice's basic lock model with
50 * Bacon's simplification of keeping a lock record for the lifetime of
54 struct _MonoThreadsSync
56 gsize owner; /* thread ID */
58 #ifdef HAVE_MOVING_COLLECTOR
61 volatile guint32 entry_count;
67 typedef struct _MonitorArray MonitorArray;
69 struct _MonitorArray {
72 MonoThreadsSync monitors [MONO_ZERO_LEN_ARRAY];
75 #define mono_monitor_allocator_lock() EnterCriticalSection (&monitor_mutex)
76 #define mono_monitor_allocator_unlock() LeaveCriticalSection (&monitor_mutex)
77 static CRITICAL_SECTION monitor_mutex;
78 static MonoThreadsSync *monitor_freelist;
79 static MonitorArray *monitor_allocated;
80 static int array_size = 16;
83 mono_monitor_init (void)
85 InitializeCriticalSection (&monitor_mutex);
88 /* LOCKING: this is called with monitor_mutex held */
90 mon_finalize (MonoThreadsSync *mon)
92 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Finalizing sync %p", mon));
94 if (mon->entry_sem != NULL) {
95 CloseHandle (mon->entry_sem);
96 mon->entry_sem = NULL;
98 /* If this isn't empty then something is seriously broken - it
99 * means a thread is still waiting on the object that owned
100 * this lock, but the object has been finalized.
102 g_assert (mon->wait_list == NULL);
104 mon->entry_count = 0;
105 /* owner and nest are set in mon_new, no need to zero them out */
107 mon->data = monitor_freelist;
108 monitor_freelist = mon;
111 /* LOCKING: this is called with monitor_mutex held */
112 static MonoThreadsSync *
115 MonoThreadsSync *new;
117 if (!monitor_freelist) {
118 MonitorArray *marray;
120 /* see if any sync block has been collected */
122 for (marray = monitor_allocated; marray; marray = marray->next) {
123 for (i = 0; i < marray->num_monitors; ++i) {
124 if (marray->monitors [i].data == NULL) {
125 new = &marray->monitors [i];
126 new->data = monitor_freelist;
127 monitor_freelist = new;
130 /* small perf tweak to avoid scanning all the blocks */
134 /* need to allocate a new array of monitors */
135 if (!monitor_freelist) {
137 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": allocating more monitors: %d", array_size));
138 marray = g_malloc0 (sizeof (MonoArray) + array_size * sizeof (MonoThreadsSync));
139 marray->num_monitors = array_size;
141 /* link into the freelist */
142 for (i = 0; i < marray->num_monitors - 1; ++i) {
143 marray->monitors [i].data = &marray->monitors [i + 1];
145 marray->monitors [i].data = NULL; /* the last one */
146 monitor_freelist = &marray->monitors [0];
147 /* we happend the marray instead of prepending so that
148 * the collecting loop above will need to scan smaller arrays first
150 if (!monitor_allocated) {
151 monitor_allocated = marray;
153 last = monitor_allocated;
161 new = monitor_freelist;
162 monitor_freelist = new->data;
171 * Format of the lock word:
172 * thinhash | fathash | data
174 * thinhash is the lower bit: if set data is the shifted hashcode of the object.
175 * fathash is another bit: if set the hash code is stored in the MonoThreadsSync
176 * struct pointed to by data
177 * if neither bit is set and data is non-NULL, data is a MonoThreadsSync
181 MonoThreadsSync *sync;
185 LOCK_WORD_THIN_HASH = 1,
186 LOCK_WORD_FAT_HASH = 1 << 1,
187 LOCK_WORD_BITS_MASK = 0x3,
188 LOCK_WORD_HASH_SHIFT = 2
191 #define MONO_OBJECT_ALIGNMENT_SHIFT 3
197 * Calculate a hash code for @obj that is constant while @obj is alive.
200 mono_object_hash (MonoObject* obj)
202 #ifdef HAVE_MOVING_COLLECTOR
207 lw.sync = obj->synchronisation;
208 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
209 /*g_print ("fast thin hash %d for obj %p store\n", (unsigned int)lw.lock_word >> LOCK_WORD_HASH_SHIFT, obj);*/
210 return (unsigned int)lw.lock_word >> LOCK_WORD_HASH_SHIFT;
212 if (lw.lock_word & LOCK_WORD_FAT_HASH) {
213 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
214 /*g_print ("fast fat hash %d for obj %p store\n", lw.sync->hash_code, obj);*/
215 return lw.sync->hash_code;
218 * while we are inside this function, the GC will keep this object pinned,
219 * since we are in the unamanged stack. Thanks to this and to the hash
220 * function that depends only on the address, we can ignore the races if
221 * another thread computes the hash at the same time, because it'll end up
222 * with the same value.
224 hash = (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
225 /* clear the top bits as they can be discarded */
226 hash &= ~(LOCK_WORD_BITS_MASK << 30);
227 /* no hash flags were set, so it must be a MonoThreadsSync pointer if not NULL */
229 lw.sync->hash_code = hash;
230 /*g_print ("storing hash code %d for obj %p in sync %p\n", hash, obj, lw.sync);*/
231 lw.lock_word |= LOCK_WORD_FAT_HASH;
232 /* this is safe since we don't deflate locks */
233 obj->synchronisation = lw.sync;
235 /*g_print ("storing thin hash code %d for obj %p\n", hash, obj);*/
236 lw.lock_word = LOCK_WORD_THIN_HASH | (hash << LOCK_WORD_HASH_SHIFT);
237 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, NULL) == NULL)
239 /*g_print ("failed store\n");*/
240 /* someone set the hash flag or someone inflated the object */
241 lw.sync = obj->synchronisation;
242 if (lw.lock_word & LOCK_WORD_THIN_HASH)
244 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
245 lw.sync->hash_code = hash;
246 lw.lock_word |= LOCK_WORD_FAT_HASH;
247 /* this is safe since we don't deflate locks */
248 obj->synchronisation = lw.sync;
253 * Wang's address-based hash function:
254 * http://www.concentric.net/~Ttwang/tech/addrhash.htm
256 return (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
260 /* If allow_interruption==TRUE, the method will be interrumped if abort or suspend
261 * is requested. In this case it returns -1.
264 mono_monitor_try_enter_internal (MonoObject *obj, guint32 ms, gboolean allow_interruption)
266 MonoThreadsSync *mon;
267 gsize id = GetCurrentThreadId ();
269 guint32 then = 0, now, delta;
273 LOCK_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
274 ": (%d) Trying to lock object %p (%d ms)", id, obj, ms));
277 mon = obj->synchronisation;
279 /* If the object has never been locked... */
281 mono_monitor_allocator_lock ();
283 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, mon, NULL) == NULL) {
284 mono_gc_weak_link_add (&mon->data, obj);
285 mono_monitor_allocator_unlock ();
286 /* Successfully locked */
289 #ifdef HAVE_MOVING_COLLECTOR
291 lw.sync = obj->synchronisation;
292 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
293 MonoThreadsSync *oldlw = lw.sync;
294 /* move the already calculated hash */
295 mon->hash_code = lw.lock_word >> LOCK_WORD_HASH_SHIFT;
297 lw.lock_word |= LOCK_WORD_FAT_HASH;
298 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, oldlw) == oldlw) {
299 mono_gc_weak_link_add (&mon->data, obj);
300 mono_monitor_allocator_unlock ();
301 /* Successfully locked */
305 mono_monitor_allocator_unlock ();
308 } else if (lw.lock_word & LOCK_WORD_FAT_HASH) {
310 mono_monitor_allocator_unlock ();
311 /* get the old lock without the fat hash bit */
312 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
316 mono_monitor_allocator_unlock ();
317 mon = obj->synchronisation;
321 mono_monitor_allocator_unlock ();
322 mon = obj->synchronisation;
326 #ifdef HAVE_MOVING_COLLECTOR
329 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
330 MonoThreadsSync *oldlw = lw.sync;
331 mono_monitor_allocator_lock ();
333 /* move the already calculated hash */
334 mon->hash_code = lw.lock_word >> LOCK_WORD_HASH_SHIFT;
336 lw.lock_word |= LOCK_WORD_FAT_HASH;
337 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, oldlw) == oldlw) {
338 mono_gc_weak_link_add (&mon->data, obj);
339 mono_monitor_allocator_unlock ();
340 /* Successfully locked */
344 mono_monitor_allocator_unlock ();
351 #ifdef HAVE_MOVING_COLLECTOR
355 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
360 /* If the object is currently locked by this thread... */
361 if (mon->owner == id) {
366 /* If the object has previously been locked but isn't now... */
368 /* This case differs from Dice's case 3 because we don't
369 * deflate locks or cache unused lock records
371 if (mon->owner == 0) {
372 /* Try to install our ID in the owner field, nest
373 * should have been left at 1 by the previous unlock
376 if (InterlockedCompareExchangePointer ((gpointer *)&mon->owner, (gpointer)id, 0) == 0) {
378 g_assert (mon->nest == 1);
386 /* The object must be locked by someone else... */
388 /* If ms is 0 we don't block, but just fail straight away */
390 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) timed out, returning FALSE", id));
394 /* The slow path begins here. We need to make sure theres a
395 * semaphore handle (creating it if necessary), and block on
398 if (mon->entry_sem == NULL) {
399 /* Create the semaphore */
400 sem = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
401 if (InterlockedCompareExchangePointer ((gpointer*)&mon->entry_sem, sem, NULL) != NULL) {
402 /* Someone else just put a handle here */
407 /* If we need to time out, record a timestamp and adjust ms,
408 * because WaitForSingleObject doesn't tell us how long it
411 * Don't block forever here, because theres a chance the owner
412 * thread released the lock while we were creating the
413 * semaphore: we would not get the wakeup. Using the event
414 * handle technique from pulse/wait would involve locking the
415 * lock struct and therefore slowing down the fast path.
417 if (ms != INFINITE) {
418 then = GetTickCount ();
428 InterlockedIncrement (&mon->entry_count);
429 ret = WaitForSingleObjectEx (mon->entry_sem, waitms, allow_interruption);
430 InterlockedDecrement (&mon->entry_count);
432 if (ms != INFINITE) {
433 now = GetTickCount ();
436 /* The counter must have wrapped around */
437 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
438 ": wrapped around! now=0x%x then=0x%x", now, then));
440 now += (0xffffffff - then);
443 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": wrap rejig: now=0x%x then=0x%x delta=0x%x", now, then, now-then));
453 if ((ret == WAIT_TIMEOUT || (ret == WAIT_IO_COMPLETION && !allow_interruption)) && ms > 0) {
458 if (ret == WAIT_TIMEOUT || (ret == WAIT_IO_COMPLETION && !allow_interruption)) {
459 /* Infinite wait, so just try again */
464 if (ret == WAIT_OBJECT_0) {
465 /* retry from the top */
469 /* We must have timed out */
470 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) timed out waiting, returning FALSE", id));
472 if (ret == WAIT_IO_COMPLETION)
479 mono_monitor_enter (MonoObject *obj)
481 return mono_monitor_try_enter_internal (obj, INFINITE, FALSE) == 1;
485 mono_monitor_try_enter (MonoObject *obj, guint32 ms)
487 return mono_monitor_try_enter_internal (obj, ms, FALSE) == 1;
491 mono_monitor_exit (MonoObject *obj)
493 MonoThreadsSync *mon;
496 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Unlocking %p", GetCurrentThreadId (), obj));
498 mon = obj->synchronisation;
500 #ifdef HAVE_MOVING_COLLECTOR
504 if (lw.lock_word & LOCK_WORD_THIN_HASH)
506 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
511 /* No one ever used Enter. Just ignore the Exit request as MS does */
514 if (mon->owner != GetCurrentThreadId ()) {
518 nest = mon->nest - 1;
520 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
521 ": (%d) Object %p is now unlocked", GetCurrentThreadId (), obj));
523 /* object is now unlocked, leave nest==1 so we don't
524 * need to set it when the lock is reacquired
528 /* Do the wakeup stuff. It's possible that the last
529 * blocking thread gave up waiting just before we
530 * release the semaphore resulting in a futile wakeup
531 * next time there's contention for this object, but
532 * it means we don't have to waste time locking the
535 if (mon->entry_count > 0) {
536 ReleaseSemaphore (mon->entry_sem, 1, NULL);
539 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
540 ": (%d) Object %p is now locked %d times", GetCurrentThreadId (), obj, nest));
546 ves_icall_System_Threading_Monitor_Monitor_try_enter (MonoObject *obj, guint32 ms)
551 res = mono_monitor_try_enter_internal (obj, ms, TRUE);
553 mono_thread_interruption_checkpoint ();
560 ves_icall_System_Threading_Monitor_Monitor_exit (MonoObject *obj)
562 mono_monitor_exit (obj);
566 ves_icall_System_Threading_Monitor_Monitor_test_owner (MonoObject *obj)
568 MonoThreadsSync *mon;
570 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
571 ": Testing if %p is owned by thread %d", obj, GetCurrentThreadId()));
573 mon = obj->synchronisation;
574 #ifdef HAVE_MOVING_COLLECTOR
578 if (lw.lock_word & LOCK_WORD_THIN_HASH)
580 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
588 if(mon->owner==GetCurrentThreadId ()) {
596 ves_icall_System_Threading_Monitor_Monitor_test_synchronised (MonoObject *obj)
598 MonoThreadsSync *mon;
600 LOCK_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
601 ": (%d) Testing if %p is owned by any thread", GetCurrentThreadId (), obj));
603 mon = obj->synchronisation;
604 #ifdef HAVE_MOVING_COLLECTOR
608 if (lw.lock_word & LOCK_WORD_THIN_HASH)
610 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
618 if (mon->owner != 0) {
625 /* All wait list manipulation in the pulse, pulseall and wait
626 * functions happens while the monitor lock is held, so we don't need
627 * any extra struct locking
631 ves_icall_System_Threading_Monitor_Monitor_pulse (MonoObject *obj)
633 MonoThreadsSync *mon;
635 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Pulsing %p",
636 GetCurrentThreadId (), obj));
638 mon = obj->synchronisation;
639 #ifdef HAVE_MOVING_COLLECTOR
643 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
644 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
647 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
652 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
655 if (mon->owner != GetCurrentThreadId ()) {
656 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
660 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) %d threads waiting",
661 GetCurrentThreadId (), g_slist_length (mon->wait_list)));
663 if (mon->wait_list != NULL) {
664 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
665 ": (%d) signalling and dequeuing handle %p",
666 GetCurrentThreadId (), mon->wait_list->data));
668 SetEvent (mon->wait_list->data);
669 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
674 ves_icall_System_Threading_Monitor_Monitor_pulse_all (MonoObject *obj)
676 MonoThreadsSync *mon;
678 LOCK_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Pulsing all %p",
679 GetCurrentThreadId (), obj));
681 mon = obj->synchronisation;
682 #ifdef HAVE_MOVING_COLLECTOR
686 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
687 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
690 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
695 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
698 if (mon->owner != GetCurrentThreadId ()) {
699 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
703 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) %d threads waiting",
704 GetCurrentThreadId (), g_slist_length (mon->wait_list)));
706 while (mon->wait_list != NULL) {
707 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
708 ": (%d) signalling and dequeuing handle %p",
709 GetCurrentThreadId (), mon->wait_list->data));
711 SetEvent (mon->wait_list->data);
712 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
717 ves_icall_System_Threading_Monitor_Monitor_wait (MonoObject *obj, guint32 ms)
719 MonoThreadsSync *mon;
723 gboolean success = FALSE;
725 MonoThread *thread = mono_thread_current ();
727 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
728 ": (%d) Trying to wait for %p with timeout %dms",
729 GetCurrentThreadId (), obj, ms));
731 mon = obj->synchronisation;
732 #ifdef HAVE_MOVING_COLLECTOR
736 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
737 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
740 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
745 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
748 if (mon->owner != GetCurrentThreadId ()) {
749 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
753 event = CreateEvent (NULL, FALSE, FALSE, NULL);
755 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to set up wait event"));
759 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) queuing handle %p",
760 GetCurrentThreadId (), event));
762 mono_monitor_enter (thread->synch_lock);
763 thread->state |= ThreadState_WaitSleepJoin;
764 mono_monitor_exit (thread->synch_lock);
766 mon->wait_list = g_slist_append (mon->wait_list, event);
768 /* Save the nest count, and release the lock */
771 mono_monitor_exit (obj);
773 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Unlocked %p lock %p",
774 GetCurrentThreadId (), obj, mon));
776 /* There's no race between unlocking mon and waiting for the
777 * event, because auto reset events are sticky, and this event
778 * is private to this thread. Therefore even if the event was
779 * signalled before we wait, we still succeed.
781 ret = WaitForSingleObjectEx (event, ms, TRUE);
783 /* Reset the thread state fairly early, so we don't have to worry
784 * about the monitor error checking
786 mono_monitor_enter (thread->synch_lock);
787 thread->state &= ~ThreadState_WaitSleepJoin;
788 mono_monitor_exit (thread->synch_lock);
790 if (mono_thread_interruption_requested ()) {
795 /* Regain the lock with the previous nest count */
797 regain = mono_monitor_try_enter_internal (obj, INFINITE, TRUE);
799 mono_thread_interruption_checkpoint ();
800 } while (regain == -1);
803 /* Something went wrong, so throw a
804 * SynchronizationLockException
807 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to regain lock"));
813 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Regained %p lock %p",
814 GetCurrentThreadId (), obj, mon));
816 if (ret == WAIT_TIMEOUT) {
817 /* Poll the event again, just in case it was signalled
818 * while we were trying to regain the monitor lock
820 ret = WaitForSingleObjectEx (event, 0, FALSE);
823 /* Pulse will have popped our event from the queue if it signalled
824 * us, so we only do it here if the wait timed out.
826 * This avoids a race condition where the thread holding the
827 * lock can Pulse several times before the WaitForSingleObject
828 * returns. If we popped the queue here then this event might
829 * be signalled more than once, thereby starving another
833 if (ret == WAIT_OBJECT_0) {
834 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Success",
835 GetCurrentThreadId ()));
838 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed, dequeuing handle %p",
839 GetCurrentThreadId (), event));
840 /* No pulse, so we have to remove ourself from the
843 mon->wait_list = g_slist_remove (mon->wait_list, event);