summaryrefslogtreecommitdiff
path: root/src/vm/syncblk.h
blob: 1ae14489c311af7241931056a6f92c7407663676 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
// 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.H
//

//
// Definition of a SyncBlock and the SyncBlockCache which manages it

// See file:#SyncBlockOverview Sync block overview

#ifndef _SYNCBLK_H_
#define _SYNCBLK_H_

#include "util.hpp"
#include "slist.h"
#include "crst.h"
#include "vars.hpp"

// #SyncBlockOverview
// 
// Every Object is preceded by an ObjHeader (at a negative offset). The code:ObjHeader has an index to a
// code:SyncBlock. This index is 0 for the bulk of all instances, which indicates that the object shares a
// dummy SyncBlock with most other objects.
//
// The SyncBlock is primarily responsible for object synchronization. However, it is also a "kitchen sink" of
// sparsely allocated instance data. For instance, the default implementation of Hash() is based on the
// existence of a code:SyncTableEntry. And objects exposed to or from COM, or through context boundaries, can
// store sparse data here.
//
// SyncTableEntries and SyncBlocks are allocated in non-GC memory. A weak pointer from the SyncTableEntry to
// the instance is used to ensure that the SyncBlock and SyncTableEntry are reclaimed (recycled) when the
// instance dies.
//
// The organization of the SyncBlocks isn't intuitive (at least to me). Here's the explanation:
//
// Before each Object is an code:ObjHeader. If the object has a code:SyncBlock, the code:ObjHeader contains a
// non-0 index to it.
//
// The index is looked up in the code:g_pSyncTable of SyncTableEntries. This means the table is consecutive
// for all outstanding indices. Whenever it needs to grow, it doubles in size and copies all the original
// entries. The old table is kept until GC time, when it can be safely discarded.
//
// Each code:SyncTableEntry has a backpointer to the object and a forward pointer to the actual SyncBlock.
// The SyncBlock is allocated out of a SyncBlockArray which is essentially just a block of SyncBlocks.
//
// The code:SyncBlockArray s are managed by a code:SyncBlockCache that handles the actual allocations and
// frees of the blocks.
//
// So...
//
// Each allocation and release has to handle free lists in the table of entries and the table of blocks.
//
// We burn an extra 4 bytes for the pointer from the SyncTableEntry to the SyncBlock.
//
// The reason for this is that many objects have a SyncTableEntry but no SyncBlock. That's because someone
// (e.g. HashTable) called Hash() on them.
//
// Incidentally, there's a better write-up of all this stuff in the archives.

#ifdef _TARGET_X86_
#include <pshpack4.h>
#endif // _TARGET_X86_

// forwards:
class SyncBlock;
class SyncBlockCache;
class SyncTableEntry;
class SyncBlockArray;
class AwareLock;
class Thread;
class AppDomain;

#ifdef EnC_SUPPORTED
class EnCSyncBlockInfo;
typedef DPTR(EnCSyncBlockInfo) PTR_EnCSyncBlockInfo;

#endif // EnC_SUPPORTED

#include "eventstore.hpp"

#include "eventstore.hpp"

#include "synch.h"

// At a negative offset from each Object is an ObjHeader.  The 'size' of the
// object includes these bytes.  However, we rely on the previous object allocation
// to zero out the ObjHeader for the current allocation.  And the limits of the
// GC space are initialized to respect this "off by one" error.

// m_SyncBlockValue is carved up into an index and a set of bits.  Steal bits by
// reducing the mask.  We use the very high bit, in _DEBUG, to be sure we never forget
// to mask the Value to obtain the Index

    // These first three are only used on strings (If the first one is on, we know whether 
    // the string has high byte characters, and the second bit tells which way it is. 
    // Note that we are reusing the FINALIZER_RUN bit since strings don't have finalizers,
    // so the value of this bit does not matter for strings
#define BIT_SBLK_STRING_HAS_NO_HIGH_CHARS   0x80000000

#define BIT_SBLK_STRING_HIGH_CHARS_KNOWN    0x40000000
#define BIT_SBLK_STRING_HAS_SPECIAL_SORT    0xC0000000
#define BIT_SBLK_STRING_HIGH_CHAR_MASK      0xC0000000

#define BIT_SBLK_FINALIZER_RUN              0x40000000
#define BIT_SBLK_GC_RESERVE                 0x20000000

// This lock is only taken when we need to modify the index value in m_SyncBlockValue. 
// It should not be taken if the object already has a real syncblock index. 
#define BIT_SBLK_SPIN_LOCK                  0x10000000

#define BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX    0x08000000

// if BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX is clear, the rest of the header dword is layed out as follows:
// - lower ten bits (bits 0 thru 9) is thread id used for the thin locks
//   value is zero if no thread is holding the lock
// - following six bits (bits 10 thru 15) is recursion level used for the thin locks
//   value is zero if lock is not taken or only taken once by the same thread
#define SBLK_MASK_LOCK_THREADID             0x000003FF   // special value of 0 + 1023 thread ids
#define SBLK_MASK_LOCK_RECLEVEL             0x0000FC00   // 64 recursion levels
#define SBLK_LOCK_RECLEVEL_INC              0x00000400   // each level is this much higher than the previous one
#define SBLK_RECLEVEL_SHIFT                 10           // shift right this much to get recursion level

// add more bits here... (adjusting the following mask to make room)

// if BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX is set, 
// then if BIT_SBLK_IS_HASHCODE is also set, the rest of the dword is the hash code (bits 0 thru 25),
// otherwise the rest of the dword is the sync block index (bits 0 thru 25)
#define BIT_SBLK_IS_HASHCODE            0x04000000

#define HASHCODE_BITS                   26

#define MASK_HASHCODE                   ((1<<HASHCODE_BITS)-1)
#define SYNCBLOCKINDEX_BITS             26
#define MASK_SYNCBLOCKINDEX             ((1<<SYNCBLOCKINDEX_BITS)-1)

// Spin for about 1000 cycles before waiting longer.
#define     BIT_SBLK_SPIN_COUNT         1000

// The GC is highly dependent on SIZE_OF_OBJHEADER being exactly the sizeof(ObjHeader)
// We define this macro so that the preprocessor can calculate padding structures.
#ifdef _WIN64
#define SIZEOF_OBJHEADER    8
#else // !_WIN64
#define SIZEOF_OBJHEADER    4
#endif // !_WIN64
 

