-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathcs.cpp
1603 lines (1349 loc) · 55.5 KB
/
cs.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
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
///////////////////////////////////////////////////////////////////////////////
//
// File:
// cs.cpp
//
// Purpose:
// Implementation of critical sections
//
///////////////////////////////////////////////////////////////////////////////
#include "pal/thread.hpp"
#include "pal/cs.hpp"
#include "pal/malloc.hpp"
#include "pal/list.h"
#include "pal/dbgmsg.h"
#include "pal/init.h"
#include "pal/process.h"
#include <sched.h>
#include <pthread.h>
using namespace CorUnix;
//
// Uncomment the following line to turn CS behavior from
// unfair to fair lock
//
// #define PALCS_TRANSFER_OWNERSHIP_ON_RELEASE
//
// Uncomment the following line to enable simple mutex based CSs
// Note: when MUTEX_BASED_CSS is defined, PALCS_TRANSFER_OWNERSHIP_ON_RELEASE
// has no effect
//
// #define MUTEX_BASED_CSS
//
// Important notes on critical sections layout/semantics on Unix
//
// 1) The PAL_CRITICAL_SECTION structure below must match the size of the
// CRITICAL_SECTION defined in pal.h. Besides the "windows part"
// of both the structures must be identical.
// 2) Both PAL_CRITICAL_SECTION and CRITICAL_SECTION currently do not match
// the size of the Windows' CRITICAL_SECTION.
// - From unmanaged code point of view, one should never make assumptions
// on the size and layout of the CRITICAL_SECTION structure, and anyway
// on Unix PAL's CRITICAL_SECTION extends the Windows one, so that some
// assumptions may still work.
// - From managed code point of view, one could try to interop directly
// to unmanaged critical sections APIs (though that would be quite
// meaningless). In order to do that, she would need to define a copy
// of the CRITICAL_SECTION structure in his/her code, and that may lead
// to access random data beyond the structure limit, if that managed
// code is compiled on Unix.
// In case such scenario should be supported, the current implementation
// will have to be modified in a way to go back to the original Windows
// CRITICAL_SECTION layout. That would require to dynamically allocate
// the native data and use LockSemaphore as a pointer to it. The current
// solution intentionally avoids that since an effort has been made to
// make CSs objects completely independent from any other PAL subsystem,
// so that they can be used during initialization and shutdown.
// In case the "dynamically allocate native data" solution should be
// implemented, CSs would acquire a dependency on memory allocation and
// thread suspension subsystems, since the first contention on a specific
// CS would trigger the native data allocation.
// 3) The semantics of the LockCount field has not been kept compatible with
// the Windows implementation.
// Both on Windows and Unix the lower bit of LockCount indicates
// whether or not the CS is locked (for both fair and unfair lock
// solution), the second bit indicates whether or not currently there is a
// waiter that has been awakened and that is trying to acquire the CS
// (only unfair lock solution, unused in the fair one); starting from the
// third bit, LockCount represents the number of waiter threads currently
// waiting on the CS.
// Windows, anyway, implements this semantics in negative logic, so that
// an unlocked CS is represented by a LockCount == -1 (i.e. 0xFFFFFFFF,
// all the bits set), while on Unix an unlocked CS has LockCount == 0.
// Windows needs to use negative logic to support legacy code bad enough
// to directly access CS's fields making the assumption that
// LockCount == -1 means CS unlocked. Unix will not support that, and
// it uses positive logic.
// 4) The CRITICAL_SECTION_DEBUG_INFO layout on Unix is intentionally not
// compatible with the Windows layout.
// 5) For legacy code dependencies issues similar to those just described for
// the LockCount field, Windows CS code maintains a per-process list of
// debug info for all the CSs, both on debug and free/retail builds. On
// Unix such a list is maintained only on debug builds, and no debug
// info structure is allocated on free/retail builds
//
SET_DEFAULT_DEBUG_CHANNEL(CRITSEC);
#ifdef TRACE_CS_LOGIC
#define CS_TRACE TRACE
#else
#ifdef __GNUC__
#define CS_TRACE(args...)
#else
#define CS_TRACE(...)
#endif
#endif // TRACE_CS_LOGIC
//
// Note: PALCS_LOCK_WAITER_INC must be 2 * PALCS_LOCK_AWAKENED_WAITER
//
#define PALCS_LOCK_INIT 0
#define PALCS_LOCK_BIT 1
#define PALCS_LOCK_AWAKENED_WAITER 2
#define PALCS_LOCK_WAITER_INC 4
#define PALCS_GETLBIT(val) ((int)(0!=(PALCS_LOCK_BIT&val)))
#define PALCS_GETAWBIT(val) ((int)(0!=(PALCS_LOCK_AWAKENED_WAITER&val)))
#define PALCS_GETWCOUNT(val) (val/PALCS_LOCK_WAITER_INC)
enum PalCsInitState
{
PalCsNotInitialized, // Critical section not initialized (InitializedCriticalSection
// has not yet been called, or DeleteCriticalsection has been
// called).
PalCsUserInitialized, // Critical section initialized from the user point of view,
// i.e. InitializedCriticalSection has been called.
PalCsFullyInitializing, // A thread found the CS locked, this is the first contention on
// this CS, and the thread is initializing the CS's native data.
PalCsFullyInitialized // Internal CS's native data has been fully initialized.
};
enum PalCsWaiterReturnState
{
PalCsReturnWaiterAwakened,
PalCsWaiterDidntWait
};
struct _PAL_CRITICAL_SECTION; // fwd declaration
typedef struct _CRITICAL_SECTION_DEBUG_INFO
{
LIST_ENTRY Link;
struct _PAL_CRITICAL_SECTION * pOwnerCS;
Volatile<ULONG> lAcquireCount;
Volatile<ULONG> lEnterCount;
Volatile<LONG> lContentionCount;
} CRITICAL_SECTION_DEBUG_INFO, *PCRITICAL_SECTION_DEBUG_INFO;
typedef struct _PAL_CRITICAL_SECTION_NATIVE_DATA
{
pthread_mutex_t mutex;
pthread_cond_t condition;
int iPredicate;
} PAL_CRITICAL_SECTION_NATIVE_DATA, *PPAL_CRITICAL_SECTION_NATIVE_DATA;
typedef struct _PAL_CRITICAL_SECTION {
// Windows part
PCRITICAL_SECTION_DEBUG_INFO DebugInfo;
Volatile<LONG> LockCount;
LONG RecursionCount;
SIZE_T OwningThread;
HANDLE LockSemaphore;
ULONG_PTR SpinCount;
// Private Unix part
BOOL fInternal;
Volatile<PalCsInitState> cisInitState;
PAL_CRITICAL_SECTION_NATIVE_DATA csndNativeData;
} PAL_CRITICAL_SECTION, *PPAL_CRITICAL_SECTION, *LPPAL_CRITICAL_SECTION;
#ifdef _DEBUG
namespace CorUnix
{
PAL_CRITICAL_SECTION g_csPALCSsListLock;
LIST_ENTRY g_PALCSList = { &g_PALCSList, &g_PALCSList};
}
#endif // _DEBUG
#define ObtainCurrentThreadId(thread) ObtainCurrentThreadIdImpl(thread, __func__)
static SIZE_T ObtainCurrentThreadIdImpl(CPalThread *pCurrentThread, const char *callingFuncName)
{
SIZE_T threadId;
if(pCurrentThread)
{
threadId = pCurrentThread->GetThreadId();
}
else
{
threadId = GetCurrentThreadId();
CS_TRACE("Early %s, no pthread data, getting TID internally\n", callingFuncName);
}
_ASSERTE(0 != threadId);
return threadId;
}
/*++
Function:
InitializeCriticalSection
See MSDN doc.
--*/
void InitializeCriticalSection(LPCRITICAL_SECTION lpCriticalSection)
{
PERF_ENTRY(InitializeCriticalSection);
ENTRY("InitializeCriticalSection(lpCriticalSection=%p)\n",
lpCriticalSection);
InternalInitializeCriticalSectionAndSpinCount(lpCriticalSection,
0, false);
LOGEXIT("InitializeCriticalSection returns void\n");
PERF_EXIT(InitializeCriticalSection);
}
/*++
Function:
InitializeCriticalSectionEx - Flags is ignored.
See MSDN doc.
--*/
BOOL InitializeCriticalSectionEx(LPCRITICAL_SECTION lpCriticalSection, DWORD dwSpinCount, DWORD Flags)
{
PERF_ENTRY(InitializeCriticalSection);
ENTRY("InitializeCriticalSectionEx(lpCriticalSection=%p, dwSpinCount=%d, Flags=%d)\n",
lpCriticalSection, dwSpinCount, Flags);
InternalInitializeCriticalSectionAndSpinCount(lpCriticalSection, dwSpinCount, false);
LOGEXIT("InitializeCriticalSectionEx returns TRUE\n");
PERF_EXIT(InitializeCriticalSection);
return true;
}
/*++
Function:
InitializeCriticalSectionAndSpinCount
See MSDN doc.
--*/
BOOL InitializeCriticalSectionAndSpinCount(LPCRITICAL_SECTION lpCriticalSection,
DWORD dwSpinCount)
{
BOOL bRet = TRUE;
PERF_ENTRY(InitializeCriticalSectionAndSpinCount);
ENTRY("InitializeCriticalSectionAndSpinCount(lpCriticalSection=%p, "
"dwSpinCount=%u)\n", lpCriticalSection, dwSpinCount);
InternalInitializeCriticalSectionAndSpinCount(lpCriticalSection,
dwSpinCount, false);
LOGEXIT("InitializeCriticalSectionAndSpinCount returns BOOL %d\n",
bRet);
PERF_EXIT(InitializeCriticalSectionAndSpinCount);
return bRet;
}
/*++
Function:
DeleteCriticalSection
See MSDN doc.
--*/
void DeleteCriticalSection(LPCRITICAL_SECTION lpCriticalSection)
{
PERF_ENTRY(DeleteCriticalSection);
ENTRY("DeleteCriticalSection(lpCriticalSection=%p)\n", lpCriticalSection);
InternalDeleteCriticalSection(lpCriticalSection);
LOGEXIT("DeleteCriticalSection returns void\n");
PERF_EXIT(DeleteCriticalSection);
}
/*++
Function:
EnterCriticalSection
See MSDN doc.
--*/
void EnterCriticalSection(LPCRITICAL_SECTION lpCriticalSection)
{
PERF_ENTRY(EnterCriticalSection);
ENTRY("EnterCriticalSection(lpCriticalSection=%p)\n", lpCriticalSection);
CPalThread * pThread = InternalGetCurrentThread();
InternalEnterCriticalSection(pThread, lpCriticalSection);
LOGEXIT("EnterCriticalSection returns void\n");
PERF_EXIT(EnterCriticalSection);
}
/*++
Function:
TryEnterCriticalSection
See MSDN doc.
--*/
BOOL TryEnterCriticalSection(LPCRITICAL_SECTION lpCriticalSection)
{
PERF_ENTRY(TryEnterCriticalSection);
ENTRY("TryEnterCriticalSection(lpCriticalSection=%p)\n", lpCriticalSection);
CPalThread * pThread = InternalGetCurrentThread();
bool fRet = InternalTryEnterCriticalSection(pThread,
lpCriticalSection);
LOGEXIT("TryEnterCriticalSection returns bool %d\n", (int)fRet);
PERF_EXIT(TryEnterCriticalSection);
return (BOOL)fRet;
}
/*++
Function:
LeaveCriticalSection
See MSDN doc.
--*/
VOID LeaveCriticalSection(LPCRITICAL_SECTION lpCriticalSection)
{
PERF_ENTRY(LeaveCriticalSection);
ENTRY("LeaveCriticalSection(lpCriticalSection=%p)\n", lpCriticalSection);
CPalThread * pThread = InternalGetCurrentThread();
InternalLeaveCriticalSection(pThread, lpCriticalSection);
LOGEXIT("LeaveCriticalSection returns void\n");
PERF_EXIT(LeaveCriticalSection);
}
/*++
Function:
InternalInitializeCriticalSection
Initializes a critical section. It assumes the CS is an internal one,
i.e. thread entering it will be marked unsafe for suspension
--*/
VOID InternalInitializeCriticalSection(CRITICAL_SECTION *pcs)
{
InternalInitializeCriticalSectionAndSpinCount(pcs, 0, true);
}
/*++
Function:
InternalDeleteCriticalSection
Deletes a critical section
--*/
VOID InternalDeleteCriticalSection(
PCRITICAL_SECTION pCriticalSection)
{
PAL_CRITICAL_SECTION * pPalCriticalSection =
reinterpret_cast<PAL_CRITICAL_SECTION*>(pCriticalSection);
_ASSERT_MSG(PalCsUserInitialized == pPalCriticalSection->cisInitState ||
PalCsFullyInitialized == pPalCriticalSection->cisInitState,
"CS %p is not initialized", pPalCriticalSection);
#ifdef _DEBUG
CPalThread * pThread =
(PALIsThreadDataInitialized() ? GetCurrentPalThread() : NULL);
if (0 != pPalCriticalSection->LockCount)
{
SIZE_T tid;
tid = ObtainCurrentThreadId(pThread);
int iWaiterCount = (int)PALCS_GETWCOUNT(pPalCriticalSection->LockCount);
if (0 != (PALCS_LOCK_BIT & pPalCriticalSection->LockCount))
{
// CS is locked
if (tid != pPalCriticalSection->OwningThread)
{
// not owner
ASSERT("Thread tid=%u deleting a CS owned by thread tid=%u\n",
tid, pPalCriticalSection->OwningThread);
}
else
{
// owner
if (0 != iWaiterCount)
{
ERROR("Thread tid=%u is deleting a CS with %d threads waiting on it\n",
tid, iWaiterCount);
}
else
{
WARN("Thread tid=%u is deleting a critical section it still owns\n",
tid);
}
}
}
else
{
// CS is not locked
if (0 != iWaiterCount)
{
ERROR("Deleting a CS with %d threads waiting on it\n",
iWaiterCount);
}
else
{
ERROR("Thread tid=%u is deleting a critical section currently not "
"owned, but with one waiter awakened\n", tid);
}
}
}
if (NULL != pPalCriticalSection->DebugInfo)
{
if (pPalCriticalSection != &CorUnix::g_csPALCSsListLock)
{
InternalEnterCriticalSection(pThread,
reinterpret_cast<CRITICAL_SECTION*>(&g_csPALCSsListLock));
RemoveEntryList(&pPalCriticalSection->DebugInfo->Link);
InternalLeaveCriticalSection(pThread,
reinterpret_cast<CRITICAL_SECTION*>(&g_csPALCSsListLock));
}
else
{
RemoveEntryList(&pPalCriticalSection->DebugInfo->Link);
}
#ifdef PAL_TRACK_CRITICAL_SECTIONS_DATA
LONG lVal, lNewVal;
Volatile<LONG> * plDest;
// Update delete count
InterlockedIncrement(pPalCriticalSection->fInternal ?
&g_lPALCSInternalDeleteCount : &g_lPALCSDeleteCount);
// Update acquire count
plDest = pPalCriticalSection->fInternal ?
&g_lPALCSInternalAcquireCount : &g_lPALCSAcquireCount;
do {
lVal = *plDest;
lNewVal = lVal + pPalCriticalSection->DebugInfo->lAcquireCount;
lNewVal = InterlockedCompareExchange(plDest, lNewVal, lVal);
} while (lVal != lNewVal);
// Update enter count
plDest = pPalCriticalSection->fInternal ?
&g_lPALCSInternalEnterCount : &g_lPALCSEnterCount;
do {
lVal = *plDest;
lNewVal = lVal + pPalCriticalSection->DebugInfo->lEnterCount;
lNewVal = InterlockedCompareExchange(plDest, lNewVal, lVal);
} while (lVal != lNewVal);
// Update contention count
plDest = pPalCriticalSection->fInternal ?
&g_lPALCSInternalContentionCount : &g_lPALCSContentionCount;
do {
lVal = *plDest;
lNewVal = lVal + pPalCriticalSection->DebugInfo->lContentionCount;
lNewVal = InterlockedCompareExchange(plDest, lNewVal, lVal);
} while (lVal != lNewVal);
#endif // PAL_TRACK_CRITICAL_SECTIONS_DATA
InternalDelete(pPalCriticalSection->DebugInfo);
pPalCriticalSection->DebugInfo = NULL;
}
#endif // _DEBUG
if (PalCsFullyInitialized == pPalCriticalSection->cisInitState)
{
int iRet;
// destroy condition
iRet = pthread_cond_destroy(&pPalCriticalSection->csndNativeData.condition);
_ASSERT_MSG(0 == iRet, "Failed destroying condition in CS @ %p "
"[err=%d]\n", pPalCriticalSection, iRet);
// destroy mutex
iRet = pthread_mutex_destroy(&pPalCriticalSection->csndNativeData.mutex);
_ASSERT_MSG(0 == iRet, "Failed destroying mutex in CS @ %p "
"[err=%d]\n", pPalCriticalSection, iRet);
}
// Reset critical section state
pPalCriticalSection->cisInitState = PalCsNotInitialized;
}
// The following PALCEnterCriticalSection and PALCLeaveCriticalSection
// functions are intended to provide CorUnix's InternalEnterCriticalSection
// and InternalLeaveCriticalSection functionalities to legacy C code,
// which has no knowledge of CPalThread, classes and namespaces.
/*++
Function:
PALCEnterCriticalSection
Provides CorUnix's InternalEnterCriticalSection functionality to legacy C code,
which has no knowledge of CPalThread, classes and namespaces.
--*/
VOID PALCEnterCriticalSection(CRITICAL_SECTION * pcs)
{
CPalThread * pThread =
(PALIsThreadDataInitialized() ? GetCurrentPalThread() : NULL);
CorUnix::InternalEnterCriticalSection(pThread, pcs);
}
/*++
Function:
PALCLeaveCriticalSection
Provides CorUnix's InternalLeaveCriticalSection functionality to legacy C code,
which has no knowledge of CPalThread, classes and namespaces.
--*/
VOID PALCLeaveCriticalSection(CRITICAL_SECTION * pcs)
{
CPalThread * pThread =
(PALIsThreadDataInitialized() ? GetCurrentPalThread() : NULL);
CorUnix::InternalLeaveCriticalSection(pThread, pcs);
}
namespace CorUnix
{
static PalCsWaiterReturnState PALCS_WaitOnCS(
PAL_CRITICAL_SECTION * pPalCriticalSection,
LONG lInc);
static PAL_ERROR PALCS_DoActualWait(PAL_CRITICAL_SECTION * pPalCriticalSection);
static PAL_ERROR PALCS_WakeUpWaiter(PAL_CRITICAL_SECTION * pPalCriticalSection);
static bool PALCS_FullyInitialize(PAL_CRITICAL_SECTION * pPalCriticalSection);
#ifdef _DEBUG
enum CSSubSysInitState
{
CSSubSysNotInitialzed,
CSSubSysInitializing,
CSSubSysInitialized
};
static Volatile<CSSubSysInitState> csssInitState = CSSubSysNotInitialzed;
#ifdef PAL_TRACK_CRITICAL_SECTIONS_DATA
static Volatile<LONG> g_lPALCSInitializeCount = 0;
static Volatile<LONG> g_lPALCSDeleteCount = 0;
static Volatile<LONG> g_lPALCSAcquireCount = 0;
static Volatile<LONG> g_lPALCSEnterCount = 0;
static Volatile<LONG> g_lPALCSContentionCount = 0;
static Volatile<LONG> g_lPALCSInternalInitializeCount = 0;
static Volatile<LONG> g_lPALCSInternalDeleteCount = 0;
static Volatile<LONG> g_lPALCSInternalAcquireCount = 0;
static Volatile<LONG> g_lPALCSInternalEnterCount = 0;
static Volatile<LONG> g_lPALCSInternalContentionCount = 0;
#endif // PAL_TRACK_CRITICAL_SECTIONS_DATA
#endif // _DEBUG
/*++
Function:
CorUnix::CriticalSectionSubSysInitialize
Initializes CS subsystem
--*/
void CriticalSectionSubSysInitialize()
{
static_assert(sizeof(CRITICAL_SECTION) >= sizeof(PAL_CRITICAL_SECTION),
"PAL fatal internal error: sizeof(CRITICAL_SECTION) is "
"smaller than sizeof(PAL_CRITICAL_SECTION)");
#ifdef _DEBUG
LONG lRet = InterlockedCompareExchange((LONG *)&csssInitState,
(LONG)CSSubSysInitializing,
(LONG)CSSubSysNotInitialzed);
if ((LONG)CSSubSysNotInitialzed == lRet)
{
InitializeListHead(&g_PALCSList);
InternalInitializeCriticalSectionAndSpinCount(
reinterpret_cast<CRITICAL_SECTION*>(&g_csPALCSsListLock),
0, true);
InterlockedExchange((LONG *)&csssInitState,
(LONG)CSSubSysInitialized);
}
else
{
while (csssInitState != CSSubSysInitialized)
{
sched_yield();
}
}
#endif // _DEBUG
}
/*++
Function:
CorUnix::InternalInitializeCriticalSectionAndSpinCount
Initializes a CS with the given spin count. If 'fInternal' is true
the CS will be treatead as an internal one for its whole lifetime,
i.e. any thread that will enter it will be marked as unsafe for
suspension as long as it holds the CS
--*/
void InternalInitializeCriticalSectionAndSpinCount(
PCRITICAL_SECTION pCriticalSection,
DWORD dwSpinCount,
bool fInternal)
{
PAL_CRITICAL_SECTION * pPalCriticalSection =
reinterpret_cast<PAL_CRITICAL_SECTION*>(pCriticalSection);
#ifndef PALCS_TRANSFER_OWNERSHIP_ON_RELEASE
// Make sure bits are defined in a usable way
_ASSERTE(PALCS_LOCK_AWAKENED_WAITER * 2 == PALCS_LOCK_WAITER_INC);
#endif // !PALCS_TRANSFER_OWNERSHIP_ON_RELEASE
// Make sure structure sizes are compatible
_ASSERTE(sizeof(CRITICAL_SECTION) >= sizeof(PAL_CRITICAL_SECTION));
#ifdef _DEBUG
if (sizeof(CRITICAL_SECTION) > sizeof(PAL_CRITICAL_SECTION))
{
WARN("PAL_CS_NATIVE_DATA_SIZE appears to be defined to a value (%d) "
"larger than needed on this platform (%d).\n",
sizeof(CRITICAL_SECTION), sizeof(PAL_CRITICAL_SECTION));
}
#endif // _DEBUG
// Init CS data
pPalCriticalSection->DebugInfo = NULL;
pPalCriticalSection->LockCount = 0;
pPalCriticalSection->RecursionCount = 0;
pPalCriticalSection->SpinCount = dwSpinCount;
pPalCriticalSection->OwningThread = NULL;
pPalCriticalSection->LockSemaphore = NULL;
pPalCriticalSection->fInternal = fInternal;
#ifdef _DEBUG
CPalThread * pThread =
(PALIsThreadDataInitialized() ? GetCurrentPalThread() : NULL);
pPalCriticalSection->DebugInfo = InternalNew<CRITICAL_SECTION_DEBUG_INFO>();
_ASSERT_MSG(NULL != pPalCriticalSection->DebugInfo,
"Failed to allocate debug info for new CS\n");
// Init debug info data
pPalCriticalSection->DebugInfo->lAcquireCount = 0;
pPalCriticalSection->DebugInfo->lEnterCount = 0;
pPalCriticalSection->DebugInfo->lContentionCount = 0;
pPalCriticalSection->DebugInfo->pOwnerCS = pPalCriticalSection;
// Insert debug info struct in global list
if (pPalCriticalSection != &g_csPALCSsListLock)
{
InternalEnterCriticalSection(pThread,
reinterpret_cast<CRITICAL_SECTION*>(&g_csPALCSsListLock));
InsertTailList(&g_PALCSList, &pPalCriticalSection->DebugInfo->Link);
InternalLeaveCriticalSection(pThread,
reinterpret_cast<CRITICAL_SECTION*>(&g_csPALCSsListLock));
}
else
{
InsertTailList(&g_PALCSList, &pPalCriticalSection->DebugInfo->Link);
}
#ifdef PAL_TRACK_CRITICAL_SECTIONS_DATA
InterlockedIncrement(fInternal ?
&g_lPALCSInternalInitializeCount : &g_lPALCSInitializeCount);
#endif // PAL_TRACK_CRITICAL_SECTIONS_DATA
#endif // _DEBUG
// Set initializazion state
pPalCriticalSection->cisInitState = PalCsUserInitialized;
#ifdef MUTEX_BASED_CSS
bool fInit;
do
{
fInit = PALCS_FullyInitialize(pPalCriticalSection);
_ASSERTE(fInit);
} while (!fInit && 0 == sched_yield());
if (fInit)
{
// Set initializazion state
pPalCriticalSection->cisInitState = PalCsFullyInitialized;
}
#endif // MUTEX_BASED_CSS
}
#ifndef MUTEX_BASED_CSS
/*++
Function:
CorUnix::InternalEnterCriticalSection
Enters a CS, causing the thread to block if the CS is owned by
another thread
--*/
void InternalEnterCriticalSection(
CPalThread * pThread,
PCRITICAL_SECTION pCriticalSection)
{
PAL_CRITICAL_SECTION * pPalCriticalSection =
reinterpret_cast<PAL_CRITICAL_SECTION*>(pCriticalSection);
LONG lSpinCount;
LONG lVal, lNewVal;
LONG lBitsToChange, lWaitInc;
PalCsWaiterReturnState cwrs;
SIZE_T threadId;
_ASSERTE(PalCsNotInitialized != pPalCriticalSection->cisInitState);
threadId = ObtainCurrentThreadId(pThread);
// Check if the current thread already owns the CS
//
// Note: there is no need for this double check to be atomic. In fact
// if the first check fails, the second doesn't count (and it's not
// even executed). If the first one succeeds and the second one
// doesn't, it doesn't matter if LockCount has already changed by the
// time OwningThread is tested. Instead, if the first one succeeded,
// and the second also succeeds, LockCount cannot have changed in the
// meanwhile, since this is the owning thread and only the owning
// thread can change the lock bit when the CS is owned.
if ((pPalCriticalSection->LockCount & PALCS_LOCK_BIT) &&
(pPalCriticalSection->OwningThread == threadId))
{
pPalCriticalSection->RecursionCount += 1;
#ifdef _DEBUG
if (NULL != pPalCriticalSection->DebugInfo)
{
pPalCriticalSection->DebugInfo->lEnterCount += 1;
}
#endif // _DEBUG
goto IECS_exit;
}
// Set bits to change and waiter increment for an incoming thread
lBitsToChange = PALCS_LOCK_BIT;
lWaitInc = PALCS_LOCK_WAITER_INC;
lSpinCount = pPalCriticalSection->SpinCount;
while (TRUE)
{
// Either this is an incoming thread, and therefore lBitsToChange
// is just PALCS_LOCK_BIT, or this is an awakened waiter
_ASSERTE(PALCS_LOCK_BIT == lBitsToChange ||
(PALCS_LOCK_BIT | PALCS_LOCK_AWAKENED_WAITER) == lBitsToChange);
// Make sure the waiter increment is in a valid range
_ASSERTE(PALCS_LOCK_WAITER_INC == lWaitInc ||
PALCS_LOCK_AWAKENED_WAITER == lWaitInc);
do {
lVal = pPalCriticalSection->LockCount;
while (0 == (lVal & PALCS_LOCK_BIT))
{
// CS is not locked: try lo lock it
// Make sure that whether we are an incoming thread
// or the PALCS_LOCK_AWAKENED_WAITER bit is set
_ASSERTE((PALCS_LOCK_BIT == lBitsToChange) ||
(PALCS_LOCK_AWAKENED_WAITER & lVal));
lNewVal = lVal ^ lBitsToChange;
// Make sure we are actually trying to lock
_ASSERTE(lNewVal & PALCS_LOCK_BIT);
CS_TRACE("[ECS %p] Switching from {%d, %d, %d} to "
"{%d, %d, %d} ==>\n", pPalCriticalSection,
PALCS_GETWCOUNT(lVal), PALCS_GETAWBIT(lVal), PALCS_GETLBIT(lVal),
PALCS_GETWCOUNT(lNewVal), PALCS_GETAWBIT(lNewVal), PALCS_GETLBIT(lNewVal));
// Try to switch the value
lNewVal = InterlockedCompareExchange (&pPalCriticalSection->LockCount,
lNewVal, lVal);
CS_TRACE("[ECS %p] ==> %s LockCount={%d, %d, %d} "
"lVal={%d, %d, %d}\n", pPalCriticalSection,
(lNewVal == lVal) ? "OK" : "NO",
PALCS_GETWCOUNT(pPalCriticalSection->LockCount),
PALCS_GETAWBIT(pPalCriticalSection->LockCount),
PALCS_GETLBIT(pPalCriticalSection->LockCount),
PALCS_GETWCOUNT(lVal), PALCS_GETAWBIT(lVal), PALCS_GETLBIT(lVal));
if (lNewVal == lVal)
{
// CS successfully acquired
goto IECS_set_ownership;
}
// Acquisition failed, some thread raced with us;
// update value for next loop
lVal = lNewVal;
}
if (0 < lSpinCount)
{
sched_yield();
}
} while (0 <= --lSpinCount);
cwrs = PALCS_WaitOnCS(pPalCriticalSection, lWaitInc);
if (PalCsReturnWaiterAwakened == cwrs)
{
#ifdef PALCS_TRANSFER_OWNERSHIP_ON_RELEASE
//
// Fair Critical Sections
//
// In the fair lock case, when a waiter wakes up the CS
// must be locked (i.e. ownership passed on to the waiter)
_ASSERTE(0 != (PALCS_LOCK_BIT & pPalCriticalSection->LockCount));
// CS successfully acquired
goto IECS_set_ownership;
#else // PALCS_TRANSFER_OWNERSHIP_ON_RELEASE
//
// Unfair Critical Sections
//
_ASSERTE(PALCS_LOCK_AWAKENED_WAITER & pPalCriticalSection->LockCount);
lBitsToChange = PALCS_LOCK_BIT | PALCS_LOCK_AWAKENED_WAITER;
lWaitInc = PALCS_LOCK_AWAKENED_WAITER;
#endif // PALCS_TRANSFER_OWNERSHIP_ON_RELEASE
}
}
IECS_set_ownership:
// Critical section acquired: set ownership data
pPalCriticalSection->OwningThread = threadId;
pPalCriticalSection->RecursionCount = 1;
#ifdef _DEBUG
if (NULL != pPalCriticalSection->DebugInfo)
{
pPalCriticalSection->DebugInfo->lAcquireCount += 1;
pPalCriticalSection->DebugInfo->lEnterCount += 1;
}
#endif // _DEBUG
IECS_exit:
return;
}
/*++
Function:
CorUnix::InternalLeaveCriticalSection
Leaves a currently owned CS
--*/
void InternalLeaveCriticalSection(CPalThread * pThread,
PCRITICAL_SECTION pCriticalSection)
{
PAL_CRITICAL_SECTION * pPalCriticalSection =
reinterpret_cast<PAL_CRITICAL_SECTION*>(pCriticalSection);
LONG lVal, lNewVal;
#ifdef _DEBUG
SIZE_T threadId;
_ASSERTE(PalCsNotInitialized != pPalCriticalSection->cisInitState);
threadId = ObtainCurrentThreadId(pThread);
_ASSERTE(threadId == pPalCriticalSection->OwningThread);
#endif // _DEBUG
_ASSERT_MSG(PALCS_LOCK_BIT & pPalCriticalSection->LockCount,
"Trying to release an unlocked CS\n");
_ASSERT_MSG(0 < pPalCriticalSection->RecursionCount,
"Trying to release an unlocked CS\n");
if (--pPalCriticalSection->RecursionCount > 0)
{
// Recursion was > 1, still owning the CS
goto ILCS_cs_exit;
}
// Reset CS ownership
pPalCriticalSection->OwningThread = NULL;
// Load the current LockCount value
lVal = pPalCriticalSection->LockCount;
while (true)
{
_ASSERT_MSG(0 != (PALCS_LOCK_BIT & lVal),
"Trying to release an unlocked CS\n");
// NB: In the fair lock case (PALCS_TRANSFER_OWNERSHIP_ON_RELEASE) the
// PALCS_LOCK_AWAKENED_WAITER bit is not used
if ( (PALCS_LOCK_BIT == lVal)
#ifndef PALCS_TRANSFER_OWNERSHIP_ON_RELEASE
|| (PALCS_LOCK_AWAKENED_WAITER & lVal)
#endif // !PALCS_TRANSFER_OWNERSHIP_ON_RELEASE
)
{
// Whether there are no waiters (PALCS_LOCK_BIT == lVal)
// or a waiter has already been awakened, therefore we
// just need to reset the lock bit and return
lNewVal = lVal & ~PALCS_LOCK_BIT;
CS_TRACE("[LCS-UN %p] Switching from {%d, %d, %d} to "
"{%d, %d, %d} ==>\n", pPalCriticalSection,
PALCS_GETWCOUNT(lVal), PALCS_GETAWBIT(lVal), PALCS_GETLBIT(lVal),
PALCS_GETWCOUNT(lNewVal), PALCS_GETAWBIT(lNewVal), PALCS_GETLBIT(lNewVal));
lNewVal = InterlockedCompareExchange(&pPalCriticalSection->LockCount,
lNewVal, lVal);
CS_TRACE("[LCS-UN %p] ==> %s\n", pPalCriticalSection,
(lNewVal == lVal) ? "OK" : "NO");
if (lNewVal == lVal)
{
goto ILCS_cs_exit;
}
}
else
{
// There is at least one waiter, we need to wake it up
#ifdef PALCS_TRANSFER_OWNERSHIP_ON_RELEASE
// Fair lock case: passing ownership on to the first waiter.
// Here we need only to decrement the waiters count. CS will
// remain locked and ownership will be passed to the waiter,
// which will take care of setting ownership data as soon as
// it wakes up
lNewVal = lVal - PALCS_LOCK_WAITER_INC;
#else // PALCS_TRANSFER_OWNERSHIP_ON_RELEASE
// Unfair lock case: we need to atomically decrement the waiters
// count (we are about ot wake up one of them), set the
// "waiter awakened" bit and to reset the "CS locked" bit.
// Note that, since we know that at this time PALCS_LOCK_BIT
// is set and PALCS_LOCK_AWAKENED_WAITER is not set, none of
// the addenda will affect bits other than its target bit(s),
// i.e. PALCS_LOCK_BIT will not affect PALCS_LOCK_AWAKENED_WAITER,
// PALCS_LOCK_AWAKENED_WAITER will not affect the actual
// count of waiters, and the latter will not change the two
// former ones
lNewVal = lVal - PALCS_LOCK_WAITER_INC +
PALCS_LOCK_AWAKENED_WAITER - PALCS_LOCK_BIT;
#endif // PALCS_TRANSFER_OWNERSHIP_ON_RELEASE
CS_TRACE("[LCS-CN %p] Switching from {%d, %d, %d} to {%d, %d, %d} ==>\n",
pPalCriticalSection,
PALCS_GETWCOUNT(lVal), PALCS_GETAWBIT(lVal), PALCS_GETLBIT(lVal),
PALCS_GETWCOUNT(lNewVal), PALCS_GETAWBIT(lNewVal), PALCS_GETLBIT(lNewVal));
lNewVal = InterlockedCompareExchange(&pPalCriticalSection->LockCount,
lNewVal, lVal);
CS_TRACE("[LCS-CN %p] ==> %s\n", pPalCriticalSection,
(lNewVal == lVal) ? "OK" : "NO");
if (lNewVal == lVal)
{
// Wake up the waiter
PALCS_WakeUpWaiter (pPalCriticalSection);
#ifdef PALCS_TRANSFER_OWNERSHIP_ON_RELEASE
// In the fair lock case, we need to yield here to defeat
// the inherently unfair nature of the condition/predicate
// construct
sched_yield();
#endif // PALCS_TRANSFER_OWNERSHIP_ON_RELEASE
goto ILCS_cs_exit;
}
}
// CS unlock failed due to race with another thread trying to
// register as waiter on it. We need to keep on looping. We
// intentionally do not yield here in order to reserve higher
// priority for the releasing thread.
//
// At this point lNewVal contains the latest LockCount value
// retrieved by one of the two InterlockedCompareExchange above;
// we can use this value as expected LockCount for the next loop,
// without the need to fetch it again.
lVal = lNewVal;
}
ILCS_cs_exit:
return;
}
/*++
Function:
CorUnix::InternalTryEnterCriticalSection
Tries to acquire a CS. It returns true on success, false if the CS is
locked by another thread
--*/
bool InternalTryEnterCriticalSection(
CPalThread * pThread,
PCRITICAL_SECTION pCriticalSection)
{
PAL_CRITICAL_SECTION * pPalCriticalSection =
reinterpret_cast<PAL_CRITICAL_SECTION*>(pCriticalSection);
LONG lNewVal;