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