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