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