summaryrefslogtreecommitdiff
path: root/src/pal/src/synchmgr/synchmanager.hpp
blob: fdef82e936a4900a7b3a8a2c12a4087c5cdacb01 (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
// 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.

/*++



Module Name:

    synchmanager.hpp

Abstract:
    Private header file for synchronization manager and 
    controllers implementation



--*/
#ifndef _SYNCHMANAGER_HPP_
#define _SYNCHMANAGER_HPP_

#include "pal/synchobjects.hpp"
#include "pal/synchcache.hpp"
#include "pal/cs.hpp"
#include "pal/corunix.hpp"
#include "pal/thread.hpp"
#include "pal/procobj.hpp"
#include "pal/init.h"
#include "pal/process.h"

#include <sys/types.h>
#include <unistd.h>
#if HAVE_KQUEUE
#include <sys/event.h>
#endif // HAVE_KQUEUE
#include "pal/dbgmsg.h"

#ifdef _DEBUG
// #define SYNCH_OBJECT_VALIDATION
// #define SYNCH_STATISTICS
#endif

#ifdef SYNCH_OBJECT_VALIDATION
#define VALIDATEOBJECT(obj) ((obj)->ValidateObject())
#else
#define VALIDATEOBJECT(obj)
#endif

namespace CorUnix
{
    const DWORD WTLN_FLAG_OWNER_OBJECT_IS_SHARED                 = 1<<0;
    const DWORD WTLN_FLAG_WAIT_ALL                               = 1<<1;
    const DWORD WTLN_FLAG_DELEGATED_OBJECT_SIGNALING_IN_PROGRESS = 1<<2;

#ifdef SYNCH_OBJECT_VALIDATION
    const DWORD HeadSignature  = 0x48454144;
    const DWORD TailSignature  = 0x5441494C;
    const DWORD EmptySignature = 0xBAADF00D;
#endif

    enum THREAD_WAIT_STATE
    {
        TWS_ACTIVE,
        TWS_WAITING,
        TWS_ALERTABLE,
        TWS_EARLYDEATH,
    };

    enum WaitCompletionState
    {
        WaitIsNotSatisfied,
        WaitIsSatisfied,
        WaitMayBeSatisfied
    };

    typedef union _SynchDataGenrPtr
    {
        SharedID shrid;
        CSynchData * ptr;
    } SynchDataGenrPtr;

    typedef union _WTLNodeGenrPtr
    {
        SharedID shrid;
        struct _WaitingThreadsListNode * ptr;
    } WTLNodeGenrPtr;

    typedef struct _WaitingThreadsListNode
    {
#ifdef SYNCH_OBJECT_VALIDATION
        DWORD dwDebugHeadSignature;
#endif
        WTLNodeGenrPtr ptrNext;
        WTLNodeGenrPtr ptrPrev;
        SharedID shridSHRThis;

        // Data
        DWORD dwThreadId;
        DWORD dwProcessId;
        DWORD dwObjIndex;
        DWORD dwFlags;

        // Pointers to related objects
        SharedID shridWaitingState; 
        SynchDataGenrPtr ptrOwnerObjSynchData;
        struct _ThreadWaitInfo * ptwiWaitInfo;  // valid only in the 
                                                // target process
#ifdef SYNCH_OBJECT_VALIDATION
        _WaitingThreadsListNode();
        ~_WaitingThreadsListNode();
        void ValidateObject(void);
        void ValidateEmptyObject(void);
        void InvalidateObject(void);

        DWORD dwDebugTailSignature;
#endif
    } WaitingThreadsListNode;

    typedef struct _DeferredSignalingListNode
    {
        LIST_ENTRY Link;
        CPalThread * pthrTarget;
    } DeferredSignalingListNode;

    typedef struct _OwnedObjectsListNode
    {
        LIST_ENTRY Link;
        CSynchData * pPalObjSynchData;
    } OwnedObjectsListNode;

    typedef struct _ThreadApcInfoNode
    {
        struct _ThreadApcInfoNode * pNext;
        PAPCFUNC pfnAPC;
        ULONG_PTR pAPCData;
    } ThreadApcInfoNode;

    class CPalSynchronizationManager; // fwd declaration
    class CProcProcessLocalData;      // fwd declaration

    class CSynchData
    {
#ifdef SYNCH_OBJECT_VALIDATION
        DWORD m_dwDebugHeadSignature;
#endif
        // NB: For perforformance purposes this class is supposed
        //     to have no virtual methods, and no destructor.

        WTLNodeGenrPtr  m_ptrWTLHead;
        WTLNodeGenrPtr  m_ptrWTLTail;
        ULONG m_ulcWaitingThreads;
        SharedID m_shridThis;
        ObjectDomain m_odObjectDomain; 
        PalObjectTypeId m_otiObjectTypeId;
        LONG  m_lRefCount;
        LONG  m_lSignalCount;

        // Ownership data
        LONG  m_lOwnershipCount;
        DWORD m_dwOwnerPid;
        DWORD m_dwOwnerTid; // used only by remote processes
                            // (thread ids may be recycled)
        CPalThread * m_pOwnerThread; // valid only on the target process
        OwnedObjectsListNode * m_poolnOwnedObjectListNode;
        bool m_fAbandoned;

#ifdef SYNCH_STATISTICS
        ULONG m_lStatWaitCount;
        ULONG m_lStatContentionCount;
#endif

    public:
        CSynchData() 
            : m_ulcWaitingThreads(0), m_shridThis(NULLSharedID), m_lRefCount(1),
              m_lSignalCount(0), m_lOwnershipCount(0), m_dwOwnerPid(0),
              m_dwOwnerTid(0), m_pOwnerThread(NULL), 
              m_poolnOwnedObjectListNode(NULL), m_fAbandoned(false)
        { 
            // m_ptrWTLHead, m_ptrWTLTail, m_odObjectDomain 
            // and m_otiObjectTypeId are initialized by
            // CPalSynchronizationManager::AllocateObjectSynchData
#ifdef SYNCH_STATISTICS
            m_lStatWaitCount = 0;
            m_lStatContentionCount = 0;
#endif
#ifdef SYNCH_OBJECT_VALIDATION
            ValidateEmptyObject();
            m_dwDebugHeadSignature = HeadSignature;;
            m_dwDebugTailSignature = TailSignature;
#endif
        }

        LONG AddRef()
        {
            return InterlockedIncrement(&m_lRefCount); 
        }

        LONG Release(CPalThread * pthrCurrent);

        bool CanWaiterWaitWithoutBlocking(
            CPalThread * pWaiterThread,
            bool * pfAbandoned);

        PAL_ERROR ReleaseWaiterWithoutBlocking(
            CPalThread * pthrCurrent,
            CPalThread * pthrTarget);

        void WaiterEnqueue(WaitingThreadsListNode * pwtlnNewNode);
        void SharedWaiterEnqueue(SharedID shridNewNode);

        // Object Domain accessor methods
        ObjectDomain GetObjectDomain(void)
        {
            return m_odObjectDomain;
        }
        void SetObjectDomain(ObjectDomain odObjectDomain)
        {
            m_odObjectDomain = odObjectDomain;
        }

        // Object Type accessor methods
        CObjectType * GetObjectType(void)
        {
            return CObjectType::GetObjectTypeById(m_otiObjectTypeId);
        }
        PalObjectTypeId GetObjectTypeId(void)
        {
            return m_otiObjectTypeId;
        }
        void SetObjectType(CObjectType * pot)
        {
            m_otiObjectTypeId = pot->GetId();
        }
        void SetObjectType(PalObjectTypeId oti)
        {
            m_otiObjectTypeId = oti;
        }

        // Object shared 'this' pointer accessor methods
        SharedID GetSharedThis (void)
        {
            return m_shridThis;
        }
        void SetSharedThis (SharedID shridThis)
        {
            m_shridThis = shridThis;
        }

        void Signal(
            CPalThread * pthrCurrent, 
            LONG lSignalCount, 
            bool fWorkerThread);

        bool ReleaseFirstWaiter(
            CPalThread * pthrCurrent,
            bool * pfDelegated,
            bool fWorkerThread);

        LONG ReleaseAllLocalWaiters(
            CPalThread * pthrCurrent);

        WaitCompletionState IsRestOfWaitAllSatisfied(
            WaitingThreadsListNode * pwtlnNode);

        // Object signal count accessor methods
        LONG GetSignalCount(void) 
        {
            _ASSERTE(m_lSignalCount >= 0);
            return m_lSignalCount; 
        }
        void SetSignalCount(LONG lSignalCount) 
        { 
            _ASSERTE(m_lSignalCount >= 0);
            _ASSERTE(lSignalCount >= 0);
            m_lSignalCount = lSignalCount; 
        }
        LONG DecrementSignalCount(void) 
        {
            _ASSERTE(m_lSignalCount > 0);
            return --m_lSignalCount; 
        }

        // Object ownership accessor methods
        void SetOwner(CPalThread * pOwnerThread);
        void ResetOwnership(void);
        PAL_ERROR AssignOwnershipToThread(
            CPalThread * pthrCurrent,
            CPalThread * pthrTarget);
        DWORD GetOwnerProcessID(void) 
        { 
            return m_dwOwnerPid; 
        }
        DWORD GetOwnerThreadID(void) 
        { 
            return m_dwOwnerTid; 
        }
        CPalThread * GetOwnerThread(void) 
        { 
            return m_pOwnerThread; 
        }
        OwnedObjectsListNode * GetOwnershipListNode(void)
        {
            return m_poolnOwnedObjectListNode;
        }
        void SetOwnershipListNode(OwnedObjectsListNode * pooln)
        {
            m_poolnOwnedObjectListNode = pooln;
        }

        // Object ownership count accessor methods
        LONG GetOwnershipCount(void) 
        { 
            return m_lOwnershipCount; 
        }
        void SetOwnershipCount(LONG lOwnershipCount) 
        { 
            m_lOwnershipCount = lOwnershipCount;
        }

        // Object abandoned flag accessor methods
        void SetAbandoned(bool fAbandoned) 
                                    { m_fAbandoned = fAbandoned; }
        bool IsAbandoned(void) { return m_fAbandoned; }

        void IncrementWaitingThreadCount(void)
        {
            m_ulcWaitingThreads += 1;
        }
        void DecrementWaitingThreadCount(void)
        {
            m_ulcWaitingThreads -= 1;
        }
        ULONG GetWaitingThreadCount(void)
        {
            return m_ulcWaitingThreads;
        }


#ifdef SYNCH_STATISTICS
        void IncrementStatWaitCount(void)
        {
            m_lStatWaitCount++;
        }
        LONG GetStatWaitCount(void)
        {
            return m_lStatWaitCount;
        }
        void IncrementStatContentionCount(void)
        {
            m_lStatContentionCount++;
        }
        LONG GetStatContentionCount(void)
        {
            return m_lStatContentionCount;
        }
#endif
        //
        // Wating threads list access methods
        //
        WaitingThreadsListNode * GetWTLHeadPtr(void) 
        { 
            return m_ptrWTLHead.ptr; 
        }
        WaitingThreadsListNode * GetWTLTailPtr(void) 
        { 
            return m_ptrWTLTail.ptr; 
        }
        SharedID GetWTLHeadShmPtr(void) 
        { 
            return m_ptrWTLHead.shrid; 
        }
        SharedID GetWTLTailShmPtr(void) 
        { 
            return m_ptrWTLTail.shrid; 
        }
        void SetWTLHeadPtr(WaitingThreadsListNode * p) 
        { 
            m_ptrWTLHead.ptr = p; 
        }
        void SetWTLTailPtr(WaitingThreadsListNode * p) 
        { 
            m_ptrWTLTail.ptr = p; 
        }
        void SetWTLHeadShrPtr(SharedID shrid) 
        { 
            m_ptrWTLHead.shrid = shrid; 
        }
        void SetWTLTailShrPtr(SharedID shrid) 
        { 
            m_ptrWTLTail.shrid = shrid; 
        }
#ifdef SYNCH_OBJECT_VALIDATION
        ~CSynchData();
        void ValidateObject(bool fDestructor = false);
        void ValidateEmptyObject(void);
        void InvalidateObject(void);

        DWORD m_dwDebugTailSignature;
#endif
    };

    
    class CSynchControllerBase
    {
        friend class CPalSynchronizationManager;

        // NB: For perforformance purposes this class is supposed
        //     to have no virtual methods, contructor and 
        //     destructor
    public:
        enum ControllerType { WaitController, StateController };

    protected:
        CPalThread * m_pthrOwner;
        ControllerType m_ctCtrlrType;
        ObjectDomain m_odObjectDomain;
        CObjectType * m_potObjectType;
        CSynchData * m_psdSynchData;
        WaitDomain m_wdWaitDomain;
             
        PAL_ERROR Init(
            CPalThread * pthrCurrent,
            ControllerType ctCtrlrType,
            ObjectDomain odObjectDomain,
            CObjectType *potObjectType,
            CSynchData * psdSynchData,
            WaitDomain wdWaitDomain);
        
        void Release(void);

        void SetSynchData(CSynchData * psdSynchData) 
        { 
            m_psdSynchData = psdSynchData; 
        }
        CSynchData * GetSynchData() 
        { 
            return m_psdSynchData; 
        }
    };
        
    class CSynchWaitController : public CSynchControllerBase, 
                                 public ISynchWaitController
    {
        // Per-object-type specific data
        //
        // Process (otiProcess)
        IPalObject *m_pProcessObject; // process that owns m_pProcLocalData, this is stored without a reference
        CProcProcessLocalData * m_pProcLocalData;
        
    public:
        CSynchWaitController() : m_pProcessObject(NULL), m_pProcLocalData(NULL) {}
        virtual ~CSynchWaitController() = default;
        
        //
        // ISynchWaitController methods
        //
        virtual PAL_ERROR CanThreadWaitWithoutBlocking(
            bool * pfCanWaitWithoutBlocking,
            bool * pfAbandoned);
        
        virtual PAL_ERROR ReleaseWaitingThreadWithoutBlocking(void);
        
        virtual PAL_ERROR RegisterWaitingThread(
            WaitType wtWaitType,
            DWORD dwIndex,
            bool fAlertable);

        virtual void ReleaseController(void);

        CProcProcessLocalData * GetProcessLocalData(void);

        void SetProcessData(IPalObject* pProcessObject, CProcProcessLocalData * pProcLocalData);
    };  

    class CSynchStateController : public CSynchControllerBase, 
                                  public ISynchStateController
    {
    public:
        // NB: For perforformance purposes this class is supposed
        //     to have no constructor
        virtual ~CSynchStateController() = default;

        //
        // ISynchStateController methods
        //
        virtual PAL_ERROR GetSignalCount(LONG *plSignalCount);
        virtual PAL_ERROR SetSignalCount(LONG lNewCount);
        virtual PAL_ERROR IncrementSignalCount(LONG lAmountToIncrement);
        virtual PAL_ERROR DecrementSignalCount(LONG lAmountToDecrement);
        virtual PAL_ERROR SetOwner(CPalThread *pNewOwningThread);
        virtual PAL_ERROR DecrementOwnershipCount(void);
        virtual void ReleaseController(void);
    };    
    
    class CPalSynchronizationManager : public IPalSynchronizationManager
    {
        friend class CPalSynchMgrController;
        template <class T> friend T *CorUnix::InternalNew();

    public:
        // types
        typedef CSynchCache<CSynchWaitController>      CSynchWaitControllerCache;
        typedef CSynchCache<CSynchStateController>     CSynchStateControllerCache;
        typedef CSynchCache<CSynchData>                CSynchDataCache;
        typedef CSHRSynchCache<CSynchData>             CSHRSynchDataCache;
        typedef CSynchCache<WaitingThreadsListNode>    CWaitingThreadsListNodeCache;
        typedef CSHRSynchCache<WaitingThreadsListNode> CSHRWaitingThreadsListNodeCache;
        typedef CSynchCache<ThreadApcInfoNode>         CThreadApcInfoNodeCache;
        typedef CSynchCache<OwnedObjectsListNode>      COwnedObjectsListNodeCache;

    private:
        // types
        enum InitStatus 
        { 
            SynchMgrStatusIdle, 
            SynchMgrStatusInitializing, 
            SynchMgrStatusRunning, 
            SynchMgrStatusShuttingDown,
            SynchMgrStatusReadyForProcessShutDown,
            SynchMgrStatusError 
        };  
        enum SynchWorkerCmd 
        { 
            SynchWorkerCmdNop,
            SynchWorkerCmdRemoteSignal,
            SynchWorkerCmdDelegatedObjectSignaling,
            SynchWorkerCmdShutdown,
            SynchWorkerCmdTerminationRequest,
            SynchWorkerCmdLast
        };

        typedef struct _MonitoredProcessesListNode
        {
            struct _MonitoredProcessesListNode * pNext;
            LONG lRefCount;
            CSynchData * psdSynchData;
            DWORD dwPid;
            DWORD dwExitCode;
            bool fIsActualExitCode;

            // Object that owns pProcLocalData. This is stored, with a reference, to 
            // ensure that pProcLocalData is not deleted.
            IPalObject *pProcessObject;
            CProcProcessLocalData * pProcLocalData;
        } MonitoredProcessesListNode;

        // constants
        static const int CtrlrsCacheMaxSize                = 256;
        static const int SynchDataCacheMaxSize             = 256;
        static const int WTListNodeCacheMaxSize            = 256;
        static const int ApcInfoNodeCacheMaxSize           = 32;
        static const int OwnedObjectsListCacheMaxSize      = 16;
        static const int MaxWorkerConsecutiveEintrs        = 128;
        static const int MaxConsecutiveEagains             = 128;
        static const int WorkerThreadProcMonitoringTimeout = 250;  // ms
        static const int WorkerThreadShuttingDownTimeout   = 1000; // ms
        static const int WorkerCmdCompletionTimeout        = 250;  // ms
        static const DWORD SecondNativeWaitTimeout         = INFINITE;
        static const DWORD WorkerThreadTerminationTimeout  = 2000; // ms

        // static members
        static CPalSynchronizationManager * s_pObjSynchMgr;        
        static Volatile<LONG>               s_lInitStatus;
        static CRITICAL_SECTION             s_csSynchProcessLock;
        static CRITICAL_SECTION             s_csMonitoredProcessesLock;
        
        // members        
        DWORD                           m_dwWorkerThreadTid;
        IPalObject *                    m_pipoThread;
        CPalThread *                    m_pthrWorker;
        int                             m_iProcessPipeRead;
        int                             m_iProcessPipeWrite;
#if HAVE_KQUEUE
        int                             m_iKQueue;
        struct kevent                   m_keProcessPipeEvent;
#endif // HAVE_KQUEUE

        MonitoredProcessesListNode *    m_pmplnMonitoredProcesses;
        LONG                            m_lMonitoredProcessesCount;
        MonitoredProcessesListNode *    m_pmplnExitedNodes;

        // caches
        CSynchWaitControllerCache       m_cacheWaitCtrlrs;
        CSynchStateControllerCache      m_cacheStateCtrlrs;
        CSynchDataCache                 m_cacheSynchData;
        CSHRSynchDataCache              m_cacheSHRSynchData;
        CWaitingThreadsListNodeCache    m_cacheWTListNodes;
        CSHRWaitingThreadsListNodeCache m_cacheSHRWTListNodes;
        CThreadApcInfoNodeCache         m_cacheThreadApcInfoNodes;
        COwnedObjectsListNodeCache      m_cacheOwnedObjectsListNodes;

        // static methods
        static PAL_ERROR Initialize();
        static DWORD PALAPI WorkerThread(LPVOID pArg);

    protected:
        CPalSynchronizationManager();

        PAL_ERROR GetSynchControllersForObjects(
            CPalThread *pthrCurrent,
            IPalObject *rgObjects[],
            DWORD dwObjectCount,
            void ** ppvControllers,
            CSynchControllerBase::ControllerType ctCtrlrType);

    private:
        static IPalSynchronizationManager * CreatePalSynchronizationManager();
        static PAL_ERROR StartWorker(CPalThread * pthrCurrent);
        static PAL_ERROR PrepareForShutdown(void);

    public:
        virtual ~CPalSynchronizationManager();

        static CPalSynchronizationManager * GetInstance(void)
        { 
            // No need here to check for NULL and in case create the 
            // singleton, since its creation is enforced by the PAL 
            // initialization code.
            return s_pObjSynchMgr; 
        }

        //
        // Inline utility methods
        //
        static void AcquireLocalSynchLock(CPalThread * pthrCurrent)
        { 
            _ASSERTE(0 <= pthrCurrent->synchronizationInfo.m_lLocalSynchLockCount);
            
            if (1 == ++pthrCurrent->synchronizationInfo.m_lLocalSynchLockCount)
            {
                InternalEnterCriticalSection(pthrCurrent, &s_csSynchProcessLock);
            }
        }
        static void ReleaseLocalSynchLock(CPalThread * pthrCurrent) 
        {
            _ASSERTE(0 < pthrCurrent->synchronizationInfo.m_lLocalSynchLockCount);
            if (0 == --pthrCurrent->synchronizationInfo.m_lLocalSynchLockCount)
            {
                InternalLeaveCriticalSection(pthrCurrent, &s_csSynchProcessLock);
                
#if SYNCHMGR_SUSPENSION_SAFE_CONDITION_SIGNALING
                pthrCurrent->synchronizationInfo.RunDeferredThreadConditionSignalings();
#endif // SYNCHMGR_SUSPENSION_SAFE_CONDITION_SIGNALING
            }
        }
        static LONG ResetLocalSynchLock(CPalThread * pthrCurrent) 
        {
            LONG lRet = pthrCurrent->synchronizationInfo.m_lLocalSynchLockCount;

            _ASSERTE(0 <= lRet);
            if (0 < lRet)
            {
                pthrCurrent->synchronizationInfo.m_lLocalSynchLockCount = 0;
                InternalLeaveCriticalSection(pthrCurrent, &s_csSynchProcessLock);

#if SYNCHMGR_SUSPENSION_SAFE_CONDITION_SIGNALING
                pthrCurrent->synchronizationInfo.RunDeferredThreadConditionSignalings();
#endif // SYNCHMGR_SUSPENSION_SAFE_CONDITION_SIGNALING
            }
            return lRet;
        }
        static LONG GetLocalSynchLockCount(CPalThread * pthrCurrent) 
        {
            _ASSERTE(0 <= pthrCurrent->synchronizationInfo.m_lLocalSynchLockCount);
            return pthrCurrent->synchronizationInfo.m_lLocalSynchLockCount;
        }

        static void AcquireSharedSynchLock(CPalThread * pthrCurrent)
        {   
            _ASSERTE(0 <= pthrCurrent->synchronizationInfo.m_lSharedSynchLockCount);
            _ASSERT_MSG(0 < pthrCurrent->synchronizationInfo.m_lLocalSynchLockCount,
                "The local synch lock should be acquired before grabbing the "
                "shared one.\n");
            if (1 == ++pthrCurrent->synchronizationInfo.m_lSharedSynchLockCount)
            {
                SHMLock();
            }
        } 
        static void ReleaseSharedSynchLock(CPalThread * pthrCurrent) 
        {
            _ASSERTE(0 < pthrCurrent->synchronizationInfo.m_lSharedSynchLockCount);
            if (0 == --pthrCurrent->synchronizationInfo.m_lSharedSynchLockCount)
            {
                _ASSERT_MSG(0 < pthrCurrent->synchronizationInfo.m_lLocalSynchLockCount,
                    "Final release of the shared synch lock while not holding the "
                    "local one. Local synch lock should always be acquired first and "
                    "released last.\n");                
                SHMRelease();
            }                
        }
        static LONG ResetSharedSynchLock(CPalThread * pthrCurrent) 
        {   
            LONG lRet = pthrCurrent->synchronizationInfo.m_lSharedSynchLockCount;

            _ASSERTE(0 <= lRet);
            _ASSERTE(0 == lRet || 
                     0 < pthrCurrent->synchronizationInfo.m_lLocalSynchLockCount);
            if (0 < lRet)
            {
                pthrCurrent->synchronizationInfo.m_lSharedSynchLockCount = 0;
                SHMRelease();
            }
            return lRet;
        }
        static LONG GetSharedSynchLockCount(CPalThread * pthrCurrent) 
        {
            _ASSERTE(0 <= pthrCurrent->synchronizationInfo.m_lSharedSynchLockCount);
            _ASSERTE(0 == pthrCurrent->synchronizationInfo.m_lSharedSynchLockCount || 
                     0 < pthrCurrent->synchronizationInfo.m_lLocalSynchLockCount);
            return pthrCurrent->synchronizationInfo.m_lSharedSynchLockCount;
        }

        CSynchWaitController * CacheGetWaitCtrlr(CPalThread * pthrCurrent)
        { 
            return m_cacheWaitCtrlrs.Get(pthrCurrent); 
        }
        int CacheGetWaitCtrlr(
            CPalThread * pthrCurrent, 
            int n, 
            CSynchWaitController * prgCtrlrs[])
        { 
            return m_cacheWaitCtrlrs.Get(pthrCurrent, n, prgCtrlrs); 
        }
        void CacheAddWaitCtrlr(
            CPalThread * pthrCurrent, 
            CSynchWaitController * pCtrlr) 
        { 
            m_cacheWaitCtrlrs.Add(pthrCurrent, pCtrlr); 
        }            
        CSynchStateController * CacheGetStateCtrlr(CPalThread * pthrCurrent)
        { 
            return m_cacheStateCtrlrs.Get(pthrCurrent); 
        }
        int CacheGetStateCtrlr(
            CPalThread * pthrCurrent,
            int n, 
            CSynchStateController * prgCtrlrs[]) 
        { 
            return m_cacheStateCtrlrs.Get(pthrCurrent, n, prgCtrlrs); 
        }
        void CacheAddStateCtrlr(
            CPalThread * pthrCurrent, 
            CSynchStateController * pCtrlr) 
        { 
            m_cacheStateCtrlrs.Add(pthrCurrent, pCtrlr); 
        }

        CSynchData * CacheGetLocalSynchData(CPalThread * pthrCurrent)            
        { 
            return m_cacheSynchData.Get(pthrCurrent); 
        }
        void CacheAddLocalSynchData(
            CPalThread * pthrCurrent,
            CSynchData * psdSynchData) 
        { 
            m_cacheSynchData.Add(pthrCurrent, psdSynchData); 
        }
        SharedID CacheGetSharedSynchData(CPalThread * pthrCurrent) 
        { 
            return m_cacheSHRSynchData.Get(pthrCurrent); 
        }
        void CacheAddSharedSynchData(
            CPalThread * pthrCurrent,
            SharedID shridSData) 
        { 
            m_cacheSHRSynchData.Add(pthrCurrent, shridSData); 
        }

        WaitingThreadsListNode * CacheGetLocalWTListNode(
            CPalThread * pthrCurrent)
        { 
            return m_cacheWTListNodes.Get(pthrCurrent); 
        }
        void CacheAddLocalWTListNode(
            CPalThread * pthrCurrent,
            WaitingThreadsListNode * pWTLNode)
        { 
            m_cacheWTListNodes.Add(pthrCurrent, pWTLNode); 
        }
        SharedID CacheGetSharedWTListNode(CPalThread * pthrCurrent) 
        { 
            return m_cacheSHRWTListNodes.Get(pthrCurrent); 
        }
        void CacheAddSharedWTListNode(
            CPalThread * pthrCurrent,
            SharedID shridWTLNode) 
        { 
            m_cacheSHRWTListNodes.Add(pthrCurrent, shridWTLNode); 
        }

        ThreadApcInfoNode * CacheGetApcInfoNodes(CPalThread * pthrCurrent) 
        { 
            return m_cacheThreadApcInfoNodes.Get(pthrCurrent); 
        }
        void CacheAddApcInfoNodes(
            CPalThread * pthrCurrent,
            ThreadApcInfoNode * pNode) 
        { 
            m_cacheThreadApcInfoNodes.Add(pthrCurrent, pNode); 
        }

        OwnedObjectsListNode * CacheGetOwnedObjsListNode(
            CPalThread * pthrCurrent)
        { 
            return m_cacheOwnedObjectsListNodes.Get(pthrCurrent); 
        }
        void CacheAddOwnedObjsListNode(
            CPalThread * pthrCurrent,
            OwnedObjectsListNode * pNode) 
        { 
            m_cacheOwnedObjectsListNodes.Add(pthrCurrent, pNode); 
        }


        //
        // IPalSynchronizationManager methods
        //
        virtual PAL_ERROR BlockThread(
            CPalThread *pthrCurrent,
            DWORD dwTimeout,
            bool fAlertable,
            bool fIsSleep,
            ThreadWakeupReason *ptwrWakeupReason,
            DWORD *pdwSignaledObject);

        virtual PAL_ERROR AbandonObjectsOwnedByThread(
            CPalThread *pthrCurrent,
            CPalThread *pthrTarget);

        virtual PAL_ERROR GetSynchWaitControllersForObjects(
            CPalThread *pthrCurrent,
            IPalObject *rgObjects[],
            DWORD dwObjectCount,
            ISynchWaitController *rgControllers[]);

        virtual PAL_ERROR GetSynchStateControllersForObjects(
            CPalThread *pthrCurrent,
            IPalObject *rgObjects[],
            DWORD dwObjectCount,
            ISynchStateController *rgControllers[]);

        virtual PAL_ERROR AllocateObjectSynchData(
            CObjectType *potObjectType,
            ObjectDomain odObjectDomain,
            VOID **ppvSynchData);

        virtual void FreeObjectSynchData(
            CObjectType *potObjectType,
            ObjectDomain odObjectDomain,
            VOID *pvSynchData);

        virtual PAL_ERROR PromoteObjectSynchData(
            CPalThread *pthrCurrent,
            VOID *pvLocalSynchData,
            VOID **ppvSharedSynchData);

        virtual PAL_ERROR CreateSynchStateController(
            CPalThread *pthrCurrent,
            CObjectType *potObjectType,
            VOID *pvSynchData,
            ObjectDomain odObjectDomain,
            ISynchStateController **ppStateController);

        virtual PAL_ERROR CreateSynchWaitController(
            CPalThread *pthrCurrent,
            CObjectType *potObjectType,
            VOID *pvSynchData,
            ObjectDomain odObjectDomain,
            ISynchWaitController **ppWaitController);

        virtual PAL_ERROR QueueUserAPC(
            CPalThread * pthrCurrent,
            CPalThread *pthrTarget,
            PAPCFUNC pfnAPC,
            ULONG_PTR uptrData);

        virtual PAL_ERROR SendTerminationRequestToWorkerThread();

        virtual bool AreAPCsPending(CPalThread * pthrTarget);

        virtual PAL_ERROR DispatchPendingAPCs(CPalThread * pthrCurrent);

        virtual void AcquireProcessLock(CPalThread *pthrCurrent);

        virtual void ReleaseProcessLock(CPalThread *pthrCurrent);

        //
        // Static helper methods
        //
    public:
        static PAL_ERROR WakeUpLocalThread(
            CPalThread * pthrCurrent,
            CPalThread * pthrTarget,
            ThreadWakeupReason twrWakeupReason,
            DWORD dwObjectIndex);

        static PAL_ERROR SignalThreadCondition(
            ThreadNativeWaitData * ptnwdNativeWaitData);

        static PAL_ERROR DeferThreadConditionSignaling(
            CPalThread * pthrCurrent,
            CPalThread * pthrTarget);

        static PAL_ERROR WakeUpRemoteThread(
            SharedID shridWLNode);

        static PAL_ERROR DelegateSignalingToRemoteProcess(
            CPalThread * pthrCurrent,
            DWORD dwTargetProcessId,
            SharedID shridSynchData);

        static PAL_ERROR SendMsgToRemoteWorker(
            DWORD dwProcessId,
            BYTE * pMsg,
            int iMsgSize);

        static ThreadWaitInfo * GetThreadWaitInfo(
            CPalThread * pthrCurrent);

        //
        // The following methods must be called only by a Sync*Controller or
        // while holding the required synchronization global locks
        //
        static void UnsignalRestOfLocalAwakeningWaitAll(
            CPalThread * pthrCurrent,
            CPalThread * pthrTarget,
            WaitingThreadsListNode * pwtlnNode,
            CSynchData * psdTgtObjectSynchData);

        static void MarkWaitForDelegatedObjectSignalingInProgress(
            CPalThread * pthrCurrent,
            WaitingThreadsListNode * pwtlnNode);

        static void UnmarkTWListForDelegatedObjectSignalingInProgress(
            CSynchData * pTgtObjectSynchData);

        static PAL_ERROR ThreadNativeWait(
            ThreadNativeWaitData * ptnwdNativeWaitData,
            DWORD dwTimeout,
            ThreadWakeupReason * ptwrWakeupReason,
            DWORD * pdwSignaledObject);

        static void ThreadPrepareForShutdown(void);

#ifndef CORECLR
        static bool GetProcessPipeName(
            LPSTR pDest, 
            int iDestSize,
            DWORD dwPid);
#endif // !CORECLR
        
        //
        // Non-static helper methods
        //
    private:
        LONG DoMonitorProcesses(CPalThread * pthrCurrent);

        void DiscardMonitoredProcesses(CPalThread * pthrCurrent);

        PAL_ERROR ReadCmdFromProcessPipe(
            int iPollTimeout,
            SynchWorkerCmd * pswcWorkerCmd,
            SharedID * pshridMarshaledData,
            DWORD * pdwData);

        PAL_ERROR WakeUpLocalWorkerThread(
            SynchWorkerCmd swcWorkerCmd);

        void DiscardAllPendingAPCs(
            CPalThread * pthrCurrent,
            CPalThread * pthrTarget);

        int ReadBytesFromProcessPipe(
            int iTimeout,
            BYTE * pRecvBuf,
            LONG lBytes);

        bool CreateProcessPipe();

        PAL_ERROR ShutdownProcessPipe();

    public:
        //
        // The following methods must be called only by a Sync*Controller or
        // while holding the required synchronization global locks
        //
        void UnRegisterWait(
            CPalThread * pthrCurrent,
            ThreadWaitInfo * ptwiWaitInfo,
            bool fHaveSharedLock);

        PAL_ERROR RegisterProcessForMonitoring(
            CPalThread * pthrCurrent,
            CSynchData *psdSynchData,
            IPalObject *pProcessObject,
            CProcProcessLocalData * pProcLocalData);

        PAL_ERROR UnRegisterProcessForMonitoring(
            CPalThread * pthrCurrent,
            CSynchData *psdSynchData,
            DWORD dwPid);

        //
        // Utility static methods, no lock required
        //
        static bool HasProcessExited(
            DWORD dwPid,
            DWORD * pdwExitCode,
            bool * pfIsActualExitCode);

        static bool InterlockedAwaken(
            DWORD *pWaitState,
            bool fAlertOnly);

        static PAL_ERROR GetAbsoluteTimeout(
            DWORD dwTimeout,
            struct timespec * ptsAbsTmo);
    };
}

#endif // _SYNCHMANAGER_HPP_