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)
15 #include <mono/metadata/monitor.h>
16 #include <mono/metadata/threads-types.h>
17 #include <mono/metadata/exception.h>
18 #include <mono/metadata/threads.h>
19 #include <mono/io-layer/io-layer.h>
20 #include <mono/metadata/object-internals.h>
21 #include <mono/metadata/class-internals.h>
22 #include <mono/metadata/gc-internal.h>
23 #include <mono/metadata/method-builder.h>
24 #include <mono/metadata/debug-helpers.h>
25 #include <mono/metadata/tabledefs.h>
26 #include <mono/metadata/marshal.h>
27 #include <mono/metadata/profiler-private.h>
28 #include <mono/utils/mono-time.h>
31 * Pull the list of opcodes
33 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
37 #include "mono/cil/opcode.def"
42 /*#define LOCK_DEBUG(a) do { a; } while (0)*/
46 * The monitor implementation here is based on
47 * http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf and
48 * http://www.research.ibm.com/people/d/dfb/papers/Bacon98Thin.ps
50 * The Dice paper describes a technique for saving lock record space
51 * by returning records to a free list when they become unused. That
52 * sounds like unnecessary complexity to me, though if it becomes
53 * clear that unused lock records are taking up lots of space or we
54 * need to shave more time off by avoiding a malloc then we can always
55 * implement the free list idea later. The timeout parameter to
56 * try_enter voids some of the assumptions about the reference count
57 * field in Dice's implementation too. In his version, the thread
58 * attempting to lock a contended object will block until it succeeds,
59 * so the reference count will never be decremented while an object is
62 * Bacon's thin locks have a fast path that doesn't need a lock record
63 * for the common case of locking an unlocked or shallow-nested
64 * object, but the technique relies on encoding the thread ID in 15
65 * bits (to avoid too much per-object space overhead.) Unfortunately
66 * I don't think it's possible to reliably encode a pthread_t into 15
67 * bits. (The JVM implementation used seems to have a 15-bit
68 * per-thread identifier available.)
70 * This implementation then combines Dice's basic lock model with
71 * Bacon's simplification of keeping a lock record for the lifetime of
75 struct _MonoThreadsSync
77 gsize owner; /* thread ID */
79 #ifdef HAVE_MOVING_COLLECTOR
82 volatile gint32 entry_count;
88 typedef struct _MonitorArray MonitorArray;
90 struct _MonitorArray {
93 MonoThreadsSync monitors [MONO_ZERO_LEN_ARRAY];
96 #define mono_monitor_allocator_lock() EnterCriticalSection (&monitor_mutex)
97 #define mono_monitor_allocator_unlock() LeaveCriticalSection (&monitor_mutex)
98 static CRITICAL_SECTION monitor_mutex;
99 static MonoThreadsSync *monitor_freelist;
100 static MonitorArray *monitor_allocated;
101 static int array_size = 16;
103 #ifdef HAVE_KW_THREAD
104 static __thread gsize tls_pthread_self MONO_TLS_FAST;
108 #ifdef HAVE_KW_THREAD
109 #define GetCurrentThreadId() tls_pthread_self
112 * The usual problem: we can't replace GetCurrentThreadId () with a macro because
113 * it is in a public header.
115 #define GetCurrentThreadId() ((gsize)pthread_self ())
120 mono_monitor_init (void)
122 InitializeCriticalSection (&monitor_mutex);
126 mono_monitor_cleanup (void)
128 MonoThreadsSync *mon;
129 /* MonitorArray *marray, *next = NULL; */
131 /*DeleteCriticalSection (&monitor_mutex);*/
133 /* The monitors on the freelist don't have weak links - mark them */
134 for (mon = monitor_freelist; mon; mon = mon->data)
135 mon->wait_list = (gpointer)-1;
137 /* FIXME: This still crashes with sgen (async_read.exe) */
139 for (marray = monitor_allocated; marray; marray = next) {
142 for (i = 0; i < marray->num_monitors; ++i) {
143 mon = &marray->monitors [i];
144 if (mon->wait_list != (gpointer)-1)
145 mono_gc_weak_link_remove (&mon->data);
155 * mono_monitor_init_tls:
157 * Setup TLS variables used by the monitor code for the current thread.
160 mono_monitor_init_tls (void)
162 #if !defined(HOST_WIN32) && defined(HAVE_KW_THREAD)
163 tls_pthread_self = pthread_self ();
168 monitor_is_on_freelist (MonoThreadsSync *mon)
170 MonitorArray *marray;
171 for (marray = monitor_allocated; marray; marray = marray->next) {
172 if (mon >= marray->monitors && mon < &marray->monitors [marray->num_monitors])
182 * Print a report on stdout of the managed locks currently held by
183 * threads. If @include_untaken is specified, list also inflated locks
185 * This is supposed to be used in debuggers like gdb.
188 mono_locks_dump (gboolean include_untaken)
191 int used = 0, on_freelist = 0, to_recycle = 0, total = 0, num_arrays = 0;
192 MonoThreadsSync *mon;
193 MonitorArray *marray;
194 for (mon = monitor_freelist; mon; mon = mon->data)
196 for (marray = monitor_allocated; marray; marray = marray->next) {
197 total += marray->num_monitors;
199 for (i = 0; i < marray->num_monitors; ++i) {
200 mon = &marray->monitors [i];
201 if (mon->data == NULL) {
202 if (i < marray->num_monitors - 1)
205 if (!monitor_is_on_freelist (mon->data)) {
206 MonoObject *holder = mono_gc_weak_link_get (&mon->data);
208 g_print ("Lock %p in object %p held by thread %p, nest level: %d\n",
209 mon, holder, (void*)mon->owner, mon->nest);
211 g_print ("\tWaiting on semaphore %p: %d\n", mon->entry_sem, mon->entry_count);
212 } else if (include_untaken) {
213 g_print ("Lock %p in object %p untaken\n", mon, holder);
220 g_print ("Total locks (in %d array(s)): %d, used: %d, on freelist: %d, to recycle: %d\n",
221 num_arrays, total, used, on_freelist, to_recycle);
224 /* LOCKING: this is called with monitor_mutex held */
226 mon_finalize (MonoThreadsSync *mon)
228 LOCK_DEBUG (g_message ("%s: Finalizing sync %p", __func__, mon));
230 if (mon->entry_sem != NULL) {
231 CloseHandle (mon->entry_sem);
232 mon->entry_sem = NULL;
234 /* If this isn't empty then something is seriously broken - it
235 * means a thread is still waiting on the object that owned
236 * this lock, but the object has been finalized.
238 g_assert (mon->wait_list == NULL);
240 mon->entry_count = 0;
241 /* owner and nest are set in mon_new, no need to zero them out */
243 mon->data = monitor_freelist;
244 monitor_freelist = mon;
245 mono_perfcounters->gc_sync_blocks--;
248 /* LOCKING: this is called with monitor_mutex held */
249 static MonoThreadsSync *
252 MonoThreadsSync *new;
254 if (!monitor_freelist) {
255 MonitorArray *marray;
257 /* see if any sync block has been collected */
259 for (marray = monitor_allocated; marray; marray = marray->next) {
260 for (i = 0; i < marray->num_monitors; ++i) {
261 if (marray->monitors [i].data == NULL) {
262 new = &marray->monitors [i];
263 if (new->wait_list) {
264 /* Orphaned events left by aborted threads */
265 while (new->wait_list) {
266 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d): Closing orphaned event %d", GetCurrentThreadId (), new->wait_list->data));
267 CloseHandle (new->wait_list->data);
268 new->wait_list = g_slist_remove (new->wait_list, new->wait_list->data);
271 mono_gc_weak_link_remove (&new->data);
272 new->data = monitor_freelist;
273 monitor_freelist = new;
276 /* small perf tweak to avoid scanning all the blocks */
280 /* need to allocate a new array of monitors */
281 if (!monitor_freelist) {
283 LOCK_DEBUG (g_message ("%s: allocating more monitors: %d", __func__, array_size));
284 marray = g_malloc0 (sizeof (MonoArray) + array_size * sizeof (MonoThreadsSync));
285 marray->num_monitors = array_size;
287 /* link into the freelist */
288 for (i = 0; i < marray->num_monitors - 1; ++i) {
289 marray->monitors [i].data = &marray->monitors [i + 1];
291 marray->monitors [i].data = NULL; /* the last one */
292 monitor_freelist = &marray->monitors [0];
293 /* we happend the marray instead of prepending so that
294 * the collecting loop above will need to scan smaller arrays first
296 if (!monitor_allocated) {
297 monitor_allocated = marray;
299 last = monitor_allocated;
307 new = monitor_freelist;
308 monitor_freelist = new->data;
313 mono_perfcounters->gc_sync_blocks++;
318 * Format of the lock word:
319 * thinhash | fathash | data
321 * thinhash is the lower bit: if set data is the shifted hashcode of the object.
322 * fathash is another bit: if set the hash code is stored in the MonoThreadsSync
323 * struct pointed to by data
324 * if neither bit is set and data is non-NULL, data is a MonoThreadsSync
328 MonoThreadsSync *sync;
332 LOCK_WORD_THIN_HASH = 1,
333 LOCK_WORD_FAT_HASH = 1 << 1,
334 LOCK_WORD_BITS_MASK = 0x3,
335 LOCK_WORD_HASH_SHIFT = 2
338 #define MONO_OBJECT_ALIGNMENT_SHIFT 3
344 * Calculate a hash code for @obj that is constant while @obj is alive.
347 mono_object_hash (MonoObject* obj)
349 #ifdef HAVE_MOVING_COLLECTOR
354 lw.sync = obj->synchronisation;
355 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
356 /*g_print ("fast thin hash %d for obj %p store\n", (unsigned int)lw.lock_word >> LOCK_WORD_HASH_SHIFT, obj);*/
357 return (unsigned int)lw.lock_word >> LOCK_WORD_HASH_SHIFT;
359 if (lw.lock_word & LOCK_WORD_FAT_HASH) {
360 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
361 /*g_print ("fast fat hash %d for obj %p store\n", lw.sync->hash_code, obj);*/
362 return lw.sync->hash_code;
365 * while we are inside this function, the GC will keep this object pinned,
366 * since we are in the unmanaged stack. Thanks to this and to the hash
367 * function that depends only on the address, we can ignore the races if
368 * another thread computes the hash at the same time, because it'll end up
369 * with the same value.
371 hash = (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
372 /* clear the top bits as they can be discarded */
373 hash &= ~(LOCK_WORD_BITS_MASK << 30);
374 /* no hash flags were set, so it must be a MonoThreadsSync pointer if not NULL */
376 lw.sync->hash_code = hash;
377 /*g_print ("storing hash code %d for obj %p in sync %p\n", hash, obj, lw.sync);*/
378 lw.lock_word |= LOCK_WORD_FAT_HASH;
379 /* this is safe since we don't deflate locks */
380 obj->synchronisation = lw.sync;
382 /*g_print ("storing thin hash code %d for obj %p\n", hash, obj);*/
383 lw.lock_word = LOCK_WORD_THIN_HASH | (hash << LOCK_WORD_HASH_SHIFT);
384 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, NULL) == NULL)
386 /*g_print ("failed store\n");*/
387 /* someone set the hash flag or someone inflated the object */
388 lw.sync = obj->synchronisation;
389 if (lw.lock_word & LOCK_WORD_THIN_HASH)
391 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
392 lw.sync->hash_code = hash;
393 lw.lock_word |= LOCK_WORD_FAT_HASH;
394 /* this is safe since we don't deflate locks */
395 obj->synchronisation = lw.sync;
400 * Wang's address-based hash function:
401 * http://www.concentric.net/~Ttwang/tech/addrhash.htm
403 return (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
407 /* If allow_interruption==TRUE, the method will be interrumped if abort or suspend
408 * is requested. In this case it returns -1.
411 mono_monitor_try_enter_internal (MonoObject *obj, guint32 ms, gboolean allow_interruption)
413 MonoThreadsSync *mon;
414 gsize id = GetCurrentThreadId ();
416 guint32 then = 0, now, delta;
419 MonoInternalThread *thread;
421 LOCK_DEBUG (g_message("%s: (%d) Trying to lock object %p (%d ms)", __func__, id, obj, ms));
423 if (G_UNLIKELY (!obj)) {
424 mono_raise_exception (mono_get_exception_argument_null ("obj"));
429 mon = obj->synchronisation;
431 /* If the object has never been locked... */
432 if (G_UNLIKELY (mon == NULL)) {
433 mono_monitor_allocator_lock ();
435 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, mon, NULL) == NULL) {
436 mono_gc_weak_link_add (&mon->data, obj, FALSE);
437 mono_monitor_allocator_unlock ();
438 /* Successfully locked */
441 #ifdef HAVE_MOVING_COLLECTOR
443 lw.sync = obj->synchronisation;
444 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
445 MonoThreadsSync *oldlw = lw.sync;
446 /* move the already calculated hash */
447 mon->hash_code = lw.lock_word >> LOCK_WORD_HASH_SHIFT;
449 lw.lock_word |= LOCK_WORD_FAT_HASH;
450 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, oldlw) == oldlw) {
451 mono_gc_weak_link_add (&mon->data, obj, FALSE);
452 mono_monitor_allocator_unlock ();
453 /* Successfully locked */
457 mono_monitor_allocator_unlock ();
460 } else if (lw.lock_word & LOCK_WORD_FAT_HASH) {
462 mono_monitor_allocator_unlock ();
463 /* get the old lock without the fat hash bit */
464 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
468 mono_monitor_allocator_unlock ();
469 mon = obj->synchronisation;
473 mono_monitor_allocator_unlock ();
474 mon = obj->synchronisation;
478 #ifdef HAVE_MOVING_COLLECTOR
481 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
482 MonoThreadsSync *oldlw = lw.sync;
483 mono_monitor_allocator_lock ();
485 /* move the already calculated hash */
486 mon->hash_code = lw.lock_word >> LOCK_WORD_HASH_SHIFT;
488 lw.lock_word |= LOCK_WORD_FAT_HASH;
489 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, oldlw) == oldlw) {
490 mono_gc_weak_link_add (&mon->data, obj, TRUE);
491 mono_monitor_allocator_unlock ();
492 /* Successfully locked */
496 mono_monitor_allocator_unlock ();
503 #ifdef HAVE_MOVING_COLLECTOR
507 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
512 /* If the object has previously been locked but isn't now... */
514 /* This case differs from Dice's case 3 because we don't
515 * deflate locks or cache unused lock records
517 if (G_LIKELY (mon->owner == 0)) {
518 /* Try to install our ID in the owner field, nest
519 * should have been left at 1 by the previous unlock
522 if (G_LIKELY (InterlockedCompareExchangePointer ((gpointer *)&mon->owner, (gpointer)id, 0) == 0)) {
524 g_assert (mon->nest == 1);
532 /* If the object is currently locked by this thread... */
533 if (mon->owner == id) {
538 /* The object must be locked by someone else... */
539 mono_perfcounters->thread_contentions++;
541 /* If ms is 0 we don't block, but just fail straight away */
543 LOCK_DEBUG (g_message ("%s: (%d) timed out, returning FALSE", __func__, id));
547 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_CONTENTION);
549 /* The slow path begins here. */
551 /* a small amount of duplicated code, but it allows us to insert the profiler
552 * callbacks without impacting the fast path: from here on we don't need to go back to the
553 * retry label, but to retry_contended. At this point mon is already installed in the object
556 /* This case differs from Dice's case 3 because we don't
557 * deflate locks or cache unused lock records
559 if (G_LIKELY (mon->owner == 0)) {
560 /* Try to install our ID in the owner field, nest
561 * should have been left at 1 by the previous unlock
564 if (G_LIKELY (InterlockedCompareExchangePointer ((gpointer *)&mon->owner, (gpointer)id, 0) == 0)) {
566 g_assert (mon->nest == 1);
567 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_DONE);
572 /* If the object is currently locked by this thread... */
573 if (mon->owner == id) {
575 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_DONE);
579 /* We need to make sure there's a semaphore handle (creating it if
580 * necessary), and block on it
582 if (mon->entry_sem == NULL) {
583 /* Create the semaphore */
584 sem = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
585 g_assert (sem != NULL);
586 if (InterlockedCompareExchangePointer ((gpointer*)&mon->entry_sem, sem, NULL) != NULL) {
587 /* Someone else just put a handle here */
592 /* If we need to time out, record a timestamp and adjust ms,
593 * because WaitForSingleObject doesn't tell us how long it
596 * Don't block forever here, because theres a chance the owner
597 * thread released the lock while we were creating the
598 * semaphore: we would not get the wakeup. Using the event
599 * handle technique from pulse/wait would involve locking the
600 * lock struct and therefore slowing down the fast path.
602 if (ms != INFINITE) {
603 then = mono_msec_ticks ();
613 InterlockedIncrement (&mon->entry_count);
615 mono_perfcounters->thread_queue_len++;
616 mono_perfcounters->thread_queue_max++;
617 thread = mono_thread_internal_current ();
619 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
622 * We pass TRUE instead of allow_interruption since we have to check for the
623 * StopRequested case below.
625 ret = WaitForSingleObjectEx (mon->entry_sem, waitms, TRUE);
627 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
629 InterlockedDecrement (&mon->entry_count);
630 mono_perfcounters->thread_queue_len--;
632 if (ms != INFINITE) {
633 now = mono_msec_ticks ();
636 /* The counter must have wrapped around */
637 LOCK_DEBUG (g_message ("%s: wrapped around! now=0x%x then=0x%x", __func__, now, then));
639 now += (0xffffffff - then);
642 LOCK_DEBUG (g_message ("%s: wrap rejig: now=0x%x then=0x%x delta=0x%x", __func__, now, then, now-then));
652 if ((ret == WAIT_TIMEOUT || (ret == WAIT_IO_COMPLETION && !allow_interruption)) && ms > 0) {
654 goto retry_contended;
657 if (ret == WAIT_TIMEOUT || (ret == WAIT_IO_COMPLETION && !allow_interruption)) {
658 if (ret == WAIT_IO_COMPLETION && (mono_thread_test_state (mono_thread_internal_current (), (ThreadState_StopRequested|ThreadState_SuspendRequested)))) {
660 * We have to obey a stop/suspend request even if
661 * allow_interruption is FALSE to avoid hangs at shutdown.
663 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_FAIL);
666 /* Infinite wait, so just try again */
667 goto retry_contended;
671 if (ret == WAIT_OBJECT_0) {
672 /* retry from the top */
673 goto retry_contended;
676 /* We must have timed out */
677 LOCK_DEBUG (g_message ("%s: (%d) timed out waiting, returning FALSE", __func__, id));
679 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_FAIL);
681 if (ret == WAIT_IO_COMPLETION)
688 mono_monitor_enter (MonoObject *obj)
690 return mono_monitor_try_enter_internal (obj, INFINITE, FALSE) == 1;
694 mono_monitor_try_enter (MonoObject *obj, guint32 ms)
696 return mono_monitor_try_enter_internal (obj, ms, FALSE) == 1;
700 mono_monitor_exit (MonoObject *obj)
702 MonoThreadsSync *mon;
705 LOCK_DEBUG (g_message ("%s: (%d) Unlocking %p", __func__, GetCurrentThreadId (), obj));
707 if (G_UNLIKELY (!obj)) {
708 mono_raise_exception (mono_get_exception_argument_null ("obj"));
712 mon = obj->synchronisation;
714 #ifdef HAVE_MOVING_COLLECTOR
718 if (lw.lock_word & LOCK_WORD_THIN_HASH)
720 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
724 if (G_UNLIKELY (mon == NULL)) {
725 /* No one ever used Enter. Just ignore the Exit request as MS does */
728 if (G_UNLIKELY (mon->owner != GetCurrentThreadId ())) {
732 nest = mon->nest - 1;
734 LOCK_DEBUG (g_message ("%s: (%d) Object %p is now unlocked", __func__, GetCurrentThreadId (), obj));
736 /* object is now unlocked, leave nest==1 so we don't
737 * need to set it when the lock is reacquired
741 /* Do the wakeup stuff. It's possible that the last
742 * blocking thread gave up waiting just before we
743 * release the semaphore resulting in a futile wakeup
744 * next time there's contention for this object, but
745 * it means we don't have to waste time locking the
748 if (mon->entry_count > 0) {
749 ReleaseSemaphore (mon->entry_sem, 1, NULL);
752 LOCK_DEBUG (g_message ("%s: (%d) Object %p is now locked %d times", __func__, GetCurrentThreadId (), obj, nest));
758 mono_monitor_get_object_monitor_weak_link (MonoObject *object)
761 MonoThreadsSync *sync = NULL;
763 lw.sync = object->synchronisation;
764 if (lw.lock_word & LOCK_WORD_FAT_HASH) {
765 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
767 } else if (!(lw.lock_word & LOCK_WORD_THIN_HASH)) {
771 if (sync && sync->data)
777 emit_obj_syncp_check (MonoMethodBuilder *mb, int syncp_loc, int *obj_null_branch, int *syncp_true_false_branch,
778 int *thin_hash_branch, gboolean branch_on_true)
785 mono_mb_emit_byte (mb, CEE_LDARG_0);
786 *obj_null_branch = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
791 ldc.i4 G_STRUCT_OFFSET(MonoObject, synchronisation) objp off
796 brtrue/false.s syncp_true_false
799 mono_mb_emit_byte (mb, CEE_LDARG_0);
800 mono_mb_emit_byte (mb, CEE_CONV_I);
801 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoObject, synchronisation));
802 mono_mb_emit_byte (mb, CEE_ADD);
803 mono_mb_emit_byte (mb, CEE_LDIND_I);
804 mono_mb_emit_stloc (mb, syncp_loc);
807 if (mono_gc_is_moving ()) {
808 /*check for a thin hash*/
809 mono_mb_emit_ldloc (mb, syncp_loc);
810 mono_mb_emit_icon (mb, 0x01);
811 mono_mb_emit_byte (mb, CEE_CONV_I);
812 mono_mb_emit_byte (mb, CEE_AND);
813 *thin_hash_branch = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
816 mono_mb_emit_ldloc (mb, syncp_loc);
817 mono_mb_emit_icon (mb, ~0x3);
818 mono_mb_emit_byte (mb, CEE_CONV_I);
819 mono_mb_emit_byte (mb, CEE_AND);
820 mono_mb_emit_stloc (mb, syncp_loc);
822 *thin_hash_branch = 0;
825 mono_mb_emit_ldloc (mb, syncp_loc);
826 *syncp_true_false_branch = mono_mb_emit_short_branch (mb, branch_on_true ? CEE_BRTRUE_S : CEE_BRFALSE_S);
830 mono_monitor_get_fast_enter_method (MonoMethod *monitor_enter_method)
832 static MonoMethod *fast_monitor_enter;
833 static MonoMethod *compare_exchange_method;
835 MonoMethodBuilder *mb;
836 int obj_null_branch, syncp_null_branch, has_owner_branch, other_owner_branch, tid_branch, thin_hash_branch;
837 int tid_loc, syncp_loc, owner_loc;
838 int thread_tls_offset;
840 thread_tls_offset = mono_thread_get_tls_offset ();
841 if (thread_tls_offset == -1)
844 if (fast_monitor_enter)
845 return fast_monitor_enter;
847 if (!compare_exchange_method) {
848 MonoMethodDesc *desc;
851 desc = mono_method_desc_new ("Interlocked:CompareExchange(intptr&,intptr,intptr)", FALSE);
852 class = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
853 compare_exchange_method = mono_method_desc_search_in_class (desc, class);
854 mono_method_desc_free (desc);
856 if (!compare_exchange_method)
860 mb = mono_mb_new (mono_defaults.monitor_class, "FastMonitorEnter", MONO_WRAPPER_UNKNOWN);
862 mb->method->slot = -1;
863 mb->method->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_STATIC |
864 METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
866 tid_loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
867 syncp_loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
868 owner_loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
870 emit_obj_syncp_check (mb, syncp_loc, &obj_null_branch, &syncp_null_branch, &thin_hash_branch, FALSE);
873 mono. tls thread_tls_offset threadp
874 ldc.i4 G_STRUCT_OFFSET(MonoThread, tid) threadp off
879 ldc.i4 G_STRUCT_OFFSET(MonoThreadsSync, owner) syncp off
887 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
888 mono_mb_emit_byte (mb, CEE_MONO_TLS);
889 mono_mb_emit_i4 (mb, thread_tls_offset);
890 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoInternalThread, tid));
891 mono_mb_emit_byte (mb, CEE_ADD);
892 mono_mb_emit_byte (mb, CEE_LDIND_I);
893 mono_mb_emit_stloc (mb, tid_loc);
894 mono_mb_emit_ldloc (mb, syncp_loc);
895 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, owner));
896 mono_mb_emit_byte (mb, CEE_ADD);
897 mono_mb_emit_byte (mb, CEE_LDIND_I);
898 mono_mb_emit_stloc (mb, owner_loc);
899 mono_mb_emit_ldloc (mb, owner_loc);
900 tid_branch = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
904 ldc.i4 G_STRUCT_OFFSET(MonoThreadsSync, owner) syncp off
907 ldc.i4 0 &owner tid 0
908 call System.Threading.Interlocked.CompareExchange oldowner
913 mono_mb_emit_ldloc (mb, syncp_loc);
914 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, owner));
915 mono_mb_emit_byte (mb, CEE_ADD);
916 mono_mb_emit_ldloc (mb, tid_loc);
917 mono_mb_emit_byte (mb, CEE_LDC_I4_0);
918 mono_mb_emit_managed_call (mb, compare_exchange_method, NULL);
919 has_owner_branch = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
920 mono_mb_emit_byte (mb, CEE_RET);
928 ldc.i4 G_STRUCT_OFFSET(MonoThreadsSync, nest) syncp off
932 ldc.i4 1 &nest nest 1
938 mono_mb_patch_short_branch (mb, tid_branch);
939 mono_mb_emit_ldloc (mb, owner_loc);
940 mono_mb_emit_ldloc (mb, tid_loc);
941 other_owner_branch = mono_mb_emit_short_branch (mb, CEE_BNE_UN_S);
942 mono_mb_emit_ldloc (mb, syncp_loc);
943 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, nest));
944 mono_mb_emit_byte (mb, CEE_ADD);
945 mono_mb_emit_byte (mb, CEE_DUP);
946 mono_mb_emit_byte (mb, CEE_LDIND_I4);
947 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
948 mono_mb_emit_byte (mb, CEE_ADD);
949 mono_mb_emit_byte (mb, CEE_STIND_I4);
950 mono_mb_emit_byte (mb, CEE_RET);
953 obj_null, syncp_null, has_owner, other_owner:
955 call System.Threading.Monitor.Enter
959 if (thin_hash_branch)
960 mono_mb_patch_short_branch (mb, thin_hash_branch);
961 mono_mb_patch_short_branch (mb, obj_null_branch);
962 mono_mb_patch_short_branch (mb, syncp_null_branch);
963 mono_mb_patch_short_branch (mb, has_owner_branch);
964 mono_mb_patch_short_branch (mb, other_owner_branch);
965 mono_mb_emit_byte (mb, CEE_LDARG_0);
966 mono_mb_emit_managed_call (mb, monitor_enter_method, NULL);
967 mono_mb_emit_byte (mb, CEE_RET);
969 fast_monitor_enter = mono_mb_create_method (mb, mono_signature_no_pinvoke (monitor_enter_method), 5);
972 return fast_monitor_enter;
976 mono_monitor_get_fast_exit_method (MonoMethod *monitor_exit_method)
978 static MonoMethod *fast_monitor_exit;
980 MonoMethodBuilder *mb;
981 int obj_null_branch, has_waiting_branch, has_syncp_branch, owned_branch, nested_branch, thin_hash_branch;
982 int thread_tls_offset;
985 thread_tls_offset = mono_thread_get_tls_offset ();
986 if (thread_tls_offset == -1)
989 if (fast_monitor_exit)
990 return fast_monitor_exit;
992 mb = mono_mb_new (mono_defaults.monitor_class, "FastMonitorExit", MONO_WRAPPER_UNKNOWN);
994 mb->method->slot = -1;
995 mb->method->flags = METHOD_ATTRIBUTE_PUBLIC | METHOD_ATTRIBUTE_STATIC |
996 METHOD_ATTRIBUTE_HIDE_BY_SIG | METHOD_ATTRIBUTE_FINAL;
998 syncp_loc = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
1000 emit_obj_syncp_check (mb, syncp_loc, &obj_null_branch, &has_syncp_branch, &thin_hash_branch, TRUE);
1006 mono_mb_emit_byte (mb, CEE_RET);
1011 ldc.i4 G_STRUCT_OFFSET(MonoThreadsSync, owner) syncp off
1014 mono. tls thread_tls_offset owner threadp
1015 ldc.i4 G_STRUCT_OFFSET(MonoThread, tid) owner threadp off
1021 mono_mb_patch_short_branch (mb, has_syncp_branch);
1022 mono_mb_emit_ldloc (mb, syncp_loc);
1023 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, owner));
1024 mono_mb_emit_byte (mb, CEE_ADD);
1025 mono_mb_emit_byte (mb, CEE_LDIND_I);
1026 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
1027 mono_mb_emit_byte (mb, CEE_MONO_TLS);
1028 mono_mb_emit_i4 (mb, thread_tls_offset);
1029 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoInternalThread, tid));
1030 mono_mb_emit_byte (mb, CEE_ADD);
1031 mono_mb_emit_byte (mb, CEE_LDIND_I);
1032 owned_branch = mono_mb_emit_short_branch (mb, CEE_BEQ_S);
1038 mono_mb_emit_byte (mb, CEE_RET);
1043 ldc.i4 G_STRUCT_OFFSET(MonoThreadsSync, nest) syncp off
1048 ldc.i4 1 &nest nest nest 1
1049 bgt.un.s nested &nest nest
1052 mono_mb_patch_short_branch (mb, owned_branch);
1053 mono_mb_emit_ldloc (mb, syncp_loc);
1054 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, nest));
1055 mono_mb_emit_byte (mb, CEE_ADD);
1056 mono_mb_emit_byte (mb, CEE_DUP);
1057 mono_mb_emit_byte (mb, CEE_LDIND_I4);
1058 mono_mb_emit_byte (mb, CEE_DUP);
1059 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1060 nested_branch = mono_mb_emit_short_branch (mb, CEE_BGT_UN_S);
1066 ldc.i4 G_STRUCT_OFFSET(MonoThreadsSync, entry_count) syncp off
1069 brtrue.s has_waiting
1072 mono_mb_emit_byte (mb, CEE_POP);
1073 mono_mb_emit_byte (mb, CEE_POP);
1074 mono_mb_emit_ldloc (mb, syncp_loc);
1075 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, entry_count));
1076 mono_mb_emit_byte (mb, CEE_ADD);
1077 mono_mb_emit_byte (mb, CEE_LDIND_I4);
1078 has_waiting_branch = mono_mb_emit_short_branch (mb, CEE_BRTRUE_S);
1082 ldc.i4 G_STRUCT_OFFSET(MonoThreadsSync, owner) syncp off
1089 mono_mb_emit_ldloc (mb, syncp_loc);
1090 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoThreadsSync, owner));
1091 mono_mb_emit_byte (mb, CEE_ADD);
1092 mono_mb_emit_byte (mb, CEE_LDNULL);
1093 mono_mb_emit_byte (mb, CEE_STIND_I);
1094 mono_mb_emit_byte (mb, CEE_RET);
1098 ldc.i4 1 &nest nest 1
1104 mono_mb_patch_short_branch (mb, nested_branch);
1105 mono_mb_emit_byte (mb, CEE_LDC_I4_1);
1106 mono_mb_emit_byte (mb, CEE_SUB);
1107 mono_mb_emit_byte (mb, CEE_STIND_I4);
1108 mono_mb_emit_byte (mb, CEE_RET);
1111 obj_null, has_waiting:
1113 call System.Threading.Monitor.Exit
1117 if (thin_hash_branch)
1118 mono_mb_patch_short_branch (mb, thin_hash_branch);
1119 mono_mb_patch_short_branch (mb, obj_null_branch);
1120 mono_mb_patch_short_branch (mb, has_waiting_branch);
1121 mono_mb_emit_byte (mb, CEE_LDARG_0);
1122 mono_mb_emit_managed_call (mb, monitor_exit_method, NULL);
1123 mono_mb_emit_byte (mb, CEE_RET);
1125 fast_monitor_exit = mono_mb_create_method (mb, mono_signature_no_pinvoke (monitor_exit_method), 5);
1128 return fast_monitor_exit;
1132 mono_monitor_get_fast_path (MonoMethod *enter_or_exit)
1134 if (strcmp (enter_or_exit->name, "Enter") == 0)
1135 return mono_monitor_get_fast_enter_method (enter_or_exit);
1136 if (strcmp (enter_or_exit->name, "Exit") == 0)
1137 return mono_monitor_get_fast_exit_method (enter_or_exit);
1138 g_assert_not_reached ();
1143 * mono_monitor_threads_sync_member_offset:
1144 * @owner_offset: returns size and offset of the "owner" member
1145 * @nest_offset: returns size and offset of the "nest" member
1146 * @entry_count_offset: returns size and offset of the "entry_count" member
1148 * Returns the offsets and sizes of three members of the
1149 * MonoThreadsSync struct. The Monitor ASM fastpaths need this.
1152 mono_monitor_threads_sync_members_offset (int *owner_offset, int *nest_offset, int *entry_count_offset)
1156 #define ENCODE_OFF_SIZE(o,s) (((o) << 8) | ((s) & 0xff))
1158 *owner_offset = ENCODE_OFF_SIZE (G_STRUCT_OFFSET (MonoThreadsSync, owner), sizeof (ts.owner));
1159 *nest_offset = ENCODE_OFF_SIZE (G_STRUCT_OFFSET (MonoThreadsSync, nest), sizeof (ts.nest));
1160 *entry_count_offset = ENCODE_OFF_SIZE (G_STRUCT_OFFSET (MonoThreadsSync, entry_count), sizeof (ts.entry_count));
1164 ves_icall_System_Threading_Monitor_Monitor_try_enter (MonoObject *obj, guint32 ms)
1169 res = mono_monitor_try_enter_internal (obj, ms, TRUE);
1171 mono_thread_interruption_checkpoint ();
1172 } while (res == -1);
1178 ves_icall_System_Threading_Monitor_Monitor_try_enter_with_atomic_var (MonoObject *obj, guint32 ms, char *lockTaken)
1182 res = mono_monitor_try_enter_internal (obj, ms, TRUE);
1183 /*This means we got interrupted during the wait and didn't got the monitor.*/
1185 mono_thread_interruption_checkpoint ();
1186 } while (res == -1);
1187 /*It's safe to do it from here since interruption would happen only on the wrapper.*/
1188 *lockTaken = res == 1;
1192 ves_icall_System_Threading_Monitor_Monitor_test_owner (MonoObject *obj)
1194 MonoThreadsSync *mon;
1196 LOCK_DEBUG (g_message ("%s: Testing if %p is owned by thread %d", __func__, obj, GetCurrentThreadId()));
1198 mon = obj->synchronisation;
1199 #ifdef HAVE_MOVING_COLLECTOR
1203 if (lw.lock_word & LOCK_WORD_THIN_HASH)
1205 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1213 if(mon->owner==GetCurrentThreadId ()) {
1221 ves_icall_System_Threading_Monitor_Monitor_test_synchronised (MonoObject *obj)
1223 MonoThreadsSync *mon;
1225 LOCK_DEBUG (g_message("%s: (%d) Testing if %p is owned by any thread", __func__, GetCurrentThreadId (), obj));
1227 mon = obj->synchronisation;
1228 #ifdef HAVE_MOVING_COLLECTOR
1232 if (lw.lock_word & LOCK_WORD_THIN_HASH)
1234 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1242 if (mon->owner != 0) {
1249 /* All wait list manipulation in the pulse, pulseall and wait
1250 * functions happens while the monitor lock is held, so we don't need
1251 * any extra struct locking
1255 ves_icall_System_Threading_Monitor_Monitor_pulse (MonoObject *obj)
1257 MonoThreadsSync *mon;
1259 LOCK_DEBUG (g_message ("%s: (%d) Pulsing %p", __func__, GetCurrentThreadId (), obj));
1261 mon = obj->synchronisation;
1262 #ifdef HAVE_MOVING_COLLECTOR
1266 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
1267 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1270 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1275 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1278 if (mon->owner != GetCurrentThreadId ()) {
1279 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
1283 LOCK_DEBUG (g_message ("%s: (%d) %d threads waiting", __func__, GetCurrentThreadId (), g_slist_length (mon->wait_list)));
1285 if (mon->wait_list != NULL) {
1286 LOCK_DEBUG (g_message ("%s: (%d) signalling and dequeuing handle %p", __func__, GetCurrentThreadId (), mon->wait_list->data));
1288 SetEvent (mon->wait_list->data);
1289 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1294 ves_icall_System_Threading_Monitor_Monitor_pulse_all (MonoObject *obj)
1296 MonoThreadsSync *mon;
1298 LOCK_DEBUG (g_message("%s: (%d) Pulsing all %p", __func__, GetCurrentThreadId (), obj));
1300 mon = obj->synchronisation;
1301 #ifdef HAVE_MOVING_COLLECTOR
1305 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
1306 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1309 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1314 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1317 if (mon->owner != GetCurrentThreadId ()) {
1318 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
1322 LOCK_DEBUG (g_message ("%s: (%d) %d threads waiting", __func__, GetCurrentThreadId (), g_slist_length (mon->wait_list)));
1324 while (mon->wait_list != NULL) {
1325 LOCK_DEBUG (g_message ("%s: (%d) signalling and dequeuing handle %p", __func__, GetCurrentThreadId (), mon->wait_list->data));
1327 SetEvent (mon->wait_list->data);
1328 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1333 ves_icall_System_Threading_Monitor_Monitor_wait (MonoObject *obj, guint32 ms)
1335 MonoThreadsSync *mon;
1339 gboolean success = FALSE;
1341 MonoInternalThread *thread = mono_thread_internal_current ();
1343 LOCK_DEBUG (g_message ("%s: (%d) Trying to wait for %p with timeout %dms", __func__, GetCurrentThreadId (), obj, ms));
1345 mon = obj->synchronisation;
1346 #ifdef HAVE_MOVING_COLLECTOR
1350 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
1351 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1354 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1359 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
1362 if (mon->owner != GetCurrentThreadId ()) {
1363 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
1367 /* Do this WaitSleepJoin check before creating the event handle */
1368 mono_thread_current_check_pending_interrupt ();
1370 event = CreateEvent (NULL, FALSE, FALSE, NULL);
1371 if (event == NULL) {
1372 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to set up wait event"));
1376 LOCK_DEBUG (g_message ("%s: (%d) queuing handle %p", __func__, GetCurrentThreadId (), event));
1378 mono_thread_current_check_pending_interrupt ();
1380 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1382 mon->wait_list = g_slist_append (mon->wait_list, event);
1384 /* Save the nest count, and release the lock */
1387 mono_monitor_exit (obj);
1389 LOCK_DEBUG (g_message ("%s: (%d) Unlocked %p lock %p", __func__, GetCurrentThreadId (), obj, mon));
1391 /* There's no race between unlocking mon and waiting for the
1392 * event, because auto reset events are sticky, and this event
1393 * is private to this thread. Therefore even if the event was
1394 * signalled before we wait, we still succeed.
1396 ret = WaitForSingleObjectEx (event, ms, TRUE);
1398 /* Reset the thread state fairly early, so we don't have to worry
1399 * about the monitor error checking
1401 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1403 if (mono_thread_interruption_requested ()) {
1405 * Can't remove the event from wait_list, since the monitor is not locked by
1406 * us. So leave it there, mon_new () will delete it when the mon structure
1407 * is placed on the free list.
1408 * FIXME: The caller expects to hold the lock after the wait returns, but it
1409 * doesn't happen in this case:
1410 * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=97268
1415 /* Regain the lock with the previous nest count */
1417 regain = mono_monitor_try_enter_internal (obj, INFINITE, TRUE);
1419 mono_thread_interruption_checkpoint ();
1420 } while (regain == -1);
1423 /* Something went wrong, so throw a
1424 * SynchronizationLockException
1426 CloseHandle (event);
1427 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to regain lock"));
1433 LOCK_DEBUG (g_message ("%s: (%d) Regained %p lock %p", __func__, GetCurrentThreadId (), obj, mon));
1435 if (ret == WAIT_TIMEOUT) {
1436 /* Poll the event again, just in case it was signalled
1437 * while we were trying to regain the monitor lock
1439 ret = WaitForSingleObjectEx (event, 0, FALSE);
1442 /* Pulse will have popped our event from the queue if it signalled
1443 * us, so we only do it here if the wait timed out.
1445 * This avoids a race condition where the thread holding the
1446 * lock can Pulse several times before the WaitForSingleObject
1447 * returns. If we popped the queue here then this event might
1448 * be signalled more than once, thereby starving another
1452 if (ret == WAIT_OBJECT_0) {
1453 LOCK_DEBUG (g_message ("%s: (%d) Success", __func__, GetCurrentThreadId ()));
1456 LOCK_DEBUG (g_message ("%s: (%d) Wait failed, dequeuing handle %p", __func__, GetCurrentThreadId (), event));
1457 /* No pulse, so we have to remove ourself from the
1460 mon->wait_list = g_slist_remove (mon->wait_list, event);
1462 CloseHandle (event);