2 * monitor.c: Monitor locking functions
5 * Dick Porter (dick@ximian.com)
7 * (C) 2003 Ximian, Inc.
14 #include <mono/metadata/monitor.h>
15 #include <mono/metadata/threads-types.h>
16 #include <mono/metadata/exception.h>
17 #include <mono/metadata/threads.h>
18 #include <mono/io-layer/io-layer.h>
19 #include <mono/metadata/object-internals.h>
20 #include <mono/metadata/class-internals.h>
21 #include <mono/metadata/gc-internal.h>
22 #include <mono/metadata/method-builder.h>
23 #include <mono/metadata/debug-helpers.h>
24 #include <mono/metadata/tabledefs.h>
25 #include <mono/metadata/marshal.h>
26 #include <mono/utils/mono-time.h>
29 * Pull the list of opcodes
31 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
35 #include "mono/cil/opcode.def"
40 /*#define LOCK_DEBUG(a) do { a; } while (0)*/
44 * The monitor implementation here is based on
45 * http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf and
46 * http://www.research.ibm.com/people/d/dfb/papers/Bacon98Thin.ps
48 * The Dice paper describes a technique for saving lock record space
49 * by returning records to a free list when they become unused. That
50 * sounds like unnecessary complexity to me, though if it becomes
51 * clear that unused lock records are taking up lots of space or we
52 * need to shave more time off by avoiding a malloc then we can always
53 * implement the free list idea later. The timeout parameter to
54 * try_enter voids some of the assumptions about the reference count
55 * field in Dice's implementation too. In his version, the thread
56 * attempting to lock a contended object will block until it succeeds,
57 * so the reference count will never be decremented while an object is
60 * Bacon's thin locks have a fast path that doesn't need a lock record
61 * for the common case of locking an unlocked or shallow-nested
62 * object, but the technique relies on encoding the thread ID in 15
63 * bits (to avoid too much per-object space overhead.) Unfortunately
64 * I don't think it's possible to reliably encode a pthread_t into 15
65 * bits. (The JVM implementation used seems to have a 15-bit
66 * per-thread identifier available.)
68 * This implementation then combines Dice's basic lock model with
69 * Bacon's simplification of keeping a lock record for the lifetime of
73 struct _MonoThreadsSync
75 gsize owner; /* thread ID */
77 #ifdef HAVE_MOVING_COLLECTOR
80 volatile gint32 entry_count;
86 typedef struct _MonitorArray MonitorArray;
88 struct _MonitorArray {
91 MonoThreadsSync monitors [MONO_ZERO_LEN_ARRAY];
94 #define mono_monitor_allocator_lock() EnterCriticalSection (&monitor_mutex)
95 #define mono_monitor_allocator_unlock() LeaveCriticalSection (&monitor_mutex)
96 static CRITICAL_SECTION monitor_mutex;
97 static MonoThreadsSync *monitor_freelist;
98 static MonitorArray *monitor_allocated;
99 static int array_size = 16;
101 #ifdef HAVE_KW_THREAD
102 static __thread gsize tls_pthread_self MONO_TLS_FAST;
105 #ifndef PLATFORM_WIN32
106 #ifdef HAVE_KW_THREAD
107 #define GetCurrentThreadId() tls_pthread_self
110 * The usual problem: we can't replace GetCurrentThreadId () with a macro because
111 * it is in a public header.
113 #define GetCurrentThreadId() ((gsize)pthread_self ())
118 mono_monitor_init (void)
120 InitializeCriticalSection (&monitor_mutex);
124 mono_monitor_cleanup (void)
126 /*DeleteCriticalSection (&monitor_mutex);*/
130 * mono_monitor_init_tls:
132 * Setup TLS variables used by the monitor code for the current thread.
135 mono_monitor_init_tls (void)
137 #if !defined(PLATFORM_WIN32) && defined(HAVE_KW_THREAD)
138 tls_pthread_self = pthread_self ();
143 monitor_is_on_freelist (MonoThreadsSync *mon)
145 MonitorArray *marray;
146 for (marray = monitor_allocated; marray; marray = marray->next) {
147 if (mon >= marray->monitors && mon < &marray->monitors [marray->num_monitors])
157 * Print a report on stdout of the managed locks currently held by
158 * threads. If @include_untaken is specified, list also inflated locks
160 * This is supposed to be used in debuggers like gdb.
163 mono_locks_dump (gboolean include_untaken)
166 int used = 0, on_freelist = 0, to_recycle = 0, total = 0, num_arrays = 0;
167 MonoThreadsSync *mon;
168 MonitorArray *marray;
169 for (mon = monitor_freelist; mon; mon = mon->data)
171 for (marray = monitor_allocated; marray; marray = marray->next) {
172 total += marray->num_monitors;
174 for (i = 0; i < marray->num_monitors; ++i) {
175 mon = &marray->monitors [i];
176 if (mon->data == NULL) {
177 if (i < marray->num_monitors - 1)
180 if (!monitor_is_on_freelist (mon->data)) {
181 MonoObject *holder = mono_gc_weak_link_get (&mon->data);
183 g_print ("Lock %p in object %p held by thread %p, nest level: %d\n",
184 mon, holder, (void*)mon->owner, mon->nest);
186 g_print ("\tWaiting on semaphore %p: %d\n", mon->entry_sem, mon->entry_count);
187 } else if (include_untaken) {
188 g_print ("Lock %p in object %p untaken\n", mon, holder);
195 g_print ("Total locks (in %d array(s)): %d, used: %d, on freelist: %d, to recycle: %d\n",
196 num_arrays, total, used, on_freelist, to_recycle);
199 /* LOCKING: this is called with monitor_mutex held */
201 mon_finalize (MonoThreadsSync *mon)
203 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Finalizing sync %p", mon));
205 if (mon->entry_sem != NULL) {
206 CloseHandle (mon->entry_sem);
207 mon->entry_sem = NULL;
209 /* If this isn't empty then something is seriously broken - it
210 * means a thread is still waiting on the object that owned
211 * this lock, but the object has been finalized.
213 g_assert (mon->wait_list == NULL);
215 mon->entry_count = 0;
216 /* owner and nest are set in mon_new, no need to zero them out */
218 mon->data = monitor_freelist;
219 monitor_freelist = mon;
220 mono_perfcounters->gc_sync_blocks--;
223 /* LOCKING: this is called with monitor_mutex held */
224 static MonoThreadsSync *
227 MonoThreadsSync *new;
229 if (!monitor_freelist) {
230 MonitorArray *marray;
232 /* see if any sync block has been collected */
234 for (marray = monitor_allocated; marray; marray = marray->next) {
235 for (i = 0; i < marray->num_monitors; ++i) {
236 if (marray->monitors [i].data == NULL) {
237 new = &marray->monitors [i];
238 new->data = monitor_freelist;
239 monitor_freelist = new;
242 /* small perf tweak to avoid scanning all the blocks */
246 /* need to allocate a new array of monitors */
247 if (!monitor_freelist) {
249 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": allocating more monitors: %d", array_size));
250 marray = g_malloc0 (sizeof (MonoArray) + array_size * sizeof (MonoThreadsSync));
251 marray->num_monitors = array_size;
253 /* link into the freelist */
254 for (i = 0; i < marray->num_monitors - 1; ++i) {
255 marray->monitors [i].data = &marray->monitors [i + 1];
257 marray->monitors [i].data = NULL; /* the last one */
258 monitor_freelist = &marray->monitors [0];
259 /* we happend the marray instead of prepending so that
260 * the collecting loop above will need to scan smaller arrays first
262 if (!monitor_allocated) {
263 monitor_allocated = marray;
265 last = monitor_allocated;
273 new = monitor_freelist;
274 monitor_freelist = new->data;
279 mono_perfcounters->gc_sync_blocks++;
284 * Format of the lock word:
285 * thinhash | fathash | data
287 * thinhash is the lower bit: if set data is the shifted hashcode of the object.
288 * fathash is another bit: if set the hash code is stored in the MonoThreadsSync
289 * struct pointed to by data
290 * if neither bit is set and data is non-NULL, data is a MonoThreadsSync
294 MonoThreadsSync *sync;
298 LOCK_WORD_THIN_HASH = 1,
299 LOCK_WORD_FAT_HASH = 1 << 1,
300 LOCK_WORD_BITS_MASK = 0x3,
301 LOCK_WORD_HASH_SHIFT = 2
304 #define MONO_OBJECT_ALIGNMENT_SHIFT 3
310 * Calculate a hash code for @obj that is constant while @obj is alive.
313 mono_object_hash (MonoObject* obj)
315 #ifdef HAVE_MOVING_COLLECTOR
320 lw.sync = obj->synchronisation;
321 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
322 /*g_print ("fast thin hash %d for obj %p store\n", (unsigned int)lw.lock_word >> LOCK_WORD_HASH_SHIFT, obj);*/
323 return (unsigned int)lw.lock_word >> LOCK_WORD_HASH_SHIFT;
325 if (lw.lock_word & LOCK_WORD_FAT_HASH) {
326 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
327 /*g_print ("fast fat hash %d for obj %p store\n", lw.sync->hash_code, obj);*/
328 return lw.sync->hash_code;
331 * while we are inside this function, the GC will keep this object pinned,
332 * since we are in the unmanaged stack. Thanks to this and to the hash
333 * function that depends only on the address, we can ignore the races if
334 * another thread computes the hash at the same time, because it'll end up
335 * with the same value.
337 hash = (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
338 /* clear the top bits as they can be discarded */
339 hash &= ~(LOCK_WORD_BITS_MASK << 30);
340 /* no hash flags were set, so it must be a MonoThreadsSync pointer if not NULL */
342 lw.sync->hash_code = hash;
343 /*g_print ("storing hash code %d for obj %p in sync %p\n", hash, obj, lw.sync);*/
344 lw.lock_word |= LOCK_WORD_FAT_HASH;
345 /* this is safe since we don't deflate locks */
346 obj->synchronisation = lw.sync;
348 /*g_print ("storing thin hash code %d for obj %p\n", hash, obj);*/
349 lw.lock_word = LOCK_WORD_THIN_HASH | (hash << LOCK_WORD_HASH_SHIFT);
350 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, NULL) == NULL)
352 /*g_print ("failed store\n");*/
353 /* someone set the hash flag or someone inflated the object */
354 lw.sync = obj->synchronisation;
355 if (lw.lock_word & LOCK_WORD_THIN_HASH)
357 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
358 lw.sync->hash_code = hash;
359 lw.lock_word |= LOCK_WORD_FAT_HASH;
360 /* this is safe since we don't deflate locks */
361 obj->synchronisation = lw.sync;
366 * Wang's address-based hash function:
367 * http://www.concentric.net/~Ttwang/tech/addrhash.htm
369 return (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
373 /* If allow_interruption==TRUE, the method will be interrumped if abort or suspend
374 * is requested. In this case it returns -1.
377 mono_monitor_try_enter_internal (MonoObject *obj, guint32 ms, gboolean allow_interruption)
379 MonoThreadsSync *mon;
380 gsize id = GetCurrentThreadId ();
382 guint32 then = 0, now, delta;
387 LOCK_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
388 ": (%d) Trying to lock object %p (%d ms)", id, obj, ms));
390 if (G_UNLIKELY (!obj)) {
391 mono_raise_exception (mono_get_exception_argument_null ("obj"));
396 mon = obj->synchronisation;
398 /* If the object has never been locked... */
399 if (G_UNLIKELY (mon == NULL)) {
400 mono_monitor_allocator_lock ();
402 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, mon, NULL) == NULL) {
403 mono_gc_weak_link_add (&mon->data, obj);
404 mono_monitor_allocator_unlock ();
405 /* Successfully locked */
408 #ifdef HAVE_MOVING_COLLECTOR
410 lw.sync = obj->synchronisation;
411 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
412 MonoThreadsSync *oldlw = lw.sync;
413 /* move the already calculated hash */
414 mon->hash_code = lw.lock_word >> LOCK_WORD_HASH_SHIFT;
416 lw.lock_word |= LOCK_WORD_FAT_HASH;
417 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, oldlw) == oldlw) {
418 mono_gc_weak_link_add (&mon->data, obj);
419 mono_monitor_allocator_unlock ();
420 /* Successfully locked */
424 mono_monitor_allocator_unlock ();
427 } else if (lw.lock_word & LOCK_WORD_FAT_HASH) {
429 mono_monitor_allocator_unlock ();
430 /* get the old lock without the fat hash bit */
431 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
435 mono_monitor_allocator_unlock ();
436 mon = obj->synchronisation;
440 mono_monitor_allocator_unlock ();
441 mon = obj->synchronisation;
445 #ifdef HAVE_MOVING_COLLECTOR
448 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
449 MonoThreadsSync *oldlw = lw.sync;
450 mono_monitor_allocator_lock ();
452 /* move the already calculated hash */
453 mon->hash_code = lw.lock_word >> LOCK_WORD_HASH_SHIFT;
455 lw.lock_word |= LOCK_WORD_FAT_HASH;
456 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, oldlw) == oldlw) {
457 mono_gc_weak_link_add (&mon->data, obj);
458 mono_monitor_allocator_unlock ();
459 /* Successfully locked */
463 mono_monitor_allocator_unlock ();
470 #ifdef HAVE_MOVING_COLLECTOR
474 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
479 /* If the object has previously been locked but isn't now... */
481 /* This case differs from Dice's case 3 because we don't
482 * deflate locks or cache unused lock records
484 if (G_LIKELY (mon->owner == 0)) {
485 /* Try to install our ID in the owner field, nest
486 * should have been left at 1 by the previous unlock
489 if (G_LIKELY (InterlockedCompareExchangePointer ((gpointer *)&mon->owner, (gpointer)id, 0) == 0)) {
491 g_assert (mon->nest == 1);
499 /* If the object is currently locked by this thread... */
500 if (mon->owner == id) {
505 /* The object must be locked by someone else... */
506 mono_perfcounters->thread_contentions++;
508 /* If ms is 0 we don't block, but just fail straight away */
510 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) timed out, returning FALSE", id));
514 /* The slow path begins here. We need to make sure theres a
515 * semaphore handle (creating it if necessary), and block on
518 if (mon->entry_sem == NULL) {
519 /* Create the semaphore */
520 sem = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
521 g_assert (sem != NULL);
522 if (InterlockedCompareExchangePointer ((gpointer*)&mon->entry_sem, sem, NULL) != NULL) {
523 /* Someone else just put a handle here */
528 /* If we need to time out, record a timestamp and adjust ms,
529 * because WaitForSingleObject doesn't tell us how long it
532 * Don't block forever here, because theres a chance the owner
533 * thread released the lock while we were creating the
534 * semaphore: we would not get the wakeup. Using the event
535 * handle technique from pulse/wait would involve locking the
536 * lock struct and therefore slowing down the fast path.
538 if (ms != INFINITE) {
539 then = mono_msec_ticks ();
549 InterlockedIncrement (&mon->entry_count);
551 mono_perfcounters->thread_queue_len++;
552 mono_perfcounters->thread_queue_max++;
553 thread = mono_thread_current ();
555 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
558 * We pass TRUE instead of allow_interruption since we have to check for the
559 * StopRequested case below.
561 ret = WaitForSingleObjectEx (mon->entry_sem, waitms, TRUE);
563 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
565 InterlockedDecrement (&mon->entry_count);
566 mono_perfcounters->thread_queue_len--;
568 if (ms != INFINITE) {
569 now = mono_msec_ticks ();
572 /* The counter must have wrapped around */
573 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
574 ": wrapped around! now=0x%x then=0x%x", now, then));
576 now += (0xffffffff - then);
579 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": wrap rejig: now=0x%x then=0x%x delta=0x%x", now, then, now-then));
589 if ((ret == WAIT_TIMEOUT || (ret == WAIT_IO_COMPLETION && !allow_interruption)) && ms > 0) {
594 if (ret == WAIT_TIMEOUT || (ret == WAIT_IO_COMPLETION && !allow_interruption)) {
595 if (ret == WAIT_IO_COMPLETION && mono_thread_test_state (mono_thread_current (), ThreadState_StopRequested)) {
597 * We have to obey a stop request even if allow_interruption is
598 * FALSE to avoid hangs at shutdown.
602 /* Infinite wait, so just try again */
607 if (ret == WAIT_OBJECT_0) {
608 /* retry from the top */
612 /* We must have timed out */
613 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) timed out waiting, returning FALSE", id));
615 if (ret == WAIT_IO_COMPLETION)
622 mono_monitor_enter (MonoObject *obj)
624 return mono_monitor_try_enter_internal (obj, INFINITE, FALSE) == 1;
628 mono_monitor_try_enter (MonoObject *obj, guint32 ms)
630 return mono_monitor_try_enter_internal (obj, ms, FALSE) == 1;
634 mono_monitor_exit (MonoObject *obj)
636 MonoThreadsSync *mon;
639 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Unlocking %p", GetCurrentThreadId (), obj));
641 if (G_UNLIKELY (!obj)) {
642 mono_raise_exception (mono_get_exception_argument_null ("obj"));
646 mon = obj->synchronisation;
648 #ifdef HAVE_MOVING_COLLECTOR
652 if (lw.lock_word & LOCK_WORD_THIN_HASH)
654 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
658 if (G_UNLIKELY (mon == NULL)) {
659 /* No one ever used Enter. Just ignore the Exit request as MS does */
662 if (G_UNLIKELY (mon->owner != GetCurrentThreadId ())) {
666 nest = mon->nest - 1;
668 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
669 ": (%d) Object %p is now unlocked", GetCurrentThreadId (), obj));
671 /* object is now unlocked, leave nest==1 so we don't
672 * need to set it when the lock is reacquired
676 /* Do the wakeup stuff. It's possible that the last
677 * blocking thread gave up waiting just before we
678 * release the semaphore resulting in a futile wakeup
679 * next time there's contention for this object, but
680 * it means we don't have to waste time locking the
683 if (mon->entry_count > 0) {
684 ReleaseSemaphore (mon->entry_sem, 1, NULL);
687 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
688 ": (%d) Object %p is now locked %d times", GetCurrentThreadId (), obj, nest));
694 emit_obj_syncp_check (MonoMethodBuilder *mb, int syncp_loc, int *obj_null_branch, int *syncp_true_false_branch,
695 gboolean branch_on_true)
702 mono_mb_emit_byte (mb, CEE_LDARG_0);
703 *obj_null_branch = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
708 ldc.i4 G_STRUCT_OFFSET(MonoObject, synchronisation) objp off
713 brtrue/false.s syncp_true_false
716 mono_mb_emit_byte (mb, CEE_LDARG_0);
717 mono_mb_emit_byte (mb, CEE_CONV_I);
718 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoObject, synchronisation));
719 mono_mb_emit_byte (mb, CEE_ADD);
720 mono_mb_emit_byte (mb, CEE_LDIND_I);
721 mono_mb_emit_stloc (mb, syncp_loc);
722 mono_mb_emit_ldloc (mb, syncp_loc);
723 *syncp_true_false_branch = mono_mb_emit_short_branch (mb, branch_on_true ? CEE_BRTRUE_S : CEE_BRFALSE_S);
727 mono_monitor_get_fast_enter_method (MonoMethod *monitor_enter_method)
729 static MonoMethod *fast_monitor_enter;
730 static MonoMethod *compare_exchange_method;
732 MonoMethodBuilder *mb;
733 int obj_null_branch, syncp_null_branch, has_owner_branch, other_owner_branch, tid_branch;
734 int tid_loc, syncp_loc, owner_loc;
735 int thread_tls_offset;
737 #ifdef HAVE_MOVING_COLLECTOR
741 thread_tls_offset = mono_thread_get_tls_offset ();
742 if (thread_tls_offset == -1)
745 if (fast_monitor_enter)
746 return fast_monitor_enter;
748 if (!compare_exchange_method) {
749 MonoMethodDesc *desc;
752 desc = mono_method_desc_new ("Interlocked:CompareExchange(intptr&,intptr,intptr)", FALSE);
753 class = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
754 compare_exchange_method = mono_method_desc_search_in_class (desc, class);
755 mono_method_desc_free (desc);
757 if (!compare_exchange_method)
761 mb = mono_mb_new (mono_defaults.monitor_class, "FastMonitorEnter", MONO_WRAPPER_UNKNOWN);
763 mb->method->slot = -1;
764 mb->method->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_STATIC |
765 METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
767 tid_loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
768 syncp_loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
769 owner_loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
771 emit_obj_syncp_check (mb, syncp_loc, &obj_null_branch, &syncp_null_branch, FALSE);
774 mono. tls thread_tls_offset threadp
775 ldc.i4 G_STRUCT_OFFSET(MonoThread, tid) threadp off
780 ldc.i4 G_STRUCT_OFFSET(MonoThreadsSync, owner) syncp off
788 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
789 mono_mb_emit_byte (mb, CEE_MONO_TLS);
790 mono_mb_emit_i4 (mb, thread_tls_offset);
791 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThread, tid));
792 mono_mb_emit_byte (mb, CEE_ADD);
793 mono_mb_emit_byte (mb, CEE_LDIND_I);
794 mono_mb_emit_stloc (mb, tid_loc);
795 mono_mb_emit_ldloc (mb, syncp_loc);
796 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, owner));
797 mono_mb_emit_byte (mb, CEE_ADD);
798 mono_mb_emit_byte (mb, CEE_LDIND_I);
799 mono_mb_emit_stloc (mb, owner_loc);
800 mono_mb_emit_ldloc (mb, owner_loc);
801 tid_branch = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
805 ldc.i4 G_STRUCT_OFFSET(MonoThreadsSync, owner) syncp off
808 ldc.i4 0 &owner tid 0
809 call System.Threading.Interlocked.CompareExchange oldowner
814 mono_mb_emit_ldloc (mb, syncp_loc);
815 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, owner));
816 mono_mb_emit_byte (mb, CEE_ADD);
817 mono_mb_emit_ldloc (mb, tid_loc);
818 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
819 mono_mb_emit_managed_call (mb, compare_exchange_method, NULL);
820 has_owner_branch = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
821 mono_mb_emit_byte (mb, CEE_RET);
829 ldc.i4 G_STRUCT_OFFSET(MonoThreadsSync, nest) syncp off
833 ldc.i4 1 &nest nest 1
839 mono_mb_patch_short_branch (mb, tid_branch);
840 mono_mb_emit_ldloc (mb, owner_loc);
841 mono_mb_emit_ldloc (mb, tid_loc);
842 other_owner_branch = mono_mb_emit_short_branch (mb, CEE_BNE_UN_S);
843 mono_mb_emit_ldloc (mb, syncp_loc);
844 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, nest));
845 mono_mb_emit_byte (mb, CEE_ADD);
846 mono_mb_emit_byte (mb, CEE_DUP);
847 mono_mb_emit_byte (mb, CEE_LDIND_I4);
848 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
849 mono_mb_emit_byte (mb, CEE_ADD);
850 mono_mb_emit_byte (mb, CEE_STIND_I4);
851 mono_mb_emit_byte (mb, CEE_RET);
854 obj_null, syncp_null, has_owner, other_owner:
856 call System.Threading.Monitor.Enter
860 mono_mb_patch_short_branch (mb, obj_null_branch);
861 mono_mb_patch_short_branch (mb, syncp_null_branch);
862 mono_mb_patch_short_branch (mb, has_owner_branch);
863 mono_mb_patch_short_branch (mb, other_owner_branch);
864 mono_mb_emit_byte (mb, CEE_LDARG_0);
865 mono_mb_emit_managed_call (mb, monitor_enter_method, NULL);
866 mono_mb_emit_byte (mb, CEE_RET);
868 fast_monitor_enter = mono_mb_create_method (mb, mono_signature_no_pinvoke (monitor_enter_method), 5);
871 return fast_monitor_enter;
875 mono_monitor_get_fast_exit_method (MonoMethod *monitor_exit_method)
877 static MonoMethod *fast_monitor_exit;
879 MonoMethodBuilder *mb;
880 int obj_null_branch, has_waiting_branch, has_syncp_branch, owned_branch, nested_branch;
881 int thread_tls_offset;
884 #ifdef HAVE_MOVING_COLLECTOR
888 thread_tls_offset = mono_thread_get_tls_offset ();
889 if (thread_tls_offset == -1)
892 if (fast_monitor_exit)
893 return fast_monitor_exit;
895 mb = mono_mb_new (mono_defaults.monitor_class, "FastMonitorExit", MONO_WRAPPER_UNKNOWN);
897 mb->method->slot = -1;
898 mb->method->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_STATIC |
899 METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
901 syncp_loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
903 emit_obj_syncp_check (mb, syncp_loc, &obj_null_branch, &has_syncp_branch, TRUE);
909 mono_mb_emit_byte (mb, CEE_RET);
914 ldc.i4 G_STRUCT_OFFSET(MonoThreadsSync, owner) syncp off
917 mono. tls thread_tls_offset owner threadp
918 ldc.i4 G_STRUCT_OFFSET(MonoThread, tid) owner threadp off
924 mono_mb_patch_short_branch (mb, has_syncp_branch);
925 mono_mb_emit_ldloc (mb, syncp_loc);
926 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, owner));
927 mono_mb_emit_byte (mb, CEE_ADD);
928 mono_mb_emit_byte (mb, CEE_LDIND_I);
929 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
930 mono_mb_emit_byte (mb, CEE_MONO_TLS);
931 mono_mb_emit_i4 (mb, thread_tls_offset);
932 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThread, tid));
933 mono_mb_emit_byte (mb, CEE_ADD);
934 mono_mb_emit_byte (mb, CEE_LDIND_I);
935 owned_branch = mono_mb_emit_short_branch (mb, CEE_BEQ_S);
941 mono_mb_emit_byte (mb, CEE_RET);
946 ldc.i4 G_STRUCT_OFFSET(MonoThreadsSync, nest) syncp off
951 ldc.i4 1 &nest nest nest 1
952 bgt.un.s nested &nest nest
955 mono_mb_patch_short_branch (mb, owned_branch);
956 mono_mb_emit_ldloc (mb, syncp_loc);
957 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, nest));
958 mono_mb_emit_byte (mb, CEE_ADD);
959 mono_mb_emit_byte (mb, CEE_DUP);
960 mono_mb_emit_byte (mb, CEE_LDIND_I4);
961 mono_mb_emit_byte (mb, CEE_DUP);
962 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
963 nested_branch = mono_mb_emit_short_branch (mb, CEE_BGT_UN_S);
969 ldc.i4 G_STRUCT_OFFSET(MonoThreadsSync, entry_count) syncp off
975 mono_mb_emit_byte (mb, CEE_POP);
976 mono_mb_emit_byte (mb, CEE_POP);
977 mono_mb_emit_ldloc (mb, syncp_loc);
978 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, entry_count));
979 mono_mb_emit_byte (mb, CEE_ADD);
980 mono_mb_emit_byte (mb, CEE_LDIND_I4);
981 has_waiting_branch = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
985 ldc.i4 G_STRUCT_OFFSET(MonoThreadsSync, owner) syncp off
992 mono_mb_emit_ldloc (mb, syncp_loc);
993 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, owner));
994 mono_mb_emit_byte (mb, CEE_ADD);
995 mono_mb_emit_byte (mb, CEE_LDNULL);
996 mono_mb_emit_byte (mb, CEE_STIND_I);
997 mono_mb_emit_byte (mb, CEE_RET);
1001 ldc.i4 1 &nest nest 1
1007 mono_mb_patch_short_branch (mb, nested_branch);
1008 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1009 mono_mb_emit_byte (mb, CEE_SUB);
1010 mono_mb_emit_byte (mb, CEE_STIND_I4);
1011 mono_mb_emit_byte (mb, CEE_RET);
1014 obj_null, has_waiting:
1016 call System.Threading.Monitor.Exit
1020 mono_mb_patch_short_branch (mb, obj_null_branch);
1021 mono_mb_patch_short_branch (mb, has_waiting_branch);
1022 mono_mb_emit_byte (mb, CEE_LDARG_0);
1023 mono_mb_emit_managed_call (mb, monitor_exit_method, NULL);
1024 mono_mb_emit_byte (mb, CEE_RET);
1026 fast_monitor_exit = mono_mb_create_method (mb, mono_signature_no_pinvoke (monitor_exit_method), 5);
1029 return fast_monitor_exit;
1033 mono_monitor_get_fast_path (MonoMethod *enter_or_exit)
1035 if (strcmp (enter_or_exit->name, "Enter") == 0)
1036 return mono_monitor_get_fast_enter_method (enter_or_exit);
1037 if (strcmp (enter_or_exit->name, "Exit") == 0)
1038 return mono_monitor_get_fast_exit_method (enter_or_exit);
1039 g_assert_not_reached ();
1044 * mono_monitor_threads_sync_member_offset:
1045 * @owner_offset: returns size and offset of the "owner" member
1046 * @nest_offset: returns size and offset of the "nest" member
1047 * @entry_count_offset: returns size and offset of the "entry_count" member
1049 * Returns the offsets and sizes of three members of the
1050 * MonoThreadsSync struct. The Monitor ASM fastpaths need this.
1053 mono_monitor_threads_sync_members_offset (int *owner_offset, int *nest_offset, int *entry_count_offset)
1057 #define ENCODE_OFF_SIZE(o,s) (((o) << 8) | ((s) & 0xff))
1059 *owner_offset = ENCODE_OFF_SIZE (G_STRUCT_OFFSET (MonoThreadsSync, owner), sizeof (ts.owner));
1060 *nest_offset = ENCODE_OFF_SIZE (G_STRUCT_OFFSET (MonoThreadsSync, nest), sizeof (ts.nest));
1061 *entry_count_offset = ENCODE_OFF_SIZE (G_STRUCT_OFFSET (MonoThreadsSync, entry_count), sizeof (ts.entry_count));
1065 ves_icall_System_Threading_Monitor_Monitor_try_enter (MonoObject *obj, guint32 ms)
1070 res = mono_monitor_try_enter_internal (obj, ms, TRUE);
1072 mono_thread_interruption_checkpoint ();
1073 } while (res == -1);
1079 ves_icall_System_Threading_Monitor_Monitor_test_owner (MonoObject *obj)
1081 MonoThreadsSync *mon;
1083 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1084 ": Testing if %p is owned by thread %d", obj, GetCurrentThreadId()));
1086 mon = obj->synchronisation;
1087 #ifdef HAVE_MOVING_COLLECTOR
1091 if (lw.lock_word & LOCK_WORD_THIN_HASH)
1093 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1101 if(mon->owner==GetCurrentThreadId ()) {
1109 ves_icall_System_Threading_Monitor_Monitor_test_synchronised (MonoObject *obj)
1111 MonoThreadsSync *mon;
1113 LOCK_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
1114 ": (%d) Testing if %p is owned by any thread", GetCurrentThreadId (), obj));
1116 mon = obj->synchronisation;
1117 #ifdef HAVE_MOVING_COLLECTOR
1121 if (lw.lock_word & LOCK_WORD_THIN_HASH)
1123 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1131 if (mon->owner != 0) {
1138 /* All wait list manipulation in the pulse, pulseall and wait
1139 * functions happens while the monitor lock is held, so we don't need
1140 * any extra struct locking
1144 ves_icall_System_Threading_Monitor_Monitor_pulse (MonoObject *obj)
1146 MonoThreadsSync *mon;
1148 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Pulsing %p",
1149 GetCurrentThreadId (), obj));
1151 mon = obj->synchronisation;
1152 #ifdef HAVE_MOVING_COLLECTOR
1156 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
1157 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1160 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1165 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1168 if (mon->owner != GetCurrentThreadId ()) {
1169 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
1173 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) %d threads waiting",
1174 GetCurrentThreadId (), g_slist_length (mon->wait_list)));
1176 if (mon->wait_list != NULL) {
1177 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1178 ": (%d) signalling and dequeuing handle %p",
1179 GetCurrentThreadId (), mon->wait_list->data));
1181 SetEvent (mon->wait_list->data);
1182 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1187 ves_icall_System_Threading_Monitor_Monitor_pulse_all (MonoObject *obj)
1189 MonoThreadsSync *mon;
1191 LOCK_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Pulsing all %p",
1192 GetCurrentThreadId (), obj));
1194 mon = obj->synchronisation;
1195 #ifdef HAVE_MOVING_COLLECTOR
1199 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
1200 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1203 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1208 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1211 if (mon->owner != GetCurrentThreadId ()) {
1212 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
1216 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) %d threads waiting",
1217 GetCurrentThreadId (), g_slist_length (mon->wait_list)));
1219 while (mon->wait_list != NULL) {
1220 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1221 ": (%d) signalling and dequeuing handle %p",
1222 GetCurrentThreadId (), mon->wait_list->data));
1224 SetEvent (mon->wait_list->data);
1225 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1230 ves_icall_System_Threading_Monitor_Monitor_wait (MonoObject *obj, guint32 ms)
1232 MonoThreadsSync *mon;
1236 gboolean success = FALSE;
1238 MonoThread *thread = mono_thread_current ();
1240 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
1241 ": (%d) Trying to wait for %p with timeout %dms",
1242 GetCurrentThreadId (), obj, ms));
1244 mon = obj->synchronisation;
1245 #ifdef HAVE_MOVING_COLLECTOR
1249 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
1250 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1253 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1258 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1261 if (mon->owner != GetCurrentThreadId ()) {
1262 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
1266 /* Do this WaitSleepJoin check before creating the event handle */
1267 mono_thread_current_check_pending_interrupt ();
1269 event = CreateEvent (NULL, FALSE, FALSE, NULL);
1270 if (event == NULL) {
1271 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to set up wait event"));
1275 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) queuing handle %p",
1276 GetCurrentThreadId (), event));
1278 mono_thread_current_check_pending_interrupt ();
1280 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1282 mon->wait_list = g_slist_append (mon->wait_list, event);
1284 /* Save the nest count, and release the lock */
1287 mono_monitor_exit (obj);
1289 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Unlocked %p lock %p",
1290 GetCurrentThreadId (), obj, mon));
1292 /* There's no race between unlocking mon and waiting for the
1293 * event, because auto reset events are sticky, and this event
1294 * is private to this thread. Therefore even if the event was
1295 * signalled before we wait, we still succeed.
1297 ret = WaitForSingleObjectEx (event, ms, TRUE);
1299 /* Reset the thread state fairly early, so we don't have to worry
1300 * about the monitor error checking
1302 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1304 if (mono_thread_interruption_requested ()) {
1305 CloseHandle (event);
1309 /* Regain the lock with the previous nest count */
1311 regain = mono_monitor_try_enter_internal (obj, INFINITE, TRUE);
1313 mono_thread_interruption_checkpoint ();
1314 } while (regain == -1);
1317 /* Something went wrong, so throw a
1318 * SynchronizationLockException
1320 CloseHandle (event);
1321 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to regain lock"));
1327 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Regained %p lock %p",
1328 GetCurrentThreadId (), obj, mon));
1330 if (ret == WAIT_TIMEOUT) {
1331 /* Poll the event again, just in case it was signalled
1332 * while we were trying to regain the monitor lock
1334 ret = WaitForSingleObjectEx (event, 0, FALSE);
1337 /* Pulse will have popped our event from the queue if it signalled
1338 * us, so we only do it here if the wait timed out.
1340 * This avoids a race condition where the thread holding the
1341 * lock can Pulse several times before the WaitForSingleObject
1342 * returns. If we popped the queue here then this event might
1343 * be signalled more than once, thereby starving another
1347 if (ret == WAIT_OBJECT_0) {
1348 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Success",
1349 GetCurrentThreadId ()));
1352 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed, dequeuing handle %p",
1353 GetCurrentThreadId (), event));
1354 /* No pulse, so we have to remove ourself from the
1357 mon->wait_list = g_slist_remove (mon->wait_list, event);
1359 CloseHandle (event);