This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
syncblk.cpp
2999 lines (2554 loc) · 88.9 KB
/
syncblk.cpp
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// SYNCBLK.CPP
//
//
// Definition of a SyncBlock and the SyncBlockCache which manages it
//
#include "common.h"
#include "vars.hpp"
#include "util.hpp"
#include "class.h"
#include "object.h"
#include "threads.h"
#include "excep.h"
#include "threads.h"
#include "syncblk.h"
#include "interoputil.h"
#include "encee.h"
#include "eventtrace.h"
#include "dllimportcallback.h"
#include "comcallablewrapper.h"
#include "eeconfig.h"
#include "corhost.h"
#include "comdelegate.h"
#include "finalizerthread.h"
#ifdef FEATURE_COMINTEROP
#include "runtimecallablewrapper.h"
#endif // FEATURE_COMINTEROP
// Allocate 4K worth. Typically enough
#define MAXSYNCBLOCK (0x1000-sizeof(void*))/sizeof(SyncBlock)
#define SYNC_TABLE_INITIAL_SIZE 250
//#define DUMP_SB
class SyncBlockArray
{
public:
SyncBlockArray *m_Next;
BYTE m_Blocks[MAXSYNCBLOCK * sizeof (SyncBlock)];
};
// For in-place constructor
BYTE g_SyncBlockCacheInstance[sizeof(SyncBlockCache)];
SPTR_IMPL (SyncBlockCache, SyncBlockCache, s_pSyncBlockCache);
#ifndef DACCESS_COMPILE
#ifndef FEATURE_PAL
// static
SLIST_HEADER InteropSyncBlockInfo::s_InteropInfoStandbyList;
#endif // !FEATURE_PAL
InteropSyncBlockInfo::~InteropSyncBlockInfo()
{
CONTRACTL
{
NOTHROW;
DESTRUCTOR_CHECK;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
FreeUMEntryThunkOrInterceptStub();
}
#ifndef FEATURE_PAL
// Deletes all items in code:s_InteropInfoStandbyList.
void InteropSyncBlockInfo::FlushStandbyList()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
PSLIST_ENTRY pEntry = InterlockedFlushSList(&InteropSyncBlockInfo::s_InteropInfoStandbyList);
while (pEntry)
{
PSLIST_ENTRY pNextEntry = pEntry->Next;
// make sure to use the global delete since the destructor has already run
::delete (void *)pEntry;
pEntry = pNextEntry;
}
}
#endif // !FEATURE_PAL
void InteropSyncBlockInfo::FreeUMEntryThunkOrInterceptStub()
{
CONTRACTL
{
NOTHROW;
DESTRUCTOR_CHECK;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END
if (!g_fEEShutDown)
{
void *pUMEntryThunk = GetUMEntryThunk();
if (pUMEntryThunk != NULL)
{
COMDelegate::RemoveEntryFromFPtrHash((UPTR)pUMEntryThunk);
UMEntryThunk::FreeUMEntryThunk((UMEntryThunk *)pUMEntryThunk);
}
else
{
#if defined(_TARGET_X86_)
Stub *pInterceptStub = GetInterceptStub();
if (pInterceptStub != NULL)
{
// There may be multiple chained stubs
pInterceptStub->DecRef();
}
#else // _TARGET_X86_
// Intercept stubs are currently not used on other platforms.
_ASSERTE(GetInterceptStub() == NULL);
#endif // _TARGET_X86_
}
}
m_pUMEntryThunkOrInterceptStub = NULL;
}
#ifdef FEATURE_COMINTEROP
// Returns either NULL or an RCW on which AcquireLock has been called.
RCW* InteropSyncBlockInfo::GetRCWAndIncrementUseCount()
{
LIMITED_METHOD_CONTRACT;
DWORD dwSwitchCount = 0;
while (true)
{
RCW *pRCW = VolatileLoad(&m_pRCW);
if ((size_t)pRCW <= 0x1)
{
// the RCW never existed or has been released
return NULL;
}
if (((size_t)pRCW & 0x1) == 0x0)
{
// it looks like we have a chance, try to acquire the lock
RCW *pLockedRCW = (RCW *)((size_t)pRCW | 0x1);
if (InterlockedCompareExchangeT(&m_pRCW, pLockedRCW, pRCW) == pRCW)
{
// we have the lock on the m_pRCW field, now we can safely "use" the RCW
pRCW->IncrementUseCount();
// release the m_pRCW lock
VolatileStore(&m_pRCW, pRCW);
// and return the RCW
return pRCW;
}
}
// somebody else holds the lock, retry
__SwitchToThread(0, ++dwSwitchCount);
}
}
// Sets the m_pRCW field in a thread-safe manner, pRCW can be NULL.
void InteropSyncBlockInfo::SetRawRCW(RCW* pRCW)
{
LIMITED_METHOD_CONTRACT;
if (pRCW != NULL)
{
// we never set two different RCWs on a single object
_ASSERTE(m_pRCW == NULL);
m_pRCW = pRCW;
}
else
{
DWORD dwSwitchCount = 0;
while (true)
{
RCW *pOldRCW = VolatileLoad(&m_pRCW);
if ((size_t)pOldRCW <= 0x1)
{
// the RCW never existed or has been released
VolatileStore(&m_pRCW, (RCW *)0x1);
return;
}
if (((size_t)pOldRCW & 0x1) == 0x0)
{
// it looks like we have a chance, set the RCW to 0x1
if (InterlockedCompareExchangeT(&m_pRCW, (RCW *)0x1, pOldRCW) == pOldRCW)
{
// we made it
return;
}
}
// somebody else holds the lock, retry
__SwitchToThread(0, ++dwSwitchCount);
}
}
}
#endif // FEATURE_COMINTEROP
#endif // !DACCESS_COMPILE
PTR_SyncTableEntry SyncTableEntry::GetSyncTableEntry()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
return (PTR_SyncTableEntry)g_pSyncTable;
}
#ifndef DACCESS_COMPILE
SyncTableEntry*& SyncTableEntry::GetSyncTableEntryByRef()
{
LIMITED_METHOD_CONTRACT;
return g_pSyncTable;
}
/* static */
SyncBlockCache*& SyncBlockCache::GetSyncBlockCache()
{
LIMITED_METHOD_CONTRACT;
return s_pSyncBlockCache;
}
//----------------------------------------------------------------------------
//
// ThreadQueue Implementation
//
//----------------------------------------------------------------------------
#endif //!DACCESS_COMPILE
// Given a link in the chain, get the Thread that it represents
/* static */
inline PTR_WaitEventLink ThreadQueue::WaitEventLinkForLink(PTR_SLink pLink)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
return (PTR_WaitEventLink) (((PTR_BYTE) pLink) - offsetof(WaitEventLink, m_LinkSB));
}
#ifndef DACCESS_COMPILE
// Unlink the head of the Q. We are always in the SyncBlock's critical
// section.
/* static */
inline WaitEventLink *ThreadQueue::DequeueThread(SyncBlock *psb)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
CAN_TAKE_LOCK;
}
CONTRACTL_END;
// Be careful, the debugger inspects the queue from out of process and just looks at the memory...
// it must be valid even if the lock is held. Be careful if you change the way the queue is updated.
SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache());
WaitEventLink *ret = NULL;
SLink *pLink = psb->m_Link.m_pNext;
if (pLink)
{
psb->m_Link.m_pNext = pLink->m_pNext;
#ifdef _DEBUG
pLink->m_pNext = (SLink *)POISONC;
#endif
ret = WaitEventLinkForLink(pLink);
_ASSERTE(ret->m_WaitSB == psb);
}
return ret;
}
// Enqueue is the slow one. We have to find the end of the Q since we don't
// want to burn storage for this in the SyncBlock.
/* static */
inline void ThreadQueue::EnqueueThread(WaitEventLink *pWaitEventLink, SyncBlock *psb)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
CAN_TAKE_LOCK;
}
CONTRACTL_END;
_ASSERTE (pWaitEventLink->m_LinkSB.m_pNext == NULL);
// Be careful, the debugger inspects the queue from out of process and just looks at the memory...
// it must be valid even if the lock is held. Be careful if you change the way the queue is updated.
SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache());
SLink *pPrior = &psb->m_Link;
while (pPrior->m_pNext)
{
// We shouldn't already be in the waiting list!
_ASSERTE(pPrior->m_pNext != &pWaitEventLink->m_LinkSB);
pPrior = pPrior->m_pNext;
}
pPrior->m_pNext = &pWaitEventLink->m_LinkSB;
}
// Wade through the SyncBlock's list of waiting threads and remove the
// specified thread.
/* static */
BOOL ThreadQueue::RemoveThread (Thread *pThread, SyncBlock *psb)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
BOOL res = FALSE;
// Be careful, the debugger inspects the queue from out of process and just looks at the memory...
// it must be valid even if the lock is held. Be careful if you change the way the queue is updated.
SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache());
SLink *pPrior = &psb->m_Link;
SLink *pLink;
WaitEventLink *pWaitEventLink;
while ((pLink = pPrior->m_pNext) != NULL)
{
pWaitEventLink = WaitEventLinkForLink(pLink);
if (pWaitEventLink->m_Thread == pThread)
{
pPrior->m_pNext = pLink->m_pNext;
#ifdef _DEBUG
pLink->m_pNext = (SLink *)POISONC;
#endif
_ASSERTE(pWaitEventLink->m_WaitSB == psb);
res = TRUE;
break;
}
pPrior = pLink;
}
return res;
}
#endif //!DACCESS_COMPILE
#ifdef DACCESS_COMPILE
// Enumerates the threads in the queue from front to back by calling
// pCallbackFunction on each one
/* static */
void ThreadQueue::EnumerateThreads(SyncBlock *psb, FP_TQ_THREAD_ENUMERATION_CALLBACK pCallbackFunction, void* pUserData)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
SUPPORTS_DAC;
PTR_SLink pLink = psb->m_Link.m_pNext;
PTR_WaitEventLink pWaitEventLink;
while (pLink != NULL)
{
pWaitEventLink = WaitEventLinkForLink(pLink);
pCallbackFunction(pWaitEventLink->m_Thread, pUserData);
pLink = pLink->m_pNext;
}
}
#endif //DACCESS_COMPILE
#ifndef DACCESS_COMPILE
// ***************************************************************************
//
// Ephemeral Bitmap Helper
//
// ***************************************************************************
#define card_size 32
#define card_word_width 32
size_t CardIndex (size_t card)
{
LIMITED_METHOD_CONTRACT;
return card_size * card;
}
size_t CardOf (size_t idx)
{
LIMITED_METHOD_CONTRACT;
return idx / card_size;
}
size_t CardWord (size_t card)
{
LIMITED_METHOD_CONTRACT;
return card / card_word_width;
}
inline
unsigned CardBit (size_t card)
{
LIMITED_METHOD_CONTRACT;
return (unsigned)(card % card_word_width);
}
inline
void SyncBlockCache::SetCard (size_t card)
{
WRAPPER_NO_CONTRACT;
m_EphemeralBitmap [CardWord (card)] =
(m_EphemeralBitmap [CardWord (card)] | (1 << CardBit (card)));
}
inline
void SyncBlockCache::ClearCard (size_t card)
{
WRAPPER_NO_CONTRACT;
m_EphemeralBitmap [CardWord (card)] =
(m_EphemeralBitmap [CardWord (card)] & ~(1 << CardBit (card)));
}
inline
BOOL SyncBlockCache::CardSetP (size_t card)
{
WRAPPER_NO_CONTRACT;
return ( m_EphemeralBitmap [ CardWord (card) ] & (1 << CardBit (card)));
}
inline
void SyncBlockCache::CardTableSetBit (size_t idx)
{
WRAPPER_NO_CONTRACT;
SetCard (CardOf (idx));
}
size_t BitMapSize (size_t cacheSize)
{
LIMITED_METHOD_CONTRACT;
return (cacheSize + card_size * card_word_width - 1)/ (card_size * card_word_width);
}
// ***************************************************************************
//
// SyncBlockCache class implementation
//
// ***************************************************************************
SyncBlockCache::SyncBlockCache()
: m_pCleanupBlockList(NULL),
m_FreeBlockList(NULL),
// NOTE: CRST_UNSAFE_ANYMODE prevents a GC mode switch when entering this crst.
// If you remove this flag, we will switch to preemptive mode when entering
// g_criticalSection, which means all functions that enter it will become
// GC_TRIGGERS. (This includes all uses of LockHolder around SyncBlockCache::GetSyncBlockCache().
// So be sure to update the contracts if you remove this flag.
m_CacheLock(CrstSyncBlockCache, (CrstFlags) (CRST_UNSAFE_ANYMODE | CRST_DEBUGGER_THREAD)),
m_FreeCount(0),
m_ActiveCount(0),
m_SyncBlocks(0),
m_FreeSyncBlock(0),
m_FreeSyncTableIndex(1),
m_FreeSyncTableList(0),
m_SyncTableSize(SYNC_TABLE_INITIAL_SIZE),
m_OldSyncTables(0),
m_bSyncBlockCleanupInProgress(FALSE),
m_EphemeralBitmap(0)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
}
// This method is NO longer called.
SyncBlockCache::~SyncBlockCache()
{
CONTRACTL
{
DESTRUCTOR_CHECK;
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// Clear the list the fast way.
m_FreeBlockList = NULL;
//<TODO>@todo we can clear this fast too I guess</TODO>
m_pCleanupBlockList = NULL;
// destruct all arrays
while (m_SyncBlocks)
{
SyncBlockArray *next = m_SyncBlocks->m_Next;
delete m_SyncBlocks;
m_SyncBlocks = next;
}
// Also, now is a good time to clean up all the old tables which we discarded
// when we overflowed them.
SyncTableEntry* arr;
while ((arr = m_OldSyncTables) != 0)
{
m_OldSyncTables = (SyncTableEntry*)arr[0].m_Object.Load();
delete arr;
}
}
// When the GC determines that an object is dead the low bit of the
// m_Object field of SyncTableEntry is set, however it is not
// cleaned up because we cant do the COM interop cleanup at GC time.
// It is put on a cleanup list and at a later time (typically during
// finalization, this list is cleaned up.
//
void SyncBlockCache::CleanupSyncBlocks()
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_MODE_COOPERATIVE;
_ASSERTE(GetThread() == FinalizerThread::GetFinalizerThread());
// Set the flag indicating sync block cleanup is in progress.
// IMPORTANT: This must be set before the sync block cleanup bit is reset on the thread.
m_bSyncBlockCleanupInProgress = TRUE;
struct Param
{
SyncBlockCache *pThis;
SyncBlock* psb;
#ifdef FEATURE_COMINTEROP
RCW* pRCW;
#endif
} param;
param.pThis = this;
param.psb = NULL;
#ifdef FEATURE_COMINTEROP
param.pRCW = NULL;
#endif
EE_TRY_FOR_FINALLY(Param *, pParam, ¶m)
{
// reset the flag
FinalizerThread::GetFinalizerThread()->ResetSyncBlockCleanup();
// walk the cleanup list and cleanup 'em up
while ((pParam->psb = pParam->pThis->GetNextCleanupSyncBlock()) != NULL)
{
#ifdef FEATURE_COMINTEROP
InteropSyncBlockInfo* pInteropInfo = pParam->psb->GetInteropInfoNoCreate();
if (pInteropInfo)
{
pParam->pRCW = pInteropInfo->GetRawRCW();
if (pParam->pRCW)
{
// We should have initialized the cleanup list with the
// first RCW cache we created
_ASSERTE(g_pRCWCleanupList != NULL);
g_pRCWCleanupList->AddWrapper(pParam->pRCW);
pParam->pRCW = NULL;
pInteropInfo->SetRawRCW(NULL);
}
}
#endif // FEATURE_COMINTEROP
// Delete the sync block.
pParam->pThis->DeleteSyncBlock(pParam->psb);
pParam->psb = NULL;
// pulse GC mode to allow GC to perform its work
if (FinalizerThread::GetFinalizerThread()->CatchAtSafePointOpportunistic())
{
FinalizerThread::GetFinalizerThread()->PulseGCMode();
}
}
#ifdef FEATURE_COMINTEROP
// Now clean up the rcw's sorted by context
if (g_pRCWCleanupList != NULL)
g_pRCWCleanupList->CleanupAllWrappers();
#endif // FEATURE_COMINTEROP
}
EE_FINALLY
{
// We are finished cleaning up the sync blocks.
m_bSyncBlockCleanupInProgress = FALSE;
#ifdef FEATURE_COMINTEROP
if (param.pRCW)
param.pRCW->Cleanup();
#endif
if (param.psb)
DeleteSyncBlock(param.psb);
} EE_END_FINALLY;
}
// create the sync block cache
/* static */
void SyncBlockCache::Attach()
{
LIMITED_METHOD_CONTRACT;
}
// create the sync block cache
/* static */
void SyncBlockCache::Start()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
DWORD* bm = new DWORD [BitMapSize(SYNC_TABLE_INITIAL_SIZE+1)];
memset (bm, 0, BitMapSize (SYNC_TABLE_INITIAL_SIZE+1)*sizeof(DWORD));
SyncTableEntry::GetSyncTableEntryByRef() = new SyncTableEntry[SYNC_TABLE_INITIAL_SIZE+1];
#ifdef _DEBUG
for (int i=0; i<SYNC_TABLE_INITIAL_SIZE+1; i++) {
SyncTableEntry::GetSyncTableEntry()[i].m_SyncBlock = NULL;
}
#endif
SyncTableEntry::GetSyncTableEntry()[0].m_SyncBlock = 0;
SyncBlockCache::GetSyncBlockCache() = new (&g_SyncBlockCacheInstance) SyncBlockCache;
SyncBlockCache::GetSyncBlockCache()->m_EphemeralBitmap = bm;
#ifndef FEATURE_PAL
InitializeSListHead(&InteropSyncBlockInfo::s_InteropInfoStandbyList);
#endif // !FEATURE_PAL
}
// destroy the sync block cache
/* static */
void SyncBlockCache::Stop()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// cache must be destroyed first, since it can traverse the table to find all the
// sync blocks which are live and thus must have their critical sections destroyed.
if (SyncBlockCache::GetSyncBlockCache())
{
delete SyncBlockCache::GetSyncBlockCache();
SyncBlockCache::GetSyncBlockCache() = 0;
}
if (SyncTableEntry::GetSyncTableEntry())
{
delete SyncTableEntry::GetSyncTableEntry();
SyncTableEntry::GetSyncTableEntryByRef() = 0;
}
}
void SyncBlockCache::InsertCleanupSyncBlock(SyncBlock* psb)
{
CONTRACTL
{
INSTANCE_CHECK;
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// free up the threads that are waiting before we use the link
// for other purposes
if (psb->m_Link.m_pNext != NULL)
{
while (ThreadQueue::DequeueThread(psb) != NULL)
continue;
}
#ifdef FEATURE_COMINTEROP
if (psb->m_pInteropInfo)
{
// called during GC
// so do only minorcleanup
MinorCleanupSyncBlockComData(psb->m_pInteropInfo);
}
#endif // FEATURE_COMINTEROP
// This method will be called only by the GC thread
//<TODO>@todo add an assert for the above statement</TODO>
// we don't need to lock here
//EnterCacheLock();
psb->m_Link.m_pNext = m_pCleanupBlockList;
m_pCleanupBlockList = &psb->m_Link;
// we don't need a lock here
//LeaveCacheLock();
}
SyncBlock* SyncBlockCache::GetNextCleanupSyncBlock()
{
LIMITED_METHOD_CONTRACT;
// we don't need a lock here,
// as this is called only on the finalizer thread currently
SyncBlock *psb = NULL;
if (m_pCleanupBlockList)
{
// get the actual sync block pointer
psb = (SyncBlock *) (((BYTE *) m_pCleanupBlockList) - offsetof(SyncBlock, m_Link));
m_pCleanupBlockList = m_pCleanupBlockList->m_pNext;
}
return psb;
}
// returns and removes the next free syncblock from the list
// the cache lock must be entered to call this
SyncBlock *SyncBlockCache::GetNextFreeSyncBlock()
{
CONTRACTL
{
INJECT_FAULT(COMPlusThrowOM());
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
#ifdef _DEBUG // Instrumentation for OOM fault injection testing
delete new char;
#endif
SyncBlock *psb;
SLink *plst = m_FreeBlockList;
m_ActiveCount++;
if (plst)
{
m_FreeBlockList = m_FreeBlockList->m_pNext;
// shouldn't be 0
m_FreeCount--;
// get the actual sync block pointer
psb = (SyncBlock *) (((BYTE *) plst) - offsetof(SyncBlock, m_Link));
return psb;
}
else
{
if ((m_SyncBlocks == NULL) || (m_FreeSyncBlock >= MAXSYNCBLOCK))
{
#ifdef DUMP_SB
// LogSpewAlways("Allocating new syncblock array\n");
// DumpSyncBlockCache();
#endif
SyncBlockArray* newsyncblocks = new(SyncBlockArray);
if (!newsyncblocks)
COMPlusThrowOM ();
newsyncblocks->m_Next = m_SyncBlocks;
m_SyncBlocks = newsyncblocks;
m_FreeSyncBlock = 0;
}
return &(((SyncBlock*)m_SyncBlocks->m_Blocks)[m_FreeSyncBlock++]);
}
}
void SyncBlockCache::Grow()
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
STRESS_LOG0(LF_SYNC, LL_INFO10000, "SyncBlockCache::NewSyncBlockSlot growing SyncBlockCache \n");
NewArrayHolder<SyncTableEntry> newSyncTable (NULL);
NewArrayHolder<DWORD> newBitMap (NULL);
DWORD * oldBitMap;
// Compute the size of the new synctable. Normally, we double it - unless
// doing so would create slots with indices too high to fit within the
// mask. If so, we create a synctable up to the mask limit. If we're
// already at the mask limit, then caller is out of luck.
DWORD newSyncTableSize;
if (m_SyncTableSize <= (MASK_SYNCBLOCKINDEX >> 1))
{
newSyncTableSize = m_SyncTableSize * 2;
}
else
{
newSyncTableSize = MASK_SYNCBLOCKINDEX;
}
if (!(newSyncTableSize > m_SyncTableSize)) // Make sure we actually found room to grow!
{
COMPlusThrowOM();
}
newSyncTable = new SyncTableEntry[newSyncTableSize];
newBitMap = new DWORD[BitMapSize (newSyncTableSize)];
{
//! From here on, we assume that we will succeed and start doing global side-effects.
//! Any operation that could fail must occur before this point.
CANNOTTHROWCOMPLUSEXCEPTION();
FAULT_FORBID();
newSyncTable.SuppressRelease();
newBitMap.SuppressRelease();
// We chain old table because we can't delete
// them before all the threads are stoppped
// (next GC)
SyncTableEntry::GetSyncTableEntry() [0].m_Object = (Object *)m_OldSyncTables;
m_OldSyncTables = SyncTableEntry::GetSyncTableEntry();
memset (newSyncTable, 0, newSyncTableSize*sizeof (SyncTableEntry));
memset (newBitMap, 0, BitMapSize (newSyncTableSize)*sizeof (DWORD));
CopyMemory (newSyncTable, SyncTableEntry::GetSyncTableEntry(),
m_SyncTableSize*sizeof (SyncTableEntry));
CopyMemory (newBitMap, m_EphemeralBitmap,
BitMapSize (m_SyncTableSize)*sizeof (DWORD));
oldBitMap = m_EphemeralBitmap;
m_EphemeralBitmap = newBitMap;
delete[] oldBitMap;
_ASSERTE((m_SyncTableSize & MASK_SYNCBLOCKINDEX) == m_SyncTableSize);
// note: we do not care if another thread does not see the new size
// however we really do not want it to see the new size without seeing the new array
//@TODO do we still leak here if two threads come here at the same time ?
FastInterlockExchangePointer(&SyncTableEntry::GetSyncTableEntryByRef(), newSyncTable.GetValue());
m_FreeSyncTableIndex++;
m_SyncTableSize = newSyncTableSize;
#ifdef _DEBUG
static int dumpSBOnResize = -1;
if (dumpSBOnResize == -1)
dumpSBOnResize = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_SBDumpOnResize);
if (dumpSBOnResize)
{
LogSpewAlways("SyncBlockCache resized\n");
DumpSyncBlockCache();
}
#endif
}
}
DWORD SyncBlockCache::NewSyncBlockSlot(Object *obj)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
_ASSERTE(m_CacheLock.OwnedByCurrentThread()); // GetSyncBlock takes the lock, make sure no one else does.
DWORD indexNewEntry;
if (m_FreeSyncTableList)
{
indexNewEntry = (DWORD)(m_FreeSyncTableList >> 1);
_ASSERTE ((size_t)SyncTableEntry::GetSyncTableEntry()[indexNewEntry].m_Object.Load() & 1);
m_FreeSyncTableList = (size_t)SyncTableEntry::GetSyncTableEntry()[indexNewEntry].m_Object.Load() & ~1;
}
else if ((indexNewEntry = (DWORD)(m_FreeSyncTableIndex)) >= m_SyncTableSize)
{
// This is kept out of line to keep stuff like the C++ EH prolog (needed for holders) off
// of the common path.
Grow();
}
else
{
#ifdef _DEBUG
static int dumpSBOnNewIndex = -1;
if (dumpSBOnNewIndex == -1)
dumpSBOnNewIndex = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_SBDumpOnNewIndex);
if (dumpSBOnNewIndex)
{
LogSpewAlways("SyncBlockCache index incremented\n");
DumpSyncBlockCache();
}
#endif
m_FreeSyncTableIndex ++;
}
CardTableSetBit (indexNewEntry);
// In debug builds the m_SyncBlock at indexNewEntry should already be null, since we should
// start out with a null table and always null it out on delete.
_ASSERTE(SyncTableEntry::GetSyncTableEntry() [indexNewEntry].m_SyncBlock == NULL);
SyncTableEntry::GetSyncTableEntry() [indexNewEntry].m_SyncBlock = NULL;
SyncTableEntry::GetSyncTableEntry() [indexNewEntry].m_Object = obj;
_ASSERTE(indexNewEntry != 0);
return indexNewEntry;
}
// free a used sync block, only called from CleanupSyncBlocks.
void SyncBlockCache::DeleteSyncBlock(SyncBlock *psb)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
// clean up comdata
if (psb->m_pInteropInfo)
{
#ifdef FEATURE_COMINTEROP
CleanupSyncBlockComData(psb->m_pInteropInfo);
#endif // FEATURE_COMINTEROP
#ifndef FEATURE_PAL
if (g_fEEShutDown)
{
delete psb->m_pInteropInfo;
}