This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
win32threadpool.h
1109 lines (863 loc) · 38 KB
/
win32threadpool.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*++
Module Name:
Win32ThreadPool.h
Abstract:
This module is the header file for thread pools using Win32 APIs.
Revision History:
--*/
#ifndef _WIN32THREADPOOL_H
#define _WIN32THREADPOOL_H
#include "delegateinfo.h"
#include "util.hpp"
#include "nativeoverlapped.h"
#include "hillclimbing.h"
#define MAX_WAITHANDLES 64
#define MAX_CACHED_EVENTS 40 // upper limit on number of wait events cached
#define WAIT_REGISTERED 0x01
#define WAIT_ACTIVE 0x02
#define WAIT_DELETE 0x04
#define TIMER_REGISTERED 0x01
#define TIMER_ACTIVE 0x02
#define TIMER_DELETE 0x04
#define WAIT_SINGLE_EXECUTION 0x00000001
#define WAIT_FREE_CONTEXT 0x00000002
#define WAIT_INTERNAL_COMPLETION 0x00000004
#define QUEUE_ONLY 0x00000000 // do not attempt to call on the thread
#define CALL_OR_QUEUE 0x00000001 // call on the same thread if not too busy, else queue
const int MaxLimitThreadsPerCPU=250; // upper limit on number of cp threads per CPU
const int MaxFreeCPThreadsPerCPU=2; // upper limit on number of free cp threads per CPU
const int CpuUtilizationHigh=95; // remove threads when above this
const int CpuUtilizationLow =80; // inject more threads if below this
#ifndef FEATURE_PAL
extern HANDLE (WINAPI *g_pufnCreateIoCompletionPort)(HANDLE FileHandle,
HANDLE ExistingCompletionPort,
ULONG_PTR CompletionKey,
DWORD NumberOfConcurrentThreads);
extern int (WINAPI *g_pufnNtQueryInformationThread) (HANDLE ThreadHandle,
THREADINFOCLASS ThreadInformationClass,
PVOID ThreadInformation,
ULONG ThreadInformationLength,
PULONG ReturnLength);
extern int (WINAPI * g_pufnNtQuerySystemInformation) (SYSTEM_INFORMATION_CLASS SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength OPTIONAL);
#endif // !FEATURE_PAL
#define FILETIME_TO_INT64(t) (*(__int64*)&(t))
#define MILLI_TO_100NANO(x) (x * 10000) // convert from milliseond to 100 nanosecond unit
/**
* This type is supposed to be private to ThreadpoolMgr.
* It's at global scope because Strike needs to be able to access its
* definition.
*/
struct WorkRequest {
WorkRequest* next;
LPTHREAD_START_ROUTINE Function;
PVOID Context;
};
typedef struct _IOCompletionContext
{
DWORD ErrorCode;
DWORD numBytesTransferred;
LPOVERLAPPED lpOverlapped;
size_t key;
} IOCompletionContext, *PIOCompletionContext;
typedef DPTR(WorkRequest) PTR_WorkRequest;
class ThreadpoolMgr
{
friend class ClrDataAccess;
friend struct DelegateInfo;
friend class ThreadPoolNative;
friend class TimerNative;
friend class UnManagedPerAppDomainTPCount;
friend class ManagedPerAppDomainTPCount;
friend class PerAppDomainTPCountList;
friend class HillClimbing;
friend struct _DacGlobals;
public:
struct ThreadCounter
{
static const int MaxPossibleCount = 0x7fff;
// padding to ensure we get our own cache line
BYTE padding1[MAX_CACHE_LINE_SIZE];
union Counts
{
struct
{
//
// Note: these are signed rather than unsigned to allow us to detect under/overflow.
//
int MaxWorking : 16; //Determined by HillClimbing; adjusted elsewhere for timeouts, etc.
int NumActive : 16; //Active means working or waiting on WorkerSemaphore. These are "warm/hot" threads.
int NumWorking : 16; //Trying to get work from various queues. Not waiting on either semaphore.
int NumRetired : 16; //Not trying to get work; waiting on RetiredWorkerSemaphore. These are "cold" threads.
// Note: the only reason we need "retired" threads at all is that it allows some threads to eventually time out
// even if other threads are getting work. If we ever make WorkerSemaphore a true LIFO semaphore, we will no longer
// need the concept of "retirement" - instead, the very "coldest" threads will naturally be the first to time out.
};
LONGLONG AsLongLong;
bool operator==(Counts other) {LIMITED_METHOD_CONTRACT; return AsLongLong == other.AsLongLong;}
} counts;
// padding to ensure we get our own cache line
BYTE padding2[MAX_CACHE_LINE_SIZE];
Counts GetCleanCounts()
{
LIMITED_METHOD_CONTRACT;
#ifdef _WIN64
// VolatileLoad x64 bit read is atomic
return DangerousGetDirtyCounts();
#else // !_WIN64
// VolatileLoad may result in torn read
Counts result;
#ifndef DACCESS_COMPILE
result.AsLongLong = FastInterlockCompareExchangeLong(&counts.AsLongLong, 0, 0);
ValidateCounts(result);
#else
result.AsLongLong = 0; //prevents prefast warning for DAC builds
#endif
return result;
#endif // !_WIN64
}
//
// This does a non-atomic read of the counts. The returned value is suitable only
// for use inside of a read-compare-exchange loop, where the compare-exhcange must succeed
// before any action is taken. Use GetCleanWorkerCounts for other needs, but keep in mind
// it's much slower.
//
Counts DangerousGetDirtyCounts()
{
LIMITED_METHOD_CONTRACT;
Counts result;
#ifndef DACCESS_COMPILE
result.AsLongLong = VolatileLoad(&counts.AsLongLong);
#else
result.AsLongLong = 0; //prevents prefast warning for DAC builds
#endif
return result;
}
Counts CompareExchangeCounts(Counts newCounts, Counts oldCounts)
{
LIMITED_METHOD_CONTRACT;
Counts result;
#ifndef DACCESS_COMPILE
result.AsLongLong = FastInterlockCompareExchangeLong(&counts.AsLongLong, newCounts.AsLongLong, oldCounts.AsLongLong);
if (result == oldCounts)
{
// can only do validation on success; if we failed, it may have been due to a previous
// dirty read, which may contain invalid values.
ValidateCounts(result);
ValidateCounts(newCounts);
}
#else
result.AsLongLong = 0; //prevents prefast warning for DAC builds
#endif
return result;
}
private:
static void ValidateCounts(Counts counts)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(counts.MaxWorking > 0);
_ASSERTE(counts.NumActive >= 0);
_ASSERTE(counts.NumWorking >= 0);
_ASSERTE(counts.NumRetired >= 0);
_ASSERTE(counts.NumWorking <= counts.NumActive);
}
};
public:
static void ReportThreadStatus(bool isWorking);
// enumeration of different kinds of memory blocks that are recycled
enum MemType
{
MEMTYPE_AsyncCallback = 0,
MEMTYPE_DelegateInfo = 1,
MEMTYPE_WorkRequest = 2,
MEMTYPE_COUNT = 3,
};
typedef struct {
INT32 TimerId;
} TimerInfoContext;
static BOOL Initialize();
static BOOL SetMaxThreadsHelper(DWORD MaxWorkerThreads,
DWORD MaxIOCompletionThreads);
static BOOL SetMaxThreads(DWORD MaxWorkerThreads,
DWORD MaxIOCompletionThreads);
static BOOL GetMaxThreads(DWORD* MaxWorkerThreads,
DWORD* MaxIOCompletionThreads);
static BOOL SetMinThreads(DWORD MinWorkerThreads,
DWORD MinIOCompletionThreads);
static BOOL GetMinThreads(DWORD* MinWorkerThreads,
DWORD* MinIOCompletionThreads);
static BOOL GetAvailableThreads(DWORD* AvailableWorkerThreads,
DWORD* AvailableIOCompletionThreads);
static INT32 GetThreadCount();
static BOOL QueueUserWorkItem(LPTHREAD_START_ROUTINE Function,
PVOID Context,
ULONG Flags,
BOOL UnmanagedTPRequest=TRUE);
static BOOL PostQueuedCompletionStatus(LPOVERLAPPED lpOverlapped,
LPOVERLAPPED_COMPLETION_ROUTINE Function);
inline static BOOL IsCompletionPortInitialized()
{
LIMITED_METHOD_CONTRACT;
return GlobalCompletionPort != NULL;
}
static BOOL DrainCompletionPortQueue();
static BOOL RegisterWaitForSingleObject(PHANDLE phNewWaitObject,
HANDLE hWaitObject,
WAITORTIMERCALLBACK Callback,
PVOID Context,
ULONG timeout,
DWORD dwFlag);
static BOOL UnregisterWaitEx(HANDLE hWaitObject,HANDLE CompletionEvent);
static void WaitHandleCleanup(HANDLE hWaitObject);
static BOOL WINAPI BindIoCompletionCallback(HANDLE FileHandle,
LPOVERLAPPED_COMPLETION_ROUTINE Function,
ULONG Flags,
DWORD& errorCode);
static void WINAPI WaitIOCompletionCallback(DWORD dwErrorCode,
DWORD numBytesTransferred,
LPOVERLAPPED lpOverlapped);
static VOID WINAPI CallbackForInitiateDrainageOfCompletionPortQueue(
DWORD dwErrorCode,
DWORD dwNumberOfBytesTransfered,
LPOVERLAPPED lpOverlapped
);
static VOID WINAPI CallbackForContinueDrainageOfCompletionPortQueue(
DWORD dwErrorCode,
DWORD dwNumberOfBytesTransfered,
LPOVERLAPPED lpOverlapped
);
static BOOL SetAppDomainRequestsActive(BOOL UnmanagedTP = FALSE);
static void ClearAppDomainRequestsActive(BOOL UnmanagedTP = FALSE, LONG index = -1);
static inline void UpdateLastDequeueTime()
{
LIMITED_METHOD_CONTRACT;
VolatileStore(&LastDequeueTime, (unsigned int)GetTickCount());
}
static BOOL CreateTimerQueueTimer(PHANDLE phNewTimer,
WAITORTIMERCALLBACK Callback,
PVOID Parameter,
DWORD DueTime,
DWORD Period,
ULONG Flags);
static BOOL ChangeTimerQueueTimer(HANDLE Timer,
ULONG DueTime,
ULONG Period);
static BOOL DeleteTimerQueueTimer(HANDLE Timer,
HANDLE CompletionEvent);
static void RecycleMemory(LPVOID mem, enum MemType memType);
static void FlushQueueOfTimerInfos();
static BOOL HaveTimerInfosToFlush() { return TimerInfosToBeRecycled != NULL; }
#ifndef FEATURE_PAL
static LPOVERLAPPED CompletionPortDispatchWorkWithinAppDomain(Thread* pThread, DWORD* pErrorCode, DWORD* pNumBytes, size_t* pKey);
static void StoreOverlappedInfoInThread(Thread* pThread, DWORD dwErrorCode, DWORD dwNumBytes, size_t key, LPOVERLAPPED lpOverlapped);
#endif // !FEATURE_PAL
// Enable filtering of correlation ETW events for cases handled at a higher abstraction level
#ifndef DACCESS_COMPILE
static FORCEINLINE BOOL AreEtwQueueEventsSpeciallyHandled(LPTHREAD_START_ROUTINE Function)
{
// Timer events are handled at a higher abstraction level: in the managed Timer class
return (Function == ThreadpoolMgr::AsyncTimerCallbackCompletion);
}
static FORCEINLINE BOOL AreEtwIOQueueEventsSpeciallyHandled(LPOVERLAPPED_COMPLETION_ROUTINE Function)
{
// We ignore drainage events b/c they are uninteresting
// We handle registered waits at a higher abstraction level
return (Function == ThreadpoolMgr::CallbackForInitiateDrainageOfCompletionPortQueue
|| Function == ThreadpoolMgr::CallbackForContinueDrainageOfCompletionPortQueue
|| Function == ThreadpoolMgr::WaitIOCompletionCallback);
}
#endif
private:
#ifndef DACCESS_COMPILE
inline static void FreeWorkRequest(WorkRequest* workRequest)
{
RecycleMemory( workRequest, MEMTYPE_WorkRequest ); //delete workRequest;
}
inline static WorkRequest* MakeWorkRequest(LPTHREAD_START_ROUTINE function, PVOID context)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;;
WorkRequest* wr = (WorkRequest*) GetRecycledMemory(MEMTYPE_WorkRequest);
_ASSERTE(wr);
if (NULL == wr)
return NULL;
wr->Function = function;
wr->Context = context;
wr->next = NULL;
return wr;
}
#endif // #ifndef DACCESS_COMPILE
typedef struct {
DWORD numBytes;
ULONG_PTR *key;
LPOVERLAPPED pOverlapped;
DWORD errorCode;
} QueuedStatus;
typedef DPTR(struct _LIST_ENTRY) PTR_LIST_ENTRY;
typedef struct _LIST_ENTRY {
struct _LIST_ENTRY *Flink;
struct _LIST_ENTRY *Blink;
} LIST_ENTRY, *PLIST_ENTRY;
struct WaitInfo;
typedef struct {
HANDLE threadHandle;
DWORD threadId;
CLREvent startEvent;
LONG NumWaitHandles; // number of wait objects registered to the thread <=64
LONG NumActiveWaits; // number of objects, thread is actually waiting on (this may be less than
// NumWaitHandles since the thread may not have activated some waits
HANDLE waitHandle[MAX_WAITHANDLES]; // array of wait handles (copied from waitInfo since
// we need them to be contiguous)
LIST_ENTRY waitPointer[MAX_WAITHANDLES]; // array of doubly linked list of corresponding waitinfo
} ThreadCB;
typedef struct {
ULONG startTime; // time at which wait was started
// endTime = startTime+timeout
ULONG remainingTime; // endTime - currentTime
} WaitTimerInfo;
struct WaitInfo {
LIST_ENTRY link; // Win9x does not allow duplicate waithandles, so we need to
// group all waits on a single waithandle using this linked list
HANDLE waitHandle;
WAITORTIMERCALLBACK Callback;
PVOID Context;
ULONG timeout;
WaitTimerInfo timer;
DWORD flag;
DWORD state;
ThreadCB* threadCB;
LONG refCount; // when this reaches 0, the waitInfo can be safely deleted
CLREvent PartialCompletionEvent; // used to synchronize deactivation of a wait
CLREvent InternalCompletionEvent; // only one of InternalCompletion or ExternalCompletion is used
// but I cant make a union since CLREvent has a non-default constructor
HANDLE ExternalCompletionEvent; // they are signalled when all callbacks have completed (refCount=0)
OBJECTHANDLE ExternalEventSafeHandle;
} ;
// structure used to maintain global information about wait threads. Protected by WaitThreadsCriticalSection
typedef struct WaitThreadTag {
LIST_ENTRY link;
ThreadCB* threadCB;
} WaitThreadInfo;
struct AsyncCallback{
WaitInfo* wait;
BOOL waitTimedOut;
} ;
#ifndef DACCESS_COMPILE
static VOID
AcquireAsyncCallback(AsyncCallback *pAsyncCB)
{
LIMITED_METHOD_CONTRACT;
}
static VOID
ReleaseAsyncCallback(AsyncCallback *pAsyncCB)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
WaitInfo *waitInfo = pAsyncCB->wait;
ThreadpoolMgr::RecycleMemory((LPVOID*)pAsyncCB, ThreadpoolMgr::MEMTYPE_AsyncCallback);
// if this was a single execution, we now need to stop rooting registeredWaitHandle
// in a GC handle. This will cause the finalizer to pick it up and call the cleanup
// routine.
if ( (waitInfo->flag & WAIT_SINGLE_EXECUTION) && (waitInfo->flag & WAIT_FREE_CONTEXT))
{
DelegateInfo* pDelegate = (DelegateInfo*) waitInfo->Context;
_ASSERTE(pDelegate->m_registeredWaitHandle);
{
GCX_COOP();
StoreObjectInHandle(pDelegate->m_registeredWaitHandle, NULL);
}
}
if (InterlockedDecrement(&waitInfo->refCount) == 0)
ThreadpoolMgr::DeleteWait(waitInfo);
}
typedef Holder<AsyncCallback *, ThreadpoolMgr::AcquireAsyncCallback, ThreadpoolMgr::ReleaseAsyncCallback> AsyncCallbackHolder;
inline static AsyncCallback* MakeAsyncCallback()
{
WRAPPER_NO_CONTRACT;
return (AsyncCallback*) GetRecycledMemory(MEMTYPE_AsyncCallback);
}
static VOID ReleaseInfo(OBJECTHANDLE& hndSafeHandle,
HANDLE hndNativeHandle)
{
CONTRACTL
{
NOTHROW;
MODE_ANY;
GC_TRIGGERS;
}
CONTRACTL_END
// Use of EX_TRY, GCPROTECT etc in the same function is causing prefast to complain about local variables with
// same name masking each other (#246). The error could not be suppressed with "#pragma PREFAST_SUPPRESS"
#ifndef _PREFAST_
if (hndSafeHandle != NULL)
{
SAFEHANDLEREF refSH = NULL;
GCX_COOP();
GCPROTECT_BEGIN(refSH);
{
EX_TRY
{
// Read the GC handle
refSH = (SAFEHANDLEREF) ObjectToOBJECTREF(ObjectFromHandle(hndSafeHandle));
// Destroy the GC handle
DestroyHandle(hndSafeHandle);
if (refSH != NULL)
{
SafeHandleHolder h(&refSH);
HANDLE hEvent = refSH->GetHandle();
if (hEvent != INVALID_HANDLE_VALUE)
{
SetEvent(hEvent);
}
}
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions);
}
GCPROTECT_END();
hndSafeHandle = NULL;
}
#endif
}
#endif // #ifndef DACCESS_COMPILE
typedef struct {
LIST_ENTRY link;
HANDLE Handle;
} WaitEvent ;
// Timer
typedef struct {
LIST_ENTRY link; // doubly linked list of timers
ULONG FiringTime; // TickCount of when to fire next
WAITORTIMERCALLBACK Function; // Function to call when timer fires
PVOID Context; // Context to pass to function when timer fires
ULONG Period;
DWORD flag; // How do we deal with the context
DWORD state;
LONG refCount;
HANDLE ExternalCompletionEvent; // only one of this is used, but cant do a union since CLREvent has a non-default constructor
CLREvent InternalCompletionEvent; // flags indicates which one is being used
OBJECTHANDLE ExternalEventSafeHandle;
} TimerInfo;
static VOID AcquireWaitInfo(WaitInfo *pInfo)
{
}
static VOID ReleaseWaitInfo(WaitInfo *pInfo)
{
WRAPPER_NO_CONTRACT;
#ifndef DACCESS_COMPILE
ReleaseInfo(pInfo->ExternalEventSafeHandle,
pInfo->ExternalCompletionEvent);
#endif
}
static VOID AcquireTimerInfo(TimerInfo *pInfo)
{
}
static VOID ReleaseTimerInfo(TimerInfo *pInfo)
{
WRAPPER_NO_CONTRACT;
#ifndef DACCESS_COMPILE
ReleaseInfo(pInfo->ExternalEventSafeHandle,
pInfo->ExternalCompletionEvent);
#endif
}
typedef Holder<WaitInfo *, ThreadpoolMgr::AcquireWaitInfo, ThreadpoolMgr::ReleaseWaitInfo> WaitInfoHolder;
typedef Holder<TimerInfo *, ThreadpoolMgr::AcquireTimerInfo, ThreadpoolMgr::ReleaseTimerInfo> TimerInfoHolder;
typedef struct {
TimerInfo* Timer; // timer to be updated
ULONG DueTime ; // new due time
ULONG Period ; // new period
} TimerUpdateInfo;
// Definitions and data structures to support recycling of high-frequency
// memory blocks. We use a spin-lock to access the list
class RecycledListInfo
{
static const unsigned int MaxCachedEntries = 40;
struct Entry
{
Entry* next;
};
Volatile<LONG> lock; // this is the spin lock
DWORD count; // count of number of elements in the list
Entry* root; // ptr to first element of recycled list
#ifndef _WIN64
DWORD filler; // Pad the structure to a multiple of the 16.
#endif
//--//
public:
RecycledListInfo()
{
LIMITED_METHOD_CONTRACT;
lock = 0;
root = NULL;
count = 0;
}
FORCEINLINE bool CanInsert()
{
LIMITED_METHOD_CONTRACT;
return count < MaxCachedEntries;
}
FORCEINLINE LPVOID Remove()
{
LIMITED_METHOD_CONTRACT;
if(root == NULL) return NULL; // No need for acquiring the lock, there's nothing to remove.
AcquireLock();
Entry* ret = (Entry*)root;
if(ret)
{
root = ret->next;
count -= 1;
}
ReleaseLock();
return ret;
}
FORCEINLINE void Insert( LPVOID mem )
{
LIMITED_METHOD_CONTRACT;
AcquireLock();
Entry* entry = (Entry*)mem;
entry->next = root;
root = entry;
count += 1;
ReleaseLock();
}
private:
FORCEINLINE void AcquireLock()
{
LIMITED_METHOD_CONTRACT;
unsigned int rounds = 0;
DWORD dwSwitchCount = 0;
while(lock != 0 || FastInterlockExchange( &lock, 1 ) != 0)
{
YieldProcessorNormalized(); // indicate to the processor that we are spinning
rounds++;
if((rounds % 32) == 0)
{
__SwitchToThread( 0, ++dwSwitchCount );
}
}
}
FORCEINLINE void ReleaseLock()
{
LIMITED_METHOD_CONTRACT;
lock = 0;
}
};
//
// It's critical that we ensure these pointers are allocated by the linker away from
// variables that are modified a lot at runtime.
//
// The use of the CacheGuard is a temporary solution,
// the thread pool has to be refactor away from static variable and
// toward a single global structure, where we can control the locality of variables.
//
class RecycledListsWrapper
{
DWORD CacheGuardPre[MAX_CACHE_LINE_SIZE/sizeof(DWORD)];
RecycledListInfo (*pRecycledListPerProcessor)[MEMTYPE_COUNT]; // RecycledListInfo [numProc][MEMTYPE_COUNT]
DWORD CacheGuardPost[MAX_CACHE_LINE_SIZE/sizeof(DWORD)];
public:
void Initialize( unsigned int numProcs );
FORCEINLINE bool IsInitialized()
{
LIMITED_METHOD_CONTRACT;
return pRecycledListPerProcessor != NULL;
}
FORCEINLINE RecycledListInfo& GetRecycleMemoryInfo( enum MemType memType )
{
LIMITED_METHOD_CONTRACT;
DWORD processorNumber = 0;
#ifndef FEATURE_PAL
if (CPUGroupInfo::CanEnableGCCPUGroups() && CPUGroupInfo::CanEnableThreadUseAllCpuGroups())
processorNumber = CPUGroupInfo::CalculateCurrentProcessorNumber();
else
// Turns out GetCurrentProcessorNumber can return a value greater than the number of processors reported by
// GetSystemInfo, if we're running in WOW64 on a machine with >32 processors.
processorNumber = GetCurrentProcessorNumber()%NumberOfProcessors;
#else // !FEATURE_PAL
if (PAL_HasGetCurrentProcessorNumber())
{
processorNumber = GetCurrentProcessorNumber();
}
#endif // !FEATURE_PAL
return pRecycledListPerProcessor[processorNumber][memType];
}
};
#define GATE_THREAD_STATUS_NOT_RUNNING 0 // There is no gate thread
#define GATE_THREAD_STATUS_REQUESTED 1 // There is a gate thread, and someone has asked it to stick around recently
#define GATE_THREAD_STATUS_WAITING_FOR_REQUEST 2 // There is a gate thread, but nobody has asked it to stay. It may die soon
// Private methods
static DWORD WINAPI intermediateThreadProc(PVOID arg);
typedef struct {
LPTHREAD_START_ROUTINE lpThreadFunction;
PVOID lpArg;
} intermediateThreadParam;
static Thread* CreateUnimpersonatedThread(LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpArgs, BOOL *pIsCLRThread);
static BOOL CreateWorkerThread();
static void EnqueueWorkRequest(WorkRequest* wr);
static WorkRequest* DequeueWorkRequest();
static void ExecuteWorkRequest(bool* foundWork, bool* wasNotRecalled);
static DWORD WINAPI ExecuteHostRequest(PVOID pArg);
#ifndef DACCESS_COMPILE
inline static void AppendWorkRequest(WorkRequest* entry)
{
CONTRACTL
{
NOTHROW;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (WorkRequestTail)
{
_ASSERTE(WorkRequestHead != NULL);
WorkRequestTail->next = entry;
}
else
{
_ASSERTE(WorkRequestHead == NULL);
WorkRequestHead = entry;
}
WorkRequestTail = entry;
_ASSERTE(WorkRequestTail->next == NULL);
}
inline static WorkRequest* RemoveWorkRequest()
{
CONTRACTL
{
NOTHROW;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
WorkRequest* entry = NULL;
if (WorkRequestHead)
{
entry = WorkRequestHead;
WorkRequestHead = entry->next;
if (WorkRequestHead == NULL)
WorkRequestTail = NULL;
}
return entry;
}
static void EnsureInitialized();
static void InitPlatformVariables();
inline static BOOL IsInitialized()
{
LIMITED_METHOD_CONTRACT;
return Initialization == -1;
}
static void MaybeAddWorkingWorker();
static void NotifyWorkItemCompleted()
{
WRAPPER_NO_CONTRACT;
Thread::IncrementWorkerThreadPoolCompletionCount(GetThread());
UpdateLastDequeueTime();
}
static bool ShouldAdjustMaxWorkersActive()
{
WRAPPER_NO_CONTRACT;
DWORD priorTime = PriorCompletedWorkRequestsTime;
MemoryBarrier(); // read fresh value for NextCompletedWorkRequestsTime below
DWORD requiredInterval = NextCompletedWorkRequestsTime - priorTime;
DWORD elapsedInterval = GetTickCount() - priorTime;
if (elapsedInterval >= requiredInterval)
{
ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts();
if (counts.NumActive <= counts.MaxWorking)
return !IsHillClimbingDisabled;
}
return false;
}
static void AdjustMaxWorkersActive();
static bool ShouldWorkerKeepRunning();
static BOOL SuspendProcessing();
static DWORD SafeWait(CLREvent * ev, DWORD sleepTime, BOOL alertable);
static DWORD WINAPI WorkerThreadStart(LPVOID lpArgs);
static BOOL AddWaitRequest(HANDLE waitHandle, WaitInfo* waitInfo);
static ThreadCB* FindWaitThread(); // returns a wait thread that can accomodate another wait request
static BOOL CreateWaitThread();
static void WINAPI InsertNewWaitForSelf(WaitInfo* pArg);
static int FindWaitIndex(const ThreadCB* threadCB, const HANDLE waitHandle);
static DWORD MinimumRemainingWait(LIST_ENTRY* waitInfo, unsigned int numWaits);
static void ProcessWaitCompletion( WaitInfo* waitInfo,
unsigned index, // array index
BOOL waitTimedOut);
static DWORD WINAPI WaitThreadStart(LPVOID lpArgs);
static DWORD WINAPI AsyncCallbackCompletion(PVOID pArgs);
static void QueueTimerInfoForRelease(TimerInfo *pTimerInfo);
static void DeactivateWait(WaitInfo* waitInfo);
static void DeactivateNthWait(WaitInfo* waitInfo, DWORD index);
static void DeleteWait(WaitInfo* waitInfo);
inline static void ShiftWaitArray( ThreadCB* threadCB,
ULONG SrcIndex,
ULONG DestIndex,
ULONG count)
{
LIMITED_METHOD_CONTRACT;
memmove(&threadCB->waitHandle[DestIndex],
&threadCB->waitHandle[SrcIndex],
count * sizeof(HANDLE));
memmove(&threadCB->waitPointer[DestIndex],
&threadCB->waitPointer[SrcIndex],
count * sizeof(LIST_ENTRY));
}
static void WINAPI DeregisterWait(WaitInfo* pArgs);
#ifndef FEATURE_PAL
// holds the aggregate of system cpu usage of all processors
typedef struct _PROCESS_CPU_INFORMATION
{
LARGE_INTEGER idleTime;
LARGE_INTEGER kernelTime;
LARGE_INTEGER userTime;
DWORD_PTR affinityMask;
int numberOfProcessors;
SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* usageBuffer;
int usageBufferSize;
} PROCESS_CPU_INFORMATION;
static int GetCPUBusyTime_NT(PROCESS_CPU_INFORMATION* pOldInfo);
static BOOL CreateCompletionPortThread(LPVOID lpArgs);
static DWORD WINAPI CompletionPortThreadStart(LPVOID lpArgs);
public:
inline static bool HaveNativeWork()
{
LIMITED_METHOD_CONTRACT;
return WorkRequestHead != NULL;
}
static void GrowCompletionPortThreadpoolIfNeeded();
static BOOL ShouldGrowCompletionPortThreadpool(ThreadCounter::Counts counts);
#else
static int GetCPUBusyTime_NT(PAL_IOCP_CPU_INFORMATION* pOldInfo);
#endif // !FEATURE_PAL
private:
static BOOL IsIoPending();
static BOOL CreateGateThread();
static void EnsureGateThreadRunning();
static bool ShouldGateThreadKeepRunning();
static DWORD WINAPI GateThreadStart(LPVOID lpArgs);
static BOOL SufficientDelaySinceLastSample(unsigned int LastThreadCreationTime,
unsigned NumThreads, // total number of threads of that type (worker or CP)
double throttleRate=0.0 // the delay is increased by this percentage for each extra thread
);
static BOOL SufficientDelaySinceLastDequeue();
static LPVOID GetRecycledMemory(enum MemType memType);
static DWORD WINAPI TimerThreadStart(LPVOID args);
static void TimerThreadFire(); // helper method used by TimerThreadStart
static void WINAPI InsertNewTimer(TimerInfo* pArg);
static DWORD FireTimers();
static DWORD WINAPI AsyncTimerCallbackCompletion(PVOID pArgs);
static void DeactivateTimer(TimerInfo* timerInfo);
static DWORD WINAPI AsyncDeleteTimer(PVOID pArgs);
static void DeleteTimer(TimerInfo* timerInfo);
static void WINAPI UpdateTimer(TimerUpdateInfo* pArgs);
static void WINAPI DeregisterTimer(TimerInfo* pArgs);
inline static DWORD QueueDeregisterWait(HANDLE waitThread, WaitInfo* waitInfo)
{
CONTRACTL
{
NOTHROW;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
DWORD result = QueueUserAPC(reinterpret_cast<PAPCFUNC>(DeregisterWait), waitThread, reinterpret_cast<ULONG_PTR>(waitInfo));
SetWaitThreadAPCPending();
return result;
}
inline static void SetWaitThreadAPCPending() {IsApcPendingOnWaitThread = TRUE;}
inline static void ResetWaitThreadAPCPending() {IsApcPendingOnWaitThread = FALSE;}
inline static BOOL IsWaitThreadAPCPending() {return IsApcPendingOnWaitThread;}
#ifdef _DEBUG
inline static DWORD GetTickCount()