[threads] Remove ThreadState_StopRequested (#4462)
[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/metadata/object-internals.h>
22 #include <mono/metadata/class-internals.h>
23 #include <mono/metadata/gc-internals.h>
24 #include <mono/metadata/method-builder.h>
25 #include <mono/metadata/debug-helpers.h>
26 #include <mono/metadata/tabledefs.h>
27 #include <mono/metadata/marshal.h>
28 #include <mono/metadata/w32event.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 #include <mono/utils/w32api.h>
34
35 /*
36  * Pull the list of opcodes
37  */
38 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
39         a = i,
40
41 enum {
42 #include "mono/cil/opcode.def"
43         LAST = 0xff
44 };
45 #undef OPDEF
46
47 /*#define LOCK_DEBUG(a) do { a; } while (0)*/
48 #define LOCK_DEBUG(a)
49
50 /*
51  * The monitor implementation here is based on
52  * http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf and
53  * http://www.research.ibm.com/people/d/dfb/papers/Bacon98Thin.ps
54  *
55  * The Dice paper describes a technique for saving lock record space
56  * by returning records to a free list when they become unused.  That
57  * sounds like unnecessary complexity to me, though if it becomes
58  * clear that unused lock records are taking up lots of space or we
59  * need to shave more time off by avoiding a malloc then we can always
60  * implement the free list idea later.  The timeout parameter to
61  * try_enter voids some of the assumptions about the reference count
62  * field in Dice's implementation too.  In his version, the thread
63  * attempting to lock a contended object will block until it succeeds,
64  * so the reference count will never be decremented while an object is
65  * locked.
66  *
67  * Bacon's thin locks have a fast path that doesn't need a lock record
68  * for the common case of locking an unlocked or shallow-nested
69  * object.
70  */
71
72
73 typedef struct _MonitorArray MonitorArray;
74
75 struct _MonitorArray {
76         MonitorArray *next;
77         int num_monitors;
78         MonoThreadsSync monitors [MONO_ZERO_LEN_ARRAY];
79 };
80
81 #define mono_monitor_allocator_lock() mono_os_mutex_lock (&monitor_mutex)
82 #define mono_monitor_allocator_unlock() mono_os_mutex_unlock (&monitor_mutex)
83 static mono_mutex_t monitor_mutex;
84 static MonoThreadsSync *monitor_freelist;
85 static MonitorArray *monitor_allocated;
86 static int array_size = 16;
87
88 /* MonoThreadsSync status helpers */
89
90 static inline guint32
91 mon_status_get_owner (guint32 status)
92 {
93         return status & OWNER_MASK;
94 }
95
96 static inline guint32
97 mon_status_set_owner (guint32 status, guint32 owner)
98 {
99         return (status & ENTRY_COUNT_MASK) | owner;
100 }
101
102 static inline gint32
103 mon_status_get_entry_count (guint32 status)
104 {
105         gint32 entry_count = (gint32)((status & ENTRY_COUNT_MASK) >> ENTRY_COUNT_SHIFT);
106         gint32 zero = (gint32)(((guint32)ENTRY_COUNT_ZERO) >> ENTRY_COUNT_SHIFT);
107         return entry_count - zero;
108 }
109
110 static inline guint32
111 mon_status_init_entry_count (guint32 status)
112 {
113         return (status & OWNER_MASK) | ENTRY_COUNT_ZERO;
114 }
115
116 static inline guint32
117 mon_status_increment_entry_count (guint32 status)
118 {
119         return status + (1 << ENTRY_COUNT_SHIFT);
120 }
121
122 static inline guint32
123 mon_status_decrement_entry_count (guint32 status)
124 {
125         return status - (1 << ENTRY_COUNT_SHIFT);
126 }
127
128 static inline gboolean
129 mon_status_have_waiters (guint32 status)
130 {
131         return status & ENTRY_COUNT_WAITERS;
132 }
133
134 /* LockWord helpers */
135
136 static inline MonoThreadsSync*
137 lock_word_get_inflated_lock (LockWord lw)
138 {
139         lw.lock_word &= (~LOCK_WORD_STATUS_MASK);
140         return lw.sync;
141 }
142
143 static inline gboolean
144 lock_word_is_inflated (LockWord lw)
145 {
146         return lw.lock_word & LOCK_WORD_INFLATED;
147 }
148
149 static inline gboolean
150 lock_word_has_hash (LockWord lw)
151 {
152         return lw.lock_word & LOCK_WORD_HAS_HASH;
153 }
154
155 static inline LockWord
156 lock_word_set_has_hash (LockWord lw)
157 {
158         LockWord nlw;
159         nlw.lock_word = lw.lock_word | LOCK_WORD_HAS_HASH;
160         return nlw;
161 }
162
163 static inline gboolean
164 lock_word_is_free (LockWord lw)
165 {
166         return !lw.lock_word;
167 }
168
169 static inline gboolean
170 lock_word_is_flat (LockWord lw)
171 {
172         /* Return whether the lock is flat or free */
173         return (lw.lock_word & LOCK_WORD_STATUS_MASK) == LOCK_WORD_FLAT;
174 }
175
176 static inline gint32
177 lock_word_get_hash (LockWord lw)
178 {
179         return (gint32) (lw.lock_word >> LOCK_WORD_HASH_SHIFT);
180 }
181
182 static inline gint32
183 lock_word_get_nest (LockWord lw)
184 {
185         if (lock_word_is_free (lw))
186                 return 0;
187         /* Inword nest count starts from 0 */
188         return ((lw.lock_word & LOCK_WORD_NEST_MASK) >> LOCK_WORD_NEST_SHIFT) + 1;
189 }
190
191 static inline gboolean
192 lock_word_is_nested (LockWord lw)
193 {
194         return lw.lock_word & LOCK_WORD_NEST_MASK;
195 }
196
197 static inline gboolean
198 lock_word_is_max_nest (LockWord lw)
199 {
200         return (lw.lock_word & LOCK_WORD_NEST_MASK) == LOCK_WORD_NEST_MASK;
201 }
202
203 static inline LockWord
204 lock_word_increment_nest (LockWord lw)
205 {
206         lw.lock_word += 1 << LOCK_WORD_NEST_SHIFT;
207         return lw;
208 }
209
210 static inline LockWord
211 lock_word_decrement_nest (LockWord lw)
212 {
213         lw.lock_word -= 1 << LOCK_WORD_NEST_SHIFT;
214         return lw;
215 }
216
217 static inline gint32
218 lock_word_get_owner (LockWord lw)
219 {
220         return lw.lock_word >> LOCK_WORD_OWNER_SHIFT;
221 }
222
223 static inline LockWord
224 lock_word_new_thin_hash (gint32 hash)
225 {
226         LockWord lw;
227         lw.lock_word = (guint32)hash;
228         lw.lock_word = (lw.lock_word << LOCK_WORD_HASH_SHIFT) | LOCK_WORD_HAS_HASH;
229         return lw;
230 }
231
232 static inline LockWord
233 lock_word_new_inflated (MonoThreadsSync *mon)
234 {
235         LockWord lw;
236         lw.sync = mon;
237         lw.lock_word |= LOCK_WORD_INFLATED;
238         return lw;
239 }
240
241 static inline LockWord
242 lock_word_new_flat (gint32 owner)
243 {
244         LockWord lw;
245         lw.lock_word = owner;
246         lw.lock_word <<= LOCK_WORD_OWNER_SHIFT;
247         return lw;
248 }
249
250 void
251 mono_monitor_init (void)
252 {
253         mono_os_mutex_init_recursive (&monitor_mutex);
254 }
255  
256 void
257 mono_monitor_cleanup (void)
258 {
259         MonoThreadsSync *mon;
260         /* MonitorArray *marray, *next = NULL; */
261
262         /*mono_os_mutex_destroy (&monitor_mutex);*/
263
264         /* The monitors on the freelist don't have weak links - mark them */
265         for (mon = monitor_freelist; mon; mon = (MonoThreadsSync *)mon->data)
266                 mon->wait_list = (GSList *)-1;
267
268         /*
269          * FIXME: This still crashes with sgen (async_read.exe)
270          *
271          * In mini_cleanup() we first call mono_runtime_cleanup(), which calls
272          * mono_monitor_cleanup(), which is supposed to free all monitor memory.
273          *
274          * Later in mini_cleanup(), we call mono_domain_free(), which calls
275          * mono_gc_clear_domain(), which frees all weak links associated with objects.
276          * Those weak links reside in the monitor structures, which we've freed earlier.
277          *
278          * Unless we fix this dependency in the shutdown sequence this code has to remain
279          * disabled, or at least the call to g_free().
280          */
281         /*
282         for (marray = monitor_allocated; marray; marray = next) {
283                 int i;
284
285                 for (i = 0; i < marray->num_monitors; ++i) {
286                         mon = &marray->monitors [i];
287                         if (mon->wait_list != (gpointer)-1)
288                                 mono_gc_weak_link_remove (&mon->data);
289                 }
290
291                 next = marray->next;
292                 g_free (marray);
293         }
294         */
295 }
296
297 static int
298 monitor_is_on_freelist (MonoThreadsSync *mon)
299 {
300         MonitorArray *marray;
301         for (marray = monitor_allocated; marray; marray = marray->next) {
302                 if (mon >= marray->monitors && mon < &marray->monitors [marray->num_monitors])
303                         return TRUE;
304         }
305         return FALSE;
306 }
307
308 /**
309  * mono_locks_dump:
310  * @include_untaken:
311  *
312  * Print a report on stdout of the managed locks currently held by
313  * threads. If @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_monitor_event (obj, MONO_PROFILER_MONITOR_CONTENTION);
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_monitor_event (obj, MONO_PROFILER_MONITOR_DONE);
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_monitor_event (obj, MONO_PROFILER_MONITOR_DONE);
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_monitor_event (obj, MONO_PROFILER_MONITOR_FAIL);
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 gboolean
1053 mono_monitor_enter (MonoObject *obj)
1054 {
1055         return mono_monitor_enter_internal (obj);
1056 }
1057
1058 /* Called from JITted code so we return guint32 instead of gboolean */
1059 guint32
1060 mono_monitor_enter_fast (MonoObject *obj)
1061 {
1062         if (G_UNLIKELY (!obj)) {
1063                 /* don't set pending exn on the fast path, just return
1064                  * FALSE and let the slow path take care of it. */
1065                 return FALSE;
1066         }
1067         return mono_monitor_try_enter_internal (obj, 0, FALSE) == 1;
1068 }
1069
1070 gboolean
1071 mono_monitor_try_enter (MonoObject *obj, guint32 ms)
1072 {
1073         if (G_UNLIKELY (!obj)) {
1074                 mono_set_pending_exception (mono_get_exception_argument_null ("obj"));
1075                 return FALSE;
1076         }
1077         return mono_monitor_try_enter_internal (obj, ms, FALSE) == 1;
1078 }
1079
1080 void
1081 mono_monitor_exit (MonoObject *obj)
1082 {
1083         LockWord lw;
1084         
1085         LOCK_DEBUG (g_message ("%s: (%d) Unlocking %p", __func__, mono_thread_info_get_small_id (), obj));
1086
1087         if (G_UNLIKELY (!obj)) {
1088                 mono_set_pending_exception (mono_get_exception_argument_null ("obj"));
1089                 return;
1090         }
1091
1092         lw.sync = obj->synchronisation;
1093
1094         if (!mono_monitor_ensure_owned (lw, mono_thread_info_get_small_id ()))
1095                 return;
1096
1097         if (G_UNLIKELY (lock_word_is_inflated (lw)))
1098                 mono_monitor_exit_inflated (obj);
1099         else
1100                 mono_monitor_exit_flat (obj, lw);
1101 }
1102
1103 guint32
1104 mono_monitor_get_object_monitor_gchandle (MonoObject *object)
1105 {
1106         LockWord lw;
1107
1108         lw.sync = object->synchronisation;
1109
1110         if (lock_word_is_inflated (lw)) {
1111                 MonoThreadsSync *mon = lock_word_get_inflated_lock (lw);
1112                 return (guint32)mon->data;
1113         }
1114         return 0;
1115 }
1116
1117 /*
1118  * mono_monitor_threads_sync_member_offset:
1119  * @status_offset: returns size and offset of the "status" member
1120  * @nest_offset: returns size and offset of the "nest" member
1121  *
1122  * Returns the offsets and sizes of two members of the
1123  * MonoThreadsSync struct.  The Monitor ASM fastpaths need this.
1124  */
1125 void
1126 mono_monitor_threads_sync_members_offset (int *status_offset, int *nest_offset)
1127 {
1128         MonoThreadsSync ts;
1129
1130 #define ENCODE_OFF_SIZE(o,s)    (((o) << 8) | ((s) & 0xff))
1131
1132         *status_offset = ENCODE_OFF_SIZE (MONO_STRUCT_OFFSET (MonoThreadsSync, status), sizeof (ts.status));
1133         *nest_offset = ENCODE_OFF_SIZE (MONO_STRUCT_OFFSET (MonoThreadsSync, nest), sizeof (ts.nest));
1134 }
1135
1136 void
1137 ves_icall_System_Threading_Monitor_Monitor_try_enter_with_atomic_var (MonoObject *obj, guint32 ms, MonoBoolean *lockTaken)
1138 {
1139         gint32 res;
1140         gboolean allow_interruption = TRUE;
1141         if (G_UNLIKELY (!obj)) {
1142                 mono_set_pending_exception (mono_get_exception_argument_null ("obj"));
1143                 return;
1144         }
1145         do {
1146                 res = mono_monitor_try_enter_internal (obj, ms, allow_interruption);
1147                 /*This means we got interrupted during the wait and didn't got the monitor.*/
1148                 if (res == -1) {
1149                         MonoException *exc = mono_thread_interruption_checkpoint ();
1150                         if (exc) {
1151                                 mono_set_pending_exception (exc);
1152                                 return;
1153                         } else {
1154                                 //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)
1155                                 allow_interruption = FALSE;
1156                         }
1157                 }
1158         } while (res == -1);
1159         /*It's safe to do it from here since interruption would happen only on the wrapper.*/
1160         *lockTaken = res == 1;
1161 }
1162
1163 void
1164 mono_monitor_enter_v4 (MonoObject *obj, char *lock_taken)
1165 {
1166         if (*lock_taken == 1) {
1167                 mono_set_pending_exception (mono_get_exception_argument ("lockTaken", "lockTaken is already true"));
1168                 return;
1169         }
1170
1171         MonoBoolean taken;
1172
1173         ves_icall_System_Threading_Monitor_Monitor_try_enter_with_atomic_var (obj, MONO_INFINITE_WAIT, &taken);
1174         *lock_taken = taken;
1175 }
1176
1177 /* Called from JITted code */
1178 void
1179 mono_monitor_enter_v4_internal (MonoObject *obj, MonoBoolean *lock_taken)
1180 {
1181         if (*lock_taken == 1) {
1182                 mono_set_pending_exception (mono_get_exception_argument ("lockTaken", "lockTaken is already true"));
1183                 return;
1184         }
1185
1186         ves_icall_System_Threading_Monitor_Monitor_try_enter_with_atomic_var (obj, MONO_INFINITE_WAIT, lock_taken);
1187 }
1188
1189 /*
1190  * mono_monitor_enter_v4_fast:
1191  *
1192  *   Same as mono_monitor_enter_v4, but return immediately if the
1193  * monitor cannot be acquired.
1194  * Returns TRUE if the lock was acquired, FALSE otherwise.
1195  * Called from JITted code so we return guint32 instead of gboolean.
1196  */
1197 guint32
1198 mono_monitor_enter_v4_fast (MonoObject *obj, MonoBoolean *lock_taken)
1199 {
1200         if (*lock_taken == 1)
1201                 return FALSE;
1202         if (G_UNLIKELY (!obj))
1203                 return FALSE;
1204         gint32 res = mono_monitor_try_enter_internal (obj, 0, TRUE);
1205         *lock_taken = res == 1;
1206         return res == 1;
1207 }
1208
1209 MonoBoolean
1210 ves_icall_System_Threading_Monitor_Monitor_test_owner (MonoObject *obj)
1211 {
1212         LockWord lw;
1213
1214         LOCK_DEBUG (g_message ("%s: Testing if %p is owned by thread %d", __func__, obj, mono_thread_info_get_small_id()));
1215
1216         lw.sync = obj->synchronisation;
1217
1218         if (lock_word_is_flat (lw)) {
1219                 return lock_word_get_owner (lw) == mono_thread_info_get_small_id ();
1220         } else if (lock_word_is_inflated (lw)) {
1221                 return mon_status_get_owner (lock_word_get_inflated_lock (lw)->status) == mono_thread_info_get_small_id ();
1222         }
1223         
1224         return(FALSE);
1225 }
1226
1227 MonoBoolean
1228 ves_icall_System_Threading_Monitor_Monitor_test_synchronised (MonoObject *obj)
1229 {
1230         LockWord lw;
1231
1232         LOCK_DEBUG (g_message("%s: (%d) Testing if %p is owned by any thread", __func__, mono_thread_info_get_small_id (), obj));
1233
1234         lw.sync = obj->synchronisation;
1235
1236         if (lock_word_is_flat (lw)) {
1237                 return !lock_word_is_free (lw);
1238         } else if (lock_word_is_inflated (lw)) {
1239                 return mon_status_get_owner (lock_word_get_inflated_lock (lw)->status) != 0;
1240         }
1241
1242         return FALSE;
1243 }
1244
1245 /* All wait list manipulation in the pulse, pulseall and wait
1246  * functions happens while the monitor lock is held, so we don't need
1247  * any extra struct locking
1248  */
1249
1250 void
1251 ves_icall_System_Threading_Monitor_Monitor_pulse (MonoObject *obj)
1252 {
1253         int id;
1254         LockWord lw;
1255         MonoThreadsSync *mon;
1256
1257         LOCK_DEBUG (g_message ("%s: (%d) Pulsing %p", __func__, mono_thread_info_get_small_id (), obj));
1258         
1259         id = mono_thread_info_get_small_id ();
1260         lw.sync = obj->synchronisation;
1261
1262         if (!mono_monitor_ensure_owned (lw, id))
1263                 return;
1264
1265         if (!lock_word_is_inflated (lw)) {
1266                 /* No threads waiting. A wait would have inflated the lock */
1267                 return;
1268         }
1269
1270         mon = lock_word_get_inflated_lock (lw);
1271
1272         LOCK_DEBUG (g_message ("%s: (%d) %d threads waiting", __func__, mono_thread_info_get_small_id (), g_slist_length (mon->wait_list)));
1273
1274         if (mon->wait_list != NULL) {
1275                 LOCK_DEBUG (g_message ("%s: (%d) signalling and dequeuing handle %p", __func__, mono_thread_info_get_small_id (), mon->wait_list->data));
1276         
1277                 mono_w32event_set (mon->wait_list->data);
1278                 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1279         }
1280 }
1281
1282 void
1283 ves_icall_System_Threading_Monitor_Monitor_pulse_all (MonoObject *obj)
1284 {
1285         int id;
1286         LockWord lw;
1287         MonoThreadsSync *mon;
1288         
1289         LOCK_DEBUG (g_message("%s: (%d) Pulsing all %p", __func__, mono_thread_info_get_small_id (), obj));
1290
1291         id = mono_thread_info_get_small_id ();
1292         lw.sync = obj->synchronisation;
1293
1294         if (!mono_monitor_ensure_owned (lw, id))
1295                 return;
1296
1297         if (!lock_word_is_inflated (lw)) {
1298                 /* No threads waiting. A wait would have inflated the lock */
1299                 return;
1300         }
1301
1302         mon = lock_word_get_inflated_lock (lw);
1303
1304         LOCK_DEBUG (g_message ("%s: (%d) %d threads waiting", __func__, mono_thread_info_get_small_id (), g_slist_length (mon->wait_list)));
1305
1306         while (mon->wait_list != NULL) {
1307                 LOCK_DEBUG (g_message ("%s: (%d) signalling and dequeuing handle %p", __func__, mono_thread_info_get_small_id (), mon->wait_list->data));
1308         
1309                 mono_w32event_set (mon->wait_list->data);
1310                 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1311         }
1312 }
1313
1314 MonoBoolean
1315 ves_icall_System_Threading_Monitor_Monitor_wait (MonoObject *obj, guint32 ms)
1316 {
1317         LockWord lw;
1318         MonoThreadsSync *mon;
1319         HANDLE event;
1320         guint32 nest;
1321         MonoW32HandleWaitRet ret;
1322         gboolean success = FALSE;
1323         gint32 regain;
1324         MonoInternalThread *thread = mono_thread_internal_current ();
1325         int id = mono_thread_info_get_small_id ();
1326
1327         LOCK_DEBUG (g_message ("%s: (%d) Trying to wait for %p with timeout %dms", __func__, mono_thread_info_get_small_id (), obj, ms));
1328
1329         lw.sync = obj->synchronisation;
1330
1331         if (!mono_monitor_ensure_owned (lw, id))
1332                 return FALSE;
1333
1334         if (!lock_word_is_inflated (lw)) {
1335                 mono_monitor_inflate_owned (obj, id);
1336                 lw.sync = obj->synchronisation;
1337         }
1338
1339         mon = lock_word_get_inflated_lock (lw);
1340
1341         /* Do this WaitSleepJoin check before creating the event handle */
1342         if (mono_thread_current_check_pending_interrupt ())
1343                 return FALSE;
1344         
1345         event = mono_w32event_create (FALSE, FALSE);
1346         if (event == NULL) {
1347                 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Failed to set up wait event"));
1348                 return FALSE;
1349         }
1350         
1351         LOCK_DEBUG (g_message ("%s: (%d) queuing handle %p", __func__, mono_thread_info_get_small_id (), event));
1352
1353         /* This looks superfluous */
1354         if (mono_thread_current_check_pending_interrupt ()) {
1355                 mono_w32event_close (event);
1356                 return FALSE;
1357         }
1358         
1359         mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1360
1361         mon->wait_list = g_slist_append (mon->wait_list, event);
1362         
1363         /* Save the nest count, and release the lock */
1364         nest = mon->nest;
1365         mon->nest = 1;
1366         mono_memory_write_barrier ();
1367         mono_monitor_exit_inflated (obj);
1368
1369         LOCK_DEBUG (g_message ("%s: (%d) Unlocked %p lock %p", __func__, mono_thread_info_get_small_id (), obj, mon));
1370
1371         /* There's no race between unlocking mon and waiting for the
1372          * event, because auto reset events are sticky, and this event
1373          * is private to this thread.  Therefore even if the event was
1374          * signalled before we wait, we still succeed.
1375          */
1376         MONO_ENTER_GC_SAFE;
1377 #ifdef HOST_WIN32
1378         ret = mono_w32handle_convert_wait_ret (WaitForSingleObjectEx (event, ms, TRUE), 1);
1379 #else
1380         ret = mono_w32handle_wait_one (event, ms, TRUE);
1381 #endif /* HOST_WIN32 */
1382         MONO_EXIT_GC_SAFE;
1383
1384         /* Reset the thread state fairly early, so we don't have to worry
1385          * about the monitor error checking
1386          */
1387         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1388
1389         /* Regain the lock with the previous nest count */
1390         do {
1391                 regain = mono_monitor_try_enter_inflated (obj, MONO_INFINITE_WAIT, TRUE, id);
1392                 /* We must regain the lock before handling interruption requests */
1393         } while (regain == -1);
1394
1395         g_assert (regain == 1);
1396
1397         mon->nest = nest;
1398
1399         LOCK_DEBUG (g_message ("%s: (%d) Regained %p lock %p", __func__, mono_thread_info_get_small_id (), obj, mon));
1400
1401         if (ret == MONO_W32HANDLE_WAIT_RET_TIMEOUT) {
1402                 /* Poll the event again, just in case it was signalled
1403                  * while we were trying to regain the monitor lock
1404                  */
1405                 MONO_ENTER_GC_SAFE;
1406 #ifdef HOST_WIN32
1407                 ret = mono_w32handle_convert_wait_ret (WaitForSingleObjectEx (event, 0, FALSE), 1);
1408 #else
1409                 ret = mono_w32handle_wait_one (event, 0, FALSE);
1410 #endif /* HOST_WIN32 */
1411                 MONO_EXIT_GC_SAFE;
1412         }
1413
1414         /* Pulse will have popped our event from the queue if it signalled
1415          * us, so we only do it here if the wait timed out.
1416          *
1417          * This avoids a race condition where the thread holding the
1418          * lock can Pulse several times before the WaitForSingleObject
1419          * returns.  If we popped the queue here then this event might
1420          * be signalled more than once, thereby starving another
1421          * thread.
1422          */
1423         
1424         if (ret == MONO_W32HANDLE_WAIT_RET_SUCCESS_0) {
1425                 LOCK_DEBUG (g_message ("%s: (%d) Success", __func__, mono_thread_info_get_small_id ()));
1426                 success = TRUE;
1427         } else {
1428                 LOCK_DEBUG (g_message ("%s: (%d) Wait failed, dequeuing handle %p", __func__, mono_thread_info_get_small_id (), event));
1429                 /* No pulse, so we have to remove ourself from the
1430                  * wait queue
1431                  */
1432                 mon->wait_list = g_slist_remove (mon->wait_list, event);
1433         }
1434         mono_w32event_close (event);
1435         
1436         return success;
1437 }
1438