inline void InitializeSpinConstants()
{
    WRAPPER_NO_CONTRACT;

#if !defined(DACCESS_COMPILE)
    g_SpinConstants.dwInitialDuration = g_pConfig->SpinInitialDuration();
    g_SpinConstants.dwMaximumDuration = min(g_pConfig->SpinLimitProcCap(), g_SystemInfo.dwNumberOfProcessors) * g_pConfig->SpinLimitProcFactor() + g_pConfig->SpinLimitConstant();
    g_SpinConstants.dwBackoffFactor   = g_pConfig->SpinBackoffFactor();
    g_SpinConstants.dwRepetitions     = g_pConfig->SpinRetryCount();
    g_SpinConstants.dwMonitorSpinCount = g_SpinConstants.dwMaximumDuration == 0 ? 0 : g_pConfig->MonitorSpinCount();
#endif
}

// this is a 'GC-aware' Lock.  It is careful to enable preemptive GC before it
// attempts any operation that can block.  Once the operation is finished, it
// restores the original state of GC.

// AwareLocks can only be created inside SyncBlocks, since they depend on the
// enclosing SyncBlock for coordination.  This is enforced by the private ctor.
typedef DPTR(class AwareLock) PTR_AwareLock;

class AwareLock
{
    friend class CheckAsmOffsets;

    friend class SyncBlockCache;
    friend class SyncBlock;

public:
    enum EnterHelperResult {
        EnterHelperResult_Entered,
        EnterHelperResult_Contention,
        EnterHelperResult_UseSlowPath
    };

    enum LeaveHelperAction {
        LeaveHelperAction_None,
        LeaveHelperAction_Signal,
        LeaveHelperAction_Yield,
        LeaveHelperAction_Contention,
        LeaveHelperAction_Error,
    };

private:
    class LockState
    {
    private:
        // Layout constants for m_state
        static const UINT32 IsLockedMask = (UINT32)1 << 0; // bit 0
        static const UINT32 ShouldNotPreemptWaitersMask = (UINT32)1 << 1; // bit 1
        static const UINT32 SpinnerCountIncrement = (UINT32)1 << 2;
        static const UINT32 SpinnerCountMask = (UINT32)0x7 << 2; // bits 2-4
        static const UINT32 IsWaiterSignaledToWakeMask = (UINT32)1 << 5; // bit 5
        static const UINT8 WaiterCountShift = 6;
        static const UINT32 WaiterCountIncrement = (UINT32)1 << WaiterCountShift;
        static const UINT32 WaiterCountMask = (UINT32)-1 >> WaiterCountShift << WaiterCountShift; // bits 6-31

    private:
        UINT32 m_state;

    public:
        LockState(UINT32 state = 0) : m_state(state)
        {
            LIMITED_METHOD_CONTRACT;
        }

    public:
        UINT32 GetState() const
        {
            LIMITED_METHOD_CONTRACT;
            return m_state;
        }

        UINT32 GetMonitorHeldState() const
        {
            LIMITED_METHOD_CONTRACT;
            static_assert_no_msg(IsLockedMask == 1);
            static_assert_no_msg(WaiterCountShift >= 1);

            // Return only the locked state and waiter count in the previous (m_MonitorHeld) layout for the debugger:
            //   bit 0: 1 if locked, 0 otherwise
            //   bits 1-31: waiter count
            UINT32 state = m_state;
            return (state & IsLockedMask) + (state >> WaiterCountShift << 1);
        }

    public:
        bool IsUnlockedWithNoWaiters() const
        {
            LIMITED_METHOD_CONTRACT;
            return !(m_state & (IsLockedMask + WaiterCountMask));
        }

        void InitializeToLockedWithNoWaiters()
        {
            LIMITED_METHOD_CONTRACT;
            _ASSERTE(!m_state);

            m_state = IsLockedMask;
        }

    public:
        bool IsLocked() const
        {
            LIMITED_METHOD_CONTRACT;
            return !!(m_state & IsLockedMask);
        }

    private:
        void InvertIsLocked()
        {
            LIMITED_METHOD_CONTRACT;
            m_state ^= IsLockedMask;
        }

    public:
        bool ShouldNotPreemptWaiters() const
        {
            LIMITED_METHOD_CONTRACT;
            return !!(m_state & ShouldNotPreemptWaitersMask);
        }

    private:
        void InvertShouldNotPreemptWaiters()
        {
            WRAPPER_NO_CONTRACT;

            m_state ^= ShouldNotPreemptWaitersMask;
            _ASSERTE(!ShouldNotPreemptWaiters() || HasAnyWaiters());
        }

        bool ShouldNonWaiterAttemptToAcquireLock() const
        {
            WRAPPER_NO_CONTRACT;
            _ASSERTE(!ShouldNotPreemptWaiters() || HasAnyWaiters());

            return !(m_state & (IsLockedMask + ShouldNotPreemptWaitersMask));
        }

    public:
        bool HasAnySpinners() const
        {
            LIMITED_METHOD_CONTRACT;
            return !!(m_state & SpinnerCountMask);
        }

    private:
        bool TryIncrementSpinnerCount()
        {
            WRAPPER_NO_CONTRACT;

            LockState newState = m_state + SpinnerCountIncrement;
            if (newState.HasAnySpinners()) // overflow check
            {
                m_state = newState;
                return true;
            }
            return false;
        }

        void DecrementSpinnerCount()
        {
            WRAPPER_NO_CONTRACT;
            _ASSERTE(HasAnySpinners());

            m_state -= SpinnerCountIncrement;
        }

    public:
        bool IsWaiterSignaledToWake() const
        {
            LIMITED_METHOD_CONTRACT;
            return !!(m_state & IsWaiterSignaledToWakeMask);
        }

    private:
        void InvertIsWaiterSignaledToWake()
        {
            LIMITED_METHOD_CONTRACT;
            m_state ^= IsWaiterSignaledToWakeMask;
        }

    public:
        bool HasAnyWaiters() const
        {
            LIMITED_METHOD_CONTRACT;
            return m_state >= WaiterCountIncrement;
        }

    private:
        void IncrementWaiterCount()
        {
            LIMITED_METHOD_CONTRACT;
            _ASSERTE(m_state + WaiterCountIncrement >= WaiterCountIncrement);

            m_state += WaiterCountIncrement;
        }

        void DecrementWaiterCount()
        {
            WRAPPER_NO_CONTRACT;
            _ASSERTE(HasAnyWaiters());

            m_state -= WaiterCountIncrement;
        }

    private:
        bool NeedToSignalWaiter() const
        {
            WRAPPER_NO_CONTRACT;
            return HasAnyWaiters() && !(m_state & (SpinnerCountMask + IsWaiterSignaledToWakeMask));
        }

    private:
        operator UINT32() const
        {
            LIMITED_METHOD_CONTRACT;
            return m_state;
        }

        LockState &operator =(UINT32 state)
        {
            LIMITED_METHOD_CONTRACT;

            m_state = state;
            return *this;
        }

    public:
        LockState VolatileLoadWithoutBarrier() const
        {
            WRAPPER_NO_CONTRACT;
            return ::VolatileLoadWithoutBarrier(&m_state);
        }

