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/abi-details.h>
16 #include <mono/metadata/monitor.h>
17 #include <mono/metadata/threads-types.h>
18 #include <mono/metadata/exception.h>
19 #include <mono/metadata/threads.h>
20 #include <mono/io-layer/io-layer.h>
21 #include <mono/metadata/object-internals.h>
22 #include <mono/metadata/class-internals.h>
23 #include <mono/metadata/gc-internal.h>
24 #include <mono/metadata/method-builder.h>
25 #include <mono/metadata/debug-helpers.h>
26 #include <mono/metadata/tabledefs.h>
27 #include <mono/metadata/marshal.h>
28 #include <mono/utils/mono-threads.h>
29 #include <mono/metadata/profiler-private.h>
30 #include <mono/utils/mono-time.h>
31 #include <mono/utils/atomic.h>
34 * Pull the list of opcodes
36 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
40 #include "mono/cil/opcode.def"
45 /*#define LOCK_DEBUG(a) do { a; } while (0)*/
49 * The monitor implementation here is based on
50 * http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf and
51 * http://www.research.ibm.com/people/d/dfb/papers/Bacon98Thin.ps
53 * The Dice paper describes a technique for saving lock record space
54 * by returning records to a free list when they become unused. That
55 * sounds like unnecessary complexity to me, though if it becomes
56 * clear that unused lock records are taking up lots of space or we
57 * need to shave more time off by avoiding a malloc then we can always
58 * implement the free list idea later. The timeout parameter to
59 * try_enter voids some of the assumptions about the reference count
60 * field in Dice's implementation too. In his version, the thread
61 * attempting to lock a contended object will block until it succeeds,
62 * so the reference count will never be decremented while an object is
65 * Bacon's thin locks have a fast path that doesn't need a lock record
66 * for the common case of locking an unlocked or shallow-nested
67 * object, but the technique relies on encoding the thread ID in 15
68 * bits (to avoid too much per-object space overhead.) Unfortunately
69 * I don't think it's possible to reliably encode a pthread_t into 15
70 * bits. (The JVM implementation used seems to have a 15-bit
71 * per-thread identifier available.)
73 * This implementation then combines Dice's basic lock model with
74 * Bacon's simplification of keeping a lock record for the lifetime of
79 typedef struct _MonitorArray MonitorArray;
81 struct _MonitorArray {
84 MonoThreadsSync monitors [MONO_ZERO_LEN_ARRAY];
87 #define mono_monitor_allocator_lock() mono_mutex_lock (&monitor_mutex)
88 #define mono_monitor_allocator_unlock() mono_mutex_unlock (&monitor_mutex)
89 static mono_mutex_t monitor_mutex;
90 static MonoThreadsSync *monitor_freelist;
91 static MonitorArray *monitor_allocated;
92 static int array_size = 16;
95 mon_status_get_owner (guint32 status)
97 return status & OWNER_MASK;
100 static inline guint32
101 mon_status_set_owner (guint32 status, guint32 owner)
103 return (status & ENTRY_COUNT_MASK) | owner;
107 mon_status_get_entry_count (guint32 status)
109 gint32 entry_count = (gint32)((status & ENTRY_COUNT_MASK) >> ENTRY_COUNT_SHIFT);
110 gint32 zero = (gint32)(((guint32)ENTRY_COUNT_ZERO) >> ENTRY_COUNT_SHIFT);
111 return entry_count - zero;
114 static inline guint32
115 mon_status_init_entry_count (guint32 status)
117 return (status & OWNER_MASK) | ENTRY_COUNT_ZERO;
120 static inline guint32
121 mon_status_increment_entry_count (guint32 status)
123 return status + (1 << ENTRY_COUNT_SHIFT);
126 static inline guint32
127 mon_status_decrement_entry_count (guint32 status)
129 return status - (1 << ENTRY_COUNT_SHIFT);
132 static inline gboolean
133 mon_status_have_waiters (guint32 status)
135 return status & ENTRY_COUNT_WAITERS;
139 mono_monitor_init (void)
141 mono_mutex_init_recursive (&monitor_mutex);
145 mono_monitor_cleanup (void)
147 MonoThreadsSync *mon;
148 /* MonitorArray *marray, *next = NULL; */
150 /*mono_mutex_destroy (&monitor_mutex);*/
152 /* The monitors on the freelist don't have weak links - mark them */
153 for (mon = monitor_freelist; mon; mon = mon->data)
154 mon->wait_list = (gpointer)-1;
156 /* FIXME: This still crashes with sgen (async_read.exe) */
158 for (marray = monitor_allocated; marray; marray = next) {
161 for (i = 0; i < marray->num_monitors; ++i) {
162 mon = &marray->monitors [i];
163 if (mon->wait_list != (gpointer)-1)
164 mono_gc_weak_link_remove (&mon->data);
174 monitor_is_on_freelist (MonoThreadsSync *mon)
176 MonitorArray *marray;
177 for (marray = monitor_allocated; marray; marray = marray->next) {
178 if (mon >= marray->monitors && mon < &marray->monitors [marray->num_monitors])
188 * Print a report on stdout of the managed locks currently held by
189 * threads. If @include_untaken is specified, list also inflated locks
191 * This is supposed to be used in debuggers like gdb.
194 mono_locks_dump (gboolean include_untaken)
197 int used = 0, on_freelist = 0, to_recycle = 0, total = 0, num_arrays = 0;
198 MonoThreadsSync *mon;
199 MonitorArray *marray;
200 for (mon = monitor_freelist; mon; mon = mon->data)
202 for (marray = monitor_allocated; marray; marray = marray->next) {
203 total += marray->num_monitors;
205 for (i = 0; i < marray->num_monitors; ++i) {
206 mon = &marray->monitors [i];
207 if (mon->data == NULL) {
208 if (i < marray->num_monitors - 1)
211 if (!monitor_is_on_freelist (mon->data)) {
212 MonoObject *holder = mono_gc_weak_link_get (&mon->data);
213 if (mon_status_get_owner (mon->status)) {
214 g_print ("Lock %p in object %p held by thread %d, nest level: %d\n",
215 mon, holder, mon_status_get_owner (mon->status), mon->nest);
217 g_print ("\tWaiting on semaphore %p: %d\n", mon->entry_sem, mon_status_get_entry_count (mon->status));
218 } else if (include_untaken) {
219 g_print ("Lock %p in object %p untaken\n", mon, holder);
226 g_print ("Total locks (in %d array(s)): %d, used: %d, on freelist: %d, to recycle: %d\n",
227 num_arrays, total, used, on_freelist, to_recycle);
230 /* LOCKING: this is called with monitor_mutex held */
232 mon_finalize (MonoThreadsSync *mon)
234 LOCK_DEBUG (g_message ("%s: Finalizing sync %p", __func__, mon));
236 if (mon->entry_sem != NULL) {
237 CloseHandle (mon->entry_sem);
238 mon->entry_sem = NULL;
240 /* If this isn't empty then something is seriously broken - it
241 * means a thread is still waiting on the object that owned
242 * this lock, but the object has been finalized.
244 g_assert (mon->wait_list == NULL);
246 /* owner and nest are set in mon_new, no need to zero them out */
248 mon->data = monitor_freelist;
249 monitor_freelist = mon;
250 #ifndef DISABLE_PERFCOUNTERS
251 mono_perfcounters->gc_sync_blocks--;
255 /* LOCKING: this is called with monitor_mutex held */
256 static MonoThreadsSync *
259 MonoThreadsSync *new;
261 if (!monitor_freelist) {
262 MonitorArray *marray;
264 /* see if any sync block has been collected */
266 for (marray = monitor_allocated; marray; marray = marray->next) {
267 for (i = 0; i < marray->num_monitors; ++i) {
268 if (marray->monitors [i].data == NULL) {
269 new = &marray->monitors [i];
270 if (new->wait_list) {
271 /* Orphaned events left by aborted threads */
272 while (new->wait_list) {
273 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d): Closing orphaned event %d", mono_thread_info_get_small_id (), new->wait_list->data));
274 CloseHandle (new->wait_list->data);
275 new->wait_list = g_slist_remove (new->wait_list, new->wait_list->data);
278 mono_gc_weak_link_remove (&new->data, TRUE);
279 new->data = monitor_freelist;
280 monitor_freelist = new;
283 /* small perf tweak to avoid scanning all the blocks */
287 /* need to allocate a new array of monitors */
288 if (!monitor_freelist) {
290 LOCK_DEBUG (g_message ("%s: allocating more monitors: %d", __func__, array_size));
291 marray = g_malloc0 (sizeof (MonoArray) + array_size * sizeof (MonoThreadsSync));
292 marray->num_monitors = array_size;
294 /* link into the freelist */
295 for (i = 0; i < marray->num_monitors - 1; ++i) {
296 marray->monitors [i].data = &marray->monitors [i + 1];
298 marray->monitors [i].data = NULL; /* the last one */
299 monitor_freelist = &marray->monitors [0];
300 /* we happend the marray instead of prepending so that
301 * the collecting loop above will need to scan smaller arrays first
303 if (!monitor_allocated) {
304 monitor_allocated = marray;
306 last = monitor_allocated;
314 new = monitor_freelist;
315 monitor_freelist = new->data;
317 new->status = mon_status_set_owner (0, id);
318 new->status = mon_status_init_entry_count (new->status);
322 #ifndef DISABLE_PERFCOUNTERS
323 mono_perfcounters->gc_sync_blocks++;
329 * Format of the lock word:
330 * thinhash | fathash | data
332 * thinhash is the lower bit: if set data is the shifted hashcode of the object.
333 * fathash is another bit: if set the hash code is stored in the MonoThreadsSync
334 * struct pointed to by data
335 * if neither bit is set and data is non-NULL, data is a MonoThreadsSync
339 MonoThreadsSync *sync;
343 LOCK_WORD_THIN_HASH = 1,
344 LOCK_WORD_FAT_HASH = 1 << 1,
345 LOCK_WORD_BITS_MASK = 0x3,
346 LOCK_WORD_HASH_SHIFT = 2
349 #define MONO_OBJECT_ALIGNMENT_SHIFT 3
355 * Calculate a hash code for @obj that is constant while @obj is alive.
358 mono_object_hash (MonoObject* obj)
360 #ifdef HAVE_MOVING_COLLECTOR
365 lw.sync = obj->synchronisation;
366 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
367 /*g_print ("fast thin hash %d for obj %p store\n", (unsigned int)lw.lock_word >> LOCK_WORD_HASH_SHIFT, obj);*/
368 return (unsigned int)lw.lock_word >> LOCK_WORD_HASH_SHIFT;
370 if (lw.lock_word & LOCK_WORD_FAT_HASH) {
371 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
372 /*g_print ("fast fat hash %d for obj %p store\n", lw.sync->hash_code, obj);*/
373 return lw.sync->hash_code;
376 * while we are inside this function, the GC will keep this object pinned,
377 * since we are in the unmanaged stack. Thanks to this and to the hash
378 * function that depends only on the address, we can ignore the races if
379 * another thread computes the hash at the same time, because it'll end up
380 * with the same value.
382 hash = (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
383 /* clear the top bits as they can be discarded */
384 hash &= ~(LOCK_WORD_BITS_MASK << 30);
385 /* no hash flags were set, so it must be a MonoThreadsSync pointer if not NULL */
387 lw.sync->hash_code = hash;
388 /*g_print ("storing hash code %d for obj %p in sync %p\n", hash, obj, lw.sync);*/
389 lw.lock_word |= LOCK_WORD_FAT_HASH;
390 /* this is safe since we don't deflate locks */
391 obj->synchronisation = lw.sync;
393 /*g_print ("storing thin hash code %d for obj %p\n", hash, obj);*/
394 lw.lock_word = LOCK_WORD_THIN_HASH | (hash << LOCK_WORD_HASH_SHIFT);
395 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, NULL) == NULL)
397 /*g_print ("failed store\n");*/
398 /* someone set the hash flag or someone inflated the object */
399 lw.sync = obj->synchronisation;
400 if (lw.lock_word & LOCK_WORD_THIN_HASH)
402 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
403 lw.sync->hash_code = hash;
404 lw.lock_word |= LOCK_WORD_FAT_HASH;
405 /* this is safe since we don't deflate locks */
406 obj->synchronisation = lw.sync;
411 * Wang's address-based hash function:
412 * http://www.concentric.net/~Ttwang/tech/addrhash.htm
414 return (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
419 mon_decrement_entry_count (MonoThreadsSync *mon)
421 guint32 old_status, tmp_status, new_status;
423 /* Decrement entry count */
424 old_status = mon->status;
426 new_status = mon_status_decrement_entry_count (old_status);
427 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
428 if (tmp_status == old_status) {
431 old_status = tmp_status;
435 /* If allow_interruption==TRUE, the method will be interrumped if abort or suspend
436 * is requested. In this case it returns -1.
439 mono_monitor_try_enter_internal (MonoObject *obj, guint32 ms, gboolean allow_interruption)
441 MonoThreadsSync *mon;
442 gsize id = mono_thread_info_get_small_id ();
444 guint32 then = 0, now, delta;
447 guint32 new_status, old_status, tmp_status;
448 MonoInternalThread *thread;
449 gboolean interrupted = FALSE;
451 LOCK_DEBUG (g_message("%s: (%d) Trying to lock object %p (%d ms)", __func__, id, obj, ms));
453 if (G_UNLIKELY (!obj)) {
454 mono_raise_exception (mono_get_exception_argument_null ("obj"));
459 mon = obj->synchronisation;
461 /* If the object has never been locked... */
462 if (G_UNLIKELY (mon == NULL)) {
463 mono_monitor_allocator_lock ();
465 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, mon, NULL) == NULL) {
466 mono_gc_weak_link_add (&mon->data, obj, TRUE);
467 mono_monitor_allocator_unlock ();
468 /* Successfully locked */
471 #ifdef HAVE_MOVING_COLLECTOR
473 lw.sync = obj->synchronisation;
474 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
475 MonoThreadsSync *oldlw = lw.sync;
476 /* move the already calculated hash */
477 mon->hash_code = lw.lock_word >> LOCK_WORD_HASH_SHIFT;
479 lw.lock_word |= LOCK_WORD_FAT_HASH;
480 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, oldlw) == oldlw) {
481 mono_gc_weak_link_add (&mon->data, obj, TRUE);
482 mono_monitor_allocator_unlock ();
483 /* Successfully locked */
487 mono_monitor_allocator_unlock ();
490 } else if (lw.lock_word & LOCK_WORD_FAT_HASH) {
492 mono_monitor_allocator_unlock ();
493 /* get the old lock without the fat hash bit */
494 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
498 mono_monitor_allocator_unlock ();
499 mon = obj->synchronisation;
503 mono_monitor_allocator_unlock ();
504 mon = obj->synchronisation;
508 #ifdef HAVE_MOVING_COLLECTOR
511 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
512 MonoThreadsSync *oldlw = lw.sync;
513 mono_monitor_allocator_lock ();
515 /* move the already calculated hash */
516 mon->hash_code = lw.lock_word >> LOCK_WORD_HASH_SHIFT;
518 lw.lock_word |= LOCK_WORD_FAT_HASH;
519 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, oldlw) == oldlw) {
520 mono_gc_weak_link_add (&mon->data, obj, TRUE);
521 mono_monitor_allocator_unlock ();
522 /* Successfully locked */
526 mono_monitor_allocator_unlock ();
533 #ifdef HAVE_MOVING_COLLECTOR
537 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
542 /* If the object has previously been locked but isn't now... */
544 /* This case differs from Dice's case 3 because we don't
545 * deflate locks or cache unused lock records
547 old_status = mon->status;
548 if (G_LIKELY (mon_status_get_owner (old_status) == 0)) {
549 /* Try to install our ID in the owner field, nest
550 * should have been left at 1 by the previous unlock
553 new_status = mon_status_set_owner (old_status, id);
554 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
555 if (G_LIKELY (tmp_status == old_status)) {
557 g_assert (mon->nest == 1);
565 /* If the object is currently locked by this thread... */
566 if (mon_status_get_owner (old_status) == id) {
571 /* The object must be locked by someone else... */
572 #ifndef DISABLE_PERFCOUNTERS
573 mono_perfcounters->thread_contentions++;
576 /* If ms is 0 we don't block, but just fail straight away */
578 LOCK_DEBUG (g_message ("%s: (%d) timed out, returning FALSE", __func__, id));
582 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_CONTENTION);
584 /* The slow path begins here. */
586 /* a small amount of duplicated code, but it allows us to insert the profiler
587 * callbacks without impacting the fast path: from here on we don't need to go back to the
588 * retry label, but to retry_contended. At this point mon is already installed in the object
591 /* This case differs from Dice's case 3 because we don't
592 * deflate locks or cache unused lock records
594 old_status = mon->status;
595 if (G_LIKELY (mon_status_get_owner (old_status) == 0)) {
596 /* Try to install our ID in the owner field, nest
597 * should have been left at 1 by the previous unlock
600 new_status = mon_status_set_owner (old_status, id);
601 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
602 if (G_LIKELY (tmp_status == old_status)) {
604 g_assert (mon->nest == 1);
605 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_DONE);
610 /* If the object is currently locked by this thread... */
611 if (mon_status_get_owner (old_status) == id) {
613 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_DONE);
617 /* We need to make sure there's a semaphore handle (creating it if
618 * necessary), and block on it
620 if (mon->entry_sem == NULL) {
621 /* Create the semaphore */
622 sem = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
623 g_assert (sem != NULL);
624 if (InterlockedCompareExchangePointer ((gpointer*)&mon->entry_sem, sem, NULL) != NULL) {
625 /* Someone else just put a handle here */
631 * We need to register ourselves as waiting if it is the first time we are waiting,
632 * of if we were signaled and failed to acquire the lock.
635 old_status = mon->status;
637 if (mon_status_get_owner (old_status) == 0)
638 goto retry_contended;
639 new_status = mon_status_increment_entry_count (old_status);
640 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
641 if (tmp_status == old_status) {
644 old_status = tmp_status;
648 if (ms != INFINITE) {
649 then = mono_msec_ticks ();
653 #ifndef DISABLE_PERFCOUNTERS
654 mono_perfcounters->thread_queue_len++;
655 mono_perfcounters->thread_queue_max++;
657 thread = mono_thread_internal_current ();
659 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
662 * We pass TRUE instead of allow_interruption since we have to check for the
663 * StopRequested case below.
665 MONO_PREPARE_BLOCKING
666 ret = WaitForSingleObjectEx (mon->entry_sem, waitms, TRUE);
669 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
671 #ifndef DISABLE_PERFCOUNTERS
672 mono_perfcounters->thread_queue_len--;
675 if (ret == WAIT_IO_COMPLETION && !allow_interruption) {
678 * We have to obey a stop/suspend request even if
679 * allow_interruption is FALSE to avoid hangs at shutdown.
681 if (!mono_thread_test_state (mono_thread_internal_current (), (ThreadState_StopRequested|ThreadState_SuspendRequested))) {
682 if (ms != INFINITE) {
683 now = mono_msec_ticks ();
685 LOCK_DEBUG (g_message ("%s: wrapped around! now=0x%x then=0x%x", __func__, now, then));
687 now += (0xffffffff - then);
690 LOCK_DEBUG (g_message ("%s: wrap rejig: now=0x%x then=0x%x delta=0x%x", __func__, now, then, now-then));
700 /* retry from the top */
701 goto retry_contended;
703 } else if (ret == WAIT_OBJECT_0) {
705 /* retry from the top */
706 goto retry_contended;
707 } else if (ret == WAIT_TIMEOUT) {
711 /* Timed out or interrupted */
712 mon_decrement_entry_count (mon);
714 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_FAIL);
716 if (ret == WAIT_IO_COMPLETION) {
717 LOCK_DEBUG (g_message ("%s: (%d) interrupted waiting, returning -1", __func__, id));
719 } else if (ret == WAIT_TIMEOUT) {
720 LOCK_DEBUG (g_message ("%s: (%d) timed out waiting, returning FALSE", __func__, id));
723 g_assert_not_reached ();
729 mono_monitor_enter (MonoObject *obj)
731 return mono_monitor_try_enter_internal (obj, INFINITE, FALSE) == 1;
735 mono_monitor_try_enter (MonoObject *obj, guint32 ms)
737 return mono_monitor_try_enter_internal (obj, ms, FALSE) == 1;
741 mono_monitor_exit (MonoObject *obj)
743 MonoThreadsSync *mon;
745 guint32 new_status, old_status, tmp_status;
747 LOCK_DEBUG (g_message ("%s: (%d) Unlocking %p", __func__, mono_thread_info_get_small_id (), obj));
749 if (G_UNLIKELY (!obj)) {
750 mono_raise_exception (mono_get_exception_argument_null ("obj"));
754 mon = obj->synchronisation;
756 #ifdef HAVE_MOVING_COLLECTOR
760 if (lw.lock_word & LOCK_WORD_THIN_HASH)
762 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
766 if (G_UNLIKELY (mon == NULL)) {
767 /* No one ever used Enter. Just ignore the Exit request as MS does */
771 old_status = mon->status;
772 if (G_UNLIKELY (mon_status_get_owner (old_status) != mono_thread_info_get_small_id ())) {
776 nest = mon->nest - 1;
779 * Release lock and do the wakeup stuff. It's possible that
780 * the last blocking thread gave up waiting just before we
781 * release the semaphore resulting in a negative entry count
782 * and a futile wakeup next time there's contention for this
786 gboolean have_waiters = mon_status_have_waiters (old_status);
788 new_status = mon_status_set_owner (old_status, 0);
790 new_status = mon_status_decrement_entry_count (new_status);
791 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
792 if (tmp_status == old_status) {
794 ReleaseSemaphore (mon->entry_sem, 1, NULL);
797 old_status = tmp_status;
799 LOCK_DEBUG (g_message ("%s: (%d) Object %p is now unlocked", __func__, mono_thread_info_get_small_id (), obj));
801 /* object is now unlocked, leave nest==1 so we don't
802 * need to set it when the lock is reacquired
806 LOCK_DEBUG (g_message ("%s: (%d) Object %p is now locked %d times", __func__, mono_thread_info_get_small_id (), obj, nest));
812 mono_monitor_get_object_monitor_weak_link (MonoObject *object)
815 MonoThreadsSync *sync = NULL;
817 lw.sync = object->synchronisation;
818 if (lw.lock_word & LOCK_WORD_FAT_HASH) {
819 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
821 } else if (!(lw.lock_word & LOCK_WORD_THIN_HASH)) {
825 if (sync && sync->data)
831 * mono_monitor_threads_sync_member_offset:
832 * @status_offset: returns size and offset of the "status" member
833 * @nest_offset: returns size and offset of the "nest" member
835 * Returns the offsets and sizes of two members of the
836 * MonoThreadsSync struct. The Monitor ASM fastpaths need this.
839 mono_monitor_threads_sync_members_offset (int *status_offset, int *nest_offset)
843 #define ENCODE_OFF_SIZE(o,s) (((o) << 8) | ((s) & 0xff))
845 *status_offset = ENCODE_OFF_SIZE (MONO_STRUCT_OFFSET (MonoThreadsSync, status), sizeof (ts.status));
846 *nest_offset = ENCODE_OFF_SIZE (MONO_STRUCT_OFFSET (MonoThreadsSync, nest), sizeof (ts.nest));
850 ves_icall_System_Threading_Monitor_Monitor_try_enter (MonoObject *obj, guint32 ms)
855 res = mono_monitor_try_enter_internal (obj, ms, TRUE);
857 mono_thread_interruption_checkpoint ();
864 ves_icall_System_Threading_Monitor_Monitor_try_enter_with_atomic_var (MonoObject *obj, guint32 ms, char *lockTaken)
868 res = mono_monitor_try_enter_internal (obj, ms, TRUE);
869 /*This means we got interrupted during the wait and didn't got the monitor.*/
871 mono_thread_interruption_checkpoint ();
873 /*It's safe to do it from here since interruption would happen only on the wrapper.*/
874 *lockTaken = res == 1;
878 mono_monitor_enter_v4 (MonoObject *obj, char *lock_taken)
880 if (*lock_taken == 1)
881 mono_raise_exception (mono_get_exception_argument ("lockTaken", "lockTaken is already true"));
883 ves_icall_System_Threading_Monitor_Monitor_try_enter_with_atomic_var (obj, INFINITE, lock_taken);
887 ves_icall_System_Threading_Monitor_Monitor_test_owner (MonoObject *obj)
889 MonoThreadsSync *mon;
891 LOCK_DEBUG (g_message ("%s: Testing if %p is owned by thread %d", __func__, obj, mono_thread_info_get_small_id()));
893 mon = obj->synchronisation;
894 #ifdef HAVE_MOVING_COLLECTOR
898 if (lw.lock_word & LOCK_WORD_THIN_HASH)
900 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
908 if (mon_status_get_owner (mon->status) == mono_thread_info_get_small_id ()) {
916 ves_icall_System_Threading_Monitor_Monitor_test_synchronised (MonoObject *obj)
918 MonoThreadsSync *mon;
920 LOCK_DEBUG (g_message("%s: (%d) Testing if %p is owned by any thread", __func__, mono_thread_info_get_small_id (), obj));
922 mon = obj->synchronisation;
923 #ifdef HAVE_MOVING_COLLECTOR
927 if (lw.lock_word & LOCK_WORD_THIN_HASH)
929 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
937 if (mon_status_get_owner (mon->status) != 0) {
944 /* All wait list manipulation in the pulse, pulseall and wait
945 * functions happens while the monitor lock is held, so we don't need
946 * any extra struct locking
950 ves_icall_System_Threading_Monitor_Monitor_pulse (MonoObject *obj)
952 MonoThreadsSync *mon;
954 LOCK_DEBUG (g_message ("%s: (%d) Pulsing %p", __func__, mono_thread_info_get_small_id (), obj));
956 mon = obj->synchronisation;
957 #ifdef HAVE_MOVING_COLLECTOR
961 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
962 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Not locked"));
965 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
970 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Not locked"));
973 if (mon_status_get_owner (mon->status) != mono_thread_info_get_small_id ()) {
974 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
978 LOCK_DEBUG (g_message ("%s: (%d) %d threads waiting", __func__, mono_thread_info_get_small_id (), g_slist_length (mon->wait_list)));
980 if (mon->wait_list != NULL) {
981 LOCK_DEBUG (g_message ("%s: (%d) signalling and dequeuing handle %p", __func__, mono_thread_info_get_small_id (), mon->wait_list->data));
983 SetEvent (mon->wait_list->data);
984 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
989 ves_icall_System_Threading_Monitor_Monitor_pulse_all (MonoObject *obj)
991 MonoThreadsSync *mon;
993 LOCK_DEBUG (g_message("%s: (%d) Pulsing all %p", __func__, mono_thread_info_get_small_id (), obj));
995 mon = obj->synchronisation;
996 #ifdef HAVE_MOVING_COLLECTOR
1000 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
1001 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Not locked"));
1004 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1009 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Not locked"));
1012 if (mon_status_get_owner (mon->status) != mono_thread_info_get_small_id ()) {
1013 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
1017 LOCK_DEBUG (g_message ("%s: (%d) %d threads waiting", __func__, mono_thread_info_get_small_id (), g_slist_length (mon->wait_list)));
1019 while (mon->wait_list != NULL) {
1020 LOCK_DEBUG (g_message ("%s: (%d) signalling and dequeuing handle %p", __func__, mono_thread_info_get_small_id (), mon->wait_list->data));
1022 SetEvent (mon->wait_list->data);
1023 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1028 ves_icall_System_Threading_Monitor_Monitor_wait (MonoObject *obj, guint32 ms)
1030 MonoThreadsSync *mon;
1034 gboolean success = FALSE;
1036 MonoInternalThread *thread = mono_thread_internal_current ();
1038 LOCK_DEBUG (g_message ("%s: (%d) Trying to wait for %p with timeout %dms", __func__, mono_thread_info_get_small_id (), obj, ms));
1040 mon = obj->synchronisation;
1041 #ifdef HAVE_MOVING_COLLECTOR
1045 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
1046 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Not locked"));
1049 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
1054 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Not locked"));
1057 if (mon_status_get_owner (mon->status) != mono_thread_info_get_small_id ()) {
1058 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
1062 /* Do this WaitSleepJoin check before creating the event handle */
1063 mono_thread_current_check_pending_interrupt ();
1065 event = CreateEvent (NULL, FALSE, FALSE, NULL);
1066 if (event == NULL) {
1067 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Failed to set up wait event"));
1071 LOCK_DEBUG (g_message ("%s: (%d) queuing handle %p", __func__, mono_thread_info_get_small_id (), event));
1073 mono_thread_current_check_pending_interrupt ();
1075 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1077 mon->wait_list = g_slist_append (mon->wait_list, event);
1079 /* Save the nest count, and release the lock */
1082 mono_monitor_exit (obj);
1084 LOCK_DEBUG (g_message ("%s: (%d) Unlocked %p lock %p", __func__, mono_thread_info_get_small_id (), obj, mon));
1086 /* There's no race between unlocking mon and waiting for the
1087 * event, because auto reset events are sticky, and this event
1088 * is private to this thread. Therefore even if the event was
1089 * signalled before we wait, we still succeed.
1091 MONO_PREPARE_BLOCKING
1092 ret = WaitForSingleObjectEx (event, ms, TRUE);
1093 MONO_FINISH_BLOCKING
1095 /* Reset the thread state fairly early, so we don't have to worry
1096 * about the monitor error checking
1098 mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1100 if (mono_thread_interruption_requested ()) {
1102 * Can't remove the event from wait_list, since the monitor is not locked by
1103 * us. So leave it there, mon_new () will delete it when the mon structure
1104 * is placed on the free list.
1105 * FIXME: The caller expects to hold the lock after the wait returns, but it
1106 * doesn't happen in this case:
1107 * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=97268
1112 /* Regain the lock with the previous nest count */
1114 regain = mono_monitor_try_enter_internal (obj, INFINITE, TRUE);
1116 mono_thread_interruption_checkpoint ();
1117 } while (regain == -1);
1120 /* Something went wrong, so throw a
1121 * SynchronizationLockException
1123 CloseHandle (event);
1124 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Failed to regain lock"));
1130 LOCK_DEBUG (g_message ("%s: (%d) Regained %p lock %p", __func__, mono_thread_info_get_small_id (), obj, mon));
1132 if (ret == WAIT_TIMEOUT) {
1133 /* Poll the event again, just in case it was signalled
1134 * while we were trying to regain the monitor lock
1136 ret = WaitForSingleObjectEx (event, 0, FALSE);
1139 /* Pulse will have popped our event from the queue if it signalled
1140 * us, so we only do it here if the wait timed out.
1142 * This avoids a race condition where the thread holding the
1143 * lock can Pulse several times before the WaitForSingleObject
1144 * returns. If we popped the queue here then this event might
1145 * be signalled more than once, thereby starving another
1149 if (ret == WAIT_OBJECT_0) {
1150 LOCK_DEBUG (g_message ("%s: (%d) Success", __func__, mono_thread_info_get_small_id ()));
1153 LOCK_DEBUG (g_message ("%s: (%d) Wait failed, dequeuing handle %p", __func__, mono_thread_info_get_small_id (), event));
1154 /* No pulse, so we have to remove ourself from the
1157 mon->wait_list = g_slist_remove (mon->wait_list, event);
1159 CloseHandle (event);