Windows x64 full AOT support for mono/mini regression tests.
[mono.git] / mono / metadata / monitor.c
1 /*
2  * monitor.c:  Monitor locking functions
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *
7  * Copyright 2003 Ximian, Inc (http://www.ximian.com)
8  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
9  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
10  */
11
12 #include <config.h>
13 #include <glib.h>
14 #include <string.h>
15
16 #include <mono/metadata/abi-details.h>
17 #include <mono/metadata/monitor.h>
18 #include <mono/metadata/threads-types.h>
19 #include <mono/metadata/exception.h>
20 #include <mono/metadata/threads.h>
21 #include <mono/io-layer/io-layer.h>
22 #include <mono/metadata/object-internals.h>
23 #include <mono/metadata/class-internals.h>
24 #include <mono/metadata/gc-internals.h>
25 #include <mono/metadata/method-builder.h>
26 #include <mono/metadata/debug-helpers.h>
27 #include <mono/metadata/tabledefs.h>
28 #include <mono/metadata/marshal.h>
29 #include <mono/utils/mono-threads.h>
30 #include <mono/metadata/profiler-private.h>
31 #include <mono/utils/mono-time.h>
32 #include <mono/utils/atomic.h>
33
34 /*
35  * Pull the list of opcodes
36  */
37 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
38         a = i,
39
40 enum {
41 #include "mono/cil/opcode.def"
42         LAST = 0xff
43 };
44 #undef OPDEF
45
46 /*#define LOCK_DEBUG(a) do { a; } while (0)*/
47 #define LOCK_DEBUG(a)
48
49 /*
50  * The monitor implementation here is based on
51  * http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf and
52  * http://www.research.ibm.com/people/d/dfb/papers/Bacon98Thin.ps
53  *
54  * The Dice paper describes a technique for saving lock record space
55  * by returning records to a free list when they become unused.  That
56  * sounds like unnecessary complexity to me, though if it becomes
57  * clear that unused lock records are taking up lots of space or we
58  * need to shave more time off by avoiding a malloc then we can always
59  * implement the free list idea later.  The timeout parameter to
60  * try_enter voids some of the assumptions about the reference count
61  * field in Dice's implementation too.  In his version, the thread
62  * attempting to lock a contended object will block until it succeeds,
63  * so the reference count will never be decremented while an object is
64  * locked.
65  *
66  * Bacon's thin locks have a fast path that doesn't need a lock record
67  * for the common case of locking an unlocked or shallow-nested
68  * object.
69  */
70
71
72 typedef struct _MonitorArray MonitorArray;
73
74 struct _MonitorArray {
75         MonitorArray *next;
76         int num_monitors;
77         MonoThreadsSync monitors [MONO_ZERO_LEN_ARRAY];
78 };
79
80 #define mono_monitor_allocator_lock() mono_os_mutex_lock (&monitor_mutex)
81 #define mono_monitor_allocator_unlock() mono_os_mutex_unlock (&monitor_mutex)
82 static mono_mutex_t monitor_mutex;
83 static MonoThreadsSync *monitor_freelist;
84 static MonitorArray *monitor_allocated;
85 static int array_size = 16;
86
87 /* MonoThreadsSync status helpers */
88
89 static inline guint32
90 mon_status_get_owner (guint32 status)
91 {
92         return status & OWNER_MASK;
93 }
94
95 static inline guint32
96 mon_status_set_owner (guint32 status, guint32 owner)
97 {
98         return (status & ENTRY_COUNT_MASK) | owner;
99 }
100
101 static inline gint32
102 mon_status_get_entry_count (guint32 status)
103 {
104         gint32 entry_count = (gint32)((status & ENTRY_COUNT_MASK) >> ENTRY_COUNT_SHIFT);
105         gint32 zero = (gint32)(((guint32)ENTRY_COUNT_ZERO) >> ENTRY_COUNT_SHIFT);
106         return entry_count - zero;
107 }
108
109 static inline guint32
110 mon_status_init_entry_count (guint32 status)
111 {
112         return (status & OWNER_MASK) | ENTRY_COUNT_ZERO;
113 }
114
115 static inline guint32
116 mon_status_increment_entry_count (guint32 status)
117 {
118         return status + (1 << ENTRY_COUNT_SHIFT);
119 }
120
121 static inline guint32
122 mon_status_decrement_entry_count (guint32 status)
123 {
124         return status - (1 << ENTRY_COUNT_SHIFT);
125 }
126
127 static inline gboolean
128 mon_status_have_waiters (guint32 status)
129 {
130         return status & ENTRY_COUNT_WAITERS;
131 }
132
133 /* LockWord helpers */
134
135 static inline MonoThreadsSync*
136 lock_word_get_inflated_lock (LockWord lw)
137 {
138         lw.lock_word &= (~LOCK_WORD_STATUS_MASK);
139         return lw.sync;
140 }
141
142 static inline gboolean
143 lock_word_is_inflated (LockWord lw)
144 {
145         return lw.lock_word & LOCK_WORD_INFLATED;
146 }
147
148 static inline gboolean
149 lock_word_has_hash (LockWord lw)
150 {
151         return lw.lock_word & LOCK_WORD_HAS_HASH;
152 }
153
154 static inline LockWord
155 lock_word_set_has_hash (LockWord lw)
156 {
157         LockWord nlw;
158         nlw.lock_word = lw.lock_word | LOCK_WORD_HAS_HASH;
159         return nlw;
160 }
161
162 static inline gboolean
163 lock_word_is_free (LockWord lw)
164 {
165         return !lw.lock_word;
166 }
167
168 static inline gboolean
169 lock_word_is_flat (LockWord lw)
170 {
171         /* Return whether the lock is flat or free */
172         return (lw.lock_word & LOCK_WORD_STATUS_MASK) == LOCK_WORD_FLAT;
173 }
174
175 static inline gint32
176 lock_word_get_hash (LockWord lw)
177 {
178         return (gint32) (lw.lock_word >> LOCK_WORD_HASH_SHIFT);
179 }
180
181 static inline gint32
182 lock_word_get_nest (LockWord lw)
183 {
184         if (lock_word_is_free (lw))
185                 return 0;
186         /* Inword nest count starts from 0 */
187         return ((lw.lock_word & LOCK_WORD_NEST_MASK) >> LOCK_WORD_NEST_SHIFT) + 1;
188 }
189
190 static inline gboolean
191 lock_word_is_nested (LockWord lw)
192 {
193         return lw.lock_word & LOCK_WORD_NEST_MASK;
194 }
195
196 static inline gboolean
197 lock_word_is_max_nest (LockWord lw)
198 {
199         return (lw.lock_word & LOCK_WORD_NEST_MASK) == LOCK_WORD_NEST_MASK;
200 }
201
202 static inline LockWord
203 lock_word_increment_nest (LockWord lw)
204 {
205         lw.lock_word += 1 << LOCK_WORD_NEST_SHIFT;
206         return lw;
207 }
208
209 static inline LockWord
210 lock_word_decrement_nest (LockWord lw)
211 {
212         lw.lock_word -= 1 << LOCK_WORD_NEST_SHIFT;
213         return lw;
214 }
215
216 static inline gint32
217 lock_word_get_owner (LockWord lw)
218 {
219         return lw.lock_word >> LOCK_WORD_OWNER_SHIFT;
220 }
221
222 static inline LockWord
223 lock_word_new_thin_hash (gint32 hash)
224 {
225         LockWord lw;
226         lw.lock_word = (guint32)hash;
227         lw.lock_word = (lw.lock_word << LOCK_WORD_HASH_SHIFT) | LOCK_WORD_HAS_HASH;
228         return lw;
229 }
230
231 static inline LockWord
232 lock_word_new_inflated (MonoThreadsSync *mon)
233 {
234         LockWord lw;
235         lw.sync = mon;
236         lw.lock_word |= LOCK_WORD_INFLATED;
237         return lw;
238 }
239
240 static inline LockWord
241 lock_word_new_flat (gint32 owner)
242 {
243         LockWord lw;
244         lw.lock_word = owner;
245         lw.lock_word <<= LOCK_WORD_OWNER_SHIFT;
246         return lw;
247 }
248
249 void
250 mono_monitor_init (void)
251 {
252         mono_os_mutex_init_recursive (&monitor_mutex);
253 }
254  
255 void
256 mono_monitor_cleanup (void)
257 {
258         MonoThreadsSync *mon;
259         /* MonitorArray *marray, *next = NULL; */
260
261         /*mono_os_mutex_destroy (&monitor_mutex);*/
262
263         /* The monitors on the freelist don't have weak links - mark them */
264         for (mon = monitor_freelist; mon; mon = (MonoThreadsSync *)mon->data)
265                 mon->wait_list = (GSList *)-1;
266
267         /*
268          * FIXME: This still crashes with sgen (async_read.exe)
269          *
270          * In mini_cleanup() we first call mono_runtime_cleanup(), which calls
271          * mono_monitor_cleanup(), which is supposed to free all monitor memory.
272          *
273          * Later in mini_cleanup(), we call mono_domain_free(), which calls
274          * mono_gc_clear_domain(), which frees all weak links associated with objects.
275          * Those weak links reside in the monitor structures, which we've freed earlier.
276          *
277          * Unless we fix this dependency in the shutdown sequence this code has to remain
278          * disabled, or at least the call to g_free().
279          */
280         /*
281         for (marray = monitor_allocated; marray; marray = next) {
282                 int i;
283
284                 for (i = 0; i < marray->num_monitors; ++i) {
285                         mon = &marray->monitors [i];
286                         if (mon->wait_list != (gpointer)-1)
287                                 mono_gc_weak_link_remove (&mon->data);
288                 }
289
290                 next = marray->next;
291                 g_free (marray);
292         }
293         */
294 }
295
296 static int
297 monitor_is_on_freelist (MonoThreadsSync *mon)
298 {
299         MonitorArray *marray;
300         for (marray = monitor_allocated; marray; marray = marray->next) {
301                 if (mon >= marray->monitors && mon < &marray->monitors [marray->num_monitors])
302                         return TRUE;
303         }
304         return FALSE;
305 }
306
307 /**
308  * mono_locks_dump:
309  * @include_untaken:
310  *
311  * Print a report on stdout of the managed locks currently held by
312  * threads. If @include_untaken is specified, list also inflated locks
313  * which are unheld.
314  * This is supposed to be used in debuggers like gdb.
315  */
316 void
317 mono_locks_dump (gboolean include_untaken)
318 {
319         int i;
320         int used = 0, on_freelist = 0, to_recycle = 0, total = 0, num_arrays = 0;
321         MonoThreadsSync *mon;
322         MonitorArray *marray;
323         for (mon = monitor_freelist; mon; mon = (MonoThreadsSync *)mon->data)
324                 on_freelist++;
325         for (marray = monitor_allocated; marray; marray = marray->next) {
326                 total += marray->num_monitors;
327                 num_arrays++;
328                 for (i = 0; i < marray->num_monitors; ++i) {
329                         mon = &marray->monitors [i];
330                         if (mon->data == NULL) {
331                                 if (i < marray->num_monitors - 1)
332                                         to_recycle++;
333                         } else {
334                                 if (!monitor_is_on_freelist ((MonoThreadsSync *)mon->data)) {
335                                         MonoObject *holder = (MonoObject *)mono_gchandle_get_target ((guint32)mon->data);
336                                         if (mon_status_get_owner (mon->status)) {
337                                                 g_print ("Lock %p in object %p held by thread %d, nest level: %d\n",
338                                                         mon, holder, mon_status_get_owner (mon->status), mon->nest);
339                                                 if (mon->entry_sem)
340                                                         g_print ("\tWaiting on semaphore %p: %d\n", mon->entry_sem, mon_status_get_entry_count (mon->status));
341                                         } else if (include_untaken) {
342                                                 g_print ("Lock %p in object %p untaken\n", mon, holder);
343                                         }
344                                         used++;
345                                 }
346                         }
347                 }
348         }
349         g_print ("Total locks (in %d array(s)): %d, used: %d, on freelist: %d, to recycle: %d\n",
350                 num_arrays, total, used, on_freelist, to_recycle);
351 }
352
353 /* LOCKING: this is called with monitor_mutex held */
354 static void 
355 mon_finalize (MonoThreadsSync *mon)
356 {
357         LOCK_DEBUG (g_message ("%s: Finalizing sync %p", __func__, mon));
358
359         if (mon->entry_sem != NULL) {
360                 CloseHandle (mon->entry_sem);
361                 mon->entry_sem = NULL;
362         }
363         /* If this isn't empty then something is seriously broken - it
364          * means a thread is still waiting on the object that owned
365          * this lock, but the object has been finalized.
366          */
367         g_assert (mon->wait_list == NULL);
368
369         /* owner and nest are set in mon_new, no need to zero them out */
370
371         mon->data = monitor_freelist;
372         monitor_freelist = mon;
373 #ifndef DISABLE_PERFCOUNTERS
374         mono_perfcounters->gc_sync_blocks--;
375 #endif
376 }
377
378 /* LOCKING: this is called with monitor_mutex held */
379 static MonoThreadsSync *
380 mon_new (gsize id)
381 {
382         MonoThreadsSync *new_;
383
384         if (!monitor_freelist) {
385                 MonitorArray *marray;
386                 int i;
387                 /* see if any sync block has been collected */
388                 new_ = NULL;
389                 for (marray = monitor_allocated; marray; marray = marray->next) {
390                         for (i = 0; i < marray->num_monitors; ++i) {
391                                 if (mono_gchandle_get_target ((guint32)marray->monitors [i].data) == NULL) {
392                                         new_ = &marray->monitors [i];
393                                         if (new_->wait_list) {
394                                                 /* Orphaned events left by aborted threads */
395                                                 while (new_->wait_list) {
396                                                         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d): Closing orphaned event %d", mono_thread_info_get_small_id (), new_->wait_list->data));
397                                                         CloseHandle (new_->wait_list->data);
398                                                         new_->wait_list = g_slist_remove (new_->wait_list, new_->wait_list->data);
399                                                 }
400                                         }
401                                         mono_gchandle_free ((guint32)new_->data);
402                                         new_->data = monitor_freelist;
403                                         monitor_freelist = new_;
404                                 }
405                         }
406                         /* small perf tweak to avoid scanning all the blocks */
407                         if (new_)
408                                 break;
409                 }
410                 /* need to allocate a new array of monitors */
411                 if (!monitor_freelist) {
412                         MonitorArray *last;
413                         LOCK_DEBUG (g_message ("%s: allocating more monitors: %d", __func__, array_size));
414                         marray = (MonitorArray *)g_malloc0 (MONO_SIZEOF_MONO_ARRAY + array_size * sizeof (MonoThreadsSync));
415                         marray->num_monitors = array_size;
416                         array_size *= 2;
417                         /* link into the freelist */
418                         for (i = 0; i < marray->num_monitors - 1; ++i) {
419                                 marray->monitors [i].data = &marray->monitors [i + 1];
420                         }
421                         marray->monitors [i].data = NULL; /* the last one */
422                         monitor_freelist = &marray->monitors [0];
423                         /* we happend the marray instead of prepending so that
424                          * the collecting loop above will need to scan smaller arrays first
425                          */
426                         if (!monitor_allocated) {
427                                 monitor_allocated = marray;
428                         } else {
429                                 last = monitor_allocated;
430                                 while (last->next)
431                                         last = last->next;
432                                 last->next = marray;
433                         }
434                 }
435         }
436
437         new_ = monitor_freelist;
438         monitor_freelist = (MonoThreadsSync *)new_->data;
439
440         new_->status = mon_status_set_owner (0, id);
441         new_->status = mon_status_init_entry_count (new_->status);
442         new_->nest = 1;
443         new_->data = NULL;
444         
445 #ifndef DISABLE_PERFCOUNTERS
446         mono_perfcounters->gc_sync_blocks++;
447 #endif
448         return new_;
449 }
450
451 static MonoThreadsSync*
452 alloc_mon (MonoObject *obj, gint32 id)
453 {
454         MonoThreadsSync *mon;
455
456         mono_monitor_allocator_lock ();
457         mon = mon_new (id);
458         mon->data = (void *)(size_t)mono_gchandle_new_weakref (obj, TRUE);
459         mono_monitor_allocator_unlock ();
460
461         return mon;
462 }
463
464
465 static void
466 discard_mon (MonoThreadsSync *mon)
467 {
468         mono_monitor_allocator_lock ();
469         mono_gchandle_free ((guint32)mon->data);
470         mon_finalize (mon);
471         mono_monitor_allocator_unlock ();
472 }
473
474 static void
475 mono_monitor_inflate_owned (MonoObject *obj, int id)
476 {
477         MonoThreadsSync *mon;
478         LockWord nlw, old_lw, tmp_lw;
479         guint32 nest;
480
481         old_lw.sync = obj->synchronisation;
482         LOCK_DEBUG (g_message ("%s: (%d) Inflating owned lock object %p; LW = %p", __func__, id, obj, old_lw.sync));
483
484         if (lock_word_is_inflated (old_lw)) {
485                 /* Someone else inflated the lock in the meantime */
486                 return;
487         }
488
489         mon = alloc_mon (obj, id);
490
491         nest = lock_word_get_nest (old_lw);
492         mon->nest = nest;
493
494         nlw = lock_word_new_inflated (mon);
495
496         mono_memory_write_barrier ();
497         tmp_lw.sync = (MonoThreadsSync *)InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, nlw.sync, old_lw.sync);
498         if (tmp_lw.sync != old_lw.sync) {
499                 /* Someone else inflated the lock in the meantime */
500                 discard_mon (mon);
501         }
502 }
503
504 static void
505 mono_monitor_inflate (MonoObject *obj)
506 {
507         MonoThreadsSync *mon;
508         LockWord nlw, old_lw;
509
510         LOCK_DEBUG (g_message ("%s: (%d) Inflating lock object %p; LW = %p", __func__, mono_thread_info_get_small_id (), obj, obj->synchronisation));
511
512         mon = alloc_mon (obj, 0);
513
514         nlw = lock_word_new_inflated (mon);
515
516         old_lw.sync = obj->synchronisation;
517
518         for (;;) {
519                 LockWord tmp_lw;
520
521                 if (lock_word_is_inflated (old_lw)) {
522                         break;
523                 }
524 #ifdef HAVE_MOVING_COLLECTOR
525                  else if (lock_word_has_hash (old_lw)) {
526                         mon->hash_code = lock_word_get_hash (old_lw);
527                         mon->status = mon_status_set_owner (mon->status, 0);
528                         nlw = lock_word_set_has_hash (nlw);
529                 }
530 #endif
531                 else if (lock_word_is_free (old_lw)) {
532                         mon->status = mon_status_set_owner (mon->status, 0);
533                         mon->nest = 1;
534                 } else {
535                         /* Lock is flat */
536                         mon->status = mon_status_set_owner (mon->status, lock_word_get_owner (old_lw));
537                         mon->nest = lock_word_get_nest (old_lw);
538                 }
539                 mono_memory_write_barrier ();
540                 tmp_lw.sync = (MonoThreadsSync *)InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, nlw.sync, old_lw.sync);
541                 if (tmp_lw.sync == old_lw.sync) {
542                         /* Successfully inflated the lock */
543                         return;
544                 }
545
546                 old_lw.sync = tmp_lw.sync;
547         }
548
549         /* Someone else inflated the lock before us */
550         discard_mon (mon);
551 }
552
553 #define MONO_OBJECT_ALIGNMENT_SHIFT     3
554
555 /*
556  * mono_object_hash:
557  * @obj: an object
558  *
559  * Calculate a hash code for @obj that is constant while @obj is alive.
560  */
561 int
562 mono_object_hash (MonoObject* obj)
563 {
564 #ifdef HAVE_MOVING_COLLECTOR
565         LockWord lw;
566         unsigned int hash;
567         if (!obj)
568                 return 0;
569         lw.sync = obj->synchronisation;
570
571         LOCK_DEBUG (g_message("%s: (%d) Get hash for object %p; LW = %p", __func__, mono_thread_info_get_small_id (), obj, obj->synchronisation));
572
573         if (lock_word_has_hash (lw)) {
574                 if (lock_word_is_inflated (lw)) {
575                         return lock_word_get_inflated_lock (lw)->hash_code;
576                 } else {
577                         return lock_word_get_hash (lw);
578                 }
579         }
580         /*
581          * while we are inside this function, the GC will keep this object pinned,
582          * since we are in the unmanaged stack. Thanks to this and to the hash
583          * function that depends only on the address, we can ignore the races if
584          * another thread computes the hash at the same time, because it'll end up
585          * with the same value.
586          */
587         hash = (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
588 #if SIZEOF_VOID_P == 4
589         /* clear the top bits as they can be discarded */
590         hash &= ~(LOCK_WORD_STATUS_MASK << (32 - LOCK_WORD_STATUS_BITS));
591 #endif
592         if (lock_word_is_free (lw)) {
593                 LockWord old_lw;
594                 lw = lock_word_new_thin_hash (hash);
595
596                 old_lw.sync = (MonoThreadsSync *)InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, NULL);
597                 if (old_lw.sync == NULL) {
598                         return hash;
599                 }
600
601                 if (lock_word_has_hash (old_lw)) {
602                         /* Done by somebody else */
603                         return hash;
604                 }
605                         
606                 mono_monitor_inflate (obj);
607                 lw.sync = obj->synchronisation;
608         } else if (lock_word_is_flat (lw)) {
609                 int id = mono_thread_info_get_small_id ();
610                 if (lock_word_get_owner (lw) == id)
611                         mono_monitor_inflate_owned (obj, id);
612                 else
613                         mono_monitor_inflate (obj);
614                 lw.sync = obj->synchronisation;
615         }
616
617         /* At this point, the lock is inflated */
618         lock_word_get_inflated_lock (lw)->hash_code = hash;
619         lw = lock_word_set_has_hash (lw);
620         mono_memory_write_barrier ();
621         obj->synchronisation = lw.sync;
622         return hash;
623 #else
624 /*
625  * Wang's address-based hash function:
626  *   http://www.concentric.net/~Ttwang/tech/addrhash.htm
627  */
628         return (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
629 #endif
630 }
631
632 static void
633 mono_monitor_ensure_owned (LockWord lw, guint32 id)
634 {
635         if (lock_word_is_flat (lw)) {
636                 if (lock_word_get_owner (lw) == id)
637                         return;
638         } else if (lock_word_is_inflated (lw)) {
639                 if (mon_status_get_owner (lock_word_get_inflated_lock (lw)->status) == id)
640                         return;
641         }
642
643         mono_set_pending_exception (mono_get_exception_synchronization_lock ("Object synchronization method was called from an unsynchronized block of code."));
644 }
645
646 /*
647  * When this function is called it has already been established that the
648  * current thread owns the monitor.
649  */
650 static void
651 mono_monitor_exit_inflated (MonoObject *obj)
652 {
653         LockWord lw;
654         MonoThreadsSync *mon;
655         guint32 nest;
656
657         lw.sync = obj->synchronisation;
658         mon = lock_word_get_inflated_lock (lw);
659
660         nest = mon->nest - 1;
661         if (nest == 0) {
662                 guint32 new_status, old_status, tmp_status;
663
664                 old_status = mon->status;
665
666                 /*
667                  * Release lock and do the wakeup stuff. It's possible that
668                  * the last blocking thread gave up waiting just before we
669                  * release the semaphore resulting in a negative entry count
670                  * and a futile wakeup next time there's contention for this
671                  * object.
672                  */
673                 for (;;) {
674                         gboolean have_waiters = mon_status_have_waiters (old_status);
675         
676                         new_status = mon_status_set_owner (old_status, 0);
677                         if (have_waiters)
678                                 new_status = mon_status_decrement_entry_count (new_status);
679                         tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
680                         if (tmp_status == old_status) {
681                                 if (have_waiters)
682                                         ReleaseSemaphore (mon->entry_sem, 1, NULL);
683                                 break;
684                         }
685                         old_status = tmp_status;
686                 }
687                 LOCK_DEBUG (g_message ("%s: (%d) Object %p is now unlocked", __func__, mono_thread_info_get_small_id (), obj));
688         
689                 /* object is now unlocked, leave nest==1 so we don't
690                  * need to set it when the lock is reacquired
691                  */
692         } else {
693                 LOCK_DEBUG (g_message ("%s: (%d) Object %p is now locked %d times", __func__, mono_thread_info_get_small_id (), obj, nest));
694                 mon->nest = nest;
695         }
696 }
697
698 /*
699  * When this function is called it has already been established that the
700  * current thread owns the monitor.
701  */
702 static void
703 mono_monitor_exit_flat (MonoObject *obj, LockWord old_lw)
704 {
705         LockWord new_lw, tmp_lw;
706         if (G_UNLIKELY (lock_word_is_nested (old_lw)))
707                 new_lw = lock_word_decrement_nest (old_lw);
708         else
709                 new_lw.lock_word = 0;
710
711         tmp_lw.sync = (MonoThreadsSync *)InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, new_lw.sync, old_lw.sync);
712         if (old_lw.sync != tmp_lw.sync) {
713                 /* Someone inflated the lock in the meantime */
714                 mono_monitor_exit_inflated (obj);
715         }
716
717         LOCK_DEBUG (g_message ("%s: (%d) Object %p is now locked %d times; LW = %p", __func__, mono_thread_info_get_small_id (), obj, lock_word_get_nest (new_lw), obj->synchronisation));
718 }
719
720 static void
721 mon_decrement_entry_count (MonoThreadsSync *mon)
722 {
723         guint32 old_status, tmp_status, new_status;
724
725         /* Decrement entry count */
726         old_status = mon->status;
727         for (;;) {
728                 new_status = mon_status_decrement_entry_count (old_status);
729                 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
730                 if (tmp_status == old_status) {
731                         break;
732                 }
733                 old_status = tmp_status;
734         }
735 }
736
737 /* If allow_interruption==TRUE, the method will be interrumped if abort or suspend
738  * is requested. In this case it returns -1.
739  */ 
740 static inline gint32 
741 mono_monitor_try_enter_inflated (MonoObject *obj, guint32 ms, gboolean allow_interruption, guint32 id)
742 {
743         LockWord lw;
744         MonoThreadsSync *mon;
745         HANDLE sem;
746         guint32 then = 0, now, delta;
747         guint32 waitms;
748         guint32 ret;
749         guint32 new_status, old_status, tmp_status;
750         MonoInternalThread *thread;
751         gboolean interrupted = FALSE;
752
753         LOCK_DEBUG (g_message("%s: (%d) Trying to lock object %p (%d ms)", __func__, id, obj, ms));
754
755         if (G_UNLIKELY (!obj)) {
756                 mono_set_pending_exception (mono_get_exception_argument_null ("obj"));
757                 return FALSE;
758         }
759
760         lw.sync = obj->synchronisation;
761         mon = lock_word_get_inflated_lock (lw);
762 retry:
763         /* This case differs from Dice's case 3 because we don't
764          * deflate locks or cache unused lock records
765          */
766         old_status = mon->status;
767         if (G_LIKELY (mon_status_get_owner (old_status) == 0)) {
768                 /* Try to install our ID in the owner field, nest
769                 * should have been left at 1 by the previous unlock
770                 * operation
771                 */
772                 new_status = mon_status_set_owner (old_status, id);
773                 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
774                 if (G_LIKELY (tmp_status == old_status)) {
775                         /* Success */
776                         g_assert (mon->nest == 1);
777                         return 1;
778                 } else {
779                         /* Trumped again! */
780                         goto retry;
781                 }
782         }
783
784         /* If the object is currently locked by this thread... */
785         if (mon_status_get_owner (old_status) == id) {
786                 mon->nest++;
787                 return 1;
788         }
789
790         /* The object must be locked by someone else... */
791 #ifndef DISABLE_PERFCOUNTERS
792         mono_perfcounters->thread_contentions++;
793 #endif
794
795         /* If ms is 0 we don't block, but just fail straight away */
796         if (ms == 0) {
797                 LOCK_DEBUG (g_message ("%s: (%d) timed out, returning FALSE", __func__, id));
798                 return 0;
799         }
800
801         mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_CONTENTION);
802
803         /* The slow path begins here. */
804 retry_contended:
805         /* a small amount of duplicated code, but it allows us to insert the profiler
806          * callbacks without impacting the fast path: from here on we don't need to go back to the
807          * retry label, but to retry_contended. At this point mon is already installed in the object
808          * header.
809          */
810         /* This case differs from Dice's case 3 because we don't
811          * deflate locks or cache unused lock records
812          */
813         old_status = mon->status;
814         if (G_LIKELY (mon_status_get_owner (old_status) == 0)) {
815                 /* Try to install our ID in the owner field, nest
816                 * should have been left at 1 by the previous unlock
817                 * operation
818                 */
819                 new_status = mon_status_set_owner (old_status, id);
820                 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
821                 if (G_LIKELY (tmp_status == old_status)) {
822                         /* Success */
823                         g_assert (mon->nest == 1);
824                         mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_DONE);
825                         return 1;
826                 }
827         }
828
829         /* If the object is currently locked by this thread... */
830         if (mon_status_get_owner (old_status) == id) {
831                 mon->nest++;
832                 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_DONE);
833                 return 1;
834         }
835
836         /* We need to make sure there's a semaphore handle (creating it if
837          * necessary), and block on it
838          */
839         if (mon->entry_sem == NULL) {
840                 /* Create the semaphore */
841                 sem = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
842                 g_assert (sem != NULL);
843                 if (InterlockedCompareExchangePointer ((gpointer*)&mon->entry_sem, sem, NULL) != NULL) {
844                         /* Someone else just put a handle here */
845                         CloseHandle (sem);
846                 }
847         }
848
849         /*
850          * We need to register ourselves as waiting if it is the first time we are waiting,
851          * of if we were signaled and failed to acquire the lock.
852          */
853         if (!interrupted) {
854                 old_status = mon->status;
855                 for (;;) {
856                         if (mon_status_get_owner (old_status) == 0)
857                                 goto retry_contended;
858                         new_status = mon_status_increment_entry_count (old_status);
859                         tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
860                         if (tmp_status == old_status) {
861                                 break;
862                         }
863                         old_status = tmp_status;
864                 }
865         }
866
867         if (ms != INFINITE) {
868                 then = mono_msec_ticks ();
869         }
870         waitms = ms;
871         
872 #ifndef DISABLE_PERFCOUNTERS
873         mono_perfcounters->thread_queue_len++;
874         mono_perfcounters->thread_queue_max++;
875 #endif
876         thread = mono_thread_internal_current ();
877
878         mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
879
880         /*
881          * We pass TRUE instead of allow_interruption since we have to check for the
882          * StopRequested case below.
883          */
884         MONO_PREPARE_BLOCKING;
885         ret = WaitForSingleObjectEx (mon->entry_sem, waitms, TRUE);
886         MONO_FINISH_BLOCKING;
887
888         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
889         
890 #ifndef DISABLE_PERFCOUNTERS
891         mono_perfcounters->thread_queue_len--;
892 #endif
893
894         if (ret == WAIT_IO_COMPLETION && !allow_interruption) {
895                 interrupted = TRUE;
896                 /* 
897                  * We have to obey a stop/suspend request even if 
898                  * allow_interruption is FALSE to avoid hangs at shutdown.
899                  */
900                 if (!mono_thread_test_state (mono_thread_internal_current (), (MonoThreadState)(ThreadState_StopRequested | ThreadState_SuspendRequested | ThreadState_AbortRequested))) {
901                         if (ms != INFINITE) {
902                                 now = mono_msec_ticks ();
903                                 if (now < then) {
904                                         LOCK_DEBUG (g_message ("%s: wrapped around! now=0x%x then=0x%x", __func__, now, then));
905
906                                         now += (0xffffffff - then);
907                                         then = 0;
908
909                                         LOCK_DEBUG (g_message ("%s: wrap rejig: now=0x%x then=0x%x delta=0x%x", __func__, now, then, now-then));
910                                 }
911
912                                 delta = now - then;
913                                 if (delta >= ms) {
914                                         ms = 0;
915                                 } else {
916                                         ms -= delta;
917                                 }
918                         }
919                         /* retry from the top */
920                         goto retry_contended;
921                 }
922         } else if (ret == WAIT_OBJECT_0) {
923                 interrupted = FALSE;
924                 /* retry from the top */
925                 goto retry_contended;
926         } else if (ret == WAIT_TIMEOUT) {
927                 /* we're done */
928         }
929
930         /* Timed out or interrupted */
931         mon_decrement_entry_count (mon);
932
933         mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_FAIL);
934
935         if (ret == WAIT_IO_COMPLETION) {
936                 LOCK_DEBUG (g_message ("%s: (%d) interrupted waiting, returning -1", __func__, id));
937                 return -1;
938         } else if (ret == WAIT_TIMEOUT) {
939                 LOCK_DEBUG (g_message ("%s: (%d) timed out waiting, returning FALSE", __func__, id));
940                 return 0;
941         } else {
942                 g_assert_not_reached ();
943                 return 0;
944         }
945 }
946
947 /*
948  * If allow_interruption == TRUE, the method will be interrupted if abort or suspend
949  * is requested. In this case it returns -1.
950  */
951 static inline gint32
952 mono_monitor_try_enter_internal (MonoObject *obj, guint32 ms, gboolean allow_interruption)
953 {
954         LockWord lw;
955         int id = mono_thread_info_get_small_id ();
956
957         LOCK_DEBUG (g_message("%s: (%d) Trying to lock object %p (%d ms)", __func__, id, obj, ms));
958
959         if (G_UNLIKELY (!obj)) {
960                 mono_set_pending_exception (mono_get_exception_argument_null ("obj"));
961                 return FALSE;
962         }
963
964         lw.sync = obj->synchronisation;
965
966         if (G_LIKELY (lock_word_is_free (lw))) {
967                 LockWord nlw = lock_word_new_flat (id);
968                 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, nlw.sync, NULL) == NULL) {
969                         return 1;
970                 } else {
971                         /* Someone acquired it in the meantime or put a hash */
972                         mono_monitor_inflate (obj);
973                         return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
974                 }
975         } else if (lock_word_is_inflated (lw)) {
976                 return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
977         } else if (lock_word_is_flat (lw)) {
978                 if (lock_word_get_owner (lw) == id) {
979                         if (lock_word_is_max_nest (lw)) {
980                                 mono_monitor_inflate_owned (obj, id);
981                                 return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
982                         } else {
983                                 LockWord nlw, old_lw;
984                                 nlw = lock_word_increment_nest (lw);
985                                 old_lw.sync = (MonoThreadsSync *)InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, nlw.sync, lw.sync);
986                                 if (old_lw.sync != lw.sync) {
987                                         /* Someone else inflated it in the meantime */
988                                         g_assert (lock_word_is_inflated (old_lw));
989                                         return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
990                                 }
991                                 return 1;
992                         }
993                 } else {
994                         mono_monitor_inflate (obj);
995                         return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
996                 }
997         } else if (lock_word_has_hash (lw)) {
998                 mono_monitor_inflate (obj);
999                 return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
1000         }
1001
1002         g_assert_not_reached ();
1003         return -1;
1004 }
1005
1006 gboolean 
1007 mono_monitor_enter (MonoObject *obj)
1008 {
1009         return mono_monitor_try_enter_internal (obj, INFINITE, FALSE) == 1;
1010 }
1011
1012 gboolean 
1013 mono_monitor_enter_fast (MonoObject *obj)
1014 {
1015         return mono_monitor_try_enter_internal (obj, 0, FALSE) == 1;
1016 }
1017
1018 gboolean
1019 mono_monitor_try_enter (MonoObject *obj, guint32 ms)
1020 {
1021         return mono_monitor_try_enter_internal (obj, ms, FALSE) == 1;
1022 }
1023
1024 void
1025 mono_monitor_exit (MonoObject *obj)
1026 {
1027         LockWord lw;
1028         
1029         LOCK_DEBUG (g_message ("%s: (%d) Unlocking %p", __func__, mono_thread_info_get_small_id (), obj));
1030
1031         if (G_UNLIKELY (!obj)) {
1032                 mono_set_pending_exception (mono_get_exception_argument_null ("obj"));
1033                 return;
1034         }
1035
1036         lw.sync = obj->synchronisation;
1037
1038         mono_monitor_ensure_owned (lw, mono_thread_info_get_small_id ());
1039
1040         if (G_UNLIKELY (lock_word_is_inflated (lw)))
1041                 mono_monitor_exit_inflated (obj);
1042         else
1043                 mono_monitor_exit_flat (obj, lw);
1044 }
1045
1046 guint32
1047 mono_monitor_get_object_monitor_gchandle (MonoObject *object)
1048 {
1049         LockWord lw;
1050
1051         lw.sync = object->synchronisation;
1052
1053         if (lock_word_is_inflated (lw)) {
1054                 MonoThreadsSync *mon = lock_word_get_inflated_lock (lw);
1055                 return (guint32)mon->data;
1056         }
1057         return 0;
1058 }
1059
1060 /*
1061  * mono_monitor_threads_sync_member_offset:
1062  * @status_offset: returns size and offset of the "status" member
1063  * @nest_offset: returns size and offset of the "nest" member
1064  *
1065  * Returns the offsets and sizes of two members of the
1066  * MonoThreadsSync struct.  The Monitor ASM fastpaths need this.
1067  */
1068 void
1069 mono_monitor_threads_sync_members_offset (int *status_offset, int *nest_offset)
1070 {
1071         MonoThreadsSync ts;
1072
1073 #define ENCODE_OFF_SIZE(o,s)    (((o) << 8) | ((s) & 0xff))
1074
1075         *status_offset = ENCODE_OFF_SIZE (MONO_STRUCT_OFFSET (MonoThreadsSync, status), sizeof (ts.status));
1076         *nest_offset = ENCODE_OFF_SIZE (MONO_STRUCT_OFFSET (MonoThreadsSync, nest), sizeof (ts.nest));
1077 }
1078
1079 gboolean 
1080 ves_icall_System_Threading_Monitor_Monitor_try_enter (MonoObject *obj, guint32 ms)
1081 {
1082         gint32 res;
1083
1084         do {
1085                 res = mono_monitor_try_enter_internal (obj, ms, TRUE);
1086                 if (res == -1) {
1087                         MonoException *exc = mono_thread_interruption_checkpoint ();
1088                         if (exc) {
1089                                 mono_set_pending_exception (exc);
1090                                 return FALSE;
1091                         }
1092                 }
1093         } while (res == -1);
1094         
1095         return res == 1;
1096 }
1097
1098 void
1099 ves_icall_System_Threading_Monitor_Monitor_try_enter_with_atomic_var (MonoObject *obj, guint32 ms, char *lockTaken)
1100 {
1101         gint32 res;
1102         do {
1103                 res = mono_monitor_try_enter_internal (obj, ms, TRUE);
1104                 /*This means we got interrupted during the wait and didn't got the monitor.*/
1105                 if (res == -1) {
1106                         MonoException *exc = mono_thread_interruption_checkpoint ();
1107                         if (exc) {
1108                                 mono_set_pending_exception (exc);
1109                                 return;
1110                         }
1111                 }
1112         } while (res == -1);
1113         /*It's safe to do it from here since interruption would happen only on the wrapper.*/
1114         *lockTaken = res == 1;
1115 }
1116
1117 void
1118 mono_monitor_enter_v4 (MonoObject *obj, char *lock_taken)
1119 {
1120         if (*lock_taken == 1) {
1121                 mono_set_pending_exception (mono_get_exception_argument ("lockTaken", "lockTaken is already true"));
1122                 return;
1123         }
1124
1125         ves_icall_System_Threading_Monitor_Monitor_try_enter_with_atomic_var (obj, INFINITE, lock_taken);
1126 }
1127
1128 /*
1129  * mono_monitor_enter_v4_fast:
1130  *
1131  *   Same as mono_monitor_enter_v4, but return immediately if the
1132  * monitor cannot be acquired.
1133  * Returns TRUE if the lock was acquired, FALSE otherwise.
1134  */
1135 gboolean
1136 mono_monitor_enter_v4_fast (MonoObject *obj, char *lock_taken)
1137 {
1138         if (*lock_taken == 1)
1139                 return FALSE;
1140         gint32 res = mono_monitor_try_enter_internal (obj, 0, TRUE);
1141         *lock_taken = res == 1;
1142         return res == 1;
1143 }
1144
1145 gboolean 
1146 ves_icall_System_Threading_Monitor_Monitor_test_owner (MonoObject *obj)
1147 {
1148         LockWord lw;
1149
1150         LOCK_DEBUG (g_message ("%s: Testing if %p is owned by thread %d", __func__, obj, mono_thread_info_get_small_id()));
1151
1152         lw.sync = obj->synchronisation;
1153
1154         if (lock_word_is_flat (lw)) {
1155                 return lock_word_get_owner (lw) == mono_thread_info_get_small_id ();
1156         } else if (lock_word_is_inflated (lw)) {
1157                 return mon_status_get_owner (lock_word_get_inflated_lock (lw)->status) == mono_thread_info_get_small_id ();
1158         }
1159         
1160         return(FALSE);
1161 }
1162
1163 gboolean 
1164 ves_icall_System_Threading_Monitor_Monitor_test_synchronised (MonoObject *obj)
1165 {
1166         LockWord lw;
1167
1168         LOCK_DEBUG (g_message("%s: (%d) Testing if %p is owned by any thread", __func__, mono_thread_info_get_small_id (), obj));
1169
1170         lw.sync = obj->synchronisation;
1171
1172         if (lock_word_is_flat (lw)) {
1173                 return !lock_word_is_free (lw);
1174         } else if (lock_word_is_inflated (lw)) {
1175                 return mon_status_get_owner (lock_word_get_inflated_lock (lw)->status) != 0;
1176         }
1177
1178         return FALSE;
1179 }
1180
1181 /* All wait list manipulation in the pulse, pulseall and wait
1182  * functions happens while the monitor lock is held, so we don't need
1183  * any extra struct locking
1184  */
1185
1186 void
1187 ves_icall_System_Threading_Monitor_Monitor_pulse (MonoObject *obj)
1188 {
1189         int id;
1190         LockWord lw;
1191         MonoThreadsSync *mon;
1192
1193         LOCK_DEBUG (g_message ("%s: (%d) Pulsing %p", __func__, mono_thread_info_get_small_id (), obj));
1194         
1195         id = mono_thread_info_get_small_id ();
1196         lw.sync = obj->synchronisation;
1197
1198         mono_monitor_ensure_owned (lw, id);
1199
1200         if (!lock_word_is_inflated (lw)) {
1201                 /* No threads waiting. A wait would have inflated the lock */
1202                 return;
1203         }
1204
1205         mon = lock_word_get_inflated_lock (lw);
1206
1207         LOCK_DEBUG (g_message ("%s: (%d) %d threads waiting", __func__, mono_thread_info_get_small_id (), g_slist_length (mon->wait_list)));
1208
1209         if (mon->wait_list != NULL) {
1210                 LOCK_DEBUG (g_message ("%s: (%d) signalling and dequeuing handle %p", __func__, mono_thread_info_get_small_id (), mon->wait_list->data));
1211         
1212                 SetEvent (mon->wait_list->data);
1213                 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1214         }
1215 }
1216
1217 void
1218 ves_icall_System_Threading_Monitor_Monitor_pulse_all (MonoObject *obj)
1219 {
1220         int id;
1221         LockWord lw;
1222         MonoThreadsSync *mon;
1223         
1224         LOCK_DEBUG (g_message("%s: (%d) Pulsing all %p", __func__, mono_thread_info_get_small_id (), obj));
1225
1226         id = mono_thread_info_get_small_id ();
1227         lw.sync = obj->synchronisation;
1228
1229         mono_monitor_ensure_owned (lw, id);
1230
1231         if (!lock_word_is_inflated (lw)) {
1232                 /* No threads waiting. A wait would have inflated the lock */
1233                 return;
1234         }
1235
1236         mon = lock_word_get_inflated_lock (lw);
1237
1238         LOCK_DEBUG (g_message ("%s: (%d) %d threads waiting", __func__, mono_thread_info_get_small_id (), g_slist_length (mon->wait_list)));
1239
1240         while (mon->wait_list != NULL) {
1241                 LOCK_DEBUG (g_message ("%s: (%d) signalling and dequeuing handle %p", __func__, mono_thread_info_get_small_id (), mon->wait_list->data));
1242         
1243                 SetEvent (mon->wait_list->data);
1244                 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1245         }
1246 }
1247
1248 gboolean
1249 ves_icall_System_Threading_Monitor_Monitor_wait (MonoObject *obj, guint32 ms)
1250 {
1251         LockWord lw;
1252         MonoThreadsSync *mon;
1253         HANDLE event;
1254         guint32 nest;
1255         guint32 ret;
1256         gboolean success = FALSE;
1257         gint32 regain;
1258         MonoInternalThread *thread = mono_thread_internal_current ();
1259         int id = mono_thread_info_get_small_id ();
1260
1261         LOCK_DEBUG (g_message ("%s: (%d) Trying to wait for %p with timeout %dms", __func__, mono_thread_info_get_small_id (), obj, ms));
1262
1263         lw.sync = obj->synchronisation;
1264
1265         mono_monitor_ensure_owned (lw, id);
1266
1267         if (!lock_word_is_inflated (lw)) {
1268                 mono_monitor_inflate_owned (obj, id);
1269                 lw.sync = obj->synchronisation;
1270         }
1271
1272         mon = lock_word_get_inflated_lock (lw);
1273
1274         /* Do this WaitSleepJoin check before creating the event handle */
1275         mono_thread_current_check_pending_interrupt ();
1276         
1277         event = CreateEvent (NULL, FALSE, FALSE, NULL);
1278         if (event == NULL) {
1279                 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Failed to set up wait event"));
1280                 return FALSE;
1281         }
1282         
1283         LOCK_DEBUG (g_message ("%s: (%d) queuing handle %p", __func__, mono_thread_info_get_small_id (), event));
1284
1285         mono_thread_current_check_pending_interrupt ();
1286         
1287         mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1288
1289         mon->wait_list = g_slist_append (mon->wait_list, event);
1290         
1291         /* Save the nest count, and release the lock */
1292         nest = mon->nest;
1293         mon->nest = 1;
1294         mono_memory_write_barrier ();
1295         mono_monitor_exit_inflated (obj);
1296
1297         LOCK_DEBUG (g_message ("%s: (%d) Unlocked %p lock %p", __func__, mono_thread_info_get_small_id (), obj, mon));
1298
1299         /* There's no race between unlocking mon and waiting for the
1300          * event, because auto reset events are sticky, and this event
1301          * is private to this thread.  Therefore even if the event was
1302          * signalled before we wait, we still succeed.
1303          */
1304         MONO_PREPARE_BLOCKING;
1305         ret = WaitForSingleObjectEx (event, ms, TRUE);
1306         MONO_FINISH_BLOCKING;
1307
1308         /* Reset the thread state fairly early, so we don't have to worry
1309          * about the monitor error checking
1310          */
1311         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1312
1313         /* Regain the lock with the previous nest count */
1314         do {
1315                 regain = mono_monitor_try_enter_inflated (obj, INFINITE, TRUE, id);
1316                 /* We must regain the lock before handling interruption requests */
1317         } while (regain == -1);
1318
1319         g_assert (regain == 1);
1320
1321         mon->nest = nest;
1322
1323         LOCK_DEBUG (g_message ("%s: (%d) Regained %p lock %p", __func__, mono_thread_info_get_small_id (), obj, mon));
1324
1325         if (ret == WAIT_TIMEOUT) {
1326                 /* Poll the event again, just in case it was signalled
1327                  * while we were trying to regain the monitor lock
1328                  */
1329                 MONO_PREPARE_BLOCKING;
1330                 ret = WaitForSingleObjectEx (event, 0, FALSE);
1331                 MONO_FINISH_BLOCKING;
1332         }
1333
1334         /* Pulse will have popped our event from the queue if it signalled
1335          * us, so we only do it here if the wait timed out.
1336          *
1337          * This avoids a race condition where the thread holding the
1338          * lock can Pulse several times before the WaitForSingleObject
1339          * returns.  If we popped the queue here then this event might
1340          * be signalled more than once, thereby starving another
1341          * thread.
1342          */
1343         
1344         if (ret == WAIT_OBJECT_0) {
1345                 LOCK_DEBUG (g_message ("%s: (%d) Success", __func__, mono_thread_info_get_small_id ()));
1346                 success = TRUE;
1347         } else {
1348                 LOCK_DEBUG (g_message ("%s: (%d) Wait failed, dequeuing handle %p", __func__, mono_thread_info_get_small_id (), event));
1349                 /* No pulse, so we have to remove ourself from the
1350                  * wait queue
1351                  */
1352                 mon->wait_list = g_slist_remove (mon->wait_list, event);
1353         }
1354         CloseHandle (event);
1355         
1356         return success;
1357 }
1358