Merge pull request #3578 from henricm/fix-win-process-test
[mono.git] / mono / metadata / monitor.c
1 /*
2  * monitor.c:  Monitor locking functions
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *
7  * Copyright 2003 Ximian, Inc (http://www.ximian.com)
8  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
9  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
10  */
11
12 #include <config.h>
13 #include <glib.h>
14 #include <string.h>
15
16 #include <mono/metadata/abi-details.h>
17 #include <mono/metadata/monitor.h>
18 #include <mono/metadata/threads-types.h>
19 #include <mono/metadata/exception.h>
20 #include <mono/metadata/threads.h>
21 #include <mono/io-layer/io-layer.h>
22 #include <mono/metadata/object-internals.h>
23 #include <mono/metadata/class-internals.h>
24 #include <mono/metadata/gc-internals.h>
25 #include <mono/metadata/method-builder.h>
26 #include <mono/metadata/debug-helpers.h>
27 #include <mono/metadata/tabledefs.h>
28 #include <mono/metadata/marshal.h>
29 #include <mono/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
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                                                         CloseHandle (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 void
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;
640         } else if (lock_word_is_inflated (lw)) {
641                 if (mon_status_get_owner (lock_word_get_inflated_lock (lw)->status) == id)
642                         return;
643         }
644
645         mono_set_pending_exception (mono_get_exception_synchronization_lock ("Object synchronization method was called from an unsynchronized block of code."));
646 }
647
648 /*
649  * When this function is called it has already been established that the
650  * current thread owns the monitor.
651  */
652 static void
653 mono_monitor_exit_inflated (MonoObject *obj)
654 {
655         LockWord lw;
656         MonoThreadsSync *mon;
657         guint32 nest;
658
659         lw.sync = obj->synchronisation;
660         mon = lock_word_get_inflated_lock (lw);
661
662         nest = mon->nest - 1;
663         if (nest == 0) {
664                 guint32 new_status, old_status, tmp_status;
665
666                 old_status = mon->status;
667
668                 /*
669                  * Release lock and do the wakeup stuff. It's possible that
670                  * the last blocking thread gave up waiting just before we
671                  * release the semaphore resulting in a negative entry count
672                  * and a futile wakeup next time there's contention for this
673                  * object.
674                  */
675                 for (;;) {
676                         gboolean have_waiters = mon_status_have_waiters (old_status);
677         
678                         new_status = mon_status_set_owner (old_status, 0);
679                         if (have_waiters)
680                                 new_status = mon_status_decrement_entry_count (new_status);
681                         tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
682                         if (tmp_status == old_status) {
683                                 if (have_waiters)
684                                         mono_coop_sem_post (mon->entry_sem);
685                                 break;
686                         }
687                         old_status = tmp_status;
688                 }
689                 LOCK_DEBUG (g_message ("%s: (%d) Object %p is now unlocked", __func__, mono_thread_info_get_small_id (), obj));
690         
691                 /* object is now unlocked, leave nest==1 so we don't
692                  * need to set it when the lock is reacquired
693                  */
694         } else {
695                 LOCK_DEBUG (g_message ("%s: (%d) Object %p is now locked %d times", __func__, mono_thread_info_get_small_id (), obj, nest));
696                 mon->nest = nest;
697         }
698 }
699
700 /*
701  * When this function is called it has already been established that the
702  * current thread owns the monitor.
703  */
704 static void
705 mono_monitor_exit_flat (MonoObject *obj, LockWord old_lw)
706 {
707         LockWord new_lw, tmp_lw;
708         if (G_UNLIKELY (lock_word_is_nested (old_lw)))
709                 new_lw = lock_word_decrement_nest (old_lw);
710         else
711                 new_lw.lock_word = 0;
712
713         tmp_lw.sync = (MonoThreadsSync *)InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, new_lw.sync, old_lw.sync);
714         if (old_lw.sync != tmp_lw.sync) {
715                 /* Someone inflated the lock in the meantime */
716                 mono_monitor_exit_inflated (obj);
717         }
718
719         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));
720 }
721
722 static void
723 mon_decrement_entry_count (MonoThreadsSync *mon)
724 {
725         guint32 old_status, tmp_status, new_status;
726
727         /* Decrement entry count */
728         old_status = mon->status;
729         for (;;) {
730                 new_status = mon_status_decrement_entry_count (old_status);
731                 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
732                 if (tmp_status == old_status) {
733                         break;
734                 }
735                 old_status = tmp_status;
736         }
737 }
738
739 /* If allow_interruption==TRUE, the method will be interrumped if abort or suspend
740  * is requested. In this case it returns -1.
741  */ 
742 static inline gint32 
743 mono_monitor_try_enter_inflated (MonoObject *obj, guint32 ms, gboolean allow_interruption, guint32 id)
744 {
745         LockWord lw;
746         MonoThreadsSync *mon;
747         HANDLE sem;
748         gint64 then = 0, now, delta;
749         guint32 waitms;
750         guint32 new_status, old_status, tmp_status;
751         MonoSemTimedwaitRet wait_ret;
752         MonoInternalThread *thread;
753         gboolean interrupted = FALSE;
754
755         LOCK_DEBUG (g_message("%s: (%d) Trying to lock object %p (%d ms)", __func__, id, obj, ms));
756
757         if (G_UNLIKELY (!obj)) {
758                 mono_set_pending_exception (mono_get_exception_argument_null ("obj"));
759                 return FALSE;
760         }
761
762         lw.sync = obj->synchronisation;
763         mon = lock_word_get_inflated_lock (lw);
764 retry:
765         /* This case differs from Dice's case 3 because we don't
766          * deflate locks or cache unused lock records
767          */
768         old_status = mon->status;
769         if (G_LIKELY (mon_status_get_owner (old_status) == 0)) {
770                 /* Try to install our ID in the owner field, nest
771                 * should have been left at 1 by the previous unlock
772                 * operation
773                 */
774                 new_status = mon_status_set_owner (old_status, id);
775                 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
776                 if (G_LIKELY (tmp_status == old_status)) {
777                         /* Success */
778                         g_assert (mon->nest == 1);
779                         return 1;
780                 } else {
781                         /* Trumped again! */
782                         goto retry;
783                 }
784         }
785
786         /* If the object is currently locked by this thread... */
787         if (mon_status_get_owner (old_status) == id) {
788                 mon->nest++;
789                 return 1;
790         }
791
792         /* The object must be locked by someone else... */
793 #ifndef DISABLE_PERFCOUNTERS
794         mono_perfcounters->thread_contentions++;
795 #endif
796
797         /* If ms is 0 we don't block, but just fail straight away */
798         if (ms == 0) {
799                 LOCK_DEBUG (g_message ("%s: (%d) timed out, returning FALSE", __func__, id));
800                 return 0;
801         }
802
803         mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_CONTENTION);
804
805         /* The slow path begins here. */
806 retry_contended:
807         /* a small amount of duplicated code, but it allows us to insert the profiler
808          * callbacks without impacting the fast path: from here on we don't need to go back to the
809          * retry label, but to retry_contended. At this point mon is already installed in the object
810          * header.
811          */
812         /* This case differs from Dice's case 3 because we don't
813          * deflate locks or cache unused lock records
814          */
815         old_status = mon->status;
816         if (G_LIKELY (mon_status_get_owner (old_status) == 0)) {
817                 /* Try to install our ID in the owner field, nest
818                 * should have been left at 1 by the previous unlock
819                 * operation
820                 */
821                 new_status = mon_status_set_owner (old_status, id);
822                 tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
823                 if (G_LIKELY (tmp_status == old_status)) {
824                         /* Success */
825                         g_assert (mon->nest == 1);
826                         mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_DONE);
827                         return 1;
828                 }
829         }
830
831         /* If the object is currently locked by this thread... */
832         if (mon_status_get_owner (old_status) == id) {
833                 mon->nest++;
834                 mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_DONE);
835                 return 1;
836         }
837
838         /* We need to make sure there's a semaphore handle (creating it if
839          * necessary), and block on it
840          */
841         if (mon->entry_sem == NULL) {
842                 /* Create the semaphore */
843                 sem = g_new0 (MonoCoopSem, 1);
844                 mono_coop_sem_init (sem, 0);
845                 if (InterlockedCompareExchangePointer ((gpointer*)&mon->entry_sem, sem, NULL) != NULL) {
846                         /* Someone else just put a handle here */
847                         mono_coop_sem_destroy (sem);
848                         g_free (sem);
849                 }
850         }
851
852         /*
853          * We need to register ourselves as waiting if it is the first time we are waiting,
854          * of if we were signaled and failed to acquire the lock.
855          */
856         if (!interrupted) {
857                 old_status = mon->status;
858                 for (;;) {
859                         if (mon_status_get_owner (old_status) == 0)
860                                 goto retry_contended;
861                         new_status = mon_status_increment_entry_count (old_status);
862                         tmp_status = InterlockedCompareExchange ((gint32*)&mon->status, new_status, old_status);
863                         if (tmp_status == old_status) {
864                                 break;
865                         }
866                         old_status = tmp_status;
867                 }
868         }
869
870         if (ms != INFINITE) {
871                 then = mono_msec_ticks ();
872         }
873         waitms = ms;
874         
875 #ifndef DISABLE_PERFCOUNTERS
876         mono_perfcounters->thread_queue_len++;
877         mono_perfcounters->thread_queue_max++;
878 #endif
879         thread = mono_thread_internal_current ();
880
881         /*
882          * If we allow interruption, we check the test state for an abort request before going into sleep.
883          * This is a workaround to the fact that Thread.Abort does non-sticky interruption of semaphores.
884          *
885          * Semaphores don't support the sticky interruption with mono_thread_info_install_interrupt.
886          *
887          * A better fix would be to switch to wait with something that allows sticky interrupts together
888          * with wrapping it with abort_protected_block_count for the non-alertable cases.
889          * And somehow make this whole dance atomic and not crazy expensive. Good luck.
890          *
891          */
892         if (allow_interruption) {
893                 if (!mono_thread_test_and_set_state (thread, (MonoThreadState)(ThreadState_StopRequested | ThreadState_AbortRequested), ThreadState_WaitSleepJoin)) {
894                         wait_ret = MONO_SEM_TIMEDWAIT_RET_ALERTED;
895                         goto done_waiting;
896                 }
897         } else {
898                 mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
899         }
900
901         /*
902          * We pass ALERTABLE instead of allow_interruption since we have to check for the
903          * StopRequested case below.
904          */
905         wait_ret = mono_coop_sem_timedwait (mon->entry_sem, waitms, MONO_SEM_FLAGS_ALERTABLE);
906
907         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
908
909 done_waiting:
910 #ifndef DISABLE_PERFCOUNTERS
911         mono_perfcounters->thread_queue_len--;
912 #endif
913
914         if (wait_ret == MONO_SEM_TIMEDWAIT_RET_ALERTED && !allow_interruption) {
915                 interrupted = TRUE;
916                 /* 
917                  * We have to obey a stop/suspend request even if 
918                  * allow_interruption is FALSE to avoid hangs at shutdown.
919                  */
920                 if (!mono_thread_test_state (mono_thread_internal_current (), (MonoThreadState)(ThreadState_StopRequested | ThreadState_SuspendRequested | ThreadState_AbortRequested))) {
921                         if (ms != INFINITE) {
922                                 now = mono_msec_ticks ();
923
924                                 /* it should not overflow before ~30k years */
925                                 g_assert (now >= then);
926
927                                 delta = now - then;
928                                 if (delta >= ms) {
929                                         ms = 0;
930                                 } else {
931                                         ms -= delta;
932                                 }
933                         }
934                         /* retry from the top */
935                         goto retry_contended;
936                 }
937         } else if (wait_ret == MONO_SEM_TIMEDWAIT_RET_SUCCESS) {
938                 interrupted = FALSE;
939                 /* retry from the top */
940                 goto retry_contended;
941         } else if (wait_ret == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT) {
942                 /* we're done */
943         }
944
945         /* Timed out or interrupted */
946         mon_decrement_entry_count (mon);
947
948         mono_profiler_monitor_event (obj, MONO_PROFILER_MONITOR_FAIL);
949
950         if (wait_ret == MONO_SEM_TIMEDWAIT_RET_ALERTED) {
951                 LOCK_DEBUG (g_message ("%s: (%d) interrupted waiting, returning -1", __func__, id));
952                 return -1;
953         } else if (wait_ret == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT) {
954                 LOCK_DEBUG (g_message ("%s: (%d) timed out waiting, returning FALSE", __func__, id));
955                 return 0;
956         } else {
957                 g_assert_not_reached ();
958                 return 0;
959         }
960 }
961
962 /*
963  * If allow_interruption == TRUE, the method will be interrupted if abort or suspend
964  * is requested. In this case it returns -1.
965  */
966 static inline gint32
967 mono_monitor_try_enter_internal (MonoObject *obj, guint32 ms, gboolean allow_interruption)
968 {
969         LockWord lw;
970         int id = mono_thread_info_get_small_id ();
971
972         LOCK_DEBUG (g_message("%s: (%d) Trying to lock object %p (%d ms)", __func__, id, obj, ms));
973
974         lw.sync = obj->synchronisation;
975
976         if (G_LIKELY (lock_word_is_free (lw))) {
977                 LockWord nlw = lock_word_new_flat (id);
978                 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, nlw.sync, NULL) == NULL) {
979                         return 1;
980                 } else {
981                         /* Someone acquired it in the meantime or put a hash */
982                         mono_monitor_inflate (obj);
983                         return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
984                 }
985         } else if (lock_word_is_inflated (lw)) {
986                 return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
987         } else if (lock_word_is_flat (lw)) {
988                 if (lock_word_get_owner (lw) == id) {
989                         if (lock_word_is_max_nest (lw)) {
990                                 mono_monitor_inflate_owned (obj, id);
991                                 return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
992                         } else {
993                                 LockWord nlw, old_lw;
994                                 nlw = lock_word_increment_nest (lw);
995                                 old_lw.sync = (MonoThreadsSync *)InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, nlw.sync, lw.sync);
996                                 if (old_lw.sync != lw.sync) {
997                                         /* Someone else inflated it in the meantime */
998                                         g_assert (lock_word_is_inflated (old_lw));
999                                         return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
1000                                 }
1001                                 return 1;
1002                         }
1003                 } else {
1004                         mono_monitor_inflate (obj);
1005                         return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
1006                 }
1007         } else if (lock_word_has_hash (lw)) {
1008                 mono_monitor_inflate (obj);
1009                 return mono_monitor_try_enter_inflated (obj, ms, allow_interruption, id);
1010         }
1011
1012         g_assert_not_reached ();
1013         return -1;
1014 }
1015
1016 gboolean 
1017 mono_monitor_enter (MonoObject *obj)
1018 {
1019         gint32 res;
1020         gboolean allow_interruption = TRUE;
1021         if (G_UNLIKELY (!obj)) {
1022                 mono_set_pending_exception (mono_get_exception_argument_null ("obj"));
1023                 return FALSE;
1024         }
1025
1026         /*
1027          * An inquisitive mind could ask what's the deal with this loop.
1028          * It exists to deal with interrupting a monitor enter that happened within an abort-protected block, like a .cctor.
1029          *
1030          * 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,
1031          * it will return NULL meaning we can't be aborted right now. Once that happens we switch to non-alertable.
1032          */
1033         do {
1034                 res = mono_monitor_try_enter_internal (obj, INFINITE, allow_interruption);
1035                 /*This means we got interrupted during the wait and didn't got the monitor.*/
1036                 if (res == -1) {
1037                         MonoException *exc = mono_thread_interruption_checkpoint ();
1038                         if (exc) {
1039                                 mono_set_pending_exception (exc);
1040                                 return FALSE;
1041                         } else {
1042                                 //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)
1043                                 allow_interruption = FALSE;
1044                         }
1045                 }
1046         } while (res == -1);
1047         return TRUE;
1048 }
1049
1050 gboolean 
1051 mono_monitor_enter_fast (MonoObject *obj)
1052 {
1053         if (G_UNLIKELY (!obj)) {
1054                 /* don't set pending exn on the fast path, just return
1055                  * FALSE and let the slow path take care of it. */
1056                 return FALSE;
1057         }
1058         return mono_monitor_try_enter_internal (obj, 0, FALSE) == 1;
1059 }
1060
1061 gboolean
1062 mono_monitor_try_enter (MonoObject *obj, guint32 ms)
1063 {
1064         if (G_UNLIKELY (!obj)) {
1065                 mono_set_pending_exception (mono_get_exception_argument_null ("obj"));
1066                 return FALSE;
1067         }
1068         return mono_monitor_try_enter_internal (obj, ms, FALSE) == 1;
1069 }
1070
1071 void
1072 mono_monitor_exit (MonoObject *obj)
1073 {
1074         LockWord lw;
1075         
1076         LOCK_DEBUG (g_message ("%s: (%d) Unlocking %p", __func__, mono_thread_info_get_small_id (), obj));
1077
1078         if (G_UNLIKELY (!obj)) {
1079                 mono_set_pending_exception (mono_get_exception_argument_null ("obj"));
1080                 return;
1081         }
1082
1083         lw.sync = obj->synchronisation;
1084
1085         mono_monitor_ensure_owned (lw, mono_thread_info_get_small_id ());
1086
1087         if (G_UNLIKELY (lock_word_is_inflated (lw)))
1088                 mono_monitor_exit_inflated (obj);
1089         else
1090                 mono_monitor_exit_flat (obj, lw);
1091 }
1092
1093 guint32
1094 mono_monitor_get_object_monitor_gchandle (MonoObject *object)
1095 {
1096         LockWord lw;
1097
1098         lw.sync = object->synchronisation;
1099
1100         if (lock_word_is_inflated (lw)) {
1101                 MonoThreadsSync *mon = lock_word_get_inflated_lock (lw);
1102                 return (guint32)mon->data;
1103         }
1104         return 0;
1105 }
1106
1107 /*
1108  * mono_monitor_threads_sync_member_offset:
1109  * @status_offset: returns size and offset of the "status" member
1110  * @nest_offset: returns size and offset of the "nest" member
1111  *
1112  * Returns the offsets and sizes of two members of the
1113  * MonoThreadsSync struct.  The Monitor ASM fastpaths need this.
1114  */
1115 void
1116 mono_monitor_threads_sync_members_offset (int *status_offset, int *nest_offset)
1117 {
1118         MonoThreadsSync ts;
1119
1120 #define ENCODE_OFF_SIZE(o,s)    (((o) << 8) | ((s) & 0xff))
1121
1122         *status_offset = ENCODE_OFF_SIZE (MONO_STRUCT_OFFSET (MonoThreadsSync, status), sizeof (ts.status));
1123         *nest_offset = ENCODE_OFF_SIZE (MONO_STRUCT_OFFSET (MonoThreadsSync, nest), sizeof (ts.nest));
1124 }
1125
1126 void
1127 ves_icall_System_Threading_Monitor_Monitor_try_enter_with_atomic_var (MonoObject *obj, guint32 ms, char *lockTaken)
1128 {
1129         gint32 res;
1130         gboolean allow_interruption = TRUE;
1131         if (G_UNLIKELY (!obj)) {
1132                 mono_set_pending_exception (mono_get_exception_argument_null ("obj"));
1133                 return;
1134         }
1135         do {
1136                 res = mono_monitor_try_enter_internal (obj, ms, allow_interruption);
1137                 /*This means we got interrupted during the wait and didn't got the monitor.*/
1138                 if (res == -1) {
1139                         MonoException *exc = mono_thread_interruption_checkpoint ();
1140                         if (exc) {
1141                                 mono_set_pending_exception (exc);
1142                                 return;
1143                         } else {
1144                                 //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)
1145                                 allow_interruption = FALSE;
1146                         }
1147                 }
1148         } while (res == -1);
1149         /*It's safe to do it from here since interruption would happen only on the wrapper.*/
1150         *lockTaken = res == 1;
1151 }
1152
1153 void
1154 mono_monitor_enter_v4 (MonoObject *obj, char *lock_taken)
1155 {
1156         if (*lock_taken == 1) {
1157                 mono_set_pending_exception (mono_get_exception_argument ("lockTaken", "lockTaken is already true"));
1158                 return;
1159         }
1160
1161         ves_icall_System_Threading_Monitor_Monitor_try_enter_with_atomic_var (obj, INFINITE, lock_taken);
1162 }
1163
1164 /*
1165  * mono_monitor_enter_v4_fast:
1166  *
1167  *   Same as mono_monitor_enter_v4, but return immediately if the
1168  * monitor cannot be acquired.
1169  * Returns TRUE if the lock was acquired, FALSE otherwise.
1170  */
1171 gboolean
1172 mono_monitor_enter_v4_fast (MonoObject *obj, char *lock_taken)
1173 {
1174         if (*lock_taken == 1)
1175                 return FALSE;
1176         if (G_UNLIKELY (!obj))
1177                 return FALSE;
1178         gint32 res = mono_monitor_try_enter_internal (obj, 0, TRUE);
1179         *lock_taken = res == 1;
1180         return res == 1;
1181 }
1182
1183 gboolean 
1184 ves_icall_System_Threading_Monitor_Monitor_test_owner (MonoObject *obj)
1185 {
1186         LockWord lw;
1187
1188         LOCK_DEBUG (g_message ("%s: Testing if %p is owned by thread %d", __func__, obj, mono_thread_info_get_small_id()));
1189
1190         lw.sync = obj->synchronisation;
1191
1192         if (lock_word_is_flat (lw)) {
1193                 return lock_word_get_owner (lw) == mono_thread_info_get_small_id ();
1194         } else if (lock_word_is_inflated (lw)) {
1195                 return mon_status_get_owner (lock_word_get_inflated_lock (lw)->status) == mono_thread_info_get_small_id ();
1196         }
1197         
1198         return(FALSE);
1199 }
1200
1201 gboolean 
1202 ves_icall_System_Threading_Monitor_Monitor_test_synchronised (MonoObject *obj)
1203 {
1204         LockWord lw;
1205
1206         LOCK_DEBUG (g_message("%s: (%d) Testing if %p is owned by any thread", __func__, mono_thread_info_get_small_id (), obj));
1207
1208         lw.sync = obj->synchronisation;
1209
1210         if (lock_word_is_flat (lw)) {
1211                 return !lock_word_is_free (lw);
1212         } else if (lock_word_is_inflated (lw)) {
1213                 return mon_status_get_owner (lock_word_get_inflated_lock (lw)->status) != 0;
1214         }
1215
1216         return FALSE;
1217 }
1218
1219 /* All wait list manipulation in the pulse, pulseall and wait
1220  * functions happens while the monitor lock is held, so we don't need
1221  * any extra struct locking
1222  */
1223
1224 void
1225 ves_icall_System_Threading_Monitor_Monitor_pulse (MonoObject *obj)
1226 {
1227         int id;
1228         LockWord lw;
1229         MonoThreadsSync *mon;
1230
1231         LOCK_DEBUG (g_message ("%s: (%d) Pulsing %p", __func__, mono_thread_info_get_small_id (), obj));
1232         
1233         id = mono_thread_info_get_small_id ();
1234         lw.sync = obj->synchronisation;
1235
1236         mono_monitor_ensure_owned (lw, id);
1237
1238         if (!lock_word_is_inflated (lw)) {
1239                 /* No threads waiting. A wait would have inflated the lock */
1240                 return;
1241         }
1242
1243         mon = lock_word_get_inflated_lock (lw);
1244
1245         LOCK_DEBUG (g_message ("%s: (%d) %d threads waiting", __func__, mono_thread_info_get_small_id (), g_slist_length (mon->wait_list)));
1246
1247         if (mon->wait_list != NULL) {
1248                 LOCK_DEBUG (g_message ("%s: (%d) signalling and dequeuing handle %p", __func__, mono_thread_info_get_small_id (), mon->wait_list->data));
1249         
1250                 mono_w32event_set (mon->wait_list->data);
1251                 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1252         }
1253 }
1254
1255 void
1256 ves_icall_System_Threading_Monitor_Monitor_pulse_all (MonoObject *obj)
1257 {
1258         int id;
1259         LockWord lw;
1260         MonoThreadsSync *mon;
1261         
1262         LOCK_DEBUG (g_message("%s: (%d) Pulsing all %p", __func__, mono_thread_info_get_small_id (), obj));
1263
1264         id = mono_thread_info_get_small_id ();
1265         lw.sync = obj->synchronisation;
1266
1267         mono_monitor_ensure_owned (lw, id);
1268
1269         if (!lock_word_is_inflated (lw)) {
1270                 /* No threads waiting. A wait would have inflated the lock */
1271                 return;
1272         }
1273
1274         mon = lock_word_get_inflated_lock (lw);
1275
1276         LOCK_DEBUG (g_message ("%s: (%d) %d threads waiting", __func__, mono_thread_info_get_small_id (), g_slist_length (mon->wait_list)));
1277
1278         while (mon->wait_list != NULL) {
1279                 LOCK_DEBUG (g_message ("%s: (%d) signalling and dequeuing handle %p", __func__, mono_thread_info_get_small_id (), mon->wait_list->data));
1280         
1281                 mono_w32event_set (mon->wait_list->data);
1282                 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
1283         }
1284 }
1285
1286 gboolean
1287 ves_icall_System_Threading_Monitor_Monitor_wait (MonoObject *obj, guint32 ms)
1288 {
1289         LockWord lw;
1290         MonoThreadsSync *mon;
1291         HANDLE event;
1292         guint32 nest;
1293         guint32 ret;
1294         gboolean success = FALSE;
1295         gint32 regain;
1296         MonoInternalThread *thread = mono_thread_internal_current ();
1297         int id = mono_thread_info_get_small_id ();
1298
1299         LOCK_DEBUG (g_message ("%s: (%d) Trying to wait for %p with timeout %dms", __func__, mono_thread_info_get_small_id (), obj, ms));
1300
1301         lw.sync = obj->synchronisation;
1302
1303         mono_monitor_ensure_owned (lw, id);
1304
1305         if (!lock_word_is_inflated (lw)) {
1306                 mono_monitor_inflate_owned (obj, id);
1307                 lw.sync = obj->synchronisation;
1308         }
1309
1310         mon = lock_word_get_inflated_lock (lw);
1311
1312         /* Do this WaitSleepJoin check before creating the event handle */
1313         if (mono_thread_current_check_pending_interrupt ())
1314                 return FALSE;
1315         
1316         event = mono_w32event_create (FALSE, FALSE);
1317         if (event == NULL) {
1318                 mono_set_pending_exception (mono_get_exception_synchronization_lock ("Failed to set up wait event"));
1319                 return FALSE;
1320         }
1321         
1322         LOCK_DEBUG (g_message ("%s: (%d) queuing handle %p", __func__, mono_thread_info_get_small_id (), event));
1323
1324         /* This looks superfluous */
1325         if (mono_thread_current_check_pending_interrupt ()) {
1326                 CloseHandle (event);
1327                 return FALSE;
1328         }
1329         
1330         mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
1331
1332         mon->wait_list = g_slist_append (mon->wait_list, event);
1333         
1334         /* Save the nest count, and release the lock */
1335         nest = mon->nest;
1336         mon->nest = 1;
1337         mono_memory_write_barrier ();
1338         mono_monitor_exit_inflated (obj);
1339
1340         LOCK_DEBUG (g_message ("%s: (%d) Unlocked %p lock %p", __func__, mono_thread_info_get_small_id (), obj, mon));
1341
1342         /* There's no race between unlocking mon and waiting for the
1343          * event, because auto reset events are sticky, and this event
1344          * is private to this thread.  Therefore even if the event was
1345          * signalled before we wait, we still succeed.
1346          */
1347         MONO_ENTER_GC_SAFE;
1348         ret = WaitForSingleObjectEx (event, ms, TRUE);
1349         MONO_EXIT_GC_SAFE;
1350
1351         /* Reset the thread state fairly early, so we don't have to worry
1352          * about the monitor error checking
1353          */
1354         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
1355
1356         /* Regain the lock with the previous nest count */
1357         do {
1358                 regain = mono_monitor_try_enter_inflated (obj, INFINITE, TRUE, id);
1359                 /* We must regain the lock before handling interruption requests */
1360         } while (regain == -1);
1361
1362         g_assert (regain == 1);
1363
1364         mon->nest = nest;
1365
1366         LOCK_DEBUG (g_message ("%s: (%d) Regained %p lock %p", __func__, mono_thread_info_get_small_id (), obj, mon));
1367
1368         if (ret == WAIT_TIMEOUT) {
1369                 /* Poll the event again, just in case it was signalled
1370                  * while we were trying to regain the monitor lock
1371                  */
1372                 MONO_ENTER_GC_SAFE;
1373                 ret = WaitForSingleObjectEx (event, 0, FALSE);
1374                 MONO_EXIT_GC_SAFE;
1375         }
1376
1377         /* Pulse will have popped our event from the queue if it signalled
1378          * us, so we only do it here if the wait timed out.
1379          *
1380          * This avoids a race condition where the thread holding the
1381          * lock can Pulse several times before the WaitForSingleObject
1382          * returns.  If we popped the queue here then this event might
1383          * be signalled more than once, thereby starving another
1384          * thread.
1385          */
1386         
1387         if (ret == WAIT_OBJECT_0) {
1388                 LOCK_DEBUG (g_message ("%s: (%d) Success", __func__, mono_thread_info_get_small_id ()));
1389                 success = TRUE;
1390         } else {
1391                 LOCK_DEBUG (g_message ("%s: (%d) Wait failed, dequeuing handle %p", __func__, mono_thread_info_get_small_id (), event));
1392                 /* No pulse, so we have to remove ourself from the
1393                  * wait queue
1394                  */
1395                 mon->wait_list = g_slist_remove (mon->wait_list, event);
1396         }
1397         CloseHandle (event);
1398         
1399         return success;
1400 }
1401