Wed Jun 9 18:23:59 CEST 2004 Paolo Molaro <lupus@ximian.com>
[mono.git] / mono / metadata / monitor.c
1 /*
2  * monitor.c:  Monitor locking functions
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *
7  * (C) 2003 Ximian, Inc.
8  */
9
10 #include <config.h>
11 #include <glib.h>
12
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
19 #include <mono/os/gc_wrapper.h>
20
21 #undef THREAD_LOCK_DEBUG
22
23 /*
24  * The monitor implementation here is based on
25  * http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf and
26  * http://www.research.ibm.com/people/d/dfb/papers/Bacon98Thin.ps
27  *
28  * The Dice paper describes a technique for saving lock record space
29  * by returning records to a free list when they become unused.  That
30  * sounds like unnecessary complexity to me, though if it becomes
31  * clear that unused lock records are taking up lots of space or we
32  * need to shave more time off by avoiding a malloc then we can always
33  * implement the free list idea later.  The timeout parameter to
34  * try_enter voids some of the assumptions about the reference count
35  * field in Dice's implementation too.  In his version, the thread
36  * attempting to lock a contended object will block until it succeeds,
37  * so the reference count will never be decremented while an object is
38  * locked.
39  *
40  * Bacon's thin locks have a fast path that doesn't need a lock record
41  * for the common case of locking an unlocked or shallow-nested
42  * object, but the technique relies on encoding the thread ID in 15
43  * bits (to avoid too much per-object space overhead.)  Unfortunately
44  * I don't think it's possible to reliably encode a pthread_t into 15
45  * bits. (The JVM implementation used seems to have a 15-bit
46  * per-thread identifier available.)
47  *
48  * This implementation then combines Dice's basic lock model with
49  * Bacon's simplification of keeping a lock record for the lifetime of
50  * an object.
51  */
52
53
54 static void mon_finalize (void *o, void *unused)
55 {
56         MonoThreadsSync *mon=(MonoThreadsSync *)o;
57         
58 #ifdef THREAD_LOCK_DEBUG
59         g_message (G_GNUC_PRETTY_FUNCTION ": Finalizing sync %p", mon);
60 #endif
61
62         if(mon->entry_sem!=NULL) {
63                 CloseHandle (mon->entry_sem);
64         }
65         /* If this isn't empty then something is seriously broken - it
66          * means a thread is still waiting on the object that owned
67          * this lock, but the object has been finalized.
68          */
69         g_assert (mon->wait_list==NULL);
70 }
71
72 static MonoThreadsSync *mon_new(guint32 id)
73 {
74         MonoThreadsSync *new;
75         
76 #if HAVE_BOEHM_GC
77         new=(MonoThreadsSync *)GC_MALLOC (sizeof(MonoThreadsSync));
78         GC_REGISTER_FINALIZER (new, mon_finalize, NULL, NULL, NULL);
79 #else
80         /* This should be freed when the object that owns it is
81          * deleted
82          */
83         new=(MonoThreadsSync *)g_new0 (MonoThreadsSync, 1);
84 #endif
85         new->owner=id;
86         new->nest=1;
87         
88         return(new);
89 }
90
91 gboolean mono_monitor_try_enter (MonoObject *obj, guint32 ms)
92 {
93         MonoThreadsSync *mon;
94         guint32 id=GetCurrentThreadId ();
95         HANDLE sem;
96         guint32 then=0, now, delta;
97         guint32 waitms;
98         guint32 ret;
99         
100 #ifdef THREAD_LOCK_DEBUG
101         g_message(G_GNUC_PRETTY_FUNCTION
102                   ": (%d) Trying to lock object %p (%d ms)", id, obj, ms);
103 #endif
104
105 retry:
106         mon=obj->synchronisation;
107
108         /* If the object has never been locked... */
109         if(mon==NULL) {
110                 mon=mon_new(id);
111                 if(InterlockedCompareExchangePointer ((gpointer*)&obj->synchronisation, mon, NULL)==NULL) {
112                         /* Successfully locked */
113                         return(TRUE);
114                 } else {
115                         /* Another thread got in first, so try again.
116                          * GC will take care of the monitor record
117                          */
118 #ifndef HAVE_BOEHM_GC
119                         mon_finalize (mon, NULL);
120 #endif
121                         goto retry;
122                 }
123         }
124
125         /* If the object is currently locked by this thread... */
126         if(mon->owner==id) {
127                 mon->nest++;
128                 return(TRUE);
129         }
130
131         /* If the object has previously been locked but isn't now... */
132
133         /* This case differs from Dice's case 3 because we don't
134          * deflate locks or cache unused lock records
135          */
136         if(mon->owner==0) {
137                 /* Try to install our ID in the owner field, nest
138                  * should have been left at 1 by the previous unlock
139                  * operation
140                  */
141                 if(InterlockedCompareExchange (&mon->owner, id, 0)==0) {
142                         /* Success */
143                         g_assert (mon->nest==1);
144                         return(TRUE);
145                 } else {
146                         /* Trumped again! */
147                         goto retry;
148                 }
149         }
150
151         /* The object must be locked by someone else... */
152
153         /* If ms is 0 we don't block, but just fail straight away */
154         if(ms==0) {
155 #ifdef THREAD_LOCK_DEBUG
156                 g_message (G_GNUC_PRETTY_FUNCTION
157                            ": (%d) timed out, returning FALSE", id);
158 #endif
159
160                 return(FALSE);
161         }
162
163         /* The slow path begins here.  We need to make sure theres a
164          * semaphore handle (creating it if necessary), and block on
165          * it
166          */
167         if(mon->entry_sem==NULL) {
168                 /* Create the semaphore */
169                 sem=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
170                 if(InterlockedCompareExchangePointer ((gpointer*)&mon->entry_sem, sem, NULL)!=NULL) {
171                         /* Someone else just put a handle here */
172                         CloseHandle (sem);
173                 }
174         }
175
176         /* If we need to time out, record a timestamp and adjust ms,
177          * because WaitForSingleObject doesn't tell us how long it
178          * waited for.
179          *
180          * Don't block forever here, because theres a chance the owner
181          * thread released the lock while we were creating the
182          * semaphore: we would not get the wakeup.  Using the event
183          * handle technique from pulse/wait would involve locking the
184          * lock struct and therefore slowing down the fast path.
185          */
186         if(ms!=INFINITE) {
187                 then=GetTickCount ();
188                 if(ms<100) {
189                         waitms=ms;
190                 } else {
191                         waitms=100;
192                 }
193         } else {
194                 waitms=100;
195         }
196         
197         InterlockedIncrement (&mon->entry_count);
198         ret=WaitForSingleObjectEx (mon->entry_sem, waitms, TRUE);
199         InterlockedDecrement (&mon->entry_count);
200
201         if(ms!=INFINITE) {
202                 now=GetTickCount ();
203                 
204                 if(now<then) {
205                         /* The counter must have wrapped around */
206 #ifdef THREAD_LOCK_DEBUG
207                         g_message (G_GNUC_PRETTY_FUNCTION
208                                    ": wrapped around! now=0x%x then=0x%x",
209                                    now, then);
210 #endif
211                         
212                         now+=(0xffffffff - then);
213                         then=0;
214
215 #ifdef THREAD_LOCK_DEBUG
216                         g_message (G_GNUC_PRETTY_FUNCTION ": wrap rejig: now=0x%x then=0x%x delta=0x%x", now, then, now-then);
217 #endif
218                 }
219                 
220                 delta=now-then;
221                 if(delta >= ms) {
222                         ms=0;
223                 } else {
224                         ms-=delta;
225                 }
226
227                 if(ret==WAIT_TIMEOUT && ms>0) {
228                         /* More time left */
229                         goto retry;
230                 }
231         } else {
232                 if(ret==WAIT_TIMEOUT) {
233                         /* Infinite wait, so just try again */
234                         goto retry;
235                 }
236         }
237         
238         if(ret==WAIT_OBJECT_0) {
239                 /* retry from the top */
240                 goto retry;
241         }
242         
243         /* We must have timed out */
244 #ifdef THREAD_LOCK_DEBUG
245         g_message (G_GNUC_PRETTY_FUNCTION
246                    ": (%d) timed out waiting, returning FALSE", id);
247 #endif
248
249         return(FALSE);
250 }
251
252 void mono_monitor_exit (MonoObject *obj)
253 {
254         MonoThreadsSync *mon;
255         guint32 nest;
256         
257 #ifdef THREAD_LOCK_DEBUG
258         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Unlocking %p",
259                   GetCurrentThreadId (), obj);
260 #endif
261
262         mon=obj->synchronisation;
263
264         if(mon==NULL) {
265                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
266                 return;
267         }
268         if(mon->owner!=GetCurrentThreadId ()) {
269                 return;
270         }
271         
272         nest=mon->nest-1;
273         if(nest==0) {
274 #ifdef THREAD_LOCK_DEBUG
275                 g_message(G_GNUC_PRETTY_FUNCTION
276                           ": (%d) Object %p is now unlocked",
277                           GetCurrentThreadId (), obj);
278 #endif
279         
280                 /* object is now unlocked, leave nest==1 so we don't
281                  * need to set it when the lock is reacquired
282                  */
283                 mon->owner=0;
284
285                 /* Do the wakeup stuff.  It's possible that the last
286                  * blocking thread gave up waiting just before we
287                  * release the semaphore resulting in a futile wakeup
288                  * next time there's contention for this object, but
289                  * it means we don't have to waste time locking the
290                  * struct.
291                  */
292                 if(mon->entry_count>0) {
293                         ReleaseSemaphore (mon->entry_sem, 1, NULL);
294                 }
295         } else {
296 #ifdef THREAD_LOCK_DEBUG
297                 g_message(G_GNUC_PRETTY_FUNCTION
298                           ": (%d) Object %p is now locked %d times",
299                           GetCurrentThreadId (), obj,
300                           nest);
301 #endif
302                 mon->nest=nest;
303         }
304 }
305
306 gboolean ves_icall_System_Threading_Monitor_Monitor_try_enter(MonoObject *obj,
307                                                               guint32 ms)
308 {
309         MONO_ARCH_SAVE_REGS;
310
311         return(mono_monitor_try_enter (obj, ms));
312 }
313
314 void ves_icall_System_Threading_Monitor_Monitor_exit(MonoObject *obj)
315 {
316         MONO_ARCH_SAVE_REGS;
317
318         mono_monitor_exit (obj);
319 }
320
321 gboolean ves_icall_System_Threading_Monitor_Monitor_test_owner(MonoObject *obj)
322 {
323         MonoThreadsSync *mon;
324         
325         MONO_ARCH_SAVE_REGS;
326
327 #ifdef THREAD_LOCK_DEBUG
328         g_message(G_GNUC_PRETTY_FUNCTION
329                   ": Testing if %p is owned by thread %d", obj,
330                   GetCurrentThreadId());
331 #endif
332         
333         mon=obj->synchronisation;
334         if(mon==NULL) {
335                 return(FALSE);
336         }
337         
338         if(mon->owner==GetCurrentThreadId ()) {
339                 return(TRUE);
340         }
341         
342         return(FALSE);
343 }
344
345 gboolean ves_icall_System_Threading_Monitor_Monitor_test_synchronised(MonoObject *obj)
346 {
347         MonoThreadsSync *mon;
348         
349         MONO_ARCH_SAVE_REGS;
350
351 #ifdef THREAD_LOCK_DEBUG
352         g_message(G_GNUC_PRETTY_FUNCTION
353                   ": (%d) Testing if %p is owned by any thread",
354                   GetCurrentThreadId (), obj);
355 #endif
356         
357         mon=obj->synchronisation;
358         if(mon==NULL) {
359                 return(FALSE);
360         }
361         
362         if(mon->owner!=0) {
363                 return(TRUE);
364         }
365         
366         return(FALSE);
367 }
368
369 /* All wait list manipulation in the pulse, pulseall and wait
370  * functions happens while the monitor lock is held, so we don't need
371  * any extra struct locking
372  */
373
374 void ves_icall_System_Threading_Monitor_Monitor_pulse(MonoObject *obj)
375 {
376         MonoThreadsSync *mon;
377         
378         MONO_ARCH_SAVE_REGS;
379
380 #ifdef THREAD_LOCK_DEBUG
381         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Pulsing %p",
382                   GetCurrentThreadId (), obj);
383 #endif
384         
385         mon=obj->synchronisation;
386         if(mon==NULL) {
387                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
388                 return;
389         }
390         if(mon->owner!=GetCurrentThreadId ()) {
391                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
392                 return;
393         }
394
395 #ifdef THREAD_LOCK_DEBUG
396         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) %d threads waiting",
397                   GetCurrentThreadId (), g_slist_length (mon->wait_list));
398 #endif
399         
400         if(mon->wait_list!=NULL) {
401 #ifdef THREAD_LOCK_DEBUG
402                 g_message(G_GNUC_PRETTY_FUNCTION
403                           ": (%d) signalling and dequeuing handle %p",
404                           GetCurrentThreadId (), mon->wait_list->data);
405 #endif
406         
407                 SetEvent (mon->wait_list->data);
408                 mon->wait_list=g_slist_remove (mon->wait_list,
409                                                mon->wait_list->data);
410         }
411 }
412
413 void ves_icall_System_Threading_Monitor_Monitor_pulse_all(MonoObject *obj)
414 {
415         MonoThreadsSync *mon;
416         
417         MONO_ARCH_SAVE_REGS;
418
419 #ifdef THREAD_LOCK_DEBUG
420         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Pulsing all %p",
421                   GetCurrentThreadId (), obj);
422 #endif
423         
424         mon=obj->synchronisation;
425         if(mon==NULL) {
426                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
427                 return;
428         }
429         if(mon->owner!=GetCurrentThreadId ()) {
430                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
431                 return;
432         }
433
434 #ifdef THREAD_LOCK_DEBUG
435         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) %d threads waiting",
436                   GetCurrentThreadId (), g_slist_length (mon->wait_list));
437 #endif
438         
439         while(mon->wait_list!=NULL) {
440 #ifdef THREAD_LOCK_DEBUG
441                 g_message(G_GNUC_PRETTY_FUNCTION
442                           ": (%d) signalling and dequeuing handle %p",
443                           GetCurrentThreadId (), mon->wait_list->data);
444 #endif
445         
446                 SetEvent (mon->wait_list->data);
447                 mon->wait_list=g_slist_remove (mon->wait_list,
448                                                mon->wait_list->data);
449         }
450 }
451
452 gboolean ves_icall_System_Threading_Monitor_Monitor_wait(MonoObject *obj,
453                                                          guint32 ms)
454 {
455         MonoThreadsSync *mon;
456         HANDLE event;
457         guint32 nest;
458         guint32 ret;
459         gboolean success=FALSE, regain;
460         
461         MONO_ARCH_SAVE_REGS;
462
463 #ifdef THREAD_LOCK_DEBUG
464         g_message(G_GNUC_PRETTY_FUNCTION
465                   ": (%d) Trying to wait for %p with timeout %dms",
466                   GetCurrentThreadId (), obj, ms);
467 #endif
468         
469         mon=obj->synchronisation;
470         if(mon==NULL) {
471                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked"));
472                 return(FALSE);
473         }
474         if(mon->owner!=GetCurrentThreadId ()) {
475                 mono_raise_exception (mono_get_exception_synchronization_lock ("Not locked by this thread"));
476                 return(FALSE);
477         }
478         
479         event=CreateEvent (NULL, FALSE, FALSE, NULL);
480         if(event==NULL) {
481                 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to set up wait event"));
482                 return(FALSE);
483         }
484         
485 #ifdef THREAD_LOCK_DEBUG
486         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) queuing handle %p",
487                   GetCurrentThreadId (), event);
488 #endif
489
490         mon->wait_list=g_slist_append (mon->wait_list, event);
491         
492         /* Save the nest count, and release the lock */
493         nest=mon->nest;
494         mon->nest=1;
495         mono_monitor_exit (obj);
496
497 #ifdef THREAD_LOCK_DEBUG
498         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Unlocked %p lock %p",
499                   GetCurrentThreadId (), obj, mon);
500 #endif
501
502         /* There's no race between unlocking mon and waiting for the
503          * event, because auto reset events are sticky, and this event
504          * is private to this thread.  Therefore even if the event was
505          * signalled before we wait, we still succeed.
506          */
507         ret=WaitForSingleObjectEx (event, ms, TRUE);
508         
509         if (mono_thread_interruption_requested ()) {
510                 CloseHandle (event);
511                 return(FALSE);
512         }
513
514         /* Regain the lock with the previous nest count */
515         regain=mono_monitor_try_enter (obj, INFINITE);
516         
517         if(regain==FALSE) {
518                 /* Something went wrong, so throw a
519                  * SynchronizationLockException
520                  */
521                 CloseHandle (event);
522                 mono_raise_exception (mono_get_exception_synchronization_lock ("Failed to regain lock"));
523                 return(FALSE);
524         }
525
526         mon->nest=nest;
527
528 #ifdef THREAD_LOCK_DEBUG
529         g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Regained %p lock %p",
530                   GetCurrentThreadId (), obj, mon);
531 #endif
532
533         if(ret==WAIT_TIMEOUT) {
534                 /* Poll the event again, just in case it was signalled
535                  * while we were trying to regain the monitor lock
536                  */
537                 ret=WaitForSingleObjectEx (event, 0, FALSE);
538         }
539
540         /* Pulse will have popped our event from the queue if it signalled
541          * us, so we only do it here if the wait timed out.
542          *
543          * This avoids a race condition where the thread holding the
544          * lock can Pulse several times before the WaitForSingleObject
545          * returns.  If we popped the queue here then this event might
546          * be signalled more than once, thereby starving another
547          * thread.
548          */
549         
550         if(ret==WAIT_OBJECT_0) {
551 #ifdef THREAD_LOCK_DEBUG
552                 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Success",
553                           GetCurrentThreadId ());
554 #endif
555                 success=TRUE;
556         } else {
557 #ifdef THREAD_LOCK_DEBUG
558                 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
559                           GetCurrentThreadId ());
560                 g_message(G_GNUC_PRETTY_FUNCTION ": (%d) dequeuing handle %p",
561                           GetCurrentThreadId (), event);
562 #endif
563                 /* No pulse, so we have to remove ourself from the
564                  * wait queue
565                  */
566                 mon->wait_list=g_slist_remove (mon->wait_list, event);
567         }
568         CloseHandle (event);
569         
570         return(success);
571 }
572