        LockState VolatileLoad() const
        {
            WRAPPER_NO_CONTRACT;
            return ::VolatileLoad(&m_state);
        }

    private:
        LockState CompareExchange(LockState toState, LockState fromState)
        {
            LIMITED_METHOD_CONTRACT;
            return (UINT32)InterlockedCompareExchange((LONG *)&m_state, (LONG)toState, (LONG)fromState);
        }

        LockState CompareExchangeAcquire(LockState toState, LockState fromState)
        {
            LIMITED_METHOD_CONTRACT;
            return (UINT32)InterlockedCompareExchangeAcquire((LONG *)&m_state, (LONG)toState, (LONG)fromState);
        }

    public:
        bool InterlockedTryLock();
        bool InterlockedTryLock(LockState state);
        bool InterlockedUnlock();
        bool InterlockedTrySetShouldNotPreemptWaitersIfNecessary(AwareLock *awareLock);
        bool InterlockedTrySetShouldNotPreemptWaitersIfNecessary(AwareLock *awareLock, LockState state);
        EnterHelperResult InterlockedTry_LockOrRegisterSpinner(LockState state);
        EnterHelperResult InterlockedTry_LockAndUnregisterSpinner();
        bool InterlockedUnregisterSpinner_TryLock();
        bool InterlockedTryLock_Or_RegisterWaiter(AwareLock *awareLock, LockState state);
        void InterlockedUnregisterWaiter();
        bool InterlockedTry_LockAndUnregisterWaiterAndObserveWakeSignal(AwareLock *awareLock);
        bool InterlockedObserveWakeSignal_Try_LockAndUnregisterWaiter(AwareLock *awareLock);
    };

    friend class LockState;

private:
    // Take care to use 'm_lockState.VolatileLoadWithoutBarrier()` when loading this value into a local variable that will be
    // reused. That prevents an optimization in the compiler that avoids stack-spilling a value loaded from memory and instead
    // reloads the value from the original memory location under the assumption that it would not be changed by another thread,
    // which can result in the local variable's value changing between reads if the memory location is modifed by another
    // thread. This is important for patterns such as:
    //
    //     T x = m_x; // no barrier
    //     if (meetsCondition(x))
    //     {
    //         assert(meetsCondition(x)); // This may fail!
    //     }
    //
    // The code should be written like this instead:
    //
    //     T x = VolatileLoadWithoutBarrier(&m_x); // compile-time barrier, no run-time barrier
    //     if (meetsCondition(x))
    //     {
    //         assert(meetsCondition(x)); // This will not fail
    //     }
    LockState m_lockState;

    ULONG           m_Recursion;
    PTR_Thread      m_HoldingThread;

    LONG            m_TransientPrecious;


    // This is a backpointer from the syncblock to the synctable entry.  This allows
    // us to recover the object that holds the syncblock.
    DWORD           m_dwSyncIndex;

    CLREvent        m_SemEvent;

    DWORD m_waiterStarvationStartTimeMs;

    static const DWORD WaiterStarvationDurationMsBeforeStoppingPreemptingWaiters = 100;

    // Only SyncBlocks can create AwareLocks.  Hence this private constructor.
    AwareLock(DWORD indx)
        : m_Recursion(0),
#ifndef DACCESS_COMPILE          
// PreFAST has trouble with intializing a NULL PTR_Thread.
          m_HoldingThread(NULL),
#endif // DACCESS_COMPILE          
          m_TransientPrecious(0),
          m_dwSyncIndex(indx),
          m_waiterStarvationStartTimeMs(0)
    {
        LIMITED_METHOD_CONTRACT;
    }

    ~AwareLock()
    {
        LIMITED_METHOD_CONTRACT;
        // We deliberately allow this to remain incremented if an exception blows
        // through a lock attempt.  This simply prevents the GC from aggressively
        // reclaiming a particular syncblock until the associated object is garbage.
        // From a perf perspective, it's not worth using SEH to prevent this from
        // happening.
        //
        // _ASSERTE(m_TransientPrecious == 0);
    }

#if defined(ENABLE_CONTRACTS_IMPL)
    // The LOCK_TAKEN/RELEASED macros need a "pointer" to the lock object to do
    // comparisons between takes & releases (and to provide debugging info to the
    // developer).  Since AwareLocks are always allocated embedded inside SyncBlocks,
    // and since SyncBlocks don't move (unlike the GC objects that use
    // the syncblocks), it's safe for us to just use the AwareLock pointer directly
    void * GetPtrForLockContract()
    {
        return (void *) this;
    }
#endif // defined(ENABLE_CONTRACTS_IMPL)

public:
    UINT32 GetLockState() const
    {
        WRAPPER_NO_CONTRACT;
        return m_lockState.VolatileLoadWithoutBarrier().GetState();
    }

    bool IsUnlockedWithNoWaiters() const
    {
        WRAPPER_NO_CONTRACT;
        return m_lockState.VolatileLoadWithoutBarrier().IsUnlockedWithNoWaiters();
    }

    UINT32 GetMonitorHeldStateVolatile() const
    {
        WRAPPER_NO_CONTRACT;
        return m_lockState.VolatileLoad().GetMonitorHeldState();
    }

    ULONG GetRecursionLevel() const
    {
        LIMITED_METHOD_CONTRACT;
        return m_Recursion;
    }

    PTR_Thread GetHoldingThread() const
    {
        LIMITED_METHOD_CONTRACT;
        return m_HoldingThread;
    }

private:
    void ResetWaiterStarvationStartTime();
    void RecordWaiterStarvationStartTime();
    bool ShouldStopPreemptingWaiters() const;

private: // friend access is required for this unsafe function
    void InitializeToLockedWithNoWaiters(ULONG recursionLevel, PTR_Thread holdingThread)
    {
        WRAPPER_NO_CONTRACT;

        m_lockState.InitializeToLockedWithNoWaiters();
        m_Recursion = recursionLevel;
        m_HoldingThread = holdingThread;
    }

public:
    static void SpinWait(const YieldProcessorNormalizationInfo &normalizationInfo, DWORD spinIteration);

    // Helper encapsulating the fast path entering monitor. Returns what kind of result was achieved.
    bool TryEnterHelper(Thread* pCurThread);

    EnterHelperResult TryEnterBeforeSpinLoopHelper(Thread *pCurThread);
    EnterHelperResult TryEnterInsideSpinLoopHelper(Thread *pCurThread);
    bool TryEnterAfterSpinLoopHelper(Thread *pCurThread);

    // Helper encapsulating the core logic for leaving monitor. Returns what kind of 
    // follow up action is necessary
    AwareLock::LeaveHelperAction LeaveHelper(Thread* pCurThread);

