2 * monitor.c: Monitor locking functions
5 * Dick Porter (dick@ximian.com)
7 * Copyright 2003 Ximian, Inc (http://www.ximian.com)
8 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #include <mono/metadata/abi-details.h>
17 #include <mono/metadata/monitor.h>
18 #include <mono/metadata/threads-types.h>
19 #include <mono/metadata/exception.h>
20 #include <mono/metadata/threads.h>
21 #include <mono/io-layer/io-layer.h>
22 #include <mono/metadata/object-internals.h>
23 #include <mono/metadata/class-internals.h>
24 #include <mono/metadata/gc-internals.h>
25 #include <mono/metadata/method-builder.h>
26 #include <mono/metadata/debug-helpers.h>
27 #include <mono/metadata/tabledefs.h>
28 #include <mono/metadata/marshal.h>
29 #include <mono/utils/mono-threads.h>
30 #include <mono/metadata/profiler-private.h>
31 #include <mono/utils/mono-time.h>
32 #include <mono/utils/atomic.h>
35 * Pull the list of opcodes
37 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
41 #include "mono/cil/opcode.def"
46 /*#define LOCK_DEBUG(a) do { a; } while (0)*/
50 * The monitor implementation here is based on
51 * http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf and
52 * http://www.research.ibm.com/people/d/dfb/papers/Bacon98Thin.ps
54 * The Dice paper describes a technique for saving lock record space
55 * by returning records to a free list when they become unused. That
56 * sounds like unnecessary complexity to me, though if it becomes
57 * clear that unused lock records are taking up lots of space or we
58 * need to shave more time off by avoiding a malloc then we can always
59 * implement the free list idea later. The timeout parameter to
60 * try_enter voids some of the assumptions about the reference count
61 * field in Dice's implementation too. In his version, the thread
62 * attempting to lock a contended object will block until it succeeds,
63 * so the reference count will never be decremented while an object is
66 * Bacon's thin locks have a fast path that doesn't need a lock record
67 * for the common case of locking an unlocked or shallow-nested
72 typedef struct _MonitorArray MonitorArray;
74 struct _MonitorArray {
77 MonoThreadsSync monitors [MONO_ZERO_LEN_ARRAY];
80 #define mono_monitor_allocator_lock() mono_os_mutex_lock (&monitor_mutex)
81 #define mono_monitor_allocator_unlock() mono_os_mutex_unlock (&monitor_mutex)
82 static mono_mutex_t monitor_mutex;
83 static MonoThreadsSync *monitor_freelist;
84 static MonitorArray *monitor_allocated;
85 static int array_size = 16;
87 /* MonoThreadsSync status helpers */
90 mon_status_get_owner (guint32 status)
92 return status & OWNER_MASK;
96 mon_status_set_owner (guint32 status, guint32 owner)
98 return (status & ENTRY_COUNT_MASK) | owner;
102 mon_status_get_entry_count (guint32 status)
104 gint32 entry_count = (gint32)((status & ENTRY_COUNT_MASK) >> ENTRY_COUNT_SHIFT);
105 gint32 zero = (gint32)(((guint32)ENTRY_COUNT_ZERO) >> ENTRY_COUNT_SHIFT);
106 return entry_count - zero;
109 static inline guint32
110 mon_status_init_entry_count (guint32 status)
112 return (status & OWNER_MASK) | ENTRY_COUNT_ZERO;
115 static inline guint32
116 mon_status_increment_entry_count (guint32 status)
118 return status + (1 << ENTRY_COUNT_SHIFT);
121 static inline guint32
122 mon_status_decrement_entry_count (guint32 status)
124 return status - (1 << ENTRY_COUNT_SHIFT);
127 static inline gboolean
128 mon_status_have_waiters (guint32 status)
130 return status & ENTRY_COUNT_WAITERS;
133 /* LockWord helpers */
135 static inline MonoThreadsSync*
136 lock_word_get_inflated_lock (LockWord lw)
138 lw.lock_word &= (~LOCK_WORD_STATUS_MASK);
142 static inline gboolean
143 lock_word_is_inflated (LockWord lw)
145 return lw.lock_word & LOCK_WORD_INFLATED;
148 static inline gboolean
149 lock_word_has_hash (LockWord lw)
151 return lw.lock_word & LOCK_WORD_HAS_HASH;
154 static inline LockWord
155 lock_word_set_has_hash (LockWord lw)
158 nlw.lock_word = lw.lock_word | LOCK_WORD_HAS_HASH;
162 static inline gboolean
163 lock_word_is_free (LockWord lw)
165 return !lw.lock_word;
168 static inline gboolean
169 lock_word_is_flat (LockWord lw)
171 /* Return whether the lock is flat or free */
172 return (lw.lock_word & LOCK_WORD_STATUS_MASK) == LOCK_WORD_FLAT;
176 lock_word_get_hash (LockWord lw)
178 return (gint32) (lw.lock_word >> LOCK_WORD_HASH_SHIFT);
182 lock_word_get_nest (LockWord lw)
184 if (lock_word_is_free (lw))
186 /* Inword nest count starts from 0 */
187 return ((lw.lock_word & LOCK_WORD_NEST_MASK) >> LOCK_WORD_NEST_SHIFT) + 1;
190 static inline gboolean
191 lock_word_is_nested (LockWord lw)
193 return lw.lock_word & LOCK_WORD_NEST_MASK;
196 static inline gboolean
197 lock_word_is_max_nest (LockWord lw)
199 return (lw.lock_word & LOCK_WORD_NEST_MASK) == LOCK_WORD_NEST_MASK;
202 static inline LockWord
203 lock_word_increment_nest (LockWord lw)
205 lw.lock_word += 1 << LOCK_WORD_NEST_SHIFT;
209 static inline LockWord
210 lock_word_decrement_nest (LockWord lw)
212 lw.lock_word -= 1 << LOCK_WORD_NEST_SHIFT;
217 lock_word_get_owner (LockWord lw)
219 return lw.lock_word >> LOCK_WORD_OWNER_SHIFT;
222 static inline LockWord
223 lock_word_new_thin_hash (gint32 hash)
226 lw.lock_word = (guint32)hash;
227 lw.lock_word = (lw.lock_word << LOCK_WORD_HASH_SHIFT) | LOCK_WORD_HAS_HASH;
231 static inline LockWord
232 lock_word_new_inflated (MonoThreadsSync *mon)
236 lw.lock_word |= LOCK_WORD_INFLATED;
240 static inline LockWord
241 lock_word_new_flat (gint32 owner)
244 lw.lock_word = owner;
245 lw.lock_word <<= LOCK_WORD_OWNER_SHIFT;
250 mono_monitor_init (void)
252 mono_os_mutex_init_recursive (&monitor_mutex);
256 mono_monitor_cleanup (void)
258 MonoThreadsSync *mon;
259 /* MonitorArray *marray, *next = NULL; */
261 /*mono_os_mutex_destroy (&monitor_mutex);*/
263 /* The monitors on the freelist don't have weak links - mark them */
264 for (mon = monitor_freelist; mon; mon = (MonoThreadsSync *)mon->data)
265 mon->wait_list = (GSList *)-1;
268 * FIXME: This still crashes with sgen (async_read.exe)
270 * In mini_cleanup() we first call mono_runtime_cleanup(), which calls
271 * mono_monitor_cleanup(), which is supposed to free all monitor memory.
273 * Later in mini_cleanup(), we call mono_domain_free(), which calls
274 * mono_gc_clear_domain(), which frees all weak links associated with objects.
275 * Those weak links reside in the monitor structures, which we've freed earlier.
277 * Unless we fix this dependency in the shutdown sequence this code has to remain
278 * disabled, or at least the call to g_free().
281 for (marray = monitor_allocated; marray; marray = next) {
284 for (i = 0; i < marray->num_monitors; ++i) {
285 mon = &marray->monitors [i];
286 if (mon->wait_list != (gpointer)-1)
287 mono_gc_weak_link_remove (&mon->data);
297 monitor_is_on_freelist (MonoThreadsSync *mon)
299 MonitorArray *marray;
300 for (marray = monitor_allocated; marray; marray = marray->next) {
301 if (mon >= marray->monitors && mon < &marray->monitors [marray->num_monitors])
311 * Print a report on stdout of the managed locks currently held by
312 * threads. If @include_untaken is specified, list also inflated locks
314 * This is supposed to be used in debuggers like gdb.
317 mono_locks_dump (gboolean include_untaken)
320 int used = 0, on_freelist = 0, to_recycle = 0, total = 0, num_arrays = 0;
321 MonoThreadsSync *mon;
322 MonitorArray *marray;
323 for (mon = monitor_freelist; mon; mon = (MonoThreadsSync *)mon->data)
325 for (marray = monitor_allocated; marray; marray = marray->next) {
326 total += marray->num_monitors;
328 for (i = 0; i < marray->num_monitors; ++i) {
329 mon = &marray->monitors [i];
330 if (mon->data == NULL) {
331 if (i < marray->num_monitors - 1)
334 if (!monitor_is_on_freelist ((MonoThreadsSync *)mon->data)) {
335 MonoObject *holder = (MonoObject *)mono_gchandle_get_target ((guint32)mon->data);
336 if (mon_status_get_owner (mon->status)) {
337 g_print ("Lock %p in object %p held by thread %d, nest level: %d\n",
338 mon, holder, mon_status_get_owner (mon->status), mon->nest);
340 g_print ("\tWaiting on semaphore %p: %d\n", mon->entry_sem, mon_status_get_entry_count (mon->status));
341 } else if (include_untaken) {
342 g_print ("Lock %p in object %p untaken\n", mon, holder);
349 g_print ("Total locks (in %d array(s)): %d, used: %d, on freelist: %d, to recycle: %d\n",
350 num_arrays, total, used, on_freelist, to_recycle);
353 /* LOCKING: this is called with monitor_mutex held */
355 mon_finalize (MonoThreadsSync *mon)
357 LOCK_DEBUG (g_message ("%s: Finalizing sync %p", __func__, mon));
359 if (mon->entry_sem != NULL) {
360 CloseHandle (mon->entry_sem);
361 mon->entry_sem = NULL;
363 /* If this isn't empty then something is seriously broken - it
364 * means a thread is still waiting on the object that owned
365 * this lock, but the object has been finalized.
367 g_assert (mon->wait_list == NULL);
369 /* owner and nest are set in mon_new, no need to zero them out */
371 mon->data = monitor_freelist;
372 monitor_freelist = mon;
373 #ifndef DISABLE_PERFCOUNTERS
374 mono_perfcounters->gc_sync_blocks--;
378 /* LOCKING: this is called with monitor_mutex held */
379 static MonoThreadsSync *
382 MonoThreadsSync *new_;
384 if (!monitor_freelist) {
385 MonitorArray *marray;
387 /* see if any sync block has been collected */
389 for (marray = monitor_allocated; marray; marray = marray->next) {
390 for (i = 0; i < marray->num_monitors; ++i) {
391 if (mono_gchandle_get_target ((guint32)marray->monitors [i].data) == NULL) {
392 new_ = &marray->monitors [i];
393 if (new_->wait_list) {
394 /* Orphaned events left by aborted threads */
395 while (new_->wait_list) {
396 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d): Closing orphaned event %d", mono_thread_info_get_small_id (), new_->wait_list->data));
397 CloseHandle (new_->wait_list->data);
398 new_->wait_list = g_slist_remove (new_->wait_list, new_->wait_list->data);
401 mono_gchandle_free ((guint32)new_->data);
402 new_->data = monitor_freelist;
403 monitor_freelist = new_;
406 /* small perf tweak to avoid scanning all the blocks */
410 /* need to allocate a new array of monitors */
411 if (!monitor_freelist) {
413 LOCK_DEBUG (g_message ("%s: allocating more monitors: %d", __func__, array_size));
414 marray = (MonitorArray *)g_malloc0 (MONO_SIZEOF_MONO_ARRAY + array_size * sizeof (MonoThreadsSync));
415 marray->num_monitors = array_size;
417 /* link into the freelist */
418 for (i = 0; i < marray->num_monitors - 1; ++i) {
419 marray->monitors [i].data = &marray->monitors [i + 1];
421 marray->monitors [i].data = NULL; /* the last one */
422 monitor_freelist = &marray->monitors [0];
423 /* we happend the marray instead of prepending so that
424 * the collecting loop above will need to scan smaller arrays first
426 if (!monitor_allocated) {
427 monitor_allocated = marray;
429 last = monitor_allocated;
437 new_ = monitor_freelist;
438 monitor_freelist = (MonoThreadsSync *)new_->data;
440 new_->status = mon_status_set_owner (0, id);
441 new_->status = mon_status_init_entry_count (new_->status);
445 #ifndef DISABLE_PERFCOUNTERS
446 mono_perfcounters->gc_sync_blocks++;
451 static MonoThreadsSync*
452 alloc_mon (MonoObject *obj, gint32 id)
454 MonoThreadsSync *mon;
456 mono_monitor_allocator_lock ();
458 mon->data = (void *)(size_t)mono_gchandle_new_weakref (obj, TRUE);
459 mono_monitor_allocator_unlock ();
466 discard_mon (MonoThreadsSync *mon)
468 mono_monitor_allocator_lock ();
469 mono_gchandle_free ((guint32)mon->data);
471 mono_monitor_allocator_unlock ();
475 mono_monitor_inflate_owned (MonoObject *obj, int id)
477 MonoThreadsSync *mon;
478 LockWord nlw, old_lw, tmp_lw;
481 old_lw.sync = obj->synchronisation;
482 LOCK_DEBUG (g_message ("%s: (%d) Inflating owned lock object %p; LW = %p", __func__, id, obj, old_lw.sync));
484 if (lock_word_is_inflated (old_lw)) {
485 /* Someone else inflated the lock in the meantime */
489 mon = alloc_mon (obj, id);
491 nest = lock_word_get_nest (old_lw);
494 nlw = lock_word_new_inflated (mon);
496 mono_memory_write_barrier ();
497 tmp_lw.sync = (MonoThreadsSync *)InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, nlw.sync, old_lw.sync);
498 if (tmp_lw.sync != old_lw.sync) {
499 /* Someone else inflated the lock in the meantime */
505 mono_monitor_inflate (MonoObject *obj)
507 MonoThreadsSync *mon;
508 LockWord nlw, old_lw;
510 LOCK_DEBUG (g_message ("%s: (%d) Inflating lock object %p; LW = %p", __func__, mono_thread_info_get_small_id (), obj, obj->synchronisation));
512 mon = alloc_mon (obj, 0);
514 nlw = lock_word_new_inflated (mon);
516 old_lw.sync = obj->synchronisation;
521 if (lock_word_is_inflated (old_lw)) {
524 #ifdef HAVE_MOVING_COLLECTOR
525 else if (lock_word_has_hash (old_lw)) {
526 mon->hash_code = lock_word_get_hash (old_lw);
527 mon->status = mon_status_set_owner (mon->status, 0);
528 nlw = lock_word_set_has_hash (nlw);
531 else if (lock_word_is_free (old_lw)) {
532 mon->status = mon_status_set_owner (mon->status, 0);
536 mon->status = mon_status_set_owner (mon->status, lock_word_get_owner (old_lw));
537 mon->nest = lock_word_get_nest (old_lw);
539 mono_memory_write_barrier ();
540 tmp_lw.sync = (MonoThreadsSync *)InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, nlw.sync, old_lw.sync);
541 if (tmp_lw.sync == old_lw.sync) {
542 /* Successfully inflated the lock */
546 old_lw.sync = tmp_lw.sync;
549 /* Someone else inflated the lock before us */
553 #define MONO_OBJECT_ALIGNMENT_SHIFT 3
559 * Calculate a hash code for @obj that is constant while @obj is alive.
562 mono_object_hash (MonoObject* obj)
564 #ifdef HAVE_MOVING_COLLECTOR
569 lw.sync = obj->synchronisation;
571 LOCK_DEBUG (g_message("%s: (%d) Get hash for object %p; LW = %p", __func__, mono_thread_info_get_small_id (), obj, obj->synchronisation));
573 if (lock_word_has_hash (lw)) {
574 if (lock_word_is_inflated (lw)) {
575 return lock_word_get_inflated_lock (lw)->hash_code;
577 return lock_word_get_hash (lw);
581 * while we are inside this function, the GC will keep this object pinned,
582 * since we are in the unmanaged stack. Thanks to this and to the hash
583 * function that depends only on the address, we can ignore the races if
584 * another thread computes the hash at the same time, because it'll end up
585 * with the same value.
587 hash = (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
588 #if SIZEOF_VOID_P == 4
589 /* clear the top bits as they can be discarded */
590 hash &= ~(LOCK_WORD_STATUS_MASK << (32 - LOCK_WORD_STATUS_BITS));
592 if (lock_word_is_free (lw)) {
594 lw = lock_word_new_thin_hash (hash);
596 old_lw.sync = (MonoThreadsSync *)InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, NULL);
597 if (old_lw.sync == NULL) {
601 if (lock_word_has_hash (old_lw)) {
602 /* Done by somebody else */
606 mono_monitor_inflate (obj);
607 lw.sync = obj->synchronisation;
608 } else if (lock_word_is_flat (lw)) {
609 int id = mono_thread_info_get_small_id ();
610 if (lock_word_get_owner (lw) == id)
611 mono_monitor_inflate_owned (obj, id);
613 mono_monitor_inflate (obj);
614 lw.sync = obj->synchronisation;
617 /* At this point, the lock is inflated */
618 lock_word_get_inflated_lock (lw)->hash_code = hash;
619 lw = lock_word_set_has_hash (lw);
620 mono_memory_write_barrier ();
621 obj->synchronisation = lw.sync;
625 * Wang's address-based hash function:
626 * http://www.concentric.net/~Ttwang/tech/addrhash.htm
628 return (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
633 mono_monitor_ensure_owned (LockWord lw, guint32 id)
635 if (lock_word_is_flat (lw)) {
636 if (lock_word_get_owner (lw) == id)
638 } else if (lock_word_is_inflated (lw)) {
639 if (mon_status_get_owner (lock_word_get_inflated_lock (lw)->status) == id)
643 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Object synchronization method was called from an unsynchronized block of code."));
647 * When this function is called it has already been established that the
648 * current thread owns the monitor.
651 mono_monitor_exit_inflated (MonoObject *obj)
654 MonoThreadsSync *mon;
657 lw.sync = obj->synchronisation;
658 mon = lock_word_get_inflated_lock (lw);
660 nest = mon->nest - 1;
662 guint32 new_status, old_status, tmp_status;
664 old_status = mon->status;
667 * Release lock and do the wakeup stuff. It's possible that
668 * the last blocking thread gave up waiting just before we
669 * release the semaphore resulting in a negative entry count
670 * and a futile wakeup next time there's contention for this
674 gboolean have_waiters = mon_status_have_waiters (old_status);
676 new_status = mon_status_set_owner (old_status, 0);
678 new_status = mon_status_decrement_entry_count (new_status);
679 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
680 if (tmp_status == old_status) {
682 ReleaseSemaphore (mon->entry_sem, 1, NULL);
685 old_status = tmp_status;
687 LOCK_DEBUG (g_message ("%s: (%d) Object %p is now unlocked", __func__, mono_thread_info_get_small_id (), obj));
689 /* object is now unlocked, leave nest==1 so we don't
690 * need to set it when the lock is reacquired
693 LOCK_DEBUG (g_message ("%s: (%d) Object %p is now locked %d times", __func__, mono_thread_info_get_small_id (), obj, nest));
699 * When this function is called it has already been established that the
700 * current thread owns the monitor.
703 mono_monitor_exit_flat (MonoObject *obj, LockWord old_lw)
705 LockWord new_lw, tmp_lw;
706 if (G_UNLIKELY (lock_word_is_nested (old_lw)))
707 new_lw = lock_word_decrement_nest (old_lw);
709 new_lw.lock_word = 0;
711 tmp_lw.sync = (MonoThreadsSync *)InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, new_lw.sync, old_lw.sync);
712 if (old_lw.sync != tmp_lw.sync) {
713 /* Someone inflated the lock in the meantime */
714 mono_monitor_exit_inflated (obj);
717 LOCK_DEBUG (g_message ("%s: (%d) Object %p is now locked %d times; LW = %p", __func__, mono_thread_info_get_small_id (), obj, lock_word_get_nest (new_lw), obj->synchronisation));
721 mon_decrement_entry_count (MonoThreadsSync *mon)
723 guint32 old_status, tmp_status, new_status;
725 /* Decrement entry count */
726 old_status = mon->status;
728 new_status = mon_status_decrement_entry_count (old_status);
729 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
730 if (tmp_status == old_status) {
733 old_status = tmp_status;
737 /* If allow_interruption==TRUE, the method will be interrumped if abort or suspend
738 * is requested. In this case it returns -1.
741 mono_monitor_try_enter_inflated (MonoObject *obj, guint32 ms, gboolean allow_interruption, guint32 id)
744 MonoThreadsSync *mon;
746 gint64 then = 0, now, delta;
749 guint32 new_status, old_status, tmp_status;
750 MonoInternalThread *thread;
751 gboolean interrupted = FALSE;
753 LOCK_DEBUG (g_message("%s: (%d) Trying to lock object %p (%d ms)", __func__, id, obj, ms));
755 if (G_UNLIKELY (!obj)) {
756 mono_set_pending_exception (mono_get_exception_argument_null ("obj"));
760 lw.sync = obj->synchronisation;
761 mon = lock_word_get_inflated_lock (lw);
763 /* This case differs from Dice's case 3 because we don't
764 * deflate locks or cache unused lock records
766 old_status = mon->status;
767 if (G_LIKELY (mon_status_get_owner (old_status) == 0)) {
768 /* Try to install our ID in the owner field, nest
769 * should have been left at 1 by the previous unlock
772 new_status = mon_status_set_owner (old_status, id);
773 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
774 if (G_LIKELY (tmp_status == old_status)) {
776 g_assert (mon->nest == 1);
784 /* If the object is currently locked by this thread... */
785 if (mon_status_get_owner (old_status) == id) {
790 /* The object must be locked by someone else... */
791 #ifndef DISABLE_PERFCOUNTERS
792 mono_perfcounters->thread_contentions++;
795 /* If ms is 0 we don't block, but just fail straight away */
797 LOCK_DEBUG (g_message ("%s: (%d) timed out, returning FALSE", __func__, id));
801 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_CONTENTION);
803 /* The slow path begins here. */
805 /* a small amount of duplicated code, but it allows us to insert the profiler
806 * callbacks without impacting the fast path: from here on we don't need to go back to the
807 * retry label, but to retry_contended. At this point mon is already installed in the object
810 /* This case differs from Dice's case 3 because we don't
811 * deflate locks or cache unused lock records
813 old_status = mon->status;
814 if (G_LIKELY (mon_status_get_owner (old_status) == 0)) {
815 /* Try to install our ID in the owner field, nest
816 * should have been left at 1 by the previous unlock
819 new_status = mon_status_set_owner (old_status, id);
820 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
821 if (G_LIKELY (tmp_status == old_status)) {
823 g_assert (mon->nest == 1);
824 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_DONE);
829 /* If the object is currently locked by this thread... */
830 if (mon_status_get_owner (old_status) == id) {
832 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_DONE);
836 /* We need to make sure there's a semaphore handle (creating it if
837 * necessary), and block on it
839 if (mon->entry_sem == NULL) {
840 /* Create the semaphore */
841 sem = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
842 g_assert (sem != NULL);
843 if (InterlockedCompareExchangePointer ((gpointer*)&mon->entry_sem, sem, NULL) != NULL) {
844 /* Someone else just put a handle here */
850 * We need to register ourselves as waiting if it is the first time we are waiting,
851 * of if we were signaled and failed to acquire the lock.
854 old_status = mon->status;
856 if (mon_status_get_owner (old_status) == 0)
857 goto retry_contended;
858 new_status = mon_status_increment_entry_count (old_status);
859 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
860 if (tmp_status == old_status) {
863 old_status = tmp_status;
867 if (ms != INFINITE) {
868 then = mono_msec_ticks ();
872 #ifndef DISABLE_PERFCOUNTERS
873 mono_perfcounters->thread_queue_len++;
874 mono_perfcounters->thread_queue_max++;
876 thread = mono_thread_internal_current ();
878 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
881 * We pass TRUE instead of allow_interruption since we have to check for the
882 * StopRequested case below.
885 ret = WaitForSingleObjectEx (mon->entry_sem, waitms, TRUE);
888 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
890 #ifndef DISABLE_PERFCOUNTERS
891 mono_perfcounters->thread_queue_len--;
894 if (ret == WAIT_IO_COMPLETION && !allow_interruption) {
897 * We have to obey a stop/suspend request even if
898 * allow_interruption is FALSE to avoid hangs at shutdown.
900 if (!mono_thread_test_state (mono_thread_internal_current (), (MonoThreadState)(ThreadState_StopRequested | ThreadState_SuspendRequested | ThreadState_AbortRequested))) {
901 if (ms != INFINITE) {
902 now = mono_msec_ticks ();
904 /* it should not overflow before ~30k years */
905 g_assert (now >= then);
914 /* retry from the top */
915 goto retry_contended;
917 } else if (ret == WAIT_OBJECT_0) {
919 /* retry from the top */
920 goto retry_contended;
921 } else if (ret == WAIT_TIMEOUT) {
925 /* Timed out or interrupted */
926 mon_decrement_entry_count (mon);
928 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_FAIL);
930 if (ret == WAIT_IO_COMPLETION) {
931 LOCK_DEBUG (g_message ("%s: (%d) interrupted waiting, returning -1", __func__, id));
933 } else if (ret == WAIT_TIMEOUT) {
934 LOCK_DEBUG (g_message ("%s: (%d) timed out waiting, returning FALSE", __func__, id));
937 g_assert_not_reached ();
943 * If allow_interruption == TRUE, the method will be interrupted if abort or suspend
944 * is requested. In this case it returns -1.
947 mono_monitor_try_enter_internal (MonoObject *obj, guint32 ms, gboolean allow_interruption)
950 int id = mono_thread_info_get_small_id ();
952 LOCK_DEBUG (g_message("%s: (%d) Trying to lock object %p (%d ms)", __func__, id, obj, ms));
954 if (G_UNLIKELY (!obj)) {
955 mono_set_pending_exception (mono_get_exception_argument_null ("obj"));
959 lw.sync = obj->synchronisation;
961 if (G_LIKELY (lock_word_is_free (lw))) {
962 LockWord nlw = lock_word_new_flat (id);
963 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, nlw.sync, NULL) == NULL) {
966 /* Someone acquired it in the meantime or put a hash */
967 mono_monitor_inflate (obj);
968 return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
970 } else if (lock_word_is_inflated (lw)) {
971 return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
972 } else if (lock_word_is_flat (lw)) {
973 if (lock_word_get_owner (lw) == id) {
974 if (lock_word_is_max_nest (lw)) {
975 mono_monitor_inflate_owned (obj, id);
976 return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
978 LockWord nlw, old_lw;
979 nlw = lock_word_increment_nest (lw);
980 old_lw.sync = (MonoThreadsSync *)InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, nlw.sync, lw.sync);
981 if (old_lw.sync != lw.sync) {
982 /* Someone else inflated it in the meantime */
983 g_assert (lock_word_is_inflated (old_lw));
984 return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
989 mono_monitor_inflate (obj);
990 return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
992 } else if (lock_word_has_hash (lw)) {
993 mono_monitor_inflate (obj);
994 return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
997 g_assert_not_reached ();
1002 mono_monitor_enter (MonoObject *obj)
1004 return mono_monitor_try_enter_internal (obj, INFINITE, FALSE) == 1;
1008 mono_monitor_enter_fast (MonoObject *obj)
1010 return mono_monitor_try_enter_internal (obj, 0, FALSE) == 1;
1014 mono_monitor_try_enter (MonoObject *obj, guint32 ms)
1016 return mono_monitor_try_enter_internal (obj, ms, FALSE) == 1;
1020 mono_monitor_exit (MonoObject *obj)
1024 LOCK_DEBUG (g_message ("%s: (%d) Unlocking %p", __func__, mono_thread_info_get_small_id (), obj));
1026 if (G_UNLIKELY (!obj)) {
1027 mono_set_pending_exception (mono_get_exception_argument_null ("obj"));
1031 lw.sync = obj->synchronisation;
1033 mono_monitor_ensure_owned (lw, mono_thread_info_get_small_id ());
1035 if (G_UNLIKELY (lock_word_is_inflated (lw)))
1036 mono_monitor_exit_inflated (obj);
1038 mono_monitor_exit_flat (obj, lw);
1042 mono_monitor_get_object_monitor_gchandle (MonoObject *object)
1046 lw.sync = object->synchronisation;
1048 if (lock_word_is_inflated (lw)) {
1049 MonoThreadsSync *mon = lock_word_get_inflated_lock (lw);
1050 return (guint32)mon->data;
1056 * mono_monitor_threads_sync_member_offset:
1057 * @status_offset: returns size and offset of the "status" member
1058 * @nest_offset: returns size and offset of the "nest" member
1060 * Returns the offsets and sizes of two members of the
1061 * MonoThreadsSync struct. The Monitor ASM fastpaths need this.
1064 mono_monitor_threads_sync_members_offset (int *status_offset, int *nest_offset)
1068 #define ENCODE_OFF_SIZE(o,s) (((o) << 8) | ((s) & 0xff))
1070 *status_offset = ENCODE_OFF_SIZE (MONO_STRUCT_OFFSET (MonoThreadsSync, status), sizeof (ts.status));
1071 *nest_offset = ENCODE_OFF_SIZE (MONO_STRUCT_OFFSET (MonoThreadsSync, nest), sizeof (ts.nest));
1075 ves_icall_System_Threading_Monitor_Monitor_try_enter_with_atomic_var (MonoObject *obj, guint32 ms, char *lockTaken)
1079 res = mono_monitor_try_enter_internal (obj, ms, TRUE);
1080 /*This means we got interrupted during the wait and didn't got the monitor.*/
1082 MonoException *exc = mono_thread_interruption_checkpoint ();
1084 mono_set_pending_exception (exc);
1088 } while (res == -1);
1089 /*It's safe to do it from here since interruption would happen only on the wrapper.*/
1090 *lockTaken = res == 1;
1094 mono_monitor_enter_v4 (MonoObject *obj, char *lock_taken)
1096 if (*lock_taken == 1) {
1097 mono_set_pending_exception (mono_get_exception_argument ("lockTaken", "lockTaken is already true"));
1101 ves_icall_System_Threading_Monitor_Monitor_try_enter_with_atomic_var (obj, INFINITE, lock_taken);
1105 * mono_monitor_enter_v4_fast:
1107 * Same as mono_monitor_enter_v4, but return immediately if the
1108 * monitor cannot be acquired.
1109 * Returns TRUE if the lock was acquired, FALSE otherwise.
1112 mono_monitor_enter_v4_fast (MonoObject *obj, char *lock_taken)
1114 if (*lock_taken == 1)
1116 if (G_UNLIKELY (!obj))
1118 gint32 res = mono_monitor_try_enter_internal (obj, 0, TRUE);
1119 *lock_taken = res == 1;
1124 ves_icall_System_Threading_Monitor_Monitor_test_owner (MonoObject *obj)
1128 LOCK_DEBUG (g_message ("%s: Testing if %p is owned by thread %d", __func__, obj, mono_thread_info_get_small_id()));
1130 lw.sync = obj->synchronisation;
1132 if (lock_word_is_flat (lw)) {
1133 return lock_word_get_owner (lw) == mono_thread_info_get_small_id ();
1134 } else if (lock_word_is_inflated (lw)) {
1135 return mon_status_get_owner (lock_word_get_inflated_lock (lw)->status) == mono_thread_info_get_small_id ();
1142 ves_icall_System_Threading_Monitor_Monitor_test_synchronised (MonoObject *obj)
1146 LOCK_DEBUG (g_message("%s: (%d) Testing if %p is owned by any thread", __func__, mono_thread_info_get_small_id (), obj));
1148 lw.sync = obj->synchronisation;
1150 if (lock_word_is_flat (lw)) {
1151 return !lock_word_is_free (lw);
1152 } else if (lock_word_is_inflated (lw)) {
1153 return mon_status_get_owner (lock_word_get_inflated_lock (lw)->status) != 0;
1159 /* All wait list manipulation in the pulse, pulseall and wait
1160 * functions happens while the monitor lock is held, so we don't need
1161 * any extra struct locking
1165 ves_icall_System_Threading_Monitor_Monitor_pulse (MonoObject *obj)
1169 MonoThreadsSync *mon;
1171 LOCK_DEBUG (g_message ("%s: (%d) Pulsing %p", __func__, mono_thread_info_get_small_id (), obj));
1173 id = mono_thread_info_get_small_id ();
1174 lw.sync = obj->synchronisation;
1176 mono_monitor_ensure_owned (lw, id);
1178 if (!lock_word_is_inflated (lw)) {
1179 /* No threads waiting. A wait would have inflated the lock */
1183 mon = lock_word_get_inflated_lock (lw);
1185 LOCK_DEBUG (g_message ("%s: (%d) %d threads waiting", __func__, mono_thread_info_get_small_id (), g_slist_length (mon->wait_list)));
1187 if (mon->wait_list != NULL) {
1188 LOCK_DEBUG (g_message ("%s: (%d) signalling and dequeuing handle %p", __func__, mono_thread_info_get_small_id (), mon->wait_list->data));
1190 SetEvent (mon->wait_list->data);
1191 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1196 ves_icall_System_Threading_Monitor_Monitor_pulse_all (MonoObject *obj)
1200 MonoThreadsSync *mon;
1202 LOCK_DEBUG (g_message("%s: (%d) Pulsing all %p", __func__, mono_thread_info_get_small_id (), obj));
1204 id = mono_thread_info_get_small_id ();
1205 lw.sync = obj->synchronisation;
1207 mono_monitor_ensure_owned (lw, id);
1209 if (!lock_word_is_inflated (lw)) {
1210 /* No threads waiting. A wait would have inflated the lock */
1214 mon = lock_word_get_inflated_lock (lw);
1216 LOCK_DEBUG (g_message ("%s: (%d) %d threads waiting", __func__, mono_thread_info_get_small_id (), g_slist_length (mon->wait_list)));
1218 while (mon->wait_list != NULL) {
1219 LOCK_DEBUG (g_message ("%s: (%d) signalling and dequeuing handle %p", __func__, mono_thread_info_get_small_id (), mon->wait_list->data));
1221 SetEvent (mon->wait_list->data);
1222 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1227 ves_icall_System_Threading_Monitor_Monitor_wait (MonoObject *obj, guint32 ms)
1230 MonoThreadsSync *mon;
1234 gboolean success = FALSE;
1236 MonoInternalThread *thread = mono_thread_internal_current ();
1237 int id = mono_thread_info_get_small_id ();
1239 LOCK_DEBUG (g_message ("%s: (%d) Trying to wait for %p with timeout %dms", __func__, mono_thread_info_get_small_id (), obj, ms));
1241 lw.sync = obj->synchronisation;
1243 mono_monitor_ensure_owned (lw, id);
1245 if (!lock_word_is_inflated (lw)) {
1246 mono_monitor_inflate_owned (obj, id);
1247 lw.sync = obj->synchronisation;
1250 mon = lock_word_get_inflated_lock (lw);
1252 /* Do this WaitSleepJoin check before creating the event handle */
1253 mono_thread_current_check_pending_interrupt ();
1255 event = CreateEvent (NULL, FALSE, FALSE, NULL);
1256 if (event == NULL) {
1257 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Failed to set up wait event"));
1261 LOCK_DEBUG (g_message ("%s: (%d) queuing handle %p", __func__, mono_thread_info_get_small_id (), event));
1263 mono_thread_current_check_pending_interrupt ();
1265 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1267 mon->wait_list = g_slist_append (mon->wait_list, event);
1269 /* Save the nest count, and release the lock */
1272 mono_memory_write_barrier ();
1273 mono_monitor_exit_inflated (obj);
1275 LOCK_DEBUG (g_message ("%s: (%d) Unlocked %p lock %p", __func__, mono_thread_info_get_small_id (), obj, mon));
1277 /* There's no race between unlocking mon and waiting for the
1278 * event, because auto reset events are sticky, and this event
1279 * is private to this thread. Therefore even if the event was
1280 * signalled before we wait, we still succeed.
1283 ret = WaitForSingleObjectEx (event, ms, TRUE);
1286 /* Reset the thread state fairly early, so we don't have to worry
1287 * about the monitor error checking
1289 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1291 /* Regain the lock with the previous nest count */
1293 regain = mono_monitor_try_enter_inflated (obj, INFINITE, TRUE, id);
1294 /* We must regain the lock before handling interruption requests */
1295 } while (regain == -1);
1297 g_assert (regain == 1);
1301 LOCK_DEBUG (g_message ("%s: (%d) Regained %p lock %p", __func__, mono_thread_info_get_small_id (), obj, mon));
1303 if (ret == WAIT_TIMEOUT) {
1304 /* Poll the event again, just in case it was signalled
1305 * while we were trying to regain the monitor lock
1308 ret = WaitForSingleObjectEx (event, 0, FALSE);
1312 /* Pulse will have popped our event from the queue if it signalled
1313 * us, so we only do it here if the wait timed out.
1315 * This avoids a race condition where the thread holding the
1316 * lock can Pulse several times before the WaitForSingleObject
1317 * returns. If we popped the queue here then this event might
1318 * be signalled more than once, thereby starving another
1322 if (ret == WAIT_OBJECT_0) {
1323 LOCK_DEBUG (g_message ("%s: (%d) Success", __func__, mono_thread_info_get_small_id ()));
1326 LOCK_DEBUG (g_message ("%s: (%d) Wait failed, dequeuing handle %p", __func__, mono_thread_info_get_small_id (), event));
1327 /* No pulse, so we have to remove ourself from the
1330 mon->wait_list = g_slist_remove (mon->wait_list, event);
1332 CloseHandle (event);