summaryrefslogtreecommitdiff
path: root/src/vm/comthreadpool.cpp
blob: 554e836e6c7bf0c8e0412545438070f2b43ec734 (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
// 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.


/*============================================================
**
** Header: COMThreadPool.cpp
**
** Purpose: Native methods on System.ThreadPool
**          and its inner classes
**
**
===========================================================*/

/********************************************************************************************************************/
#include "common.h"
#include "comdelegate.h"
#include "comthreadpool.h"
#include "threadpoolrequest.h"
#include "win32threadpool.h"
#include "class.h"
#include "object.h"
#include "field.h"
#include "excep.h"
#include "security.h"
#include "eeconfig.h"
#include "corhost.h"
#include "nativeoverlapped.h"
#include "comsynchronizable.h"
#include "callhelpers.h"
#include "appdomain.inl"
/*****************************************************************************************************/
#ifdef _DEBUG
void LogCall(MethodDesc* pMD, LPCUTF8 api)
{
    LIMITED_METHOD_CONTRACT;
    
    LPCUTF8 cls  = pMD->GetMethodTable()->GetDebugClassName();
    LPCUTF8 name = pMD->GetName();

    LOG((LF_THREADPOOL,LL_INFO1000,"%s: ", api));
    LOG((LF_THREADPOOL, LL_INFO1000,
         " calling %s.%s\n", cls, name));
}
#else
#define LogCall(pMd,api)
#endif

VOID
AcquireDelegateInfo(DelegateInfo *pDelInfo)
{
    LIMITED_METHOD_CONTRACT;
}

VOID
ReleaseDelegateInfo(DelegateInfo *pDelInfo)
{
    CONTRACTL 
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    } CONTRACTL_END;
    
    // The release methods of holders can be called with preemptive GC enabled. Ensure we're in cooperative mode
    // before calling pDelInfo->Release(), since that requires coop mode.
    GCX_COOP();

    pDelInfo->Release();
    ThreadpoolMgr::RecycleMemory( pDelInfo, ThreadpoolMgr::MEMTYPE_DelegateInfo );
}

//typedef Holder<DelegateInfo *, AcquireDelegateInfo, ReleaseDelegateInfo> DelegateInfoHolder;

typedef Wrapper<DelegateInfo *, AcquireDelegateInfo, ReleaseDelegateInfo> DelegateInfoHolder;

/*****************************************************************************************************/
// Caller has to GC protect Objectrefs being passed in
DelegateInfo *DelegateInfo::MakeDelegateInfo(AppDomain *pAppDomain,
                                             OBJECTREF *state,
                                             OBJECTREF *waitEvent,
                                             OBJECTREF *registeredWaitHandle)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        if (state != NULL || waitEvent != NULL || registeredWaitHandle != NULL) 
        {
            MODE_COOPERATIVE;
        }
        else
        {
            MODE_ANY;
        }
        PRECONDITION(state == NULL || IsProtectedByGCFrame(state));
        PRECONDITION(waitEvent == NULL || IsProtectedByGCFrame(waitEvent));
        PRECONDITION(registeredWaitHandle == NULL || IsProtectedByGCFrame(registeredWaitHandle));
        PRECONDITION(CheckPointer(pAppDomain));
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END;

    // If there were any DelegateInfos waiting to be released, they'll get flushed now
    ThreadpoolMgr::FlushQueueOfTimerInfos();
    
    DelegateInfoHolder delegateInfo = (DelegateInfo*) ThreadpoolMgr::GetRecycledMemory(ThreadpoolMgr::MEMTYPE_DelegateInfo);
    
    delegateInfo->m_appDomainId = pAppDomain->GetId();

    if (state != NULL)
        delegateInfo->m_stateHandle = pAppDomain->CreateHandle(*state);
    else
        delegateInfo->m_stateHandle = NULL;

    if (waitEvent != NULL)
        delegateInfo->m_eventHandle = pAppDomain->CreateHandle(*waitEvent);
    else
        delegateInfo->m_eventHandle = NULL;

    if (registeredWaitHandle != NULL)
        delegateInfo->m_registeredWaitHandle = pAppDomain->CreateHandle(*registeredWaitHandle);
    else
        delegateInfo->m_registeredWaitHandle = NULL;

    delegateInfo->m_overridesCount = 0;
    delegateInfo->m_hasSecurityInfo = FALSE;

    delegateInfo.SuppressRelease();
    
    return delegateInfo;
}