    void    Enter();
    BOOL    TryEnter(INT32 timeOut = 0);
    BOOL    EnterEpilog(Thread *pCurThread, INT32 timeOut = INFINITE);
    BOOL    EnterEpilogHelper(Thread *pCurThread, INT32 timeOut);
    BOOL    Leave();

    void    Signal()
    {
        WRAPPER_NO_CONTRACT;
        
        // CLREvent::SetMonitorEvent works even if the event has not been intialized yet
        m_SemEvent.SetMonitorEvent();

        m_lockState.InterlockedTrySetShouldNotPreemptWaitersIfNecessary(this);
    }

    void    AllocLockSemEvent();
    LONG    LeaveCompletely();
    BOOL    OwnedByCurrentThread();

    void    IncrementTransientPrecious()
    {
        LIMITED_METHOD_CONTRACT;
        FastInterlockIncrement(&m_TransientPrecious);
        _ASSERTE(m_TransientPrecious > 0);
    }

    void    DecrementTransientPrecious()
    {
        LIMITED_METHOD_CONTRACT;
        _ASSERTE(m_TransientPrecious > 0);
        FastInterlockDecrement(&m_TransientPrecious);
    }

    DWORD GetSyncBlockIndex();

    void SetPrecious();

    // Provide access to the object associated with this awarelock, so client can
    // protect it.
    inline OBJECTREF GetOwningObject();

    // Provide access to the Thread object that owns this awarelock.  This is used
    // to provide a host to find out owner of a lock.
    inline PTR_Thread GetOwningThread()
    {
        LIMITED_METHOD_CONTRACT;
        return m_HoldingThread;
    }
};

#ifdef FEATURE_COMINTEROP
class ComCallWrapper;
class ComClassFactory;
struct RCW;
class RCWHolder;
typedef DPTR(class ComCallWrapper)        PTR_ComCallWrapper;
#endif // FEATURE_COMINTEROP

class InteropSyncBlockInfo
{
    friend class RCWHolder;
    
public:
#ifndef FEATURE_PAL
    // List of InteropSyncBlockInfo instances that have been freed since the last syncblock cleanup.
    static SLIST_HEADER s_InteropInfoStandbyList;
#endif // !FEATURE_PAL

    InteropSyncBlockInfo()
    {
        LIMITED_METHOD_CONTRACT;
        ZeroMemory(this, sizeof(InteropSyncBlockInfo));
    }
#ifndef DACCESS_COMPILE
    ~InteropSyncBlockInfo();
#endif

#ifndef FEATURE_PAL
    // Deletes all items in code:s_InteropInfoStandbyList.
    static void FlushStandbyList();
#endif // !FEATURE_PAL

#ifdef FEATURE_COMINTEROP

    //
    // We'll be using the sentinel value of 0x1 to indicate that a particular
    // field was set at one time, but is now NULL.

#ifndef DACCESS_COMPILE
    RCW* GetRawRCW()
    {
        LIMITED_METHOD_CONTRACT;
        return (RCW *)((size_t)m_pRCW & ~1);
    }

    // Returns either NULL or an RCW on which AcquireLock has been called.
    RCW* GetRCWAndIncrementUseCount();

    // Sets the m_pRCW field in a thread-safe manner, pRCW can be NULL.
    void SetRawRCW(RCW* pRCW);

    bool RCWWasUsed()
    {
        LIMITED_METHOD_CONTRACT;

        return (m_pRCW != NULL);
    }
#else // !DACCESS_COMPILE
    TADDR DacGetRawRCW()
    {
        return (TADDR)((size_t)m_pRCW & ~1);
    }
#endif // DACCESS_COMPILE

#ifndef DACCESS_COMPILE
    void SetCCW(ComCallWrapper* pCCW)
    {
        LIMITED_METHOD_CONTRACT;

        if (pCCW == NULL)
            pCCW = (ComCallWrapper*) 0x1;
        
        m_pCCW = pCCW;
    }
#endif // !DACCESS_COMPILE

    PTR_ComCallWrapper GetCCW()
    {
        LIMITED_METHOD_DAC_CONTRACT;

        if (m_pCCW == (PTR_ComCallWrapper)0x1)
            return NULL;
        
        return m_pCCW;
    }

    bool CCWWasUsed()
    {
        LIMITED_METHOD_CONTRACT;

        if (m_pCCW == NULL)
            return false;

        return true;
    }

#ifdef FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
    void SetComClassFactory(ComClassFactory* pCCF)
    {
        LIMITED_METHOD_CONTRACT;

        if (pCCF == NULL)
            pCCF = (ComClassFactory*)0x1;
        
        m_pCCF = pCCF;
    }

    ComClassFactory* GetComClassFactory()
    {
        LIMITED_METHOD_CONTRACT;

        if (m_pCCF == (ComClassFactory*)0x1)
            return NULL;
        
        return m_pCCF;
    }

    bool CCFWasUsed()
    {
        LIMITED_METHOD_CONTRACT;

        if (m_pCCF == NULL)
            return false;

        return true;
    }
#endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
#endif // FEATURE_COMINTEROP

#if !defined(DACCESS_COMPILE)
    // set m_pUMEntryThunkOrInterceptStub if not already set - return true if not already set
    bool SetUMEntryThunk(void* pUMEntryThunk)
    {
        WRAPPER_NO_CONTRACT;
        return (FastInterlockCompareExchangePointer(&m_pUMEntryThunkOrInterceptStub,
                                                    pUMEntryThunk,
                                                    NULL) == NULL);
    }

    // set m_pUMEntryThunkOrInterceptStub if not already set - return true if not already set
    bool SetInterceptStub(Stub* pInterceptStub)
    {
        WRAPPER_NO_CONTRACT;
        void *pPtr = (void *)((UINT_PTR)pInterceptStub | 1);
        return (FastInterlockCompareExchangePointer(&m_pUMEntryThunkOrInterceptStub,
                                                    pPtr,
                                                    NULL) == NULL);
    }

    void FreeUMEntryThunkOrInterceptStub();

#endif // DACCESS_COMPILE

    void* GetUMEntryThunk()
    {
        LIMITED_METHOD_CONTRACT;
        return (((UINT_PTR)m_pUMEntryThunkOrInterceptStub & 1) ? NULL : m_pUMEntryThunkOrInterceptStub);
    }

    Stub* GetInterceptStub()
    {
        LIMITED_METHOD_CONTRACT;
        return (((UINT_PTR)m_pUMEntryThunkOrInterceptStub & 1) ? (Stub *)((UINT_PTR)m_pUMEntryThunkOrInterceptStub & ~1) : NULL);
    }

private:
    // If this is a delegate marshalled out to unmanaged code, this points
    // to the thunk generated for unmanaged code to call back on.
    // If this is a delegate representing an unmanaged function pointer,
    // this may point to a stub that intercepts calls to the unmng target.
    // An example of an intercept call is pInvokeStackImbalance MDA.
    // We differentiate between a thunk or intercept stub by setting the lowest
    // bit if it is an intercept stub.
    void*               m_pUMEntryThunkOrInterceptStub;

#ifdef FEATURE_COMINTEROP
    // If this object is being exposed to COM, it will have an associated CCW object
    PTR_ComCallWrapper  m_pCCW;
    
#ifdef FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
    // If this object represents a type object, it will have an associated class factory
    ComClassFactory*    m_pCCF;
#endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION

public:
#ifndef DACCESS_COMPILE
    // If this is a __ComObject, it will have an associated RCW object
    RCW*                m_pRCW;
#else
    // We can't define this as PTR_RCW, as this would create a typedef cycle. Use TADDR
    // instead.
    TADDR               m_pRCW;
#endif
#endif // FEATURE_COMINTEROP

};

typedef DPTR(InteropSyncBlockInfo) PTR_InteropSyncBlockInfo;

// this is a lazily created additional block for an object which contains
// synchronzation information and other "kitchen sink" data
typedef DPTR(SyncBlock) PTR_SyncBlock;
// See code:#SyncBlockOverview for more
class SyncBlock
{
    // ObjHeader creates our Mutex and Event
    friend class ObjHeader;
    friend class SyncBlockCache;
    friend struct ThreadQueue;
#ifdef DACCESS_COMPILE
    friend class ClrDataAccess;
#endif
    friend class CheckAsmOffsets;

  protected:
    AwareLock  m_Monitor;                    // the actual monitor

  public:
    // If this object is exposed to unmanaged code, we keep some extra info here.
    PTR_InteropSyncBlockInfo    m_pInteropInfo;

  protected:
#ifdef EnC_SUPPORTED
    // And if the object has new fields added via EnC, this is a list of them
    PTR_EnCSyncBlockInfo m_pEnCInfo;
#endif // EnC_SUPPORTED

    // We thread two different lists through this link.  When the SyncBlock is
    // active, we create a list of waiting threads here.  When the SyncBlock is
    // released (we recycle them), the SyncBlockCache maintains a free list of
    // SyncBlocks here.
    //
    // We can't afford to use an SList<> here because we only want to burn
    // space for the minimum, which is the pointer within an SLink.
    SLink       m_Link;

    // This is the hash code for the object. It can either have been transfered
    // from the header dword, in which case it will be limited to 26 bits, or
    // have been generated right into this member variable here, when it will
    // be a full 32 bits.

    // A 0 in this variable means no hash code has been set yet - this saves having
    // another flag to express this state, and it enables us to use a 32-bit interlocked
    // operation to set the hash code, on the other hand it means that hash codes
    // can never be 0. ObjectNative::GetHashCode in COMObject.cpp makes sure to enforce this.
    DWORD m_dwHashCode;

    // In some early version of VB when there were no arrays developers used to use BSTR as arrays
    // The way this was done was by adding a trail byte at the end of the BSTR
    // To support this scenario, we need to use the sync block for this special case and
    // save the trail character in here. 
    // This stores the trail character when a BSTR is used as an array
    WCHAR m_BSTRTrailByte;

  public:
    SyncBlock(DWORD indx)
        : m_Monitor(indx)
#ifdef EnC_SUPPORTED
        , m_pEnCInfo(PTR_NULL)
#endif // EnC_SUPPORTED
        , m_dwHashCode(0)
        , m_BSTRTrailByte(0)
    {
        LIMITED_METHOD_CONTRACT;

        m_pInteropInfo = NULL;
        
        // The monitor must be 32-bit aligned for atomicity to be guaranteed.
        _ASSERTE((((size_t) &m_Monitor) & 3) == 0);
    }

    DWORD GetSyncBlockIndex()
    {
        LIMITED_METHOD_CONTRACT;
        return m_Monitor.GetSyncBlockIndex();
    }

   // As soon as a syncblock acquires some state that cannot be recreated, we latch
   // a bit.
   void SetPrecious()
   {
       WRAPPER_NO_CONTRACT;
       m_Monitor.SetPrecious();
   }

   BOOL IsPrecious()
   {
       LIMITED_METHOD_CONTRACT;
       return (m_Monitor.m_dwSyncIndex & SyncBlockPrecious) != 0;
   }

    // True is the syncblock and its index are disposable. 
    // If new members are added to the syncblock, this 
    // method needs to be modified accordingly
    BOOL IsIDisposable()
    {
        WRAPPER_NO_CONTRACT;
        return (!IsPrecious() &&
                m_Monitor.IsUnlockedWithNoWaiters() &&
                m_Monitor.m_TransientPrecious == 0);
    }

    // Gets the InteropInfo block, creates a new one if none is present.
    InteropSyncBlockInfo* GetInteropInfo()
    {
        CONTRACT (InteropSyncBlockInfo*)
        {
            THROWS;
            GC_TRIGGERS;
            MODE_ANY;
            POSTCONDITION(CheckPointer(RETVAL));
        }
        CONTRACT_END;
        
        if (!m_pInteropInfo)
        {
            NewHolder<InteropSyncBlockInfo> pInteropInfo;
#ifndef FEATURE_PAL
            pInteropInfo = (InteropSyncBlockInfo *)InterlockedPopEntrySList(&InteropSyncBlockInfo::s_InteropInfoStandbyList);

            if (pInteropInfo != NULL)
            {
                // cache hit - reinitialize the data structure
                new (pInteropInfo) InteropSyncBlockInfo();
            }
            else
#endif // !FEATURE_PAL
            {
                pInteropInfo = new InteropSyncBlockInfo();
            }

            if (SetInteropInfo(pInteropInfo))
                pInteropInfo.SuppressRelease();
        }
        
        RETURN m_pInteropInfo;
    }

    PTR_InteropSyncBlockInfo GetInteropInfoNoCreate()
    {
        CONTRACT (PTR_InteropSyncBlockInfo)
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
            SUPPORTS_DAC;
            POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
        }
        CONTRACT_END;

        RETURN m_pInteropInfo;
    }

    // Returns false if the InteropInfo block was already set - does not overwrite the previous value.
    // True if the InteropInfo block was successfully set with the passed in value.
    bool SetInteropInfo(InteropSyncBlockInfo* pInteropInfo);
        
#ifdef EnC_SUPPORTED
    // Get information about fields added to this object by the Debugger's Edit and Continue support
    PTR_EnCSyncBlockInfo GetEnCInfo() 
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return m_pEnCInfo;
    }
        
    // Store information about fields added to this object by the Debugger's Edit and Continue support
    void SetEnCInfo(EnCSyncBlockInfo *pEnCInfo);
#endif // EnC_SUPPORTED

    DWORD GetHashCode()
    {
        LIMITED_METHOD_CONTRACT;
        return m_dwHashCode;
    }

    DWORD SetHashCode(DWORD hashCode)
    {
        WRAPPER_NO_CONTRACT;
        DWORD result = FastInterlockCompareExchange((LONG*)&m_dwHashCode, hashCode, 0);
        if (result == 0)
        {
            // the sync block now holds a hash code, which we can't afford to lose.
            SetPrecious();
            return hashCode;
        }
        else
            return result;
    }

    void *operator new (size_t sz, void* p)
    {
        LIMITED_METHOD_CONTRACT;
        return p ;
    }
    void operator delete(void *p)
    {
        LIMITED_METHOD_CONTRACT;
        // We've already destructed.  But retain the memory.
    }

    void EnterMonitor()
    {
        WRAPPER_NO_CONTRACT;
        m_Monitor.Enter();
    }

    BOOL TryEnterMonitor(INT32 timeOut = 0)
    {
        WRAPPER_NO_CONTRACT;
        return m_Monitor.TryEnter(timeOut);
    }

    // leave the monitor
    BOOL LeaveMonitor()
    {
        WRAPPER_NO_CONTRACT;
        return m_Monitor.Leave();
    }

    AwareLock* GetMonitor()
    {
        WRAPPER_NO_CONTRACT;
        SUPPORTS_DAC;
        //hold the syncblock 
#ifndef DACCESS_COMPILE
        SetPrecious();
#endif

        //Note that for DAC we did not return a PTR_ type. This pointer is interior and
        //the SyncBlock has already been marshaled so that GetMonitor could be called.
        return &m_Monitor;
    }

    AwareLock* QuickGetMonitor()
    {
        LIMITED_METHOD_CONTRACT;
    // Note that the syncblock isn't marked precious, so use caution when
    // calling this method.
        return &m_Monitor;
    }

    BOOL DoesCurrentThreadOwnMonitor()
    {
        WRAPPER_NO_CONTRACT;
        return m_Monitor.OwnedByCurrentThread();
    }

    LONG LeaveMonitorCompletely()
    {
        WRAPPER_NO_CONTRACT;
        return m_Monitor.LeaveCompletely();
    }

    BOOL Wait(INT32 timeOut, BOOL exitContext);
    void Pulse();
    void PulseAll();

    enum
    {
        // This bit indicates that the syncblock is valuable and can neither be discarded
        // nor re-created.
        SyncBlockPrecious   = 0x80000000,
    };

    BOOL HasCOMBstrTrailByte()
    {
        LIMITED_METHOD_CONTRACT;
        return (m_BSTRTrailByte!=0);
    }
    WCHAR GetCOMBstrTrailByte()
    {
        return m_BSTRTrailByte;
    }
    void SetCOMBstrTrailByte(WCHAR trailByte)
    {
        WRAPPER_NO_CONTRACT;
        m_BSTRTrailByte = trailByte;
        SetPrecious();
    }

  protected:
    // <NOTE>
    // This should ONLY be called when initializing a SyncBlock (i.e. ONLY from
    // ObjHeader::GetSyncBlock()), otherwise we'll have a race condition.
    // </NOTE>
    void InitState(ULONG recursionLevel, PTR_Thread holdingThread)
    {
        WRAPPER_NO_CONTRACT;
        m_Monitor.InitializeToLockedWithNoWaiters(recursionLevel, holdingThread);
    }

#if defined(ENABLE_CONTRACTS_IMPL)
    // The LOCK_TAKEN/RELEASED macros need a "pointer" to the lock object to do
    // comparisons between takes & releases (and to provide debugging info to the
    // developer).  Use the AwareLock (m_Monitor)
    void * GetPtrForLockContract()
    {
        return m_Monitor.GetPtrForLockContract();
    }
#endif // defined(ENABLE_CONTRACTS_IMPL)
};

class SyncTableEntry
{
  public:
    PTR_SyncBlock    m_SyncBlock;
    VolatilePtr<Object, PTR_Object> m_Object;
    static PTR_SyncTableEntry GetSyncTableEntry();
#ifndef DACCESS_COMPILE
    static SyncTableEntry*& GetSyncTableEntryByRef();
#endif
};

#ifdef _DEBUG
extern void DumpSyncBlockCache();
#endif

// this class stores free sync blocks after they're allocated and
// unused

typedef DPTR(SyncBlockCache) PTR_SyncBlockCache;

// The SyncBlockCache is the data structure that manages SyncBlocks
// as well as SyncTableEntries (See explaintation at top of this file).
//
// There is only one process global SyncBlockCache (SyncBlockCache::s_pSyncBlockCache)
// and SyncTableEntry table (g_pSyncTable).  
// 
// see code:#SyncBlockOverview for more
class SyncBlockCache
{
#ifdef DACCESS_COMPILE
    friend class ClrDataAccess;
#endif

    friend class SyncBlock;

    
  private:
    PTR_SLink   m_pCleanupBlockList;    // list of sync blocks that need cleanup
    SLink*      m_FreeBlockList;        // list of free sync blocks
    Crst        m_CacheLock;            // cache lock
    DWORD       m_FreeCount;            // count of active sync blocks
    DWORD       m_ActiveCount;          // number active
    SyncBlockArray *m_SyncBlocks;       // Array of new SyncBlocks.
    DWORD       m_FreeSyncBlock;        // Next Free Syncblock in the array 

        // The next variables deal with SyncTableEntries.  Instead of having the object-header
        // point directly at SyncBlocks, the object points a a syncTableEntry, which points at
        // the syncBlock.  This is done because in a common case (need a hash code for an object)
        // you just need a syncTableEntry.  

    DWORD       m_FreeSyncTableIndex;   // We allocate a large array of SyncTableEntry structures.  
                                        // This index points at the boundry between used, and never-been
                                        // used SyncTableEntries.  
    size_t      m_FreeSyncTableList;    // index of the first free SyncTableEntry in our free list.
                                        // The entry at this index has its m_object field to the index
                                        // of the next element (shifted by 1, low bit marks not in use)
    DWORD       m_SyncTableSize;
    SyncTableEntry *m_OldSyncTables;    // Next old SyncTable

    BOOL        m_bSyncBlockCleanupInProgress;  // A flag indicating if sync block cleanup is in progress.    
    DWORD*      m_EphemeralBitmap;      // card table for ephemeral scanning

    BOOL        GCWeakPtrScanElement(int elindex, HANDLESCANPROC scanProc, LPARAM lp1, LPARAM lp2, BOOL& cleanup);

    void SetCard (size_t card);
    void ClearCard (size_t card);
    BOOL CardSetP (size_t card);
    void CardTableSetBit (size_t idx);
    void Grow();


  public:
    SPTR_DECL(SyncBlockCache, s_pSyncBlockCache);
    static SyncBlockCache*& GetSyncBlockCache();

    void *operator new(size_t size, void *pInPlace)
    {
        LIMITED_METHOD_CONTRACT;
        return pInPlace;
    }

    void operator delete(void *p)
    {
        LIMITED_METHOD_CONTRACT;
    }

    SyncBlockCache();
    ~SyncBlockCache();

    static void Attach();
    static void Detach();
    void DoDetach();

    static void Start();
    static void Stop();

    // returns and removes next from free list
    SyncBlock* GetNextFreeSyncBlock();
    // returns and removes the next from cleanup list
    SyncBlock* GetNextCleanupSyncBlock();
    // inserts a syncblock into the cleanup list
    void    InsertCleanupSyncBlock(SyncBlock* psb);

    // Obtain a new syncblock slot in the SyncBlock table. Used as a hash code
    DWORD   NewSyncBlockSlot(Object *obj);

    // return sync block to cache or delete
    void    DeleteSyncBlock(SyncBlock *sb);

    // returns the sync block memory to the free pool but does not destruct sync block (must own cache lock already)
    void    DeleteSyncBlockMemory(SyncBlock *sb);

    // return sync block to cache or delete, called from GC
    void    GCDeleteSyncBlock(SyncBlock *sb);

    void    GCWeakPtrScan(HANDLESCANPROC scanProc, uintptr_t lp1, uintptr_t lp2);

    void    GCDone(BOOL demoting, int max_gen);

    void    CleanupSyncBlocks();

    int GetTableEntryCount()
    {
        LIMITED_METHOD_CONTRACT;
        return m_FreeSyncTableIndex - 1;
    }

    // Determines if a sync block cleanup is in progress.
    BOOL    IsSyncBlockCleanupInProgress()
    {
        LIMITED_METHOD_CONTRACT;
        return m_bSyncBlockCleanupInProgress;
    }

    DWORD GetActiveCount()
    {
        return m_ActiveCount;
    }

    // Encapsulate a CrstHolder, so that clients of our lock don't have to know
    // the details of our implementation.
    class LockHolder : public CrstHolder
    {
    public:
        LockHolder(SyncBlockCache *pCache)
            : CrstHolder(&pCache->m_CacheLock)
        {
            CONTRACTL
            {
                NOTHROW;
                GC_NOTRIGGER;
                MODE_ANY;
                CAN_TAKE_LOCK;
            }
            CONTRACTL_END;
        }
    };
    friend class LockHolder;

#ifdef _DEBUG
    friend void DumpSyncBlockCache();
#endif

#ifdef VERIFY_HEAP
    void    VerifySyncTableEntry();
#endif
};

// See code:#SyncBlockOverView for more 
class ObjHeader
{
    friend class CheckAsmOffsets;

  private:
    // !!! Notice: m_SyncBlockValue *MUST* be the last field in ObjHeader.
#ifdef _WIN64
    DWORD    m_alignpad;
#endif // _WIN64

    Volatile<DWORD> m_SyncBlockValue;      // the Index and the Bits

#if defined(_WIN64) && defined(_DEBUG)
    void IllegalAlignPad();
#endif // _WIN64 && _DEBUG

    INCONTRACT(void * GetPtrForLockContract());

  public:

    // Access to the Sync Block Index, by masking the Value.
    FORCEINLINE DWORD GetHeaderSyncBlockIndex()
    {
        LIMITED_METHOD_DAC_CONTRACT;
#if defined(_WIN64) && defined(_DEBUG) && !defined(DACCESS_COMPILE)
        // On WIN64 this field is never modified, but was initialized to 0
        if (m_alignpad != 0)
            IllegalAlignPad();
#endif // _WIN64 && _DEBUG && !DACCESS_COMPILE

        // pull the value out before checking it to avoid race condition
        DWORD value = m_SyncBlockValue.LoadWithoutBarrier();
        if ((value & (BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX | BIT_SBLK_IS_HASHCODE)) != BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX)
            return 0;
        return value & MASK_SYNCBLOCKINDEX;
    }
    // Ditto for setting the index, which is careful not to disturb the underlying
    // bit field -- even in the presence of threaded access.
    // 
    // This service can only be used to transition from a 0 index to a non-0 index.
    void SetIndex(DWORD indx)
    {
        CONTRACTL
        {
            INSTANCE_CHECK;
            NOTHROW;
            GC_NOTRIGGER;
            FORBID_FAULT;
            MODE_ANY;
            PRECONDITION(GetHeaderSyncBlockIndex() == 0);
            PRECONDITION(m_SyncBlockValue & BIT_SBLK_SPIN_LOCK);
        }
        CONTRACTL_END

        LONG newValue;
        LONG oldValue;
        while (TRUE) {
            oldValue = m_SyncBlockValue.LoadWithoutBarrier();
            _ASSERTE(GetHeaderSyncBlockIndex() == 0);
            // or in the old value except any index that is there - 
            // note that indx could be carrying the BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX bit that we need to preserve
            newValue = (indx | 
                (oldValue & ~(BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX | BIT_SBLK_IS_HASHCODE | MASK_SYNCBLOCKINDEX)));
            if (FastInterlockCompareExchange((LONG*)&m_SyncBlockValue, 
                                             newValue, 
                                             oldValue)
                == oldValue)
            {
                return;
            }
        }
    }

    // Used only during shutdown
    void ResetIndex()
    {
        LIMITED_METHOD_CONTRACT;

        _ASSERTE(m_SyncBlockValue & BIT_SBLK_SPIN_LOCK);
        FastInterlockAnd(&m_SyncBlockValue, ~(BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX | BIT_SBLK_IS_HASHCODE | MASK_SYNCBLOCKINDEX));
    }

    // Used only GC
    void GCResetIndex()
    {
        LIMITED_METHOD_CONTRACT;

        m_SyncBlockValue.RawValue() &=~(BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX | BIT_SBLK_IS_HASHCODE | MASK_SYNCBLOCKINDEX);
    }

    // For now, use interlocked operations to twiddle bits in the bitfield portion.
    // If we ever have high-performance requirements where we can guarantee that no
    // other threads are accessing the ObjHeader, this can be reconsidered for those
    // particular bits.
    void SetBit(DWORD bit)
    {
        LIMITED_METHOD_CONTRACT;

        _ASSERTE((bit & MASK_SYNCBLOCKINDEX) == 0);
        FastInterlockOr(&m_SyncBlockValue, bit);
    }
    void ClrBit(DWORD bit)
    {
        LIMITED_METHOD_CONTRACT;

        _ASSERTE((bit & MASK_SYNCBLOCKINDEX) == 0);
        FastInterlockAnd(&m_SyncBlockValue, ~bit);
    }
    //GC accesses this bit when all threads are stopped. 
    void SetGCBit()
    {
        LIMITED_METHOD_CONTRACT;

        m_SyncBlockValue.RawValue() |= BIT_SBLK_GC_RESERVE;
    }
    void ClrGCBit()
    {
        LIMITED_METHOD_CONTRACT;

        m_SyncBlockValue.RawValue() &= ~BIT_SBLK_GC_RESERVE;
    }

    // Don't bother masking out the index since anyone who wants bits will presumably
    // restrict the bits they consider.
    DWORD GetBits()
    {
        LIMITED_METHOD_CONTRACT;
        SUPPORTS_DAC;

#if defined(_WIN64) && defined(_DEBUG) && !defined(DACCESS_COMPILE)
        // On WIN64 this field is never modified, but was initialized to 0
        if (m_alignpad != 0)
            IllegalAlignPad();
#endif // _WIN64 && _DEBUG && !DACCESS_COMPILE

        return m_SyncBlockValue.LoadWithoutBarrier();
    }


    DWORD SetBits(DWORD newBits, DWORD oldBits)
    {
        LIMITED_METHOD_CONTRACT;

        _ASSERTE((oldBits & BIT_SBLK_SPIN_LOCK) == 0);
        DWORD result = FastInterlockCompareExchange((LONG*)&m_SyncBlockValue, newBits, oldBits);
        return result;
    }

#ifdef _DEBUG
    BOOL HasEmptySyncBlockInfo()
    {
        WRAPPER_NO_CONTRACT;
        return m_SyncBlockValue.LoadWithoutBarrier() == 0;
    }
#endif

    // TRUE if the header has a real SyncBlockIndex (i.e. it has an entry in the
    // SyncTable, though it doesn't necessarily have an entry in the SyncBlockCache)
    BOOL HasSyncBlockIndex()
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return (GetHeaderSyncBlockIndex() != 0);
    }

    // retrieve or allocate a sync block for this object
    SyncBlock *GetSyncBlock();

    // retrieve sync block but don't allocate
    PTR_SyncBlock PassiveGetSyncBlock()
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return g_pSyncTable [(int)GetHeaderSyncBlockIndex()].m_SyncBlock;    
    }

    DWORD GetSyncBlockIndex();

    // this enters the monitor of an object
    void EnterObjMonitor();

    // non-blocking version of above
    BOOL TryEnterObjMonitor(INT32 timeOut = 0);

    // Inlineable fast path of EnterObjMonitor/TryEnterObjMonitor. Must be called before EnterObjMonitorHelperSpin.
    AwareLock::EnterHelperResult EnterObjMonitorHelper(Thread* pCurThread);

    // Typically non-inlined spin loop for some fast paths of EnterObjMonitor/TryEnterObjMonitor. EnterObjMonitorHelper must be
    // called before this function.
    AwareLock::EnterHelperResult EnterObjMonitorHelperSpin(Thread* pCurThread);

    // leaves the monitor of an object
    BOOL LeaveObjMonitor();

    // should be called only from unwind code
    BOOL LeaveObjMonitorAtException();

    // Helper encapsulating the core logic for releasing monitor. Returns what kind of
    // follow up action is necessary
    AwareLock::LeaveHelperAction LeaveObjMonitorHelper(Thread* pCurThread);

    // Returns TRUE if the lock is owned and FALSE otherwise
    // threadId is set to the ID (Thread::GetThreadId()) of the thread which owns the lock
    // acquisitionCount is set to the number of times the lock needs to be released before
    // it is unowned
    BOOL GetThreadOwningMonitorLock(DWORD *pThreadId, DWORD *pAcquisitionCount);

    PTR_Object GetBaseObject()
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return dac_cast<PTR_Object>(dac_cast<TADDR>(this + 1));
    }

    BOOL Wait(INT32 timeOut, BOOL exitContext);
    void Pulse();
    void PulseAll();

    void EnterSpinLock();
    void ReleaseSpinLock();

    BOOL Validate (BOOL bVerifySyncBlkIndex = TRUE);
};


typedef DPTR(class ObjHeader) PTR_ObjHeader;


#define ENTER_SPIN_LOCK(pOh)        \
    pOh->EnterSpinLock();

#define LEAVE_SPIN_LOCK(pOh)        \
    pOh->ReleaseSpinLock();


#ifdef DACCESS_COMPILE
// A visitor function used to enumerate threads in the ThreadQueue below
typedef void (*FP_TQ_THREAD_ENUMERATION_CALLBACK)(PTR_Thread pThread, VOID* pUserData);
#endif

// A SyncBlock contains an m_Link field that is used for two purposes.  One
// is to manage a FIFO queue of threads that are waiting on this synchronization
// object.  The other is to thread free SyncBlocks into a list for recycling.
// We don't want to burn anything else on the SyncBlock instance, so we can't
// use an SList or similar data structure.  So here's the encapsulation for the
// queue of waiting threads.
//
// Note that Enqueue is slower than it needs to be, because we don't want to
// burn extra space in the SyncBlock to remember the head and the tail of the Q.
// An alternate approach would be to treat the list as a LIFO stack, which is not
// a fair policy because it permits to starvation.
//
// Important!!! While there is a lock that is used in process to keep multiple threads
// from altering the queue simultaneously, the queue must still be consistent at all
// times, even when the lock is held. 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.
struct ThreadQueue
{
    // Given a link in the chain, get the Thread that it represents
    static PTR_WaitEventLink WaitEventLinkForLink(PTR_SLink pLink);

    // Unlink the head of the Q.  We are always in the SyncBlock's critical
    // section.
    static WaitEventLink *DequeueThread(SyncBlock *psb);

    // 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 void          EnqueueThread(WaitEventLink *pWaitEventLink, SyncBlock *psb);
    
    // Wade through the SyncBlock's list of waiting threads and remove the
    // specified thread.
    static BOOL          RemoveThread (Thread *pThread, SyncBlock *psb);

#ifdef DACCESS_COMPILE
    // Enumerates the threads in the queue from front to back by calling
    // pCallbackFunction on each one
    static void          EnumerateThreads(SyncBlock *psb,
                                          FP_TQ_THREAD_ENUMERATION_CALLBACK pCallbackFunction,
                                          void* pUserData);
#endif
};

inline void AwareLock::SetPrecious()
{
    LIMITED_METHOD_CONTRACT;

    m_dwSyncIndex |= SyncBlock::SyncBlockPrecious;
}

inline DWORD AwareLock::GetSyncBlockIndex()
{
    LIMITED_METHOD_CONTRACT;
    return (m_dwSyncIndex & ~SyncBlock::SyncBlockPrecious);
}

#ifdef _TARGET_X86_
#include <poppack.h>
#endif // _TARGET_X86_

#endif // _SYNCBLK_H_