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