/*****************************************************************************************************/
FCIMPL2(FC_BOOL_RET, ThreadPoolNative::CorSetMaxThreads,DWORD workerThreads, DWORD completionPortThreads)
{
    FCALL_CONTRACT;

    BOOL bRet = FALSE;
    HELPER_METHOD_FRAME_BEGIN_RET_0(); // Eventually calls BEGIN_SO_INTOLERANT_CODE_NOTHROW

    bRet = ThreadpoolMgr::SetMaxThreads(workerThreads,completionPortThreads);
    HELPER_METHOD_FRAME_END();    
    FC_RETURN_BOOL(bRet);
}
FCIMPLEND

/*****************************************************************************************************/
FCIMPL2(VOID, ThreadPoolNative::CorGetMaxThreads,DWORD* workerThreads, DWORD* completionPortThreads)
{
    FCALL_CONTRACT;
    
    ThreadpoolMgr::GetMaxThreads(workerThreads,completionPortThreads);
    return;
}
FCIMPLEND

/*****************************************************************************************************/
FCIMPL2(FC_BOOL_RET, ThreadPoolNative::CorSetMinThreads,DWORD workerThreads, DWORD completionPortThreads)
{
    FCALL_CONTRACT;

    BOOL bRet = FALSE;
    HELPER_METHOD_FRAME_BEGIN_RET_0(); // Eventually calls BEGIN_SO_INTOLERANT_CODE_NOTHROW

    bRet = ThreadpoolMgr::SetMinThreads(workerThreads,completionPortThreads);
    HELPER_METHOD_FRAME_END();    
    FC_RETURN_BOOL(bRet);
}
FCIMPLEND

/*****************************************************************************************************/
FCIMPL2(VOID, ThreadPoolNative::CorGetMinThreads,DWORD* workerThreads, DWORD* completionPortThreads)
{
    FCALL_CONTRACT;

    ThreadpoolMgr::GetMinThreads(workerThreads,completionPortThreads);
    return;
}
FCIMPLEND

/*****************************************************************************************************/
FCIMPL2(VOID, ThreadPoolNative::CorGetAvailableThreads,DWORD* workerThreads, DWORD* completionPortThreads)
{
    FCALL_CONTRACT;

    ThreadpoolMgr::GetAvailableThreads(workerThreads,completionPortThreads);
    return;
}
FCIMPLEND

/*****************************************************************************************************/

FCIMPL0(VOID, ThreadPoolNative::NotifyRequestProgress)
{
    FCALL_CONTRACT;

    ThreadpoolMgr::NotifyWorkItemCompleted();

    if (ThreadpoolMgr::ShouldAdjustMaxWorkersActive())
    {
        DangerousNonHostedSpinLockTryHolder tal(&ThreadpoolMgr::ThreadAdjustmentLock);
        if (tal.Acquired())
        {
            HELPER_METHOD_FRAME_BEGIN_0();
            ThreadpoolMgr::AdjustMaxWorkersActive();
            HELPER_METHOD_FRAME_END();    
        }
        else
        {
            // the lock is held by someone else, so they will take care of this for us.
        }
    }
}
FCIMPLEND

FCIMPL1(VOID, ThreadPoolNative::ReportThreadStatus, CLR_BOOL isWorking)
{
    FCALL_CONTRACT;
    ThreadpoolMgr::ReportThreadStatus(isWorking);
}
FCIMPLEND

