2008-07-28 Marek Habersack <mhabersack@novell.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
13 #include <mono/metadata/monitor.h>
14 #include <mono/metadata/threads-types.h>
15 #include <mono/metadata/exception.h>
16 #include <mono/metadata/threads.h>
17 #include <mono/io-layer/io-layer.h>
18 #include <mono/metadata/object-internals.h>
19 #include <mono/metadata/gc-internal.h>
20 #include <mono/utils/mono-time.h>
21
22 /*#define LOCK_DEBUG(a) do { a; } while (0)*/
23 #define LOCK_DEBUG(a)
24
25 /*
26  * The monitor implementation here is based on
27  * http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf and
28  * http://www.research.ibm.com/people/d/dfb/papers/Bacon98Thin.ps
29  *
30  * The Dice paper describes a technique for saving lock record space
31  * by returning records to a free list when they become unused.  That
32  * sounds like unnecessary complexity to me, though if it becomes
33  * clear that unused lock records are taking up lots of space or we
34  * need to shave more time off by avoiding a malloc then we can always
35  * implement the free list idea later.  The timeout parameter to
36  * try_enter voids some of the assumptions about the reference count
37  * field in Dice's implementation too.  In his version, the thread
38  * attempting to lock a contended object will block until it succeeds,
39  * so the reference count will never be decremented while an object is
40  * locked.
41  *
42  * Bacon's thin locks have a fast path that doesn't need a lock record
43  * for the common case of locking an unlocked or shallow-nested
44  * object, but the technique relies on encoding the thread ID in 15
45  * bits (to avoid too much per-object space overhead.)  Unfortunately
46  * I don't think it's possible to reliably encode a pthread_t into 15
47  * bits. (The JVM implementation used seems to have a 15-bit
48  * per-thread identifier available.)
49  *
50  * This implementation then combines Dice's basic lock model with
51  * Bacon's simplification of keeping a lock record for the lifetime of
52  * an object.
53  */
54
55 struct _MonoThreadsSync
56 {
57         gsize owner;                    /* thread ID */
58         guint32 nest;
59 #ifdef HAVE_MOVING_COLLECTOR
60         gint32 hash_code;
61 #endif
62         volatile gint32 entry_count;
63         HANDLE entry_sem;
64         GSList *wait_list;
65         void *data;
66 };
67
68 typedef struct _MonitorArray MonitorArray;
69
70 struct _MonitorArray {
71         MonitorArray *next;
72         int num_monitors;
73         MonoThreadsSync monitors [MONO_ZERO_LEN_ARRAY];
74 };
75
76 #define mono_monitor_allocator_lock() EnterCriticalSection (&monitor_mutex)
77 #define mono_monitor_allocator_unlock() LeaveCriticalSection (&monitor_mutex)
78 static CRITICAL_SECTION monitor_mutex;
79 static MonoThreadsSync *monitor_freelist;
80 static MonitorArray *monitor_allocated;
81 static int array_size = 16;
82
83 #ifdef HAVE_KW_THREAD
84 static __thread gsize tls_pthread_self MONO_TLS_FAST;
85 #endif
86
87 #ifndef PLATFORM_WIN32
88 #ifdef HAVE_KW_THREAD
89 #define GetCurrentThreadId() tls_pthread_self
90 #else
91 /* 
92  * The usual problem: we can't replace GetCurrentThreadId () with a macro because
93  * it is in a public header.
94  */
95 #define GetCurrentThreadId() ((gsize)pthread_self ())
96 #endif
97 #endif
98
99 void
100 mono_monitor_init (void)
101 {
102         InitializeCriticalSection (&monitor_mutex);
103 }
104  
105 void
106 mono_monitor_cleanup (void)
107 {
108         /*DeleteCriticalSection (&monitor_mutex);*/
109 }
110
111 /*
112  * mono_monitor_init_tls:
113  *
114  *   Setup TLS variables used by the monitor code for the current thread.
115  */
116 void
117 mono_monitor_init_tls (void)
118 {
119 #if !defined(PLATFORM_WIN32) && defined(HAVE_KW_THREAD)
120         tls_pthread_self = pthread_self ();
121 #endif
122 }
123
124 static int
125 monitor_is_on_freelist (MonoThreadsSync *mon)
126 {
127         MonitorArray *marray;
128         for (marray = monitor_allocated; marray; marray = marray->next) {
129                 if (mon >= marray->monitors && mon < &marray->monitors [marray->num_monitors])
130                         return TRUE;
131         }
132         return FALSE;
133 }
134
135 /**
136  * mono_locks_dump:
137  * @include_untaken:
138  *
139  * Print a report on stdout of the managed locks currently held by
140  * threads. If @include_untaken is specified, list also inflated locks
141  * which are unheld.
142  * This is supposed to be used in debuggers like gdb.
143  */
144 void
145 mono_locks_dump (gboolean include_untaken)
146 {
147         int i;
148         int used = 0, on_freelist = 0, to_recycle = 0, total = 0, num_arrays = 0;
149         MonoThreadsSync *mon;
150         MonitorArray *marray;
151         for (mon = monitor_freelist; mon; mon = mon->data)
152                 on_freelist++;
153         for (marray = monitor_allocated; marray; marray = marray->next) {
154                 total += marray->num_monitors;
155                 num_arrays++;
156                 for (i = 0; i < marray->num_monitors; ++i) {
157                         mon = &marray->monitors [i];
158                         if (mon->data == NULL) {
159                                 if (i < marray->num_monitors - 1)
160                                         to_recycle++;
161                         } else {
162                                 if (!monitor_is_on_freelist (mon->data)) {
163                                         MonoObject *holder = mono_gc_weak_link_get (&mon->data);
164                                         if (mon->owner) {
165                                                 g_print ("Lock %p in object %p held by thread %p, nest level: %d\n",
166                                                         mon, holder, (void*)mon->owner, mon->nest);
167                                                 if (mon->entry_sem)
168                                                         g_print ("\tWaiting on semaphore %p: %d\n", mon->entry_sem, mon->entry_count);
169                                         } else if (include_untaken) {
170                                                 g_print ("Lock %p in object %p untaken\n", mon, holder);
171                                         }
172                                         used++;
173                                 }
174                         }
175                 }
176         }
177         g_print ("Total locks (in %d array(s)): %d, used: %d, on freelist: %d, to recycle: %d\n",
178                 num_arrays, total, used, on_freelist, to_recycle);
179 }
180
181 /* LOCKING: this is called with monitor_mutex held */
182 static void 
183 mon_finalize (MonoThreadsSync *mon)
184 {
185         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": Finalizing sync %p", mon));
186
187         if (mon->entry_sem != NULL) {
188                 CloseHandle (mon->entry_sem);
189                 mon->entry_sem = NULL;
190         }
191         /* If this isn't empty then something is seriously broken - it
192          * means a thread is still waiting on the object that owned
193          * this lock, but the object has been finalized.
194          */
195         g_assert (mon->wait_list == NULL);
196
197         mon->entry_count = 0;
198         /* owner and nest are set in mon_new, no need to zero them out */
199
200         mon->data = monitor_freelist;
201         monitor_freelist = mon;
202 }
203
204 /* LOCKING: this is called with monitor_mutex held */
205 static MonoThreadsSync *
206 mon_new (gsize id)
207 {
208         MonoThreadsSync *new;
209
210         if (!monitor_freelist) {
211                 MonitorArray *marray;
212                 int i;
213                 /* see if any sync block has been collected */
214                 new = NULL;
215                 for (marray = monitor_allocated; marray; marray = marray->next) {
216                         for (i = 0; i < marray->num_monitors; ++i) {
217                                 if (marray->monitors [i].data == NULL) {
218                                         new = &marray->monitors [i];
219                                         new->data = monitor_freelist;
220                                         monitor_freelist = new;
221                                 }
222                         }
223                         /* small perf tweak to avoid scanning all the blocks */
224                         if (new)
225                                 break;
226                 }
227                 /* need to allocate a new array of monitors */
228                 if (!monitor_freelist) {
229                         MonitorArray *last;
230                         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": allocating more monitors: %d", array_size));
231                         marray = g_malloc0 (sizeof (MonoArray) + array_size * sizeof (MonoThreadsSync));
232                         marray->num_monitors = array_size;
233                         array_size *= 2;
234                         /* link into the freelist */
235                         for (i = 0; i < marray->num_monitors - 1; ++i) {
236                                 marray->monitors [i].data = &marray->monitors [i + 1];
237                         }
238                         marray->monitors [i].data = NULL; /* the last one */
239                         monitor_freelist = &marray->monitors [0];
240                         /* we happend the marray instead of prepending so that
241                          * the collecting loop above will need to scan smaller arrays first
242                          */
243                         if (!monitor_allocated) {
244                                 monitor_allocated = marray;
245                         } else {
246                                 last = monitor_allocated;
247                                 while (last->next)
248                                         last = last->next;
249                                 last->next = marray;
250                         }
251                 }
252         }
253
254         new = monitor_freelist;
255         monitor_freelist = new->data;
256
257         new->owner = id;
258         new->nest = 1;
259         
260         return new;
261 }
262
263 /*
264  * Format of the lock word:
265  * thinhash | fathash | data
266  *
267  * thinhash is the lower bit: if set data is the shifted hashcode of the object.
268  * fathash is another bit: if set the hash code is stored in the MonoThreadsSync
269  *   struct pointed to by data
270  * if neither bit is set and data is non-NULL, data is a MonoThreadsSync
271  */
272 typedef union {
273         gsize lock_word;
274         MonoThreadsSync *sync;
275 } LockWord;
276
277 enum {
278         LOCK_WORD_THIN_HASH = 1,
279         LOCK_WORD_FAT_HASH = 1 << 1,
280         LOCK_WORD_BITS_MASK = 0x3,
281         LOCK_WORD_HASH_SHIFT = 2
282 };
283
284 #define MONO_OBJECT_ALIGNMENT_SHIFT     3
285
286 /*
287  * mono_object_hash:
288  * @obj: an object
289  *
290  * Calculate a hash code for @obj that is constant while @obj is alive.
291  */
292 int
293 mono_object_hash (MonoObject* obj)
294 {
295 #ifdef HAVE_MOVING_COLLECTOR
296         LockWord lw;
297         unsigned int hash;
298         if (!obj)
299                 return 0;
300         lw.sync = obj->synchronisation;
301         if (lw.lock_word & LOCK_WORD_THIN_HASH) {
302                 /*g_print ("fast thin hash %d for obj %p store\n", (unsigned int)lw.lock_word >> LOCK_WORD_HASH_SHIFT, obj);*/
303                 return (unsigned int)lw.lock_word >> LOCK_WORD_HASH_SHIFT;
304         }
305         if (lw.lock_word & LOCK_WORD_FAT_HASH) {
306                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
307                 /*g_print ("fast fat hash %d for obj %p store\n", lw.sync->hash_code, obj);*/
308                 return lw.sync->hash_code;
309         }
310         /*
311          * while we are inside this function, the GC will keep this object pinned,
312          * since we are in the unmanaged stack. Thanks to this and to the hash
313          * function that depends only on the address, we can ignore the races if
314          * another thread computes the hash at the same time, because it'll end up
315          * with the same value.
316          */
317         hash = (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
318         /* clear the top bits as they can be discarded */
319         hash &= ~(LOCK_WORD_BITS_MASK << 30);
320         /* no hash flags were set, so it must be a MonoThreadsSync pointer if not NULL */
321         if (lw.sync) {
322                 lw.sync->hash_code = hash;
323                 /*g_print ("storing hash code %d for obj %p in sync %p\n", hash, obj, lw.sync);*/
324                 lw.lock_word |= LOCK_WORD_FAT_HASH;
325                 /* this is safe since we don't deflate locks */
326                 obj->synchronisation = lw.sync;
327         } else {
328                 /*g_print ("storing thin hash code %d for obj %p\n", hash, obj);*/
329                 lw.lock_word = LOCK_WORD_THIN_HASH | (hash << LOCK_WORD_HASH_SHIFT);
330                 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, NULL) == NULL)
331                         return hash;
332                 /*g_print ("failed store\n");*/
333                 /* someone set the hash flag or someone inflated the object */
334                 lw.sync = obj->synchronisation;
335                 if (lw.lock_word & LOCK_WORD_THIN_HASH)
336                         return hash;
337                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
338                 lw.sync->hash_code = hash;
339                 lw.lock_word |= LOCK_WORD_FAT_HASH;
340                 /* this is safe since we don't deflate locks */
341                 obj->synchronisation = lw.sync;
342         }
343         return hash;
344 #else
345 /*
346  * Wang's address-based hash function:
347  *   http://www.concentric.net/~Ttwang/tech/addrhash.htm
348  */
349         return (GPOINTER_TO_UINT (obj) >> MONO_OBJECT_ALIGNMENT_SHIFT) * 2654435761u;
350 #endif
351 }
352
353 /* If allow_interruption==TRUE, the method will be interrumped if abort or suspend
354  * is requested. In this case it returns -1.
355  */ 
356 static inline gint32 
357 mono_monitor_try_enter_internal (MonoObject *obj, guint32 ms, gboolean allow_interruption)
358 {
359         MonoThreadsSync *mon;
360         gsize id = GetCurrentThreadId ();
361         HANDLE sem;
362         guint32 then = 0, now, delta;
363         guint32 waitms;
364         guint32 ret;
365         MonoThread *thread;
366
367         LOCK_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
368                   ": (%d) Trying to lock object %p (%d ms)", id, obj, ms));
369
370         if (G_UNLIKELY (!obj)) {
371                 mono_raise_exception (mono_get_exception_argument_null ("obj"));
372                 return FALSE;
373         }
374
375 retry:
376         mon = obj->synchronisation;
377
378         /* If the object has never been locked... */
379         if (G_UNLIKELY (mon == NULL)) {
380                 mono_monitor_allocator_lock ();
381                 mon = mon_new (id);
382                 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, mon, NULL) == NULL) {
383                         mono_gc_weak_link_add (&mon->data, obj);
384                         mono_monitor_allocator_unlock ();
385                         /* Successfully locked */
386                         return 1;
387                 } else {
388 #ifdef HAVE_MOVING_COLLECTOR
389                         LockWord lw;
390                         lw.sync = obj->synchronisation;
391                         if (lw.lock_word & LOCK_WORD_THIN_HASH) {
392                                 MonoThreadsSync *oldlw = lw.sync;
393                                 /* move the already calculated hash */
394                                 mon->hash_code = lw.lock_word >> LOCK_WORD_HASH_SHIFT;
395                                 lw.sync = mon;
396                                 lw.lock_word |= LOCK_WORD_FAT_HASH;
397                                 if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, oldlw) == oldlw) {
398                                         mono_gc_weak_link_add (&mon->data, obj);
399                                         mono_monitor_allocator_unlock ();
400                                         /* Successfully locked */
401                                         return 1;
402                                 } else {
403                                         mon_finalize (mon);
404                                         mono_monitor_allocator_unlock ();
405                                         goto retry;
406                                 }
407                         } else if (lw.lock_word & LOCK_WORD_FAT_HASH) {
408                                 mon_finalize (mon);
409                                 mono_monitor_allocator_unlock ();
410                                 /* get the old lock without the fat hash bit */
411                                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
412                                 mon = lw.sync;
413                         } else {
414                                 mon_finalize (mon);
415                                 mono_monitor_allocator_unlock ();
416                                 mon = obj->synchronisation;
417                         }
418 #else
419                         mon_finalize (mon);
420                         mono_monitor_allocator_unlock ();
421                         mon = obj->synchronisation;
422 #endif
423                 }
424         } else {
425 #ifdef HAVE_MOVING_COLLECTOR
426                 LockWord lw;
427                 lw.sync = mon;
428                 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
429                         MonoThreadsSync *oldlw = lw.sync;
430                         mono_monitor_allocator_lock ();
431                         mon = mon_new (id);
432                         /* move the already calculated hash */
433                         mon->hash_code = lw.lock_word >> LOCK_WORD_HASH_SHIFT;
434                         lw.sync = mon;
435                         lw.lock_word |= LOCK_WORD_FAT_HASH;
436                         if (InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, lw.sync, oldlw) == oldlw) {
437                                 mono_gc_weak_link_add (&mon->data, obj);
438                                 mono_monitor_allocator_unlock ();
439                                 /* Successfully locked */
440                                 return 1;
441                         } else {
442                                 mon_finalize (mon);
443                                 mono_monitor_allocator_unlock ();
444                                 goto retry;
445                         }
446                 }
447 #endif
448         }
449
450 #ifdef HAVE_MOVING_COLLECTOR
451         {
452                 LockWord lw;
453                 lw.sync = mon;
454                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
455                 mon = lw.sync;
456         }
457 #endif
458
459         /* If the object has previously been locked but isn't now... */
460
461         /* This case differs from Dice's case 3 because we don't
462          * deflate locks or cache unused lock records
463          */
464         if (G_LIKELY (mon->owner == 0)) {
465                 /* Try to install our ID in the owner field, nest
466                  * should have been left at 1 by the previous unlock
467                  * operation
468                  */
469                 if (G_LIKELY (InterlockedCompareExchangePointer ((gpointer *)&mon->owner, (gpointer)id, 0) == 0)) {
470                         /* Success */
471                         g_assert (mon->nest == 1);
472                         return 1;
473                 } else {
474                         /* Trumped again! */
475                         goto retry;
476                 }
477         }
478
479         /* If the object is currently locked by this thread... */
480         if (mon->owner == id) {
481                 mon->nest++;
482                 return 1;
483         }
484
485         /* The object must be locked by someone else... */
486
487         /* If ms is 0 we don't block, but just fail straight away */
488         if (ms == 0) {
489                 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) timed out, returning FALSE", id));
490                 return 0;
491         }
492
493         /* The slow path begins here.  We need to make sure theres a
494          * semaphore handle (creating it if necessary), and block on
495          * it
496          */
497         if (mon->entry_sem == NULL) {
498                 /* Create the semaphore */
499                 sem = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
500                 g_assert (sem != NULL);
501                 if (InterlockedCompareExchangePointer ((gpointer*)&mon->entry_sem, sem, NULL) != NULL) {
502                         /* Someone else just put a handle here */
503                         CloseHandle (sem);
504                 }
505         }
506         
507         /* If we need to time out, record a timestamp and adjust ms,
508          * because WaitForSingleObject doesn't tell us how long it
509          * waited for.
510          *
511          * Don't block forever here, because theres a chance the owner
512          * thread released the lock while we were creating the
513          * semaphore: we would not get the wakeup.  Using the event
514          * handle technique from pulse/wait would involve locking the
515          * lock struct and therefore slowing down the fast path.
516          */
517         if (ms != INFINITE) {
518                 then = mono_msec_ticks ();
519                 if (ms < 100) {
520                         waitms = ms;
521                 } else {
522                         waitms = 100;
523                 }
524         } else {
525                 waitms = 100;
526         }
527         
528         InterlockedIncrement (&mon->entry_count);
529
530         thread = mono_thread_current ();
531
532         mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
533         
534         ret = WaitForSingleObjectEx (mon->entry_sem, waitms, allow_interruption);
535
536         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
537         
538         InterlockedDecrement (&mon->entry_count);
539
540         if (ms != INFINITE) {
541                 now = mono_msec_ticks ();
542                 
543                 if (now < then) {
544                         /* The counter must have wrapped around */
545                         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
546                                    ": wrapped around! now=0x%x then=0x%x", now, then));
547                         
548                         now += (0xffffffff - then);
549                         then = 0;
550
551                         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": wrap rejig: now=0x%x then=0x%x delta=0x%x", now, then, now-then));
552                 }
553                 
554                 delta = now - then;
555                 if (delta >= ms) {
556                         ms = 0;
557                 } else {
558                         ms -= delta;
559                 }
560
561                 if ((ret == WAIT_TIMEOUT || (ret == WAIT_IO_COMPLETION && !allow_interruption)) && ms > 0) {
562                         /* More time left */
563                         goto retry;
564                 }
565         } else {
566                 if (ret == WAIT_TIMEOUT || (ret == WAIT_IO_COMPLETION && !allow_interruption)) {
567                         /* Infinite wait, so just try again */
568                         goto retry;
569                 }
570         }
571         
572         if (ret == WAIT_OBJECT_0) {
573                 /* retry from the top */
574                 goto retry;
575         }
576         
577         /* We must have timed out */
578         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) timed out waiting, returning FALSE", id));
579
580         if (ret == WAIT_IO_COMPLETION)
581                 return -1;
582         else 
583                 return 0;
584 }
585
586 gboolean 
587 mono_monitor_enter (MonoObject *obj)
588 {
589         return mono_monitor_try_enter_internal (obj, INFINITE, FALSE) == 1;
590 }
591
592 gboolean 
593 mono_monitor_try_enter (MonoObject *obj, guint32 ms)
594 {
595         return mono_monitor_try_enter_internal (obj, ms, FALSE) == 1;
596 }
597
598 void
599 mono_monitor_exit (MonoObject *obj)
600 {
601         MonoThreadsSync *mon;
602         guint32 nest;
603         
604         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Unlocking %p", GetCurrentThreadId (), obj));
605
606         if (G_UNLIKELY (!obj)) {
607                 mono_raise_exception (mono_get_exception_argument_null ("obj"));
608                 return;
609         }
610
611         mon = obj->synchronisation;
612
613 #ifdef HAVE_MOVING_COLLECTOR
614         {
615                 LockWord lw;
616                 lw.sync = mon;
617                 if (lw.lock_word & LOCK_WORD_THIN_HASH)
618                         return;
619                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
620                 mon = lw.sync;
621         }
622 #endif
623         if (G_UNLIKELY (mon == NULL)) {
624                 /* No one ever used Enter. Just ignore the Exit request as MS does */
625                 return;
626         }
627         if (G_UNLIKELY (mon->owner != GetCurrentThreadId ())) {
628                 return;
629         }
630         
631         nest = mon->nest - 1;
632         if (nest == 0) {
633                 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
634                           ": (%d) Object %p is now unlocked", GetCurrentThreadId (), obj));
635         
636                 /* object is now unlocked, leave nest==1 so we don't
637                  * need to set it when the lock is reacquired
638                  */
639                 mon->owner = 0;
640
641                 /* Do the wakeup stuff.  It's possible that the last
642                  * blocking thread gave up waiting just before we
643                  * release the semaphore resulting in a futile wakeup
644                  * next time there's contention for this object, but
645                  * it means we don't have to waste time locking the
646                  * struct.
647                  */
648                 if (mon->entry_count > 0) {
649                         ReleaseSemaphore (mon->entry_sem, 1, NULL);
650                 }
651         } else {
652                 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
653                           ": (%d) Object %p is now locked %d times", GetCurrentThreadId (), obj, nest));
654                 mon->nest = nest;
655         }
656 }
657
658 gboolean 
659 ves_icall_System_Threading_Monitor_Monitor_try_enter (MonoObject *obj, guint32 ms)
660 {
661         gint32 res;
662
663         do {
664                 res = mono_monitor_try_enter_internal (obj, ms, TRUE);
665                 if (res == -1)
666                         mono_thread_interruption_checkpoint ();
667         } while (res == -1);
668         
669         return res == 1;
670 }
671
672 gboolean 
673 ves_icall_System_Threading_Monitor_Monitor_test_owner (MonoObject *obj)
674 {
675         MonoThreadsSync *mon;
676         
677         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
678                   ": Testing if %p is owned by thread %d", obj, GetCurrentThreadId()));
679
680         mon = obj->synchronisation;
681 #ifdef HAVE_MOVING_COLLECTOR
682         {
683                 LockWord lw;
684                 lw.sync = mon;
685                 if (lw.lock_word & LOCK_WORD_THIN_HASH)
686                         return FALSE;
687                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
688                 mon = lw.sync;
689         }
690 #endif
691         if (mon == NULL) {
692                 return FALSE;
693         }
694         
695         if(mon->owner==GetCurrentThreadId ()) {
696                 return(TRUE);
697         }
698         
699         return(FALSE);
700 }
701
702 gboolean 
703 ves_icall_System_Threading_Monitor_Monitor_test_synchronised (MonoObject *obj)
704 {
705         MonoThreadsSync *mon;
706
707         LOCK_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION
708                   ": (%d) Testing if %p is owned by any thread", GetCurrentThreadId (), obj));
709         
710         mon = obj->synchronisation;
711 #ifdef HAVE_MOVING_COLLECTOR
712         {
713                 LockWord lw;
714                 lw.sync = mon;
715                 if (lw.lock_word & LOCK_WORD_THIN_HASH)
716                         return FALSE;
717                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
718                 mon = lw.sync;
719         }
720 #endif
721         if (mon == NULL) {
722                 return FALSE;
723         }
724         
725         if (mon->owner != 0) {
726                 return TRUE;
727         }
728         
729         return FALSE;
730 }
731
732 /* All wait list manipulation in the pulse, pulseall and wait
733  * functions happens while the monitor lock is held, so we don't need
734  * any extra struct locking
735  */
736
737 void
738 ves_icall_System_Threading_Monitor_Monitor_pulse (MonoObject *obj)
739 {
740         MonoThreadsSync *mon;
741         
742         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Pulsing %p", 
743                 GetCurrentThreadId (), obj));
744         
745         mon = obj->synchronisation;
746 #ifdef HAVE_MOVING_COLLECTOR
747         {
748                 LockWord lw;
749                 lw.sync = mon;
750                 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
751                         mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
752                         return;
753                 }
754                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
755                 mon = lw.sync;
756         }
757 #endif
758         if (mon == NULL) {
759                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
760                 return;
761         }
762         if (mon->owner != GetCurrentThreadId ()) {
763                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
764                 return;
765         }
766
767         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) %d threads waiting",
768                   GetCurrentThreadId (), g_slist_length (mon->wait_list)));
769         
770         if (mon->wait_list != NULL) {
771                 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
772                           ": (%d) signalling and dequeuing handle %p",
773                           GetCurrentThreadId (), mon->wait_list->data));
774         
775                 SetEvent (mon->wait_list->data);
776                 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
777         }
778 }
779
780 void
781 ves_icall_System_Threading_Monitor_Monitor_pulse_all (MonoObject *obj)
782 {
783         MonoThreadsSync *mon;
784         
785         LOCK_DEBUG (g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Pulsing all %p",
786                   GetCurrentThreadId (), obj));
787
788         mon = obj->synchronisation;
789 #ifdef HAVE_MOVING_COLLECTOR
790         {
791                 LockWord lw;
792                 lw.sync = mon;
793                 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
794                         mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
795                         return;
796                 }
797                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
798                 mon = lw.sync;
799         }
800 #endif
801         if (mon == NULL) {
802                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
803                 return;
804         }
805         if (mon->owner != GetCurrentThreadId ()) {
806                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
807                 return;
808         }
809
810         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) %d threads waiting",
811                   GetCurrentThreadId (), g_slist_length (mon->wait_list)));
812
813         while (mon->wait_list != NULL) {
814                 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
815                           ": (%d) signalling and dequeuing handle %p",
816                           GetCurrentThreadId (), mon->wait_list->data));
817         
818                 SetEvent (mon->wait_list->data);
819                 mon->wait_list = g_slist_remove (mon->wait_list, mon->wait_list->data);
820         }
821 }
822
823 gboolean
824 ves_icall_System_Threading_Monitor_Monitor_wait (MonoObject *obj, guint32 ms)
825 {
826         MonoThreadsSync *mon;
827         HANDLE event;
828         guint32 nest;
829         guint32 ret;
830         gboolean success = FALSE;
831         gint32 regain;
832         MonoThread *thread = mono_thread_current ();
833
834         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION
835                   ": (%d) Trying to wait for %p with timeout %dms",
836                   GetCurrentThreadId (), obj, ms));
837         
838         mon = obj->synchronisation;
839 #ifdef HAVE_MOVING_COLLECTOR
840         {
841                 LockWord lw;
842                 lw.sync = mon;
843                 if (lw.lock_word & LOCK_WORD_THIN_HASH) {
844                         mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
845                         return FALSE;
846                 }
847                 lw.lock_word &= ~LOCK_WORD_BITS_MASK;
848                 mon = lw.sync;
849         }
850 #endif
851         if (mon == NULL) {
852                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
853                 return FALSE;
854         }
855         if (mon->owner != GetCurrentThreadId ()) {
856                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
857                 return FALSE;
858         }
859
860         /* Do this WaitSleepJoin check before creating the event handle */
861         mono_thread_current_check_pending_interrupt ();
862         
863         event = CreateEvent (NULL, FALSE, FALSE, NULL);
864         if (event == NULL) {
865                 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to set up wait event"));
866                 return FALSE;
867         }
868         
869         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) queuing handle %p",
870                   GetCurrentThreadId (), event));
871
872         mono_thread_current_check_pending_interrupt ();
873         
874         mono_thread_set_state (thread, ThreadState_WaitSleepJoin);
875
876         mon->wait_list = g_slist_append (mon->wait_list, event);
877         
878         /* Save the nest count, and release the lock */
879         nest = mon->nest;
880         mon->nest = 1;
881         mono_monitor_exit (obj);
882
883         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Unlocked %p lock %p",
884                   GetCurrentThreadId (), obj, mon));
885
886         /* There's no race between unlocking mon and waiting for the
887          * event, because auto reset events are sticky, and this event
888          * is private to this thread.  Therefore even if the event was
889          * signalled before we wait, we still succeed.
890          */
891         ret = WaitForSingleObjectEx (event, ms, TRUE);
892
893         /* Reset the thread state fairly early, so we don't have to worry
894          * about the monitor error checking
895          */
896         mono_thread_clr_state (thread, ThreadState_WaitSleepJoin);
897         
898         if (mono_thread_interruption_requested ()) {
899                 CloseHandle (event);
900                 return FALSE;
901         }
902
903         /* Regain the lock with the previous nest count */
904         do {
905                 regain = mono_monitor_try_enter_internal (obj, INFINITE, TRUE);
906                 if (regain == -1) 
907                         mono_thread_interruption_checkpoint ();
908         } while (regain == -1);
909
910         if (regain == 0) {
911                 /* Something went wrong, so throw a
912                  * SynchronizationLockException
913                  */
914                 CloseHandle (event);
915                 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to regain lock"));
916                 return FALSE;
917         }
918
919         mon->nest = nest;
920
921         LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Regained %p lock %p",
922                   GetCurrentThreadId (), obj, mon));
923
924         if (ret == WAIT_TIMEOUT) {
925                 /* Poll the event again, just in case it was signalled
926                  * while we were trying to regain the monitor lock
927                  */
928                 ret = WaitForSingleObjectEx (event, 0, FALSE);
929         }
930
931         /* Pulse will have popped our event from the queue if it signalled
932          * us, so we only do it here if the wait timed out.
933          *
934          * This avoids a race condition where the thread holding the
935          * lock can Pulse several times before the WaitForSingleObject
936          * returns.  If we popped the queue here then this event might
937          * be signalled more than once, thereby starving another
938          * thread.
939          */
940         
941         if (ret == WAIT_OBJECT_0) {
942                 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Success",
943                           GetCurrentThreadId ()));
944                 success = TRUE;
945         } else {
946                 LOCK_DEBUG (g_message (G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed, dequeuing handle %p",
947                           GetCurrentThreadId (), event));
948                 /* No pulse, so we have to remove ourself from the
949                  * wait queue
950                  */
951                 mon->wait_list = g_slist_remove (mon->wait_list, event);
952         }
953         CloseHandle (event);
954         
955         return success;
956 }
957