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