FCIMPL0(FC_BOOL_RET, ThreadPoolNative::NotifyRequestComplete)
{
    FCALL_CONTRACT;

    ThreadpoolMgr::NotifyWorkItemCompleted();

    //
    // Now we need to possibly do one or both of:  reset the thread's state, and/or perform a 
    // "worker thread adjustment" (i.e., invoke Hill Climbing).  We try to avoid these at all costs,
    // because they require an expensive helper method frame.  So we first try a minimal thread reset,
    // then check if it covered everything that was needed, and we ask ThreadpoolMgr whether
    // we need a thread adjustment, before setting up the frame.
    //
    Thread *pThread = GetThread();
    _ASSERTE (pThread);

    INT32 priority = pThread->ResetManagedThreadObjectInCoopMode(ThreadNative::PRIORITY_NORMAL);

    bool needReset = 
        priority != ThreadNative::PRIORITY_NORMAL ||
        pThread->HasThreadStateNC(Thread::TSNC_SOWorkNeeded) ||
        !pThread->IsBackground() ||
        pThread->HasCriticalRegion() ||
        pThread->HasThreadAffinity();

    bool shouldAdjustWorkers = ThreadpoolMgr::ShouldAdjustMaxWorkersActive();

    // 
    // If it's time for a thread adjustment, try to get the lock.  This is just a "try," it won't block,
    // so it's ok to do this in cooperative mode.  If we can't get the lock, then some other thread is
    // already doing the thread adjustment, so we needn't bother.
    //
    DangerousNonHostedSpinLockTryHolder tal(&ThreadpoolMgr::ThreadAdjustmentLock, shouldAdjustWorkers);
    if (!tal.Acquired())
        shouldAdjustWorkers = false;

    if (needReset || shouldAdjustWorkers)
    {
        HELPER_METHOD_FRAME_BEGIN_RET_0();

        if (shouldAdjustWorkers)
        {
            ThreadpoolMgr::AdjustMaxWorkersActive();
            tal.Release();
        }

        if (needReset)
            pThread->InternalReset(FALSE, TRUE, TRUE, FALSE);

        HELPER_METHOD_FRAME_END();    
    }

    //
    // Finally, ask ThreadpoolMgr whether it's ok to keep running work on this thread.  Maybe Hill Climbing
    // wants this thread back.
    //
    BOOL result = ThreadpoolMgr::ShouldWorkerKeepRunning() ? TRUE : FALSE;
    FC_RETURN_BOOL(result);
}
FCIMPLEND


/*****************************************************************************************************/

void QCALLTYPE ThreadPoolNative::InitializeVMTp(CLR_BOOL* pEnableWorkerTracking)
{
    QCALL_CONTRACT;

    BEGIN_QCALL;
    ThreadpoolMgr::EnsureInitialized();
    *pEnableWorkerTracking = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_EnableWorkerTracking) ? TRUE : FALSE;
    END_QCALL;
}

/*****************************************************************************************************/

struct RegisterWaitForSingleObjectCallback_Args
{
    DelegateInfo *delegateInfo;
    BOOLEAN TimerOrWaitFired;
};

static VOID
RegisterWaitForSingleObjectCallback_Worker(LPVOID ptr)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    OBJECTREF orState = NULL;

    GCPROTECT_BEGIN( orState );

    RegisterWaitForSingleObjectCallback_Args *args = (RegisterWaitForSingleObjectCallback_Args *) ptr;
    orState = ObjectFromHandle(((DelegateInfo*) args->delegateInfo)->m_stateHandle);

#ifdef _DEBUG
    MethodDesc *pMeth = MscorlibBinder::GetMethod(METHOD__TPWAITORTIMER_HELPER__PERFORM_WAITORTIMER_CALLBACK);
    LogCall(pMeth,"RWSOCallback");
#endif

    // Caution: the args are not protected, we have to garantee there's no GC from here till
    // the managed call happens.
    PREPARE_NONVIRTUAL_CALLSITE(METHOD__TPWAITORTIMER_HELPER__PERFORM_WAITORTIMER_CALLBACK);
    DECLARE_ARGHOLDER_ARRAY(arg, 2);
    arg[ARGNUM_0]  = OBJECTREF_TO_ARGHOLDER(orState);
    arg[ARGNUM_1]  = DWORD_TO_ARGHOLDER(args->TimerOrWaitFired);

    // Call the method...
    CALL_MANAGED_METHOD_NORET(arg);

    GCPROTECT_END();
}


void ResetThreadSecurityState(Thread* pThread)
{
    CONTRACTL 
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    } CONTRACTL_END;
    
    if (pThread)
    {
        pThread->ResetSecurityInfo();
    }
}

// this holder resets our thread's security state
typedef Holder<Thread*, DoNothing<Thread*>, ResetThreadSecurityState> ThreadSecurityStateHolder;

VOID NTAPI RegisterWaitForSingleObjectCallback(PVOID delegateInfo, BOOLEAN TimerOrWaitFired)
{
    Thread* pThread = GetThread();
    if (pThread == NULL)
    {
        ClrFlsSetThreadType(ThreadType_Threadpool_Worker);
        pThread = SetupThreadNoThrow();
        if (pThread == NULL) {
            return;
        }
    }

    CONTRACTL
    {
        MODE_PREEMPTIVE;    // Worker thread will be in preempt mode. We switch to coop below.
        THROWS;
        GC_TRIGGERS;

        PRECONDITION(CheckPointer(delegateInfo));
    }
    CONTRACTL_END;

    // This thread should not have any locks held at entry point.
    _ASSERTE(pThread->m_dwLockCount == 0);

    GCX_COOP();

    // this holder resets our thread's security state when exiting this scope
    ThreadSecurityStateHolder  secState(pThread);

    RegisterWaitForSingleObjectCallback_Args args = { ((DelegateInfo*) delegateInfo), TimerOrWaitFired };

    ManagedThreadBase::ThreadPool(((DelegateInfo*) delegateInfo)->m_appDomainId, RegisterWaitForSingleObjectCallback_Worker, &args);

    // We should have released all locks.
    _ASSERTE(g_fEEShutDown || pThread->m_dwLockCount == 0 || pThread->m_fRudeAborted);
    return;
}

void ThreadPoolNative::Init()
{

}


FCIMPL7(LPVOID, ThreadPoolNative::CorRegisterWaitForSingleObject,
                                        Object* waitObjectUNSAFE,
                                        Object* stateUNSAFE,
                                        UINT32 timeout,
                                        CLR_BOOL executeOnlyOnce,
                                        Object* registeredWaitObjectUNSAFE,
                                        StackCrawlMark* stackMark,
                                        CLR_BOOL compressStack)
{
    FCALL_CONTRACT;
    
    HANDLE handle = 0;
    struct _gc
    {
        WAITHANDLEREF waitObject;
        OBJECTREF state;
        OBJECTREF registeredWaitObject;
    } gc;
    gc.waitObject = (WAITHANDLEREF) ObjectToOBJECTREF(waitObjectUNSAFE);
    gc.state = (OBJECTREF) stateUNSAFE;
    gc.registeredWaitObject = (OBJECTREF) registeredWaitObjectUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);  // Eventually calls BEGIN_SO_INTOLERANT_CODE_NOTHROW

    if(gc.waitObject == NULL)
        COMPlusThrow(kArgumentNullException, W("ArgumentNull_Obj"));

    _ASSERTE(gc.registeredWaitObject != NULL);

    ULONG flag = executeOnlyOnce ? WAIT_SINGLE_EXECUTION | WAIT_FREE_CONTEXT : WAIT_FREE_CONTEXT;

    HANDLE hWaitHandle = gc.waitObject->GetWaitHandle();
    _ASSERTE(hWaitHandle);

    Thread* pCurThread = GetThread();
    _ASSERTE( pCurThread);

    AppDomain* appDomain = pCurThread->GetDomain();
    _ASSERTE(appDomain);

    DelegateInfoHolder delegateInfo = DelegateInfo::MakeDelegateInfo(appDomain,
                                                                &gc.state,
                                                                (OBJECTREF *)&gc.waitObject,
                                                                &gc.registeredWaitObject);

    if (compressStack)
    {
        delegateInfo->SetThreadSecurityInfo( pCurThread, stackMark );
    }



    if (!(ThreadpoolMgr::RegisterWaitForSingleObject(&handle,
                                          hWaitHandle,
                                          RegisterWaitForSingleObjectCallback,
                                          (PVOID) delegateInfo,
                                          (ULONG) timeout,
                                          flag)))

    {
        _ASSERTE(GetLastError() != ERROR_CALL_NOT_IMPLEMENTED);

        COMPlusThrowWin32();
    }

    delegateInfo.SuppressRelease();
    HELPER_METHOD_FRAME_END();
    return (LPVOID) handle;
}
FCIMPLEND


VOID QueueUserWorkItemManagedCallback(PVOID pArg)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_COOPERATIVE;
    } CONTRACTL_END;

    _ASSERTE(NULL != pArg);

    // This thread should not have any locks held at entry point.
    _ASSERTE(GetThread()->m_dwLockCount == 0);

    bool* wasNotRecalled = (bool*)pArg;

    MethodDescCallSite dispatch(METHOD__TP_WAIT_CALLBACK__PERFORM_WAIT_CALLBACK);
    *wasNotRecalled = dispatch.Call_RetBool(NULL);
}


BOOL QCALLTYPE ThreadPoolNative::RequestWorkerThread()
{
    QCALL_CONTRACT;

    BOOL res = FALSE;

    BEGIN_QCALL;

    ThreadpoolMgr::SetAppDomainRequestsActive();

    res = ThreadpoolMgr::QueueUserWorkItem(NULL,
                                           NULL,
                                           0,
                                           FALSE);
    if (!res)
    {
        if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
            COMPlusThrow(kNotSupportedException);
        else
            COMPlusThrowWin32();
    }

    END_QCALL;
    return res;
}


/********************************************************************************************************************/

FCIMPL2(FC_BOOL_RET, ThreadPoolNative::CorUnregisterWait, LPVOID WaitHandle, Object* objectToNotify)
{
    FCALL_CONTRACT;

    BOOL retVal = false;
    SAFEHANDLEREF refSH = (SAFEHANDLEREF) ObjectToOBJECTREF(objectToNotify);
    HELPER_METHOD_FRAME_BEGIN_RET_1(refSH); // Eventually calls BEGIN_SO_INTOLERANT_CODE_NOTHROW

    HANDLE hWait = (HANDLE) WaitHandle;
    HANDLE hObjectToNotify = NULL;

    ThreadpoolMgr::WaitInfo *pWaitInfo = (ThreadpoolMgr::WaitInfo *)hWait;
    _ASSERTE(pWaitInfo != NULL);

    ThreadpoolMgr::WaitInfoHolder   wiHolder(NULL);

    if (refSH != NULL)
    {
        // Create a GCHandle in the WaitInfo, so that it can hold on to the safe handle
        pWaitInfo->ExternalEventSafeHandle = GetAppDomain()->CreateHandle(NULL);
        pWaitInfo->handleOwningAD = GetAppDomain()->GetId();

        // Holder will now release objecthandle in face of exceptions
        wiHolder.Assign(pWaitInfo);
        
        // Store SafeHandle in object handle. Holder will now release both safehandle and objecthandle
        // in case of exceptions
        StoreObjectInHandle(pWaitInfo->ExternalEventSafeHandle, refSH);

        // Acquire safe handle to examine its handle, then release.
        SafeHandleHolder shHolder(&refSH);
        
        if (refSH->GetHandle() == INVALID_HANDLE_VALUE)
        {
            hObjectToNotify = INVALID_HANDLE_VALUE;
            // We do not need the ObjectHandle, refcount on the safehandle etc
            wiHolder.Release();
            _ASSERTE(pWaitInfo->ExternalEventSafeHandle == NULL);
        }
    }

    _ASSERTE(hObjectToNotify == NULL || hObjectToNotify == INVALID_HANDLE_VALUE);
    
    // When hObjectToNotify is NULL ExternalEventSafeHandle contains event to notify (if it is non NULL).
    // When hObjectToNotify is INVALID_HANDLE_VALUE, UnregisterWaitEx blocks until dispose is complete.
    retVal = ThreadpoolMgr::UnregisterWaitEx(hWait, hObjectToNotify);

    if (retVal)
        wiHolder.SuppressRelease();
    
    HELPER_METHOD_FRAME_END();
    FC_RETURN_BOOL(retVal);
}
FCIMPLEND

/********************************************************************************************************************/
FCIMPL1(void, ThreadPoolNative::CorWaitHandleCleanupNative, LPVOID WaitHandle)
{
    FCALL_CONTRACT;

    HELPER_METHOD_FRAME_BEGIN_0(); // Eventually calls BEGIN_SO_INTOLERANT_CODE_NOTHROW

    HANDLE hWait = (HANDLE)WaitHandle;
    ThreadpoolMgr::WaitHandleCleanup(hWait);

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

/********************************************************************************************************************/

/********************************************************************************************************************/

struct BindIoCompletion_Args
{
    DWORD ErrorCode;
    DWORD numBytesTransferred;
    LPOVERLAPPED lpOverlapped;
    BOOL *pfProcessed;
};

void SetAsyncResultProperties(
    OVERLAPPEDDATAREF overlapped,
    DWORD dwErrorCode, 
    DWORD dwNumBytes
)
{
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_MODE_ANY;
    STATIC_CONTRACT_SO_TOLERANT;

}

VOID BindIoCompletionCallBack_Worker(LPVOID args)
{
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_GC_TRIGGERS;
    STATIC_CONTRACT_MODE_ANY;
    STATIC_CONTRACT_SO_INTOLERANT;

    DWORD        ErrorCode = ((BindIoCompletion_Args *)args)->ErrorCode;
    DWORD        numBytesTransferred = ((BindIoCompletion_Args *)args)->numBytesTransferred;
    LPOVERLAPPED lpOverlapped = ((BindIoCompletion_Args *)args)->lpOverlapped;

    OVERLAPPEDDATAREF overlapped = ObjectToOVERLAPPEDDATAREF(OverlappedDataObject::GetOverlapped(lpOverlapped));

    GCPROTECT_BEGIN(overlapped);
    *(((BindIoCompletion_Args *)args)->pfProcessed) = TRUE;
    // we set processed to TRUE, now it's our responsibility to guarantee proper cleanup

#ifdef _DEBUG
    MethodDesc *pMeth = MscorlibBinder::GetMethod(METHOD__IOCB_HELPER__PERFORM_IOCOMPLETION_CALLBACK);
    LogCall(pMeth,"IOCallback");
#endif

    if (overlapped->m_iocb != NULL)
    {
        // Caution: the args are not protected, we have to garantee there's no GC from here till
        PREPARE_NONVIRTUAL_CALLSITE(METHOD__IOCB_HELPER__PERFORM_IOCOMPLETION_CALLBACK);
        DECLARE_ARGHOLDER_ARRAY(arg, 3);
        arg[ARGNUM_0]  = DWORD_TO_ARGHOLDER(ErrorCode);
        arg[ARGNUM_1]  = DWORD_TO_ARGHOLDER(numBytesTransferred);
        arg[ARGNUM_2]  = PTR_TO_ARGHOLDER(lpOverlapped);

        // Call the method...
        CALL_MANAGED_METHOD_NORET(arg);
    }
    else
    {
        // no user delegate to callback
        _ASSERTE((overlapped->m_iocbHelper == NULL) || !"This is benign, but should be optimized");


        SetAsyncResultProperties(overlapped, ErrorCode, numBytesTransferred);
    }
    GCPROTECT_END();
}

void __stdcall BindIoCompletionCallbackStubEx(DWORD ErrorCode,
                                              DWORD numBytesTransferred,
                                              LPOVERLAPPED lpOverlapped,
                                              BOOL setStack)
{
    Thread* pThread = GetThread();
    if (pThread == NULL)
    {
        // TODO: how do we notify user of OOM here?
        ClrFlsSetThreadType(ThreadType_Threadpool_Worker);
        pThread = SetupThreadNoThrow();
        if (pThread == NULL) {
            return;
        }
    }

    CONTRACTL
    {
        THROWS;
        MODE_ANY;
        GC_TRIGGERS;
        SO_INTOLERANT;
    }
    CONTRACTL_END;

    // This thread should not have any locks held at entry point.
    _ASSERTE(pThread->m_dwLockCount == 0);

    LOG((LF_INTEROP, LL_INFO10000, "In IO_CallBackStub thread 0x%x retCode 0x%x, overlap 0x%x\n",  pThread, ErrorCode, lpOverlapped));

    GCX_COOP();

    // NOTE: there is a potential race between the time we retrieve the app domain pointer,
    // and the time which this thread enters the domain.
    //
    // To solve the race, we rely on the fact that there is a thread sync (via GC)
    // between releasing an app domain's handle, and destroying the app domain.  Thus
    // it is important that we not go into preemptive gc mode in that window.
    //

    //IMPORTANT - do not gc protect overlapped here - it belongs to another appdomain
    //so if it stops being pinned it should be able to go away
    OVERLAPPEDDATAREF overlapped = ObjectToOVERLAPPEDDATAREF(OverlappedDataObject::GetOverlapped(lpOverlapped));
    AppDomainFromIDHolder appDomain(ADID(overlapped->GetAppDomainId()), TRUE);
    BOOL fProcessed = FALSE;
    if (!appDomain.IsUnloaded())
    {
        // this holder resets our thread's security state when exiting this scope, 
        // but only if setStack is TRUE.
        Thread* pHolderThread = NULL;
        if (setStack)
        {
            pHolderThread = pThread; 
        }

        ThreadSecurityStateHolder  secState(pHolderThread);

        BindIoCompletion_Args args = {ErrorCode, numBytesTransferred, lpOverlapped, &fProcessed};
        appDomain.Release();
        ManagedThreadBase::ThreadPool(ADID(overlapped->GetAppDomainId()), BindIoCompletionCallBack_Worker, &args);
    }

    LOG((LF_INTEROP, LL_INFO10000, "Leaving IO_CallBackStub thread 0x%x retCode 0x%x, overlap 0x%x\n",  pThread, ErrorCode, lpOverlapped));
        // We should have released all locks.
    _ASSERTE(g_fEEShutDown || pThread->m_dwLockCount == 0 || pThread->m_fRudeAborted);
    return;
}

void WINAPI BindIoCompletionCallbackStub(DWORD ErrorCode,
                                            DWORD numBytesTransferred,
                                            LPOVERLAPPED lpOverlapped)
{
    WRAPPER_NO_CONTRACT;
    BindIoCompletionCallbackStubEx(ErrorCode, numBytesTransferred, lpOverlapped, TRUE);

#ifndef FEATURE_PAL
    extern Volatile<ULONG> g_fCompletionPortDrainNeeded;

    Thread *pThread = GetThread();
    if (g_fCompletionPortDrainNeeded && pThread)
    {
        // We have started draining completion port.
        // The next job picked up by this thread is going to be after our special marker.
        if (!pThread->IsCompletionPortDrained())
        {
            pThread->MarkCompletionPortDrained();
        }
    }
#endif // !FEATURE_PAL
}

FCIMPL1(FC_BOOL_RET, ThreadPoolNative::CorBindIoCompletionCallback, HANDLE fileHandle)
{
    FCALL_CONTRACT;

    BOOL retVal = FALSE;

    HELPER_METHOD_FRAME_BEGIN_RET_0(); // Eventually calls BEGIN_SO_INTOLERANT_CODE_NOTHROW

    HANDLE hFile = (HANDLE) fileHandle;
    DWORD errCode = 0;

    retVal = ThreadpoolMgr::BindIoCompletionCallback(hFile,
                                           BindIoCompletionCallbackStub,
                                           0,     // reserved, must be 0
                                           OUT errCode);
    if (!retVal)
    {
        if (errCode == ERROR_CALL_NOT_IMPLEMENTED)
            COMPlusThrow(kPlatformNotSupportedException);
        else
        {
            SetLastError(errCode);
            COMPlusThrowWin32();
        }
    }

    HELPER_METHOD_FRAME_END();
    FC_RETURN_BOOL(retVal);
}
FCIMPLEND

FCIMPL1(FC_BOOL_RET, ThreadPoolNative::CorPostQueuedCompletionStatus, LPOVERLAPPED lpOverlapped)
{
    FCALL_CONTRACT;

    OVERLAPPEDDATAREF   overlapped = ObjectToOVERLAPPEDDATAREF(OverlappedDataObject::GetOverlapped(lpOverlapped));

    BOOL res = FALSE;

    HELPER_METHOD_FRAME_BEGIN_RET_1(overlapped); // Eventually calls BEGIN_SO_INTOLERANT_CODE_NOTHROW

    // OS doesn't signal handle, so do it here
    overlapped->Internal = 0;

    if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_Context, ThreadPoolIOEnqueue))
        FireEtwThreadPoolIOEnqueue(lpOverlapped, OBJECTREFToObject(overlapped), false, GetClrInstanceId());
    
    res = ThreadpoolMgr::PostQueuedCompletionStatus(lpOverlapped, 
        BindIoCompletionCallbackStub);

    if (!res)
    {
        if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
            COMPlusThrow(kPlatformNotSupportedException);
        else
            COMPlusThrowWin32();
    }

    HELPER_METHOD_FRAME_END();
    FC_RETURN_BOOL(res);
}
FCIMPLEND


/********************************************************************************************************************/


/******************************************************************************************/
/*                                                                                        */
/*                              Timer Functions                                           */
/*                                                                                        */
/******************************************************************************************/

void AppDomainTimerCallback_Worker(LPVOID ptr)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;
    
#ifdef _DEBUG
    MethodDesc *pMeth = MscorlibBinder::GetMethod(METHOD__TIMER_QUEUE__APPDOMAIN_TIMER_CALLBACK);
    LogCall(pMeth,"AppDomainTimerCallback");
#endif

    MethodDescCallSite(METHOD__TIMER_QUEUE__APPDOMAIN_TIMER_CALLBACK).Call(NULL);
}

VOID WINAPI AppDomainTimerCallback(PVOID delegateInfo, BOOLEAN timerOrWaitFired)
{
    Thread* pThread = GetThread();
    if (pThread == NULL)
    {
        // TODO: how do we notify user of OOM here?
        ClrFlsSetThreadType(ThreadType_Threadpool_Worker);
        pThread = SetupThreadNoThrow();
        if (pThread == NULL) {
            return;
        }
    }

    CONTRACTL
    {
        THROWS;
        MODE_ANY;
        GC_TRIGGERS;
        SO_INTOLERANT;
        
        PRECONDITION(CheckPointer(delegateInfo));
    }
    CONTRACTL_END;

    // This thread should not have any locks held at entry point.
    _ASSERTE(pThread->m_dwLockCount == 0);

    GCX_COOP();

    {
        ThreadSecurityStateHolder  secState(pThread);
        ManagedThreadBase::ThreadPool(((DelegateInfo*)delegateInfo)->m_appDomainId, AppDomainTimerCallback_Worker, NULL);
    }
    
    // We should have released all locks.
    _ASSERTE(g_fEEShutDown || pThread->m_dwLockCount == 0 || pThread->m_fRudeAborted);
}

HANDLE QCALLTYPE AppDomainTimerNative::CreateAppDomainTimer(INT32 dueTime)
{
    QCALL_CONTRACT;

    HANDLE hTimer = NULL;
    BEGIN_QCALL;

    _ASSERTE(dueTime >= 0);

    AppDomain* pAppDomain = GetThread()->GetDomain();
    ADID adid = pAppDomain->GetId();

    DelegateInfoHolder delegateInfo = DelegateInfo::MakeDelegateInfo(
        pAppDomain,
        NULL,
        NULL,
        NULL);

    BOOL res = ThreadpoolMgr::CreateTimerQueueTimer(
        &hTimer,
        (WAITORTIMERCALLBACK)AppDomainTimerCallback,
        (PVOID)delegateInfo,
        (ULONG)dueTime,
        (ULONG)-1 /* this timer doesn't repeat */,
        0 /* no flags */);

    if (!res)
    {
        if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
            COMPlusThrow(kNotSupportedException);
        else
            COMPlusThrowWin32();
    }
    else
    {
        delegateInfo.SuppressRelease();
    }

    END_QCALL;
    return hTimer;
}

BOOL QCALLTYPE AppDomainTimerNative::DeleteAppDomainTimer(HANDLE hTimer)
{
    QCALL_CONTRACT;

    BOOL res = FALSE;
    BEGIN_QCALL;

    _ASSERTE(hTimer != NULL && hTimer != INVALID_HANDLE_VALUE);
    res = ThreadpoolMgr::DeleteTimerQueueTimer(hTimer, NULL);

    if (!res)
    {
        DWORD errorCode = ::GetLastError();
        if (errorCode != ERROR_IO_PENDING)
            COMPlusThrowWin32(HRESULT_FROM_WIN32(errorCode));
    }

    END_QCALL;
    return res;
}


BOOL QCALLTYPE AppDomainTimerNative::ChangeAppDomainTimer(HANDLE hTimer, INT32 dueTime)
{
    QCALL_CONTRACT;

    BOOL res = FALSE;
    BEGIN_QCALL;

    _ASSERTE(hTimer != NULL && hTimer != INVALID_HANDLE_VALUE);
    _ASSERTE(dueTime >= 0);

    res = ThreadpoolMgr::ChangeTimerQueueTimer(
        hTimer,
        (ULONG)dueTime,
        (ULONG)-1 /* this timer doesn't repeat */);

    if (!res)
        COMPlusThrowWin32();

    END_QCALL;
    return res;
}