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