summaryrefslogtreecommitdiff
path: root/src/vm/win32threadpool.cpp
blob: 1ec90c54bc8bb81071238a9dca339a48ea711655 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
// 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.cpp

Abstract:

    This module implements Threadpool support using Win32 APIs


Revision History:
    December 1999 - Created

--*/

#include "common.h"
#include "log.h"
#include "threadpoolrequest.h"
#include "win32threadpool.h"
#include "delegateinfo.h"
#include "eeconfig.h"
#include "dbginterface.h"
#include "corhost.h"
#include "eventtrace.h"
#include "threads.h"
#include "appdomain.inl"
#include "nativeoverlapped.h"
#include "hillclimbing.h"
#include "configuration.h"


#ifndef FEATURE_PAL
#ifndef DACCESS_COMPILE

// APIs that must be accessed through dynamic linking. 
typedef int (WINAPI *NtQueryInformationThreadProc) (
    HANDLE ThreadHandle,
    THREADINFOCLASS ThreadInformationClass,
    PVOID ThreadInformation,
    ULONG ThreadInformationLength,
    PULONG ReturnLength);
NtQueryInformationThreadProc g_pufnNtQueryInformationThread = NULL;

typedef int (WINAPI *NtQuerySystemInformationProc) ( 
    SYSTEM_INFORMATION_CLASS SystemInformationClass,
    PVOID SystemInformation,
    ULONG SystemInformationLength,
    PULONG ReturnLength OPTIONAL);
NtQuerySystemInformationProc g_pufnNtQuerySystemInformation = NULL;

typedef HANDLE (WINAPI * CreateWaitableTimerExProc) (
    LPSECURITY_ATTRIBUTES lpTimerAttributes,
    LPCTSTR lpTimerName,
    DWORD dwFlags,
    DWORD dwDesiredAccess);
CreateWaitableTimerExProc g_pufnCreateWaitableTimerEx = NULL;

typedef BOOL (WINAPI * SetWaitableTimerExProc) (
    HANDLE hTimer,
    const LARGE_INTEGER *lpDueTime,
    LONG lPeriod,
    PTIMERAPCROUTINE pfnCompletionRoutine,
    LPVOID lpArgToCompletionRoutine,
    void* WakeContext, //should be PREASON_CONTEXT, but it's not defined for us (and we don't use it)
    ULONG TolerableDelay);
SetWaitableTimerExProc g_pufnSetWaitableTimerEx = NULL;

#endif // !DACCESS_COMPILE
#endif // !FEATURE_PAL

BOOL ThreadpoolMgr::InitCompletionPortThreadpool = FALSE;
HANDLE ThreadpoolMgr::GlobalCompletionPort;                 // used for binding io completions on file handles

SVAL_IMPL(ThreadpoolMgr::ThreadCounter,ThreadpoolMgr,CPThreadCounter);

SVAL_IMPL_INIT(LONG,ThreadpoolMgr,MaxLimitTotalCPThreads,1000);   // = MaxLimitCPThreadsPerCPU * number of CPUS
SVAL_IMPL(LONG,ThreadpoolMgr,MinLimitTotalCPThreads);             
SVAL_IMPL(LONG,ThreadpoolMgr,MaxFreeCPThreads);                   // = MaxFreeCPThreadsPerCPU * Number of CPUS

Volatile<LONG> ThreadpoolMgr::NumCPInfrastructureThreads = 0;      // number of threads currently busy handling draining cycle

// Cacheline aligned, hot variable
DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) SVAL_IMPL(ThreadpoolMgr::ThreadCounter, ThreadpoolMgr, WorkerCounter);

SVAL_IMPL(LONG,ThreadpoolMgr,MinLimitTotalWorkerThreads);          // = MaxLimitCPThreadsPerCPU * number of CPUS
SVAL_IMPL(LONG,ThreadpoolMgr,MaxLimitTotalWorkerThreads);        // = MaxLimitCPThreadsPerCPU * number of CPUS

SVAL_IMPL(LONG,ThreadpoolMgr,cpuUtilization);
LONG    ThreadpoolMgr::cpuUtilizationAverage = 0;

HillClimbing ThreadpoolMgr::HillClimbingInstance;

// Cacheline aligned, 3 hot variables updated in a group
DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) LONG ThreadpoolMgr::PriorCompletedWorkRequests = 0;
DWORD ThreadpoolMgr::PriorCompletedWorkRequestsTime;
DWORD ThreadpoolMgr::NextCompletedWorkRequestsTime;

LARGE_INTEGER ThreadpoolMgr::CurrentSampleStartTime;

unsigned int ThreadpoolMgr::WorkerThreadSpinLimit;
bool ThreadpoolMgr::IsHillClimbingDisabled;
int ThreadpoolMgr::ThreadAdjustmentInterval;

#define INVALID_HANDLE ((HANDLE) -1)
#define NEW_THREAD_THRESHOLD            7       // Number of requests outstanding before we start a new thread
#define CP_THREAD_PENDINGIO_WAIT 5000           // polling interval when thread is retired but has a pending io
#define GATE_THREAD_DELAY 500 /*milliseconds*/
#define GATE_THREAD_DELAY_TOLERANCE 50 /*milliseconds*/
#define DELAY_BETWEEN_SUSPENDS 5000 + GATE_THREAD_DELAY // time to delay between suspensions
#define SUSPEND_TIME GATE_THREAD_DELAY+100      // milliseconds to suspend during SuspendProcessing

LONG ThreadpoolMgr::Initialization=0;           // indicator of whether the threadpool is initialized.

// Cacheline aligned, hot variable
DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) unsigned int ThreadpoolMgr::LastDequeueTime; // used to determine if work items are getting thread starved

// Move out of from preceeding variables' cache line
DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) int ThreadpoolMgr::offset_counter = 0;

SPTR_IMPL(WorkRequest,ThreadpoolMgr,WorkRequestHead);        // Head of work request queue
SPTR_IMPL(WorkRequest,ThreadpoolMgr,WorkRequestTail);        // Head of work request queue

SVAL_IMPL(ThreadpoolMgr::LIST_ENTRY,ThreadpoolMgr,TimerQueue);  // queue of timers

//unsigned int ThreadpoolMgr::LastCpuSamplingTime=0;      //  last time cpu utilization was sampled by gate thread
unsigned int ThreadpoolMgr::LastCPThreadCreation=0;     //  last time a completion port thread was created
unsigned int ThreadpoolMgr::NumberOfProcessors; // = NumberOfWorkerThreads - no. of blocked threads


CrstStatic ThreadpoolMgr::WorkerCriticalSection;
CLREvent * ThreadpoolMgr::RetiredCPWakeupEvent;       // wakeup event for completion port threads
CrstStatic ThreadpoolMgr::WaitThreadsCriticalSection;
ThreadpoolMgr::LIST_ENTRY ThreadpoolMgr::WaitThreadsHead;

CLRLifoSemaphore* ThreadpoolMgr::WorkerSemaphore;
CLRLifoSemaphore* ThreadpoolMgr::RetiredWorkerSemaphore;

CrstStatic ThreadpoolMgr::TimerQueueCriticalSection;
HANDLE ThreadpoolMgr::TimerThread=NULL;
Thread *ThreadpoolMgr::pTimerThread=NULL;

// Cacheline aligned, hot variable
DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) DWORD ThreadpoolMgr::LastTickCount;

#ifdef _DEBUG
DWORD ThreadpoolMgr::TickCountAdjustment=0;
#endif

// Cacheline aligned, hot variable
DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) LONG  ThreadpoolMgr::GateThreadStatus=GATE_THREAD_STATUS_NOT_RUNNING;

// Move out of from preceeding variables' cache line
DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) ThreadpoolMgr::RecycledListsWrapper ThreadpoolMgr::RecycledLists;

ThreadpoolMgr::TimerInfo *ThreadpoolMgr::TimerInfosToBeRecycled = NULL;

BOOL ThreadpoolMgr::IsApcPendingOnWaitThread = FALSE;

#ifndef DACCESS_COMPILE

// Macros for inserting/deleting from doubly linked list

#define InitializeListHead(ListHead) (\
    (ListHead)->Flink = (ListHead)->Blink = (ListHead))

//
// these are named the same as slightly different macros in the NT headers
//
#undef RemoveHeadList
#undef RemoveEntryList
#undef InsertTailList
#undef InsertHeadList

#define RemoveHeadList(ListHead,FirstEntry) \
    {\
    FirstEntry = (LIST_ENTRY*) (ListHead)->Flink;\
    ((LIST_ENTRY*)FirstEntry->Flink)->Blink = (ListHead);\
    (ListHead)->Flink = FirstEntry->Flink;\
    }

#define RemoveEntryList(Entry) {\
    LIST_ENTRY* _EX_Entry;\
        _EX_Entry = (Entry);\
        ((LIST_ENTRY*) _EX_Entry->Blink)->Flink = _EX_Entry->Flink;\
        ((LIST_ENTRY*) _EX_Entry->Flink)->Blink = _EX_Entry->Blink;\
    }

#define InsertTailList(ListHead,Entry) \
    (Entry)->Flink = (ListHead);\
    (Entry)->Blink = (ListHead)->Blink;\
    ((LIST_ENTRY*)(ListHead)->Blink)->Flink = (Entry);\
    (ListHead)->Blink = (Entry);

#define InsertHeadList(ListHead,Entry) {\
    LIST_ENTRY* _EX_Flink;\
    LIST_ENTRY* _EX_ListHead;\
    _EX_ListHead = (LIST_ENTRY*)(ListHead);\
    _EX_Flink = (LIST_ENTRY*) _EX_ListHead->Flink;\
    (Entry)->Flink = _EX_Flink;\
    (Entry)->Blink = _EX_ListHead;\
    _EX_Flink->Blink = (Entry);\
    _EX_ListHead->Flink = (Entry);\
    }

#define IsListEmpty(ListHead) \
    ((ListHead)->Flink == (ListHead))

#define SetLastHRError(hr) \
    if (HRESULT_FACILITY(hr) == FACILITY_WIN32)\
        SetLastError(HRESULT_CODE(hr));\
    else \
        SetLastError(ERROR_INVALID_DATA);\

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

void ThreadpoolMgr::RecycledListsWrapper::Initialize( unsigned int numProcs )
{
    CONTRACTL
    {
        THROWS;
        MODE_ANY;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    pRecycledListPerProcessor = new RecycledListInfo[numProcs][MEMTYPE_COUNT];
}

//--//

void ThreadpoolMgr::EnsureInitialized()
{
    CONTRACTL
    {
        THROWS;         // Initialize can throw
        MODE_ANY;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    if (IsInitialized())
        return;

    DWORD dwSwitchCount = 0;

retry:
    if (InterlockedCompareExchange(&Initialization, 1, 0) == 0)
    {
        if (Initialize())
            Initialization = -1;
        else
        {
            Initialization = 0;
            COMPlusThrowOM();
        }
    }
    else // someone has already begun initializing.
    {
        // wait until it finishes
        while (Initialization != -1)
        {
            __SwitchToThread(0, ++dwSwitchCount);
            goto retry;
        }
    }
}

DWORD GetDefaultMaxLimitWorkerThreads(DWORD minLimit)
{
    CONTRACTL
    {
        MODE_ANY;
        GC_NOTRIGGER;
        NOTHROW;
    }
    CONTRACTL_END;

    //
    // We determine the max limit for worker threads as follows:
    //
    //  1) It must be at least MinLimitTotalWorkerThreads
    //  2) It must be no greater than (half the virtual address space)/(thread stack size)
    //  3) It must be <= MaxPossibleWorkerThreads
    //
    // TODO: what about CP threads?  Can they follow a similar plan?  How do we allocate
    // thread counts between the two kinds of threads?
    //
    SIZE_T stackReserveSize = 0;
    Thread::GetProcessDefaultStackSize(&stackReserveSize, NULL);

    ULONGLONG halfVirtualAddressSpace;

    MEMORYSTATUSEX memStats;
    memStats.dwLength = sizeof(memStats);
    if (GlobalMemoryStatusEx(&memStats))
    {
        halfVirtualAddressSpace = memStats.ullTotalVirtual / 2;
    }
    else
    {
        //assume the normal Win32 32-bit virtual address space
        halfVirtualAddressSpace = 0x000000007FFE0000ull / 2;
    }

    ULONGLONG limit = halfVirtualAddressSpace / stackReserveSize;
    limit = max(limit, (ULONGLONG)minLimit);
    limit = min(limit, (ULONGLONG)ThreadpoolMgr::ThreadCounter::MaxPossibleCount);

    _ASSERTE(FitsIn<DWORD>(limit));
    return (DWORD)limit;
}

DWORD GetForceMinWorkerThreadsValue()
{
    WRAPPER_NO_CONTRACT;
    return Configuration::GetKnobDWORDValue(W("System.Threading.ThreadPool.MinThreads"), CLRConfig::INTERNAL_ThreadPool_ForceMinWorkerThreads);
}

DWORD GetForceMaxWorkerThreadsValue()
{
    WRAPPER_NO_CONTRACT;
    return Configuration::GetKnobDWORDValue(W("System.Threading.ThreadPool.MaxThreads"), CLRConfig::INTERNAL_ThreadPool_ForceMaxWorkerThreads);
}

BOOL ThreadpoolMgr::Initialize()
{
    CONTRACTL
    {
        THROWS;
        MODE_ANY;
        GC_NOTRIGGER;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END;

    BOOL bRet = FALSE;
    BOOL bExceptionCaught = FALSE;

    UnManagedPerAppDomainTPCount* pADTPCount;
    pADTPCount = PerAppDomainTPCountList::GetUnmanagedTPCount();

#ifndef FEATURE_PAL
    //ThreadPool_CPUGroup
    CPUGroupInfo::EnsureInitialized();
    if (CPUGroupInfo::CanEnableGCCPUGroups() && CPUGroupInfo::CanEnableThreadUseAllCpuGroups())
        NumberOfProcessors = CPUGroupInfo::GetNumActiveProcessors();
    else
        NumberOfProcessors = GetCurrentProcessCpuCount();
#else // !FEATURE_PAL
    NumberOfProcessors = GetCurrentProcessCpuCount();
#endif // !FEATURE_PAL
    InitPlatformVariables();

    EX_TRY
    {
        WorkerThreadSpinLimit = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_UnfairSemaphoreSpinLimit);
        IsHillClimbingDisabled = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_HillClimbing_Disable) != 0;
        ThreadAdjustmentInterval = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_HillClimbing_SampleIntervalLow);
        
        pADTPCount->InitResources();
        WorkerCriticalSection.Init(CrstThreadpoolWorker);
        WaitThreadsCriticalSection.Init(CrstThreadpoolWaitThreads);
        TimerQueueCriticalSection.Init(CrstThreadpoolTimerQueue);

        // initialize WaitThreadsHead
        InitializeListHead(&WaitThreadsHead);

        // initialize TimerQueue
        InitializeListHead(&TimerQueue);

        RetiredCPWakeupEvent = new CLREvent();
        RetiredCPWakeupEvent->CreateAutoEvent(FALSE);
        _ASSERTE(RetiredCPWakeupEvent->IsValid());

        WorkerSemaphore = new CLRLifoSemaphore();
        WorkerSemaphore->Create(0, ThreadCounter::MaxPossibleCount);

        RetiredWorkerSemaphore = new CLRLifoSemaphore();
        RetiredWorkerSemaphore->Create(0, ThreadCounter::MaxPossibleCount);

#ifndef FEATURE_PAL
        //ThreadPool_CPUGroup
        if (CPUGroupInfo::CanEnableGCCPUGroups() && CPUGroupInfo::CanEnableThreadUseAllCpuGroups())
            RecycledLists.Initialize( CPUGroupInfo::GetNumActiveProcessors() );
        else
            RecycledLists.Initialize( g_SystemInfo.dwNumberOfProcessors );
#else // !FEATURE_PAL
        RecycledLists.Initialize( PAL_GetTotalCpuCount() );
#endif // !FEATURE_PAL
    }
    EX_CATCH
    {
        pADTPCount->CleanupResources();

        if (RetiredCPWakeupEvent)
        {
            delete RetiredCPWakeupEvent;
            RetiredCPWakeupEvent = NULL;
        }

        // Note: It is fine to call Destroy on uninitialized critical sections
        WorkerCriticalSection.Destroy();
        WaitThreadsCriticalSection.Destroy();
        TimerQueueCriticalSection.Destroy();

        bExceptionCaught = TRUE;
    }
    EX_END_CATCH(SwallowAllExceptions);

    if (bExceptionCaught)
    {
        goto end;
    }

    // initialize Worker and CP thread settings
    DWORD forceMin;
    forceMin = GetForceMinWorkerThreadsValue();
    MinLimitTotalWorkerThreads = forceMin > 0 ? (LONG)forceMin : (LONG)NumberOfProcessors;

    DWORD forceMax;
    forceMax = GetForceMaxWorkerThreadsValue();
    MaxLimitTotalWorkerThreads = forceMax > 0 ? (LONG)forceMax : (LONG)GetDefaultMaxLimitWorkerThreads(MinLimitTotalWorkerThreads);

    ThreadCounter::Counts counts;
    counts.NumActive = 0;
    counts.NumWorking = 0;
    counts.NumRetired = 0;
    counts.MaxWorking = MinLimitTotalWorkerThreads;
    WorkerCounter.counts.AsLongLong = counts.AsLongLong;

#ifdef _DEBUG
    TickCountAdjustment = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadpoolTickCountAdjustment);
#endif

    // initialize CP thread settings
    MinLimitTotalCPThreads = NumberOfProcessors;

    // Use volatile store to guarantee make the value visible to the DAC (the store can be optimized out otherwise)
    VolatileStoreWithoutBarrier<LONG>(&MaxFreeCPThreads, NumberOfProcessors*MaxFreeCPThreadsPerCPU);

    counts.NumActive = 0;
    counts.NumWorking = 0;
    counts.NumRetired = 0;
    counts.MaxWorking = MinLimitTotalCPThreads;
    CPThreadCounter.counts.AsLongLong = counts.AsLongLong;

#ifndef FEATURE_PAL    
    {
        GlobalCompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
                                                      NULL,
                                                      0,        /*ignored for invalid handle value*/
                                                      NumberOfProcessors);
    }
#endif // !FEATURE_PAL    

    HillClimbingInstance.Initialize();

    bRet = TRUE;
end:
    return bRet;
}

void ThreadpoolMgr::InitPlatformVariables()
{
    CONTRACTL
    {
        NOTHROW;         
        MODE_ANY;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

#ifndef FEATURE_PAL   
    HINSTANCE  hNtDll;
    HINSTANCE  hCoreSynch;
    {
        CONTRACT_VIOLATION(GCViolation|FaultViolation);
        hNtDll = CLRLoadLibrary(W("ntdll.dll"));
        _ASSERTE(hNtDll);
#ifdef FEATURE_CORESYSTEM
        hCoreSynch = CLRLoadLibrary(W("api-ms-win-core-synch-l1-1-0.dll"));
#else
        hCoreSynch = CLRLoadLibrary(W("kernel32.dll"));
#endif
        _ASSERTE(hCoreSynch);
    }

    // These APIs must be accessed via dynamic binding since they may be removed in future
    // OS versions.
    g_pufnNtQueryInformationThread = (NtQueryInformationThreadProc)GetProcAddress(hNtDll,"NtQueryInformationThread");
    g_pufnNtQuerySystemInformation = (NtQuerySystemInformationProc)GetProcAddress(hNtDll,"NtQuerySystemInformation");


    // These APIs are only supported on newer Windows versions
    g_pufnCreateWaitableTimerEx = (CreateWaitableTimerExProc)GetProcAddress(hCoreSynch, "CreateWaitableTimerExW");
    g_pufnSetWaitableTimerEx = (SetWaitableTimerExProc)GetProcAddress(hCoreSynch, "SetWaitableTimerEx");
#endif    
}

BOOL ThreadpoolMgr::SetMaxThreadsHelper(DWORD MaxWorkerThreads,
                                        DWORD MaxIOCompletionThreads)
{
    CONTRACTL
    {
        THROWS;     // Crst can throw and toggle GC mode
        MODE_ANY;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    BOOL result = FALSE;

    // doesn't need to be WorkerCS, but using it to avoid race condition between setting min and max, and didn't want to create a new CS.
    CrstHolder csh(&WorkerCriticalSection);

    if (MaxWorkerThreads >= (DWORD)MinLimitTotalWorkerThreads &&
        MaxIOCompletionThreads >= (DWORD)MinLimitTotalCPThreads &&
        MaxWorkerThreads != 0 &&
        MaxIOCompletionThreads != 0)
    {
        if (GetForceMaxWorkerThreadsValue() == 0)
        {
            MaxLimitTotalWorkerThreads = min(MaxWorkerThreads, (DWORD)ThreadCounter::MaxPossibleCount);

            ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts();
            while (counts.MaxWorking > MaxLimitTotalWorkerThreads)
            {
                ThreadCounter::Counts newCounts = counts;
                newCounts.MaxWorking = MaxLimitTotalWorkerThreads;

                ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts);
                if (oldCounts == counts)
                    counts = newCounts;
                else
                    counts = oldCounts;
            }
        }

        MaxLimitTotalCPThreads = min(MaxIOCompletionThreads, (DWORD)ThreadCounter::MaxPossibleCount);

        result = TRUE;
    }

    return result;
 }

/************************************************************************/
BOOL ThreadpoolMgr::SetMaxThreads(DWORD MaxWorkerThreads,
                                  DWORD MaxIOCompletionThreads)
{
    CONTRACTL
    {
        THROWS;     // SetMaxThreadsHelper can throw and toggle GC mode
        MODE_ANY;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    EnsureInitialized();

    return SetMaxThreadsHelper(MaxWorkerThreads, MaxIOCompletionThreads);
}

BOOL ThreadpoolMgr::GetMaxThreads(DWORD* MaxWorkerThreads,
                                  DWORD* MaxIOCompletionThreads)
{
    LIMITED_METHOD_CONTRACT;


    if (!MaxWorkerThreads || !MaxIOCompletionThreads)
    {
        SetLastHRError(ERROR_INVALID_DATA);
        return FALSE;
    }

    EnsureInitialized();

    *MaxWorkerThreads = (DWORD)MaxLimitTotalWorkerThreads;
    *MaxIOCompletionThreads = MaxLimitTotalCPThreads;
    return TRUE;
}

BOOL ThreadpoolMgr::SetMinThreads(DWORD MinWorkerThreads,
                                  DWORD MinIOCompletionThreads)
{
    CONTRACTL
    {
        THROWS;     // Crst can throw and toggle GC mode
        MODE_ANY;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    EnsureInitialized();

    // doesn't need to be WorkerCS, but using it to avoid race condition between setting min and max, and didn't want to create a new CS.
    CrstHolder csh(&WorkerCriticalSection);

    BOOL init_result = FALSE;

    if (MinWorkerThreads >= 0 && MinIOCompletionThreads >= 0 &&
        MinWorkerThreads <= (DWORD) MaxLimitTotalWorkerThreads &&
        MinIOCompletionThreads <= (DWORD) MaxLimitTotalCPThreads)
    {
        if (GetForceMinWorkerThreadsValue() == 0)
        {
            MinLimitTotalWorkerThreads = max(1, min(MinWorkerThreads, (DWORD)ThreadCounter::MaxPossibleCount));

            ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts();
            while (counts.MaxWorking < MinLimitTotalWorkerThreads)
            {
                ThreadCounter::Counts newCounts = counts;
                newCounts.MaxWorking = MinLimitTotalWorkerThreads;

                ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts);
                if (oldCounts == counts)
                {
                    counts = newCounts;

                    // if we increased the limit, and there are pending workitems, we need
                    // to dispatch a thread to process the work.
                    if (newCounts.MaxWorking > oldCounts.MaxWorking &&
                        PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains())
                    {
                        MaybeAddWorkingWorker();
                    }
                }
                else
                {
                    counts = oldCounts;
                }
            }
        }

        MinLimitTotalCPThreads = max(1, min(MinIOCompletionThreads, (DWORD)ThreadCounter::MaxPossibleCount));

        init_result = TRUE;
    }

    return init_result;
}

BOOL ThreadpoolMgr::GetMinThreads(DWORD* MinWorkerThreads,
                                  DWORD* MinIOCompletionThreads)
{
    LIMITED_METHOD_CONTRACT;


    if (!MinWorkerThreads || !MinIOCompletionThreads)
    {
        SetLastHRError(ERROR_INVALID_DATA);
        return FALSE;
    }

    EnsureInitialized();

    *MinWorkerThreads = (DWORD)MinLimitTotalWorkerThreads;
    *MinIOCompletionThreads = MinLimitTotalCPThreads;
    return TRUE;
}

BOOL ThreadpoolMgr::GetAvailableThreads(DWORD* AvailableWorkerThreads,
                                        DWORD* AvailableIOCompletionThreads)
{
    LIMITED_METHOD_CONTRACT;

    if (!AvailableWorkerThreads || !AvailableIOCompletionThreads)
    {
        SetLastHRError(ERROR_INVALID_DATA);
        return FALSE;
    }

    EnsureInitialized();

    ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts();

    if (MaxLimitTotalWorkerThreads < counts.NumActive)
        *AvailableWorkerThreads = 0;
    else
        *AvailableWorkerThreads = MaxLimitTotalWorkerThreads - counts.NumWorking;

    counts = CPThreadCounter.GetCleanCounts();
    if (MaxLimitTotalCPThreads < counts.NumActive)
        *AvailableIOCompletionThreads = counts.NumActive - counts.NumWorking;
    else
        *AvailableIOCompletionThreads = MaxLimitTotalCPThreads - counts.NumWorking;
    return TRUE;
}

INT32 ThreadpoolMgr::GetThreadCount()
{
    WRAPPER_NO_CONTRACT;

    if (!IsInitialized())
    {
        return 0;
    }

    return WorkerCounter.DangerousGetDirtyCounts().NumActive + CPThreadCounter.DangerousGetDirtyCounts().NumActive;
}

void QueueUserWorkItemHelp(LPTHREAD_START_ROUTINE Function, PVOID Context)
{
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_GC_TRIGGERS;
    STATIC_CONTRACT_MODE_ANY;
    /* Cannot use contract here because of SEH
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;*/

    Function(Context);

    Thread *pThread = GetThread();
    if (pThread) {
        if (pThread->IsAbortRequested())
            pThread->EEResetAbort(Thread::TAR_ALL);
        pThread->InternalReset();
    }
}

//
// WorkingThreadCounts tracks the number of worker threads currently doing user work, and the maximum number of such threads
// since the last time TakeMaxWorkingThreadCount was called.  This information is for diagnostic purposes only,
// and is tracked only if the CLR config value INTERNAL_ThreadPool_EnableWorkerTracking is non-zero (this feature is off
// by default).
//
union WorkingThreadCounts
{
    struct
    {
        int currentWorking : 16;
        int maxWorking : 16;
    };

    LONG asLong;
};

WorkingThreadCounts g_workingThreadCounts;

//
// If worker tracking is enabled (see above) then this is called immediately before and after a worker thread executes
// each work item.
//
void ThreadpoolMgr::ReportThreadStatus(bool isWorking)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;
    _ASSERTE(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_EnableWorkerTracking));
    while (true)
    {
        WorkingThreadCounts currentCounts, newCounts;
        currentCounts.asLong = VolatileLoad(&g_workingThreadCounts.asLong);

        newCounts = currentCounts;

        if (isWorking)
            newCounts.currentWorking++;

        if (newCounts.currentWorking > newCounts.maxWorking)
            newCounts.maxWorking = newCounts.currentWorking;

        if (!isWorking)
            newCounts.currentWorking--;

        if (currentCounts.asLong == InterlockedCompareExchange(&g_workingThreadCounts.asLong, newCounts.asLong, currentCounts.asLong))
            break;
    }
}

//
// Returns the max working count since the previous call to TakeMaxWorkingThreadCount, and resets WorkingThreadCounts.maxWorking.
//
int TakeMaxWorkingThreadCount()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;
    _ASSERTE(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_EnableWorkerTracking));
    while (true)
    {
        WorkingThreadCounts currentCounts, newCounts;
        currentCounts.asLong = VolatileLoad(&g_workingThreadCounts.asLong);

        newCounts = currentCounts;
        newCounts.maxWorking = 0;

        if (currentCounts.asLong == InterlockedCompareExchange(&g_workingThreadCounts.asLong, newCounts.asLong, currentCounts.asLong))
        {
            // If we haven't updated the counts since the last call to TakeMaxWorkingThreadCount, then we never updated maxWorking.
            // In that case, the number of working threads for the whole period since the last TakeMaxWorkingThreadCount is the 
            // current number of working threads.
            return currentCounts.maxWorking == 0 ? currentCounts.currentWorking : currentCounts.maxWorking;
        }
    }
}


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

BOOL ThreadpoolMgr::QueueUserWorkItem(LPTHREAD_START_ROUTINE Function,
                                      PVOID Context,
                                      DWORD Flags,
                                      BOOL UnmanagedTPRequest)
{
    CONTRACTL
    {
        THROWS;     // EnsureInitialized, EnqueueWorkRequest can throw OOM
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    EnsureInitialized();


    if (Flags == CALL_OR_QUEUE)
    {
        // we've been asked to call this directly if the thread pressure is not too high

        int MinimumAvailableCPThreads = (NumberOfProcessors < 3) ? 3 : NumberOfProcessors;

        ThreadCounter::Counts counts = CPThreadCounter.GetCleanCounts();
        if ((MaxLimitTotalCPThreads - counts.NumActive) >= MinimumAvailableCPThreads )
        {
            QueueUserWorkItemHelp(Function, Context);
            return TRUE;
        }

    }

    if (UnmanagedTPRequest) 
    {
        UnManagedPerAppDomainTPCount* pADTPCount;
        pADTPCount = PerAppDomainTPCountList::GetUnmanagedTPCount(); 
        pADTPCount->QueueUnmanagedWorkRequest(Function, Context);
    }
    else
    {
        // caller has already registered its TPCount; this call is just to adjust the thread count
    }

    return TRUE;
}


bool ThreadpoolMgr::ShouldWorkerKeepRunning()
{
    WRAPPER_NO_CONTRACT;

    //
    // Maybe this thread should retire now.  Let's see.
    //
    bool shouldThisThreadKeepRunning = true;

    // Dirty read is OK here; the worst that can happen is that we won't retire this time.  In the
    // case where we might retire, we have to succeed a CompareExchange, which will have the effect
    // of validating this read.
    ThreadCounter::Counts counts = WorkerCounter.DangerousGetDirtyCounts();
    while (true)
    {
        if (counts.NumActive <= counts.MaxWorking)
        {
            shouldThisThreadKeepRunning = true;
            break;
        }

        ThreadCounter::Counts newCounts = counts;
        newCounts.NumWorking--;
        newCounts.NumActive--;
        newCounts.NumRetired++;

        ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts);

        if (oldCounts == counts)
        {
            shouldThisThreadKeepRunning = false;
            break;
        }

        counts = oldCounts;
    }

    return shouldThisThreadKeepRunning;
}

DangerousNonHostedSpinLock ThreadpoolMgr::ThreadAdjustmentLock;


//
// This method must only be called if ShouldAdjustMaxWorkersActive has returned true, *and*
// ThreadAdjustmentLock is held.
//
void ThreadpoolMgr::AdjustMaxWorkersActive()
{
    CONTRACTL
    {
        NOTHROW;
        if (GetThread()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        MODE_ANY;
    }
    CONTRACTL_END;

    _ASSERTE(ThreadAdjustmentLock.IsHeld());

    DWORD currentTicks = GetTickCount();
    LONG totalNumCompletions = (LONG)Thread::GetTotalWorkerThreadPoolCompletionCount();
    LONG numCompletions = totalNumCompletions - VolatileLoad(&PriorCompletedWorkRequests);

    LARGE_INTEGER startTime = CurrentSampleStartTime;
    LARGE_INTEGER endTime;
    QueryPerformanceCounter(&endTime);

    static LARGE_INTEGER freq;
    if (freq.QuadPart == 0)
        QueryPerformanceFrequency(&freq);

    double elapsed = (double)(endTime.QuadPart - startTime.QuadPart) / freq.QuadPart;

    //
    // It's possible for the current sample to be reset while we're holding 
    // ThreadAdjustmentLock.  This will result in a very short sample, possibly
    // with completely bogus counts.  We'll try to detect this by checking the sample
    // interval; if it's very short, then we try again later.
    //
    if (elapsed*1000.0 >= (ThreadAdjustmentInterval/2))
    {
        ThreadCounter::Counts currentCounts = WorkerCounter.GetCleanCounts();

        int newMax = HillClimbingInstance.Update(
            currentCounts.MaxWorking, 
            elapsed, 
            numCompletions,
            &ThreadAdjustmentInterval);

        while (newMax != currentCounts.MaxWorking)
        {
            ThreadCounter::Counts newCounts = currentCounts;
            newCounts.MaxWorking = newMax;

            ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, currentCounts);
            if (oldCounts == currentCounts)
            {
                //
                // If we're increasing the max, inject a thread.  If that thread finds work, it will inject
                // another thread, etc., until nobody finds work or we reach the new maximum.
                //
                // If we're reducing the max, whichever threads notice this first will retire themselves.
                //
                if (newMax > oldCounts.MaxWorking)
                    MaybeAddWorkingWorker();

                break;
            }
            else
            {
                // we failed - maybe try again
                if (oldCounts.MaxWorking > currentCounts.MaxWorking &&
                    oldCounts.MaxWorking >= newMax)
                {
                    // someone (probably the gate thread) increased the thread count more than
                    // we are about to do.  Don't interfere.
                    break;
                }

                currentCounts = oldCounts;
            }
        }

        PriorCompletedWorkRequests = totalNumCompletions;
        NextCompletedWorkRequestsTime = currentTicks + ThreadAdjustmentInterval;
        MemoryBarrier(); // flush previous writes (especially NextCompletedWorkRequestsTime)
        PriorCompletedWorkRequestsTime = currentTicks;
        CurrentSampleStartTime = endTime;;
    }
}


void ThreadpoolMgr::MaybeAddWorkingWorker()
{
    CONTRACTL
    {
        NOTHROW;
        if (GetThread()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        MODE_ANY;
    }
    CONTRACTL_END;

    // counts volatile read paired with CompareExchangeCounts loop set
    ThreadCounter::Counts counts = WorkerCounter.DangerousGetDirtyCounts();
    ThreadCounter::Counts newCounts;
    while (true)
    {
        newCounts = counts;
        newCounts.NumWorking = max(counts.NumWorking, min(counts.NumWorking + 1, counts.MaxWorking));
        newCounts.NumActive = max(counts.NumActive, newCounts.NumWorking);
        newCounts.NumRetired = max(0, counts.NumRetired - (newCounts.NumActive - counts.NumActive));

        if (newCounts == counts)
            return;

        ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts);

        if (oldCounts == counts)
            break;

        counts = oldCounts;
    }

    int toUnretire = counts.NumRetired - newCounts.NumRetired;
    int toCreate = (newCounts.NumActive - counts.NumActive) - toUnretire;
    int toRelease = (newCounts.NumWorking - counts.NumWorking) - (toUnretire + toCreate);

    _ASSERTE(toUnretire >= 0);
    _ASSERTE(toCreate >= 0);
    _ASSERTE(toRelease >= 0);
    _ASSERTE(toUnretire + toCreate + toRelease <= 1);

    if (toUnretire > 0)
    {
        RetiredWorkerSemaphore->Release(toUnretire);
    }

    if (toRelease > 0)
        WorkerSemaphore->Release(toRelease);

    while (toCreate > 0)
    {
        if (CreateWorkerThread())
        {
            toCreate--;
        }
        else
        {
            //
            // Uh-oh, we promised to create a new thread, but the creation failed.  We have to renege on our
            // promise.  This may possibly result in no work getting done for a while, but the gate thread will
            // eventually notice that no completions are happening and force the creation of a new thread.
            // Of course, there's no guarantee *that* will work - but hopefully enough time will have passed
            // to allow whoever's using all the memory right now to release some.
            //

            // counts volatile read paired with CompareExchangeCounts loop set
            counts = WorkerCounter.DangerousGetDirtyCounts();
            while (true)
            {
                //
                // If we said we would create a thread, we also said it would be working.  So we need to
                // decrement both NumWorking and NumActive by the number of threads we will no longer be creating.
                //
                newCounts = counts;
                newCounts.NumWorking -= toCreate;
                newCounts.NumActive -= toCreate;

                ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts);

                if (oldCounts == counts)
                    break;

                counts = oldCounts;
            }

            toCreate = 0;
        }
    }
}

BOOL ThreadpoolMgr::PostQueuedCompletionStatus(LPOVERLAPPED lpOverlapped,
                                      LPOVERLAPPED_COMPLETION_ROUTINE Function)
{
    CONTRACTL
    {
        THROWS;     // EnsureInitialized can throw OOM
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

#ifndef FEATURE_PAL
    EnsureInitialized();

    _ASSERTE(GlobalCompletionPort != NULL);

    if (!InitCompletionPortThreadpool)
        InitCompletionPortThreadpool = TRUE;

    GrowCompletionPortThreadpoolIfNeeded();

    // In order to allow external ETW listeners to correlate activities that use our IO completion port 
    // as a dispatch mechanism, we have to ensure the runtime's calls to ::PostQueuedCompletionStatus
    // and ::GetQueuedCompletionStatus are "annotated" with ETW events representing to operations 
    // performed.
    // There are currently 4 codepaths that post to the GlobalCompletionPort:
    // 1. and 2. - the Overlapped drainage events. Those are uninteresting to ETW listeners and 
    //    currently call the global ::PostQueuedCompletionStatus directly.
    // 3. the managed API ThreadPool.UnsafeQueueNativeOverlapped(), calling CorPostQueuedCompletionStatus()
    //    which already fires the ETW event as needed
    // 4. the managed API ThreadPool.RegisterWaitForSingleObject which needs to fire the ETW event
    //    at the time the managed API is called (on the orignial user thread), and not when the ::PQCS
    //    is called (from the dedicated wait thread).
    // If additional codepaths appear they need to either fire the ETW event before calling this or ensure
    // we do not fire an unmatched "dequeue" event in ThreadpoolMgr::CompletionPortThreadStart
    // The current possible values for Function:
    //  - CallbackForInitiateDrainageOfCompletionPortQueue and 
    //    CallbackForContinueDrainageOfCompletionPortQueue for Drainage
    //  - BindIoCompletionCallbackStub for ThreadPool.UnsafeQueueNativeOverlapped
    //  - WaitIOCompletionCallback for ThreadPool.RegisterWaitForSingleObject

    return ::PostQueuedCompletionStatus(GlobalCompletionPort,
                                        0,
                                        (ULONG_PTR) Function,
                                        lpOverlapped);
#else  
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
#endif // !FEATURE_PAL
}


void ThreadpoolMgr::WaitIOCompletionCallback(
    DWORD dwErrorCode,
    DWORD numBytesTransferred,
    LPOVERLAPPED lpOverlapped)
{
    CONTRACTL
    {
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (dwErrorCode == ERROR_SUCCESS)
        DWORD ret = AsyncCallbackCompletion((PVOID)lpOverlapped);
}

#ifndef FEATURE_PAL
// We need to make sure that the next jobs picked up by a completion port thread
// is inserted into the queue after we start cleanup.  The cleanup starts when a completion
// port thread processes a special overlapped (overlappedForInitiateCleanup).
// To do this, we loop through all completion port threads.
// 1. If a thread is in cooperative mode, it is processing a job now, and the next job
//    it picks up will be after we start cleanup.
// 2. A completion port thread may be waiting for a job, or is going to dispatch a job.
//    We can not distinguish these two.  So we queue a dummy job to the queue after the starting
//    job.
OVERLAPPED overlappedForInitiateCleanup;
OVERLAPPED overlappedForContinueCleanup;
#endif  // !FEATURE_PAL

Volatile<ULONG> g_fCompletionPortDrainNeeded = FALSE;

VOID ThreadpoolMgr::CallbackForContinueDrainageOfCompletionPortQueue(
    DWORD dwErrorCode,
    DWORD dwNumberOfBytesTransfered,
    LPOVERLAPPED lpOverlapped
    )
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

#ifndef FEATURE_PAL
    CounterHolder hldNumCPIT(&NumCPInfrastructureThreads);

    // It is OK if this overlapped is from a previous round.
    // We have started a new round.  The next job picked by this thread is
    // going to be after the marker.
    Thread* pThread = GetThread();
    if (pThread && !pThread->IsCompletionPortDrained())
    {
        pThread->MarkCompletionPortDrained();
    }
    if (g_fCompletionPortDrainNeeded)
    {
        ::PostQueuedCompletionStatus(GlobalCompletionPort,
                                             0,
                                             (ULONG_PTR)CallbackForContinueDrainageOfCompletionPortQueue,
                                             &overlappedForContinueCleanup);
        // IO Completion port thread is LIFO queue.  We want our special packet to be picked up by a different thread.
        while (g_fCompletionPortDrainNeeded && pThread->IsCompletionPortDrained())
        {
            __SwitchToThread(100, CALLER_LIMITS_SPINNING);
        }
    }
#endif // !FEATURE_PAL    
}


VOID
ThreadpoolMgr::CallbackForInitiateDrainageOfCompletionPortQueue(
    DWORD dwErrorCode,
    DWORD dwNumberOfBytesTransfered,
    LPOVERLAPPED lpOverlapped
    )
{
 #ifndef FEATURE_PAL
    CONTRACTL
    {
        NOTHROW;
        MODE_ANY;
    }
    CONTRACTL_END;

    CounterHolder hldNumCPIT(&NumCPInfrastructureThreads);
    {
        ThreadStoreLockHolder tsl;
        Thread *pThread = NULL;
        while ((pThread = ThreadStore::GetAllThreadList(pThread, Thread::TS_CompletionPortThread, Thread::TS_CompletionPortThread)) != NULL)
        {
            pThread->UnmarkCompletionPortDrained();
        }
    }

    FastInterlockOr(&g_fCompletionPortDrainNeeded, 1);

    // Wake up retiring CP Threads so it can mark its status.
    ThreadCounter::Counts counts = CPThreadCounter.GetCleanCounts();
    if (counts.NumRetired > 0)
        RetiredCPWakeupEvent->Set();

    DWORD nTry = 0;
    BOOL fTryNextTime = FALSE;
    BOOL fMore = TRUE;
    BOOL fFirstTime = TRUE;
    while (fMore)
    {
        fMore = FALSE;
        Thread *pCurThread = GetThread();
        Thread *pThread = NULL;
        {

            ThreadStoreLockHolder tsl;

            ::FlushProcessWriteBuffers();

            while ((pThread = ThreadStore::GetAllThreadList(pThread, Thread::TS_CompletionPortThread, Thread::TS_CompletionPortThread)) != NULL)
            {
                if (pThread == pCurThread || pThread->IsDead() || pThread->IsCompletionPortDrained())
                {
                    continue;
                }

                if (pThread->PreemptiveGCDisabledOther() || pThread->GetFrame() != FRAME_TOP)
                {
                    // The thread is processing an IO job now.  When it picks up next job, the job
                    // will be after the marker.
                    pThread->MarkCompletionPortDrained();
                }
                else
                {
                    if (fFirstTime)
                    {
                        ::PostQueuedCompletionStatus(GlobalCompletionPort,
                                                             0,
                                                             (ULONG_PTR)CallbackForContinueDrainageOfCompletionPortQueue,
                                                             &overlappedForContinueCleanup);
                    }
                    fMore = TRUE;
                }
            }
        }
        if (fMore)
        {
            __SwitchToThread(10, CALLER_LIMITS_SPINNING);
            nTry ++;
            if (nTry > 1000)
            {
                fTryNextTime = TRUE;
                break;
            }
        }
        fFirstTime = FALSE;
    }

    FastInterlockAnd(&g_fCompletionPortDrainNeeded, 0);
#endif // !FEATURE_PAL
}

extern void WINAPI BindIoCompletionCallbackStub(DWORD ErrorCode,
                                            DWORD numBytesTransferred,
                                            LPOVERLAPPED lpOverlapped);

void HostIOCompletionCallback(
    DWORD ErrorCode,
    DWORD numBytesTransferred,
    LPOVERLAPPED lpOverlapped)
{
#ifndef FEATURE_PAL
    if (lpOverlapped == &overlappedForInitiateCleanup)
    {
        ThreadpoolMgr::CallbackForInitiateDrainageOfCompletionPortQueue (
            ErrorCode,
            numBytesTransferred,
            lpOverlapped);
    }
    else if (lpOverlapped == &overlappedForContinueCleanup)
    {
        ThreadpoolMgr::CallbackForContinueDrainageOfCompletionPortQueue(
            ErrorCode,
            numBytesTransferred,
            lpOverlapped);
    }
    else
    {
        BindIoCompletionCallbackStub (
            ErrorCode,
            numBytesTransferred,
            lpOverlapped);
    }
#endif // !FEATURE_PAL
}

BOOL ThreadpoolMgr::DrainCompletionPortQueue()
{
#ifndef FEATURE_PAL
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (GlobalCompletionPort == 0)
    {
        return FALSE;
    }

    return ::PostQueuedCompletionStatus(GlobalCompletionPort,
                                                    0,
                                                    (ULONG_PTR)CallbackForInitiateDrainageOfCompletionPortQueue,
                                                    &overlappedForInitiateCleanup);
#else
    return FALSE;
#endif // !FEATURE_PAL
}


// This is either made by a worker thread or a CP thread
// indicated by threadTypeStatus
void ThreadpoolMgr::EnsureGateThreadRunning()
{
    LIMITED_METHOD_CONTRACT;

    while (true)
    {
        switch (GateThreadStatus)
        {
        case GATE_THREAD_STATUS_REQUESTED:
            //
            // No action needed; the gate thread is running, and someone else has already registered a request
            // for it to stay.
            //
            return;

        case GATE_THREAD_STATUS_WAITING_FOR_REQUEST:
            //
            // Prevent the gate thread from exiting, if it hasn't already done so.  If it has, we'll create it on the next iteration of
            // this loop.
            //
            FastInterlockCompareExchange(&GateThreadStatus, GATE_THREAD_STATUS_REQUESTED, GATE_THREAD_STATUS_WAITING_FOR_REQUEST);
            break;

        case GATE_THREAD_STATUS_NOT_RUNNING:
            //
            // We need to create a new gate thread
            //
            if (FastInterlockCompareExchange(&GateThreadStatus, GATE_THREAD_STATUS_REQUESTED, GATE_THREAD_STATUS_NOT_RUNNING) == GATE_THREAD_STATUS_NOT_RUNNING)
            {
                if (!CreateGateThread()) 
                {
                    //
                    // If we failed to create the gate thread, someone else will need to try again later.
                    //
                    GateThreadStatus = GATE_THREAD_STATUS_NOT_RUNNING;
                }
                return;
            }
            break;

        default:
            _ASSERTE(!"Invalid value of ThreadpoolMgr::GateThreadStatus");
        }
    }

    return;
}


bool ThreadpoolMgr::ShouldGateThreadKeepRunning()
{
    LIMITED_METHOD_CONTRACT;

    _ASSERTE(GateThreadStatus == GATE_THREAD_STATUS_WAITING_FOR_REQUEST ||
             GateThreadStatus == GATE_THREAD_STATUS_REQUESTED);

    //
    // Switch to WAITING_FOR_REQUEST, and see if we had a request since the last check.
    //
    LONG previousStatus = FastInterlockExchange(&GateThreadStatus, GATE_THREAD_STATUS_WAITING_FOR_REQUEST);

    if (previousStatus == GATE_THREAD_STATUS_WAITING_FOR_REQUEST)
    {
        //
        // No recent requests for the gate thread.  Check to see if we're still needed.
        //

        //
        // Are there any free threads in the I/O completion pool?  If there are, we don't need a gate thread.
        // This implies that whenever we decrement NumFreeCPThreads to 0, we need to call EnsureGateThreadRunning().
        //
        ThreadCounter::Counts counts = CPThreadCounter.GetCleanCounts();
        bool needGateThreadForCompletionPort = 
            InitCompletionPortThreadpool &&
            (counts.NumActive - counts.NumWorking) <= 0;

        //
        // Are there any work requests in any worker queue?  If so, we need a gate thread.
        // This imples that whenever a work queue goes from empty to non-empty, we need to call EnsureGateThreadRunning().
        //
        bool needGateThreadForWorkerThreads =
            PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains();

        //
        // If worker tracking is enabled, we need to fire periodic ETW events with active worker counts.  This is
        // done by the gate thread.
        // We don't have to do anything special with EnsureGateThreadRunning() here, because this is only needed
        // once work has been added to the queue for the first time (which is covered above).
        //
        bool needGateThreadForWorkerTracking = 
            0 != CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_EnableWorkerTracking);

        if (!(needGateThreadForCompletionPort || 
              needGateThreadForWorkerThreads ||
              needGateThreadForWorkerTracking))
        {
            //
            // It looks like we shouldn't be running.  But another thread may now tell us to run.  If so, they will set GateThreadStatus
            // back to GATE_THREAD_STATUS_REQUESTED.
            //
            previousStatus = FastInterlockCompareExchange(&GateThreadStatus, GATE_THREAD_STATUS_NOT_RUNNING, GATE_THREAD_STATUS_WAITING_FOR_REQUEST);
            if (previousStatus == GATE_THREAD_STATUS_WAITING_FOR_REQUEST)
                return false;
        }
    }


    _ASSERTE(GateThreadStatus == GATE_THREAD_STATUS_WAITING_FOR_REQUEST ||
             GateThreadStatus == GATE_THREAD_STATUS_REQUESTED);
    return true;
}



//************************************************************************
void ThreadpoolMgr::EnqueueWorkRequest(WorkRequest* workRequest)
{
    CONTRACTL
    {
        NOTHROW;
        MODE_ANY;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    AppendWorkRequest(workRequest);
}

WorkRequest* ThreadpoolMgr::DequeueWorkRequest()
{
    WorkRequest* entry = NULL;
    CONTRACT(WorkRequest*)
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;

        POSTCONDITION(CheckPointer(entry, NULL_OK));
    } CONTRACT_END;

    entry = RemoveWorkRequest();

    RETURN entry;
}

DWORD WINAPI ThreadpoolMgr::ExecuteHostRequest(PVOID pArg)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    bool foundWork, wasNotRecalled;
    ExecuteWorkRequest(&foundWork, &wasNotRecalled);
    return ERROR_SUCCESS;
}

void ThreadpoolMgr::ExecuteWorkRequest(bool* foundWork, bool* wasNotRecalled)
{
    CONTRACTL
    {
        THROWS;     // QueueUserWorkItem can throw
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    IPerAppDomainTPCount* pAdCount;

    LONG index = PerAppDomainTPCountList::GetAppDomainIndexForThreadpoolDispatch();

    if (index == 0)
    {
        *foundWork = false;
        *wasNotRecalled = true;
        return;
    }

    if (index == -1) 
    {
        pAdCount = PerAppDomainTPCountList::GetUnmanagedTPCount(); 
    } 
    else 
    {

        pAdCount = PerAppDomainTPCountList::GetPerAppdomainCount(TPIndex((DWORD)index));
        _ASSERTE(pAdCount);
    }

    pAdCount->DispatchWorkItem(foundWork, wasNotRecalled);
}

//--------------------------------------------------------------------------
//This function informs the thread scheduler that the first requests has been
//queued on an appdomain, or it's the first unmanaged TP request. 
//Arguments:
//         UnmanagedTP: Indicates that the request arises from the unmanaged 
//part of Thread Pool.
//Assumptions:
//         This function must be called under a per-appdomain lock or the 
//correct lock under unmanaged TP queue.
// 
BOOL ThreadpoolMgr::SetAppDomainRequestsActive(BOOL UnmanagedTP)
{
    CONTRACTL
    {
        NOTHROW;
        MODE_ANY;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    BOOL fShouldSignalEvent = FALSE;

    IPerAppDomainTPCount* pAdCount;

    if(UnmanagedTP)
    {
        pAdCount = PerAppDomainTPCountList::GetUnmanagedTPCount();
        _ASSERTE(pAdCount);
    }
    else
    {       
        Thread* pCurThread = GetThread();
        _ASSERTE( pCurThread);

        AppDomain* pAppDomain = pCurThread->GetDomain();
        _ASSERTE(pAppDomain);
        
        TPIndex tpindex = pAppDomain->GetTPIndex();        
        pAdCount = PerAppDomainTPCountList::GetPerAppdomainCount(tpindex);

        _ASSERTE(pAdCount);
    }

    pAdCount->SetAppDomainRequestsActive();

    return fShouldSignalEvent;
}

void ThreadpoolMgr::ClearAppDomainRequestsActive(BOOL UnmanagedTP, LONG id)
//--------------------------------------------------------------------------
//This function informs the thread scheduler that the kast request has been
//dequeued on an appdomain, or it's the last unmanaged TP request. 
//Arguments:
//         UnmanagedTP: Indicates that the request arises from the unmanaged 
//part of Thread Pool.
//         id: Indicates the id of the appdomain. The id is needed as this 
//function can be called (indirectly) from the appdomain unload thread from
//unmanaged code to clear per-appdomain state during rude unload. 
//Assumptions:
//         This function must be called under a per-appdomain lock or the 
//correct lock under unmanaged TP queue.
// 
{
    CONTRACTL
    {
        NOTHROW;
        MODE_ANY;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    IPerAppDomainTPCount* pAdCount;

    if(UnmanagedTP) 
    {
        pAdCount = PerAppDomainTPCountList::GetUnmanagedTPCount();
        _ASSERTE(pAdCount);
    } 
    else
    {
       Thread* pCurThread = GetThread();
       _ASSERTE( pCurThread);

       AppDomain* pAppDomain = pCurThread->GetDomain();
       _ASSERTE(pAppDomain);
    
       TPIndex tpindex = pAppDomain->GetTPIndex();

       pAdCount = PerAppDomainTPCountList::GetPerAppdomainCount(tpindex);

        _ASSERTE(pAdCount);
    }

    pAdCount->ClearAppDomainRequestsActive();
}


// Remove a block from the appropriate recycleList and return.
// If recycleList is empty, fall back to new.
LPVOID ThreadpoolMgr::GetRecycledMemory(enum MemType memType)
{
    LPVOID result = NULL;
    CONTRACT(LPVOID)
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM());
        POSTCONDITION(CheckPointer(result));
    } CONTRACT_END;

    if(RecycledLists.IsInitialized())
    {
        RecycledListInfo& list = RecycledLists.GetRecycleMemoryInfo( memType );

        result = list.Remove();
    }

    if(result == NULL)
    {
        switch (memType)
        {
            case MEMTYPE_DelegateInfo:
                result =  new DelegateInfo;
                break;
            case MEMTYPE_AsyncCallback:
                result =  new AsyncCallback;
                break;
            case MEMTYPE_WorkRequest:
                result =  new WorkRequest;
                break;
            default:
                _ASSERTE(!"Unknown Memtype");
                result = NULL;
                break;
        }
    }

    RETURN result;
}

// Insert freed block in recycle list. If list is full, return to system heap
void ThreadpoolMgr::RecycleMemory(LPVOID mem, enum MemType memType)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    if(RecycledLists.IsInitialized())
    {
        RecycledListInfo& list = RecycledLists.GetRecycleMemoryInfo( memType );

        if(list.CanInsert())
        {
            list.Insert( mem );
            return;
        }
    }

    switch (memType)
    {
        case MEMTYPE_DelegateInfo:
            delete (DelegateInfo*) mem;
            break;
        case MEMTYPE_AsyncCallback:
            delete (AsyncCallback*) mem;
            break;
        case MEMTYPE_WorkRequest:
            delete (WorkRequest*) mem;
            break;
        default:
            _ASSERTE(!"Unknown Memtype");

    }
}

#define THROTTLE_RATE  0.10 /* rate by which we increase the delay as number of threads increase */

// This is to avoid the 64KB/1MB aliasing problem present on Pentium 4 processors,
// which can significantly impact performance with HyperThreading enabled
DWORD WINAPI ThreadpoolMgr::intermediateThreadProc(PVOID arg)
{
    WRAPPER_NO_CONTRACT;

    offset_counter++;
    if (offset_counter * offset_multiplier > (int)GetOsPageSize())
        offset_counter = 0;

    (void)_alloca(offset_counter * offset_multiplier);

    intermediateThreadParam* param = (intermediateThreadParam*)arg;

    LPTHREAD_START_ROUTINE ThreadFcnPtr = param->lpThreadFunction;
    PVOID args = param->lpArg;
    delete param;

    return ThreadFcnPtr(args);
}

Thread* ThreadpoolMgr::CreateUnimpersonatedThread(LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpArgs, BOOL *pIsCLRThread)
{
    STATIC_CONTRACT_NOTHROW;
    if (GetThread()) { STATIC_CONTRACT_GC_TRIGGERS;} else {DISABLED(STATIC_CONTRACT_GC_NOTRIGGER);}
    STATIC_CONTRACT_MODE_ANY;
    /* cannot use contract because of SEH
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;*/

    Thread* pThread = NULL;

    if (g_fEEStarted) {
        *pIsCLRThread = TRUE;
    }
    else
        *pIsCLRThread = FALSE;
    if (*pIsCLRThread) {
        EX_TRY
        {
            pThread = SetupUnstartedThread();
        }
        EX_CATCH
        {
            pThread = NULL;
        }
        EX_END_CATCH(SwallowAllExceptions);
        if (pThread == NULL) {
            return NULL;
        }
    }
    DWORD threadId;
    BOOL bOK = FALSE;
    HANDLE threadHandle = NULL;

    if (*pIsCLRThread) {
        // CreateNewThread takes care of reverting any impersonation - so dont do anything here.
        bOK = pThread->CreateNewThread(0,               // default stack size
                                       lpStartAddress,
                                       lpArgs,           //arguments
                                       W(".NET ThreadPool Worker"));
    }
    else {
#ifndef FEATURE_PAL
        HandleHolder token;
        BOOL bReverted = FALSE;
        bOK = RevertIfImpersonated(&bReverted, &token);
        if (bOK != TRUE)
            return NULL;
#endif // !FEATURE_PAL 
        NewHolder<intermediateThreadParam> lpThreadArgs(new (nothrow) intermediateThreadParam);
        if (lpThreadArgs != NULL)
        {
            lpThreadArgs->lpThreadFunction = lpStartAddress;
            lpThreadArgs->lpArg = lpArgs;
            threadHandle = CreateThread(NULL,               // security descriptor
                                        0,                  // default stack size
                                        intermediateThreadProc,
                                        lpThreadArgs,       // arguments
                                        CREATE_SUSPENDED,
                                        &threadId);
#ifndef FEATURE_PAL
            SetThreadName(threadHandle, W(".NET ThreadPool Worker"));
#endif // !FEATURE_PAL
            if (threadHandle != NULL)
                lpThreadArgs.SuppressRelease();
        }
#ifndef FEATURE_PAL
        UndoRevert(bReverted, token);
#endif // !FEATURE_PAL 
    }

    if (*pIsCLRThread && !bOK)
    {
        pThread->DecExternalCount(FALSE);
        pThread = NULL;
    }

    if (*pIsCLRThread) {
        return pThread;
    }
    else
        return (Thread*)threadHandle;
}


BOOL ThreadpoolMgr::CreateWorkerThread()
{
    CONTRACTL
    {
        if (GetThread()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        NOTHROW;
        MODE_ANY;   // We may try to add a worker thread while queuing a work item thru an fcall
    }
    CONTRACTL_END;

    Thread *pThread;
    BOOL fIsCLRThread;
    if ((pThread = CreateUnimpersonatedThread(WorkerThreadStart, NULL, &fIsCLRThread)) != NULL)
    {
        if (fIsCLRThread) {
            pThread->ChooseThreadCPUGroupAffinity();
            pThread->StartThread();
        }
        else {
            DWORD status;
            status = ResumeThread((HANDLE)pThread);
            _ASSERTE(status != (DWORD) (-1));
            CloseHandle((HANDLE)pThread);          // we don't need this anymore
        }

        return TRUE;
    }

    return FALSE;
}


DWORD WINAPI ThreadpoolMgr::WorkerThreadStart(LPVOID lpArgs)
{
    ClrFlsSetThreadType (ThreadType_Threadpool_Worker);

    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

    Thread *pThread = NULL;
    DWORD dwSwitchCount = 0;
    BOOL fThreadInit = FALSE;

    ThreadCounter::Counts counts, oldCounts, newCounts;
    bool foundWork = true, wasNotRecalled = true;

    counts = WorkerCounter.GetCleanCounts();
    FireEtwThreadPoolWorkerThreadStart(counts.NumActive, counts.NumRetired, GetClrInstanceId());

#ifdef FEATURE_COMINTEROP
    BOOL fCoInited = FALSE;
    // Threadpool threads should be initialized as MTA. If we are unable to do so,
    // return failure.
    {
        fCoInited = SUCCEEDED(::CoInitializeEx(NULL, COINIT_MULTITHREADED));
        if (!fCoInited)
        {
            goto Exit;
        }
    }
#endif // FEATURE_COMINTEROP
Work:

    if (!fThreadInit) {
        if (g_fEEStarted) {
            pThread = SetupThreadNoThrow();
            if (pThread == NULL) {
                __SwitchToThread(0, ++dwSwitchCount);
                goto Work;
            }

            // converted to CLRThread and added to ThreadStore, pick an group affinity for this thread
            pThread->ChooseThreadCPUGroupAffinity(); 

            #ifdef FEATURE_COMINTEROP
            if (pThread->SetApartment(Thread::AS_InMTA, TRUE) != Thread::AS_InMTA)
            {
                // counts volatile read paired with CompareExchangeCounts loop set
                counts = WorkerCounter.DangerousGetDirtyCounts();
                while (true)
                {
                    newCounts = counts;
                    newCounts.NumActive--;
                    newCounts.NumWorking--;
                    oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts);
                    if (oldCounts == counts)
                        break;
                    counts = oldCounts;
                }
                goto Exit;
            }
            #endif // FEATURE_COMINTEROP

            pThread->SetBackground(TRUE);
            fThreadInit = TRUE;
        }
    }

    GCX_PREEMP_NO_DTOR();
    _ASSERTE(pThread == NULL || !pThread->PreemptiveGCDisabled());

    // make sure there's really work.  If not, go back to sleep

    // counts volatile read paired with CompareExchangeCounts loop set
    counts = WorkerCounter.DangerousGetDirtyCounts();
    while (true)
    {
        _ASSERTE(counts.NumActive > 0);
        _ASSERTE(counts.NumWorking > 0);

        newCounts = counts;

        bool retired;

        if (counts.NumActive > counts.MaxWorking)
        {
            newCounts.NumActive--;
            newCounts.NumRetired++;
            retired = true;
        }
        else
        {
            retired = false;

            if (foundWork)
                break;
        }

        newCounts.NumWorking--;

        oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts);

        if (oldCounts == counts)
        {
            if (retired)
                goto Retire;
            else
                goto WaitForWork;
        }

        counts = oldCounts;
    }

    if (GCHeapUtilities::IsGCInProgress(TRUE))
    {
        // GC is imminent, so wait until GC is complete before executing next request.
        // this reduces in-flight objects allocated right before GC, easing the GC's work
        GCHeapUtilities::WaitForGCCompletion(TRUE);
    }

    {
        ThreadpoolMgr::UpdateLastDequeueTime();
        ThreadpoolMgr::ExecuteWorkRequest(&foundWork, &wasNotRecalled);
    }

    if (foundWork)
    {
        // Reset TLS etc. for next WorkRequest.
        if (pThread == NULL)
            pThread = GetThread();

        if (pThread) 
        {
            if (pThread->IsAbortRequested())
                pThread->EEResetAbort(Thread::TAR_ALL);
            pThread->InternalReset();
        }
    }

    if (wasNotRecalled)
        goto Work;

Retire:

    counts = WorkerCounter.GetCleanCounts();
    FireEtwThreadPoolWorkerThreadRetirementStart(counts.NumActive, counts.NumRetired, GetClrInstanceId());

    // It's possible that some work came in just before we decremented the active thread count, in which 
    // case whoever queued that work may be expecting us to pick it up - so they would not have signalled
    // the worker semaphore.  If there are other threads waiting, they will never be woken up, because 
    // whoever queued the work expects that it's already been picked up.  The solution is to signal the semaphore
    // if there's any work available.
    if (PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains())
        MaybeAddWorkingWorker();

    while (true)
    {
RetryRetire:
        if (RetiredWorkerSemaphore->Wait(AppX::IsAppXProcess() ? WorkerTimeoutAppX : WorkerTimeout))
        {
            foundWork = true;

            counts = WorkerCounter.GetCleanCounts();
            FireEtwThreadPoolWorkerThreadRetirementStop(counts.NumActive, counts.NumRetired, GetClrInstanceId());
            goto Work;
        }

        if (!IsIoPending())
        {
            //
            // We're going to exit.  There's a nasty race here.  We're about to decrement NumRetired,
            // since we're going to exit.  Once we've done that, nobody will expect this thread
            // to be waiting for RetiredWorkerSemaphore.  But between now and then, other threads still
            // think we're waiting on the semaphore, and they will happily do the following to try to
            // wake us up:
            //
            // 1) Decrement NumRetired
            // 2) Increment NumActive
            // 3) Increment NumWorking
            // 4) Signal RetiredWorkerSemaphore
            //
            // We will not receive that signal.  If we don't do something special here,
            // we will decrement NumRetired an extra time, and leave the world thinking there
            // are fewer retired threads, and more working threads than reality.
            //
            // What can we do about this?  First, we *need* to decrement NumRetired.  If someone did it before us,
            // it might go negative.  This is the easiest way to tell that we've encountered this race.  In that case,
            // we will simply not commit the decrement, swallow the signal that was sent, and proceed as if we
            // got WAIT_OBJECT_0 in the wait above.
            //
            // If we don't hit zero while decrementing NumRetired, we still may have encountered this race.  But 
            // if we don't hit zero, then there's another retired thread that will pick up this signal.  So it's ok
            // to exit.
            //

            // counts volatile read paired with CompareExchangeCounts loop set
            counts = WorkerCounter.DangerousGetDirtyCounts();
            while (true)
            {
                if (counts.NumRetired == 0)
                    goto RetryRetire;

                newCounts = counts;
                newCounts.NumRetired--;

                oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts);
                if (oldCounts == counts)
                {
                    counts = newCounts;
                    break;
                }
                counts = oldCounts;
            }

            FireEtwThreadPoolWorkerThreadRetirementStop(counts.NumActive, counts.NumRetired, GetClrInstanceId());
            goto Exit;
        }
    }

WaitForWork:

    // It's possible that we decided we had no work just before some work came in, 
    // but reduced the worker count *after* the work came in.  In this case, we might
    // miss the notification of available work.  So we make a sweep through the ADs here,
    // and wake up a thread (maybe this one!) if there is work to do.
    if (PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains())
    {
        foundWork = true;
        MaybeAddWorkingWorker();
    }

    FireEtwThreadPoolWorkerThreadWait(counts.NumActive, counts.NumRetired, GetClrInstanceId());

RetryWaitForWork:
    if (WorkerSemaphore->Wait(AppX::IsAppXProcess() ? WorkerTimeoutAppX : WorkerTimeout, WorkerThreadSpinLimit, NumberOfProcessors))
    {
        foundWork = true;
        goto Work;
    }

    if (!IsIoPending())
    {
        //
        // We timed out, and are about to exit.  This puts us in a very similar situation to the
        // retirement case above - someone may think we're still waiting, and go ahead and:
        //
        // 1) Increment NumWorking
        // 2) Signal WorkerSemaphore
        //
        // The solution is much like retirement; when we're decrementing NumActive, we need to make
        // sure it doesn't drop below NumWorking.  If it would, then we need to go back and wait 
        // again.
        //

        DangerousNonHostedSpinLockHolder tal(&ThreadAdjustmentLock);

        // counts volatile read paired with CompareExchangeCounts loop set
        counts = WorkerCounter.DangerousGetDirtyCounts();
        while (true)
        {
            if (counts.NumActive == counts.NumWorking)
            {
                goto RetryWaitForWork;
            }

            newCounts = counts;
            newCounts.NumActive--;

            // if we timed out while active, then Hill Climbing needs to be told that we need fewer threads
            newCounts.MaxWorking = max(MinLimitTotalWorkerThreads, min(newCounts.NumActive, newCounts.MaxWorking));

            oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts);

            if (oldCounts == counts)
            {
                HillClimbingInstance.ForceChange(newCounts.MaxWorking, ThreadTimedOut);
                goto Exit;
            }

            counts = oldCounts;
        }
    }
    else
    {
        goto RetryWaitForWork;
    }

Exit:

#ifdef FEATURE_COMINTEROP
    if (pThread) {
        pThread->SetApartment(Thread::AS_Unknown, TRUE);
        pThread->CoUninitialize();
    }

    // Couninit the worker thread
    if (fCoInited)
    {
        CoUninitialize();
    }
#endif

    if (pThread) {
        pThread->ClearThreadCPUGroupAffinity();

        DestroyThread(pThread);
    }

    _ASSERTE(!IsIoPending());

    counts = WorkerCounter.GetCleanCounts();
    FireEtwThreadPoolWorkerThreadStop(counts.NumActive, counts.NumRetired, GetClrInstanceId());

    return ERROR_SUCCESS;
}


BOOL ThreadpoolMgr::SuspendProcessing()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

    BOOL shouldRetire = TRUE;
    DWORD sleepInterval = SUSPEND_TIME;
    int oldCpuUtilization = cpuUtilization;
    for (int i = 0; i < shouldRetire; i++)
    {
        __SwitchToThread(sleepInterval, CALLER_LIMITS_SPINNING);
        if ((cpuUtilization <= (oldCpuUtilization - 4)))
        {   // if cpu util. dips by 4% or more, then put it back in circulation
            shouldRetire = FALSE;
            break;
        }
    }

    return shouldRetire;
}


// this should only be called by unmanaged thread (i.e. there should be no mgd
// caller on the stack) since we are swallowing terminal exceptions
DWORD ThreadpoolMgr::SafeWait(CLREvent * ev, DWORD sleepTime, BOOL alertable)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_MODE_PREEMPTIVE;
    /* cannot use contract because of SEH
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;*/

    DWORD status = WAIT_TIMEOUT;
    EX_TRY
    {
        status = ev->Wait(sleepTime,FALSE);
    }
    EX_CATCH
    {
    }
    EX_END_CATCH(SwallowAllExceptions)
    return status;
}

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

BOOL ThreadpoolMgr::RegisterWaitForSingleObject(PHANDLE phNewWaitObject,
                                                HANDLE hWaitObject,
                                                WAITORTIMERCALLBACK Callback,
                                                PVOID Context,
                                                ULONG timeout,
                                                DWORD dwFlag )
{
    CONTRACTL
    {
        THROWS;
        MODE_ANY;
        if (GetThread()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
    }
    CONTRACTL_END;
    EnsureInitialized();

    ThreadCB* threadCB;
    {
        CrstHolder csh(&WaitThreadsCriticalSection);

        threadCB = FindWaitThread();
    }

    *phNewWaitObject = NULL;

    if (threadCB)
    {
        WaitInfo* waitInfo = new (nothrow) WaitInfo;

        if (waitInfo == NULL)
            return FALSE;

        waitInfo->waitHandle = hWaitObject;
        waitInfo->Callback = Callback;
        waitInfo->Context = Context;
        waitInfo->timeout = timeout;
        waitInfo->flag = dwFlag;
        waitInfo->threadCB = threadCB;
        waitInfo->state = 0;
        waitInfo->refCount = 1;     // safe to do this since no wait has yet been queued, so no other thread could be modifying this
        waitInfo->ExternalCompletionEvent = INVALID_HANDLE;
        waitInfo->ExternalEventSafeHandle = NULL;

        waitInfo->timer.startTime = GetTickCount();
        waitInfo->timer.remainingTime = timeout;

        *phNewWaitObject = waitInfo;

        // We fire the "enqueue" ETW event here, to "mark" the thread that had called the API, rather than the
        // thread that will PostQueuedCompletionStatus (the dedicated WaitThread).
        // This event correlates with ThreadPoolIODequeue in ThreadpoolMgr::AsyncCallbackCompletion
        if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolIOEnqueue))
            FireEtwThreadPoolIOEnqueue((LPOVERLAPPED)waitInfo, reinterpret_cast<void*>(Callback), (dwFlag & WAIT_SINGLE_EXECUTION) == 0, GetClrInstanceId());
    
        BOOL status = QueueUserAPC((PAPCFUNC)InsertNewWaitForSelf, threadCB->threadHandle, (size_t) waitInfo);

        if (status == FALSE)
        {
            *phNewWaitObject = NULL;
            delete waitInfo;
        }

        return status;
    }

    return FALSE;
}


// Returns a wait thread that can accomodate another wait request. The
// caller is responsible for synchronizing access to the WaitThreadsHead
ThreadpoolMgr::ThreadCB* ThreadpoolMgr::FindWaitThread()
{
    CONTRACTL
    {
        THROWS;     // CreateWaitThread can throw
        MODE_ANY;
        GC_TRIGGERS;
    }
    CONTRACTL_END;
    do
    {
        for (LIST_ENTRY* Node = (LIST_ENTRY*) WaitThreadsHead.Flink ;
             Node != &WaitThreadsHead ;
             Node = (LIST_ENTRY*)Node->Flink)
        {
            _ASSERTE(offsetof(WaitThreadInfo,link) == 0);

            ThreadCB*  threadCB = ((WaitThreadInfo*) Node)->threadCB;

            if (threadCB->NumWaitHandles < MAX_WAITHANDLES)         // this test and following ...

            {
                InterlockedIncrement(&threadCB->NumWaitHandles);    // ... increment are protected by WaitThreadsCriticalSection.
                                                                    // but there might be a concurrent decrement in DeactivateWait
                                                                    // or InsertNewWaitForSelf, hence the interlock
                return threadCB;
            }
        }

        // if reached here, there are no wait threads available, so need to create a new one
        if (!CreateWaitThread())
            return NULL;


        // Now loop back
    } while (TRUE);

}

BOOL ThreadpoolMgr::CreateWaitThread()
{
    CONTRACTL
    {
        THROWS; // CLREvent::CreateAutoEvent can throw OOM
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END;
    DWORD threadId;

    if (g_fEEShutDown & ShutDown_Finalize2){
        // The process is shutting down.  Shutdown thread has ThreadStore lock,
        // wait thread is blocked on the lock.
        return FALSE;
    }

    NewHolder<WaitThreadInfo> waitThreadInfo(new (nothrow) WaitThreadInfo);
    if (waitThreadInfo == NULL)
        return FALSE;

    NewHolder<ThreadCB> threadCB(new (nothrow) ThreadCB);

    if (threadCB == NULL)
    {
        return FALSE;
    }

    threadCB->startEvent.CreateAutoEvent(FALSE);
    HANDLE threadHandle = Thread::CreateUtilityThread(Thread::StackSize_Small, WaitThreadStart, (LPVOID)threadCB, W(".NET ThreadPool Wait"), CREATE_SUSPENDED, &threadId);

    if (threadHandle == NULL)
    {
        threadCB->startEvent.CloseEvent();
        return FALSE;
    }

    waitThreadInfo.SuppressRelease();
    threadCB.SuppressRelease();
    threadCB->threadHandle = threadHandle;
    threadCB->threadId = threadId;              // may be useful for debugging otherwise not used
    threadCB->NumWaitHandles = 0;
    threadCB->NumActiveWaits = 0;
    for (int i=0; i< MAX_WAITHANDLES; i++)
    {
        InitializeListHead(&(threadCB->waitPointer[i]));
    }

    waitThreadInfo->threadCB = threadCB;

    DWORD status = ResumeThread(threadHandle);

    {
        // We will QueueUserAPC on the newly created thread.
        // Let us wait until the thread starts running.
        GCX_PREEMP();
        DWORD timeout=500;
        while (TRUE) {
            if (g_fEEShutDown & ShutDown_Finalize2){
                // The process is shutting down.  Shutdown thread has ThreadStore lock,
                // wait thread is blocked on the lock.
                return FALSE;
            }
            DWORD wait_status = threadCB->startEvent.Wait(timeout, FALSE);
            if (wait_status == WAIT_OBJECT_0) {
                break;
            }
        }
    }
    threadCB->startEvent.CloseEvent();

    // check to see if setup succeeded
    if (threadCB->threadHandle == NULL)
        return FALSE;

    InsertHeadList(&WaitThreadsHead,&waitThreadInfo->link);

    _ASSERTE(status != (DWORD) (-1));

    return (status != (DWORD) (-1));

}

// Executed as an APC on a WaitThread. Add the wait specified in pArg to the list of objects it is waiting on
void ThreadpoolMgr::InsertNewWaitForSelf(WaitInfo* pArgs)
{
    WRAPPER_NO_CONTRACT;

    WaitInfo* waitInfo = pArgs;

    // the following is safe since only this thread is allowed to change the state
    if (!(waitInfo->state & WAIT_DELETE))
    {
        waitInfo->state =  (WAIT_REGISTERED | WAIT_ACTIVE);
    }
    else
    {
        // some thread unregistered the wait
        DeleteWait(waitInfo);
        return;
    }


    ThreadCB* threadCB = waitInfo->threadCB;

    _ASSERTE(threadCB->NumActiveWaits <= threadCB->NumWaitHandles);

    int index = FindWaitIndex(threadCB, waitInfo->waitHandle);
    _ASSERTE(index >= 0 && index <= threadCB->NumActiveWaits);

    if (index == threadCB->NumActiveWaits)
    {
        threadCB->waitHandle[threadCB->NumActiveWaits] = waitInfo->waitHandle;
        threadCB->NumActiveWaits++;
    }
    else
    {
        // this is a duplicate waithandle, so the increment in FindWaitThread
        // wasn't strictly necessary.  This will avoid unnecessary thread creation.
        InterlockedDecrement(&threadCB->NumWaitHandles);
    }

    _ASSERTE(offsetof(WaitInfo, link) == 0);
    InsertTailList(&(threadCB->waitPointer[index]), (&waitInfo->link));

    return;
}

// returns the index of the entry that matches waitHandle or next free entry if not found
int ThreadpoolMgr::FindWaitIndex(const ThreadCB* threadCB, const HANDLE waitHandle)
{
    LIMITED_METHOD_CONTRACT;

    for (int i=0;i<threadCB->NumActiveWaits; i++)
        if (threadCB->waitHandle[i] == waitHandle)
            return i;

    // else not found
    return threadCB->NumActiveWaits;
}


// if no wraparound that the timer is expired if duetime is less than current time
// if wraparound occurred, then the timer expired if dueTime was greater than last time or dueTime is less equal to current time
#define TimeExpired(last,now,duetime) (last <= now ? \
                                       (duetime <= now && duetime >= last): \
                                       (duetime >= last || duetime <= now))

#define TimeInterval(end,start) ( end > start ? (end - start) : ((0xffffffff - start) + end + 1)   )

// Returns the minimum of the remaining time to reach a timeout among all the waits
DWORD ThreadpoolMgr::MinimumRemainingWait(LIST_ENTRY* waitInfo, unsigned int numWaits)
{
    LIMITED_METHOD_CONTRACT;

    unsigned int min = (unsigned int) -1;
    DWORD currentTime = GetTickCount();

    for (unsigned i=0; i < numWaits ; i++)
    {
        WaitInfo* waitInfoPtr = (WaitInfo*) (waitInfo[i].Flink);
        PVOID waitInfoHead = &(waitInfo[i]);
        do
        {
            if (waitInfoPtr->timeout != INFINITE)
            {
                // compute remaining time
                DWORD elapsedTime = TimeInterval(currentTime,waitInfoPtr->timer.startTime );

                __int64 remainingTime = (__int64) (waitInfoPtr->timeout) - (__int64) elapsedTime;

                // update remaining time
                waitInfoPtr->timer.remainingTime =  remainingTime > 0 ? (int) remainingTime : 0;

                // ... and min
                if (waitInfoPtr->timer.remainingTime < min)
                    min = waitInfoPtr->timer.remainingTime;
            }

            waitInfoPtr = (WaitInfo*) (waitInfoPtr->link.Flink);

        } while ((PVOID) waitInfoPtr != waitInfoHead);

    }
    return min;
}

#ifdef _MSC_VER
#ifdef _WIN64
#pragma warning (disable : 4716)
#else
#pragma warning (disable : 4715)
#endif
#endif
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:22008) // "Prefast integer overflow check on (0 + lval) is bogus.  Tried local disable without luck, doing whole method."
#endif

DWORD WINAPI ThreadpoolMgr::WaitThreadStart(LPVOID lpArgs)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

    ClrFlsSetThreadType (ThreadType_Wait);

    ThreadCB* threadCB = (ThreadCB*) lpArgs;
    Thread* pThread = SetupThreadNoThrow();

    if (pThread == NULL)
    {
        _ASSERTE(threadCB->threadHandle != NULL);
        threadCB->threadHandle = NULL;
    }

    threadCB->startEvent.Set();

    if (pThread == NULL)
    {
        return 0;
    }

    {
        // wait threads never die. (Why?)
        for (;;)
        {
            DWORD status;
            DWORD timeout = 0;

            if (threadCB->NumActiveWaits == 0)
            {

#undef SleepEx
                // <TODO>@TODO Consider doing a sleep for an idle period and terminating the thread if no activity</TODO>
        //We use SleepEx instead of CLRSLeepEx because CLRSleepEx calls into SQL(or other hosts) in hosted
        //scenarios. SQL does not deliver APC's, and the waithread wait insertion/deletion logic depends on
        //APC's being delivered.
                status = SleepEx(INFINITE,TRUE);
#define SleepEx(a,b) Dont_Use_SleepEx(a,b)

                _ASSERTE(status == WAIT_IO_COMPLETION);
            }
            else if (IsWaitThreadAPCPending())
            {
                //Do a sleep if an APC is pending, This was done to solve the corner case where the wait is signaled,
                //and APC to deregiter the wait never fires. That scenario leads to an infinite loop. This check would
                //allow the thread to enter alertable wait and thus cause the APC to fire.

                ResetWaitThreadAPCPending(); 

                //We use SleepEx instead of CLRSLeepEx because CLRSleepEx calls into SQL(or other hosts) in hosted
                //scenarios. SQL does not deliver APC's, and the waithread wait insertion/deletion logic depends on
                //APC's being delivered.

                #undef SleepEx
                status = SleepEx(0,TRUE);    
                #define SleepEx(a,b) Dont_Use_SleepEx(a,b)

                continue;
            }
            else
            {
                // compute minimum timeout. this call also updates the remainingTime field for each wait
                timeout = MinimumRemainingWait(threadCB->waitPointer,threadCB->NumActiveWaits);

                status = WaitForMultipleObjectsEx(  threadCB->NumActiveWaits,
                                                    threadCB->waitHandle,
                                                    FALSE,                      // waitall
                                                    timeout,
                                                    TRUE  );                    // alertable

                _ASSERTE( (status == WAIT_TIMEOUT) ||
                          (status == WAIT_IO_COMPLETION) ||
                          //It could be that there are no waiters at this point,
                          //as the APC to deregister the wait may have run.
                          (status == WAIT_OBJECT_0) ||
                          (status >= WAIT_OBJECT_0 && status < (DWORD)(WAIT_OBJECT_0 + threadCB->NumActiveWaits))  ||
                          (status == WAIT_FAILED));

                //It could be that the last waiter also got deregistered.
                if (threadCB->NumActiveWaits == 0)
                {
                    continue;
                }
            }

            if (status == WAIT_IO_COMPLETION)
                continue;

            if (status == WAIT_TIMEOUT)
            {
                for (int i=0; i< threadCB->NumActiveWaits; i++)
                {
                    WaitInfo* waitInfo = (WaitInfo*) (threadCB->waitPointer[i]).Flink;
                    PVOID waitInfoHead = &(threadCB->waitPointer[i]);

                    do
                    {
                        _ASSERTE(waitInfo->timer.remainingTime >= timeout);

                        WaitInfo* wTemp = (WaitInfo*) waitInfo->link.Flink;

                        if (waitInfo->timer.remainingTime == timeout)
                        {
                            ProcessWaitCompletion(waitInfo,i,TRUE);
                        }

                        waitInfo = wTemp;

                    } while ((PVOID) waitInfo != waitInfoHead);
                }
            }
            else if (status >= WAIT_OBJECT_0 && status < (DWORD)(WAIT_OBJECT_0 + threadCB->NumActiveWaits))
            {
                unsigned index = status - WAIT_OBJECT_0;
                WaitInfo* waitInfo = (WaitInfo*) (threadCB->waitPointer[index]).Flink;
                PVOID waitInfoHead = &(threadCB->waitPointer[index]);
                BOOL isAutoReset;

                // Setting to unconditional TRUE is inefficient since we will re-enter the wait and release
                // the next waiter, but short of using undocumented NT apis is the only solution.
                // Querying the state with a WaitForSingleObject is not an option as it will reset an
                // auto reset event if it has been signalled since the previous wait.
                isAutoReset = TRUE;

                do
                {
                    WaitInfo* wTemp = (WaitInfo*) waitInfo->link.Flink;
                    ProcessWaitCompletion(waitInfo,index,FALSE);

                    waitInfo = wTemp;

                } while (((PVOID) waitInfo != waitInfoHead) && !isAutoReset);

                // If an app registers a recurring wait for an event that is always signalled (!),
                // then no apc's will be executed since the thread never enters the alertable state.
                // This can be fixed by doing the following:
                //     SleepEx(0,TRUE);
                // However, it causes an unnecessary context switch. It is not worth penalizing well
                // behaved apps to protect poorly written apps.


            }
            else
            {
                _ASSERTE(status == WAIT_FAILED);
                // wait failed: application error
                // find out which wait handle caused the wait to fail
                for (int i = 0; i < threadCB->NumActiveWaits; i++)
                {
                    DWORD subRet = WaitForSingleObject(threadCB->waitHandle[i], 0);

                    if (subRet != WAIT_FAILED)
                        continue;

                    // remove all waits associated with this wait handle

                    WaitInfo* waitInfo = (WaitInfo*) (threadCB->waitPointer[i]).Flink;
                    PVOID waitInfoHead = &(threadCB->waitPointer[i]);

                    do
                    {
                        WaitInfo* temp  = (WaitInfo*) waitInfo->link.Flink;

                        DeactivateNthWait(waitInfo,i);


                // Note, we cannot cleanup here since there is no way to suppress finalization
                // we will just leak, and rely on the finalizer to clean up the memory
                        //if (InterlockedDecrement(&waitInfo->refCount) == 0)
                        //    DeleteWait(waitInfo);


                        waitInfo = temp;

                    } while ((PVOID) waitInfo != waitInfoHead);

                    break;
                }
            }
        }
    }

    //This is unreachable...so no return required.
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif

#ifdef _MSC_VER
#ifdef _WIN64
#pragma warning (default : 4716)
#else
#pragma warning (default : 4715)
#endif
#endif

void ThreadpoolMgr::ProcessWaitCompletion(WaitInfo* waitInfo,
                                          unsigned index,
                                          BOOL waitTimedOut
                                         )
{
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_GC_TRIGGERS;
    STATIC_CONTRACT_MODE_PREEMPTIVE;
    /* cannot use contract because of SEH
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;*/

    AsyncCallback* asyncCallback = NULL;
    EX_TRY{
        if ( waitInfo->flag & WAIT_SINGLE_EXECUTION)
        {
            DeactivateNthWait (waitInfo,index) ;
        }
        else
        {   // reactivate wait by resetting timer
            waitInfo->timer.startTime = GetTickCount();
        }

        asyncCallback = MakeAsyncCallback();
        if (asyncCallback)
        {
            asyncCallback->wait = waitInfo;
            asyncCallback->waitTimedOut = waitTimedOut;

            InterlockedIncrement(&waitInfo->refCount);

#ifndef FEATURE_PAL
            if (FALSE == PostQueuedCompletionStatus((LPOVERLAPPED)asyncCallback, (LPOVERLAPPED_COMPLETION_ROUTINE)WaitIOCompletionCallback))
#else  // FEATURE_PAL
            if (FALSE == QueueUserWorkItem(AsyncCallbackCompletion, asyncCallback, QUEUE_ONLY))
#endif // !FEATURE_PAL
                ReleaseAsyncCallback(asyncCallback);
        }
    }
    EX_CATCH {
        if (asyncCallback)
            ReleaseAsyncCallback(asyncCallback);

        if (SwallowUnhandledExceptions())
        {
            // Do nothing to swallow the exception
        }
        else
        {
            EX_RETHROW;
        }
    }
    EX_END_CATCH(SwallowAllExceptions);
}


DWORD WINAPI ThreadpoolMgr::AsyncCallbackCompletion(PVOID pArgs)
{
    CONTRACTL
    {
        THROWS;
        MODE_PREEMPTIVE;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    Thread * pThread = GetThread();

    if (pThread == NULL)
    {
        HRESULT hr = ERROR_SUCCESS;

        ClrFlsSetThreadType(ThreadType_Threadpool_Worker);
        pThread = SetupThreadNoThrow(&hr);

        if (pThread == NULL)
        {
            return hr;
        }
    }

    {
        AsyncCallback * asyncCallback = (AsyncCallback*) pArgs;

        WaitInfo * waitInfo = asyncCallback->wait;

        AsyncCallbackHolder asyncCBHolder;
        asyncCBHolder.Assign(asyncCallback);

        // We fire the "dequeue" ETW event here, before executing the user code, to enable correlation with
        // the ThreadPoolIOEnqueue fired in ThreadpoolMgr::RegisterWaitForSingleObject
        if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolIODequeue))
            FireEtwThreadPoolIODequeue(waitInfo, reinterpret_cast<void*>(waitInfo->Callback), GetClrInstanceId());

        // the user callback can throw, the host must be prepared to handle it.
        // SQL is ok, since they have a top-level SEH handler. However, there's
        // no easy way to verify it

        ((WAITORTIMERCALLBACKFUNC) waitInfo->Callback)
                                    ( waitInfo->Context, asyncCallback->waitTimedOut != FALSE);

#ifndef FEATURE_PAL
        Thread::IncrementIOThreadPoolCompletionCount(pThread);
#endif
    }

    return ERROR_SUCCESS;
}

void ThreadpoolMgr::DeactivateWait(WaitInfo* waitInfo)
{
    LIMITED_METHOD_CONTRACT;

    ThreadCB* threadCB = waitInfo->threadCB;
    DWORD endIndex = threadCB->NumActiveWaits-1;
    DWORD index;

    for (index = 0;  index <= endIndex; index++)
    {
        LIST_ENTRY* head = &(threadCB->waitPointer[index]);
        LIST_ENTRY* current = head;
        do {
            if (current->Flink == (PVOID) waitInfo)
                goto FOUND;

            current = (LIST_ENTRY*) current->Flink;

        } while (current != head);
    }

FOUND:
    _ASSERTE(index <= endIndex);

    DeactivateNthWait(waitInfo, index);
}


void ThreadpoolMgr::DeactivateNthWait(WaitInfo* waitInfo, DWORD index)
{
    LIMITED_METHOD_CONTRACT;

    ThreadCB* threadCB = waitInfo->threadCB;

    if (waitInfo->link.Flink != waitInfo->link.Blink)
    {
        RemoveEntryList(&(waitInfo->link));
    }
    else
    {

        ULONG EndIndex = threadCB->NumActiveWaits -1;

        // Move the remaining ActiveWaitArray left.

        ShiftWaitArray( threadCB, index+1, index,EndIndex - index ) ;

        // repair the blink and flink of the first and last elements in the list
        for (unsigned int i = 0; i< EndIndex-index; i++)
        {
            WaitInfo* firstWaitInfo = (WaitInfo*) threadCB->waitPointer[index+i].Flink;
            WaitInfo* lastWaitInfo = (WaitInfo*) threadCB->waitPointer[index+i].Blink;
            firstWaitInfo->link.Blink =  &(threadCB->waitPointer[index+i]);
            lastWaitInfo->link.Flink =  &(threadCB->waitPointer[index+i]);
        }
        // initialize the entry just freed
        InitializeListHead(&(threadCB->waitPointer[EndIndex]));

        threadCB->NumActiveWaits-- ;
        InterlockedDecrement(&threadCB->NumWaitHandles);
    }

    waitInfo->state &= ~WAIT_ACTIVE ;

}

void ThreadpoolMgr::DeleteWait(WaitInfo* waitInfo)
{
    CONTRACTL
    {
        if (waitInfo->ExternalEventSafeHandle != NULL) { THROWS;} else { NOTHROW; }
        MODE_ANY;
        if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
    }
    CONTRACTL_END;

    if(waitInfo->Context && (waitInfo->flag & WAIT_FREE_CONTEXT)) {
        DelegateInfo* pDelegate = (DelegateInfo*) waitInfo->Context;

        // Since the delegate release destroys a handle, we need to be in
        // co-operative mode
        {
            GCX_COOP();
            pDelegate->Release();
        }

        RecycleMemory( pDelegate, MEMTYPE_DelegateInfo );
    }

    if (waitInfo->flag & WAIT_INTERNAL_COMPLETION)
    {
        waitInfo->InternalCompletionEvent.Set();
        return;  // waitInfo will be deleted by the thread that's waiting on this event
    }
    else if (waitInfo->ExternalCompletionEvent != INVALID_HANDLE)
    {
        SetEvent(waitInfo->ExternalCompletionEvent);
    }
    else if (waitInfo->ExternalEventSafeHandle != NULL)
    {
        // Release the safe handle and the GC handle holding it
        ReleaseWaitInfo(waitInfo);
    }

    delete waitInfo;


}



/************************************************************************/
BOOL ThreadpoolMgr::UnregisterWaitEx(HANDLE hWaitObject,HANDLE Event)
{
    CONTRACTL
    {
        THROWS; //NOTHROW;
        if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        MODE_ANY;
    }
    CONTRACTL_END;

    _ASSERTE(IsInitialized());              // cannot call unregister before first registering

    const BOOL Blocking = (Event == (HANDLE) -1);
    WaitInfo* waitInfo = (WaitInfo*) hWaitObject;

    if (!hWaitObject)
    {
        return FALSE;
    }

    // we do not allow callbacks to run in the wait thread, hence the assert
    _ASSERTE(GetCurrentThreadId() != waitInfo->threadCB->threadId);


    if (Blocking)
    {
        waitInfo->InternalCompletionEvent.CreateAutoEvent(FALSE);
        waitInfo->flag |= WAIT_INTERNAL_COMPLETION;

    }
    else
    {
        waitInfo->ExternalCompletionEvent = (Event ? Event : INVALID_HANDLE);
        _ASSERTE((waitInfo->flag & WAIT_INTERNAL_COMPLETION) == 0);
        // we still want to block until the wait has been deactivated
        waitInfo->PartialCompletionEvent.CreateAutoEvent(FALSE);
    }

    BOOL status = QueueDeregisterWait(waitInfo->threadCB->threadHandle, waitInfo);


    if (status == 0)
    {
        STRESS_LOG1(LF_THREADPOOL, LL_ERROR, "Queue APC failed in UnregisterWaitEx %x", status);

        if (Blocking)
            waitInfo->InternalCompletionEvent.CloseEvent();
        else
            waitInfo->PartialCompletionEvent.CloseEvent();
        return FALSE;
    }

    if (!Blocking)
    {
        waitInfo->PartialCompletionEvent.Wait(INFINITE,TRUE);
        waitInfo->PartialCompletionEvent.CloseEvent();
        // we cannot do DeleteWait in DeregisterWait, since the DeleteWait could happen before
        // we close the event. So, the code has been moved here.
        if (InterlockedDecrement(&waitInfo->refCount) == 0)
        {
            DeleteWait(waitInfo);
        }
    }

    else        // i.e. blocking
    {
        _ASSERTE(waitInfo->flag & WAIT_INTERNAL_COMPLETION);
        _ASSERTE(waitInfo->ExternalEventSafeHandle == NULL);

        waitInfo->InternalCompletionEvent.Wait(INFINITE,TRUE);
        waitInfo->InternalCompletionEvent.CloseEvent();
        delete waitInfo;  // if WAIT_INTERNAL_COMPLETION is not set, waitInfo will be deleted in DeleteWait
    }
    return TRUE;
}


void ThreadpoolMgr::DeregisterWait(WaitInfo* pArgs)
{
    WRAPPER_NO_CONTRACT;

    WaitInfo* waitInfo = pArgs;

    if ( ! (waitInfo->state & WAIT_REGISTERED) )
    {
        // set state to deleted, so that it does not get registered
        waitInfo->state |= WAIT_DELETE ;

        // since the wait has not even been registered, we dont need an interlock to decrease the RefCount
        waitInfo->refCount--;

        if (waitInfo->PartialCompletionEvent.IsValid())
        {
            waitInfo->PartialCompletionEvent.Set();
        }
        return;
    }

    if (waitInfo->state & WAIT_ACTIVE)
    {
        DeactivateWait(waitInfo);
    }

    if ( waitInfo->PartialCompletionEvent.IsValid())
    {
        waitInfo->PartialCompletionEvent.Set();
        return;     // we cannot delete the wait here since the PartialCompletionEvent
                    // may not have been closed yet. so, we return and rely on the waiter of PartialCompletionEvent
                    // to do the close
    }

    if (InterlockedDecrement(&waitInfo->refCount) == 0)
    {
        DeleteWait(waitInfo);
    }
    return;
}


/* This gets called in a finalizer thread ONLY IF an app does not deregister the
   the wait. Note that just because the registeredWaitHandle is collected by GC
   does not mean it is safe to delete the wait. The refcount tells us when it is
   safe.
*/
void ThreadpoolMgr::WaitHandleCleanup(HANDLE hWaitObject)
{
    LIMITED_METHOD_CONTRACT;

    WaitInfo* waitInfo = (WaitInfo*) hWaitObject;
    _ASSERTE(waitInfo->refCount > 0);

    DWORD result = QueueDeregisterWait(waitInfo->threadCB->threadHandle, waitInfo);

    if (result == 0)
        STRESS_LOG1(LF_THREADPOOL, LL_ERROR, "Queue APC failed in WaitHandleCleanup %x", result);

}

BOOL ThreadpoolMgr::CreateGateThread()
{
    LIMITED_METHOD_CONTRACT;

    HANDLE threadHandle = Thread::CreateUtilityThread(Thread::StackSize_Small, GateThreadStart, NULL, W(".NET ThreadPool Gate"));

    if (threadHandle)
    {
        CloseHandle(threadHandle);  //we don't need this anymore
        return TRUE;
    }

    return FALSE;
}



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

BOOL ThreadpoolMgr::BindIoCompletionCallback(HANDLE FileHandle,
                                            LPOVERLAPPED_COMPLETION_ROUTINE Function,
                                            ULONG Flags,
                                            DWORD& errCode)
{

    CONTRACTL
    {
        THROWS;     // EnsureInitialized can throw
        if (GetThread()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        MODE_ANY;
    }
    CONTRACTL_END;

#ifndef FEATURE_PAL
    
    errCode = S_OK;

    EnsureInitialized();


    _ASSERTE(GlobalCompletionPort != NULL);

    if (!InitCompletionPortThreadpool)
        InitCompletionPortThreadpool = TRUE;

    GrowCompletionPortThreadpoolIfNeeded();

    HANDLE h = CreateIoCompletionPort(FileHandle,
                                      GlobalCompletionPort,
                                      (ULONG_PTR) Function,
                                      NumberOfProcessors);
    if (h == NULL)
    {
        errCode = GetLastError();
        return FALSE;
    }

    _ASSERTE(h == GlobalCompletionPort);

    return TRUE;
#else // FEATURE_PAL
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
#endif // !FEATURE_PAL
}

#ifndef FEATURE_PAL
BOOL ThreadpoolMgr::CreateCompletionPortThread(LPVOID lpArgs)
{
    CONTRACTL
    {
        NOTHROW;
        if (GetThread()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        MODE_ANY;
    }
    CONTRACTL_END;

    Thread *pThread;
    BOOL fIsCLRThread;
    if ((pThread = CreateUnimpersonatedThread(CompletionPortThreadStart, lpArgs, &fIsCLRThread)) != NULL)
    {
        LastCPThreadCreation = GetTickCount();          // record this for use by logic to spawn additional threads

        if (fIsCLRThread) {
            pThread->ChooseThreadCPUGroupAffinity();
            pThread->StartThread();
        }
        else {
            DWORD status;
            status = ResumeThread((HANDLE)pThread);
            _ASSERTE(status != (DWORD) (-1));
            CloseHandle((HANDLE)pThread);          // we don't need this anymore
        }

        ThreadCounter::Counts counts = CPThreadCounter.GetCleanCounts();
        FireEtwIOThreadCreate_V1(counts.NumActive + counts.NumRetired, counts.NumRetired, GetClrInstanceId());

        return TRUE;
    }


    return FALSE;
}

DWORD WINAPI ThreadpoolMgr::CompletionPortThreadStart(LPVOID lpArgs)
{
    ClrFlsSetThreadType (ThreadType_Threadpool_IOCompletion);

    CONTRACTL
    {
        THROWS;
        if (GetThread()) { MODE_PREEMPTIVE;} else { DISABLED(MODE_ANY);}
        if (GetThread()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
    }
    CONTRACTL_END;

    DWORD numBytes=0;
    size_t key=0;

    LPOVERLAPPED pOverlapped = NULL;
    DWORD errorCode;
    PIOCompletionContext context;
    BOOL fIsCompletionContext;

    const DWORD CP_THREAD_WAIT = AppX::IsAppXProcess() ? 5000 : 15000; /* milliseconds */

    _ASSERTE(GlobalCompletionPort != NULL);

    BOOL fThreadInit = FALSE;
    Thread *pThread = NULL;

    DWORD cpThreadWait = 0;

    if (g_fEEStarted) {
        pThread = SetupThreadNoThrow();
        if (pThread == NULL) {
            return 0;
        }

        // converted to CLRThread and added to ThreadStore, pick an group affinity for this thread
        pThread->ChooseThreadCPUGroupAffinity(); 

        fThreadInit = TRUE;
    }

#ifdef FEATURE_COMINTEROP
    // Threadpool threads should be initialized as MTA. If we are unable to do so,
    // return failure.
    BOOL fCoInited = FALSE;
    {
        fCoInited = SUCCEEDED(::CoInitializeEx(NULL, COINIT_MULTITHREADED));
        if (!fCoInited)
        {
            goto Exit;
        }
    }

    if (pThread && pThread->SetApartment(Thread::AS_InMTA, TRUE) != Thread::AS_InMTA)
    {
        // @todo: should we log the failure
        goto Exit;
    }
#endif // FEATURE_COMINTEROP

    ThreadCounter::Counts oldCounts;
    ThreadCounter::Counts newCounts;

    cpThreadWait = CP_THREAD_WAIT;
    for (;; )
    {
Top:
        if (!fThreadInit) {
            if (g_fEEStarted) {
                pThread = SetupThreadNoThrow();
                if (pThread == NULL) {
                    break;
                }

                // converted to CLRThread and added to ThreadStore, pick an group affinity for this thread
                pThread->ChooseThreadCPUGroupAffinity(); 

#ifdef FEATURE_COMINTEROP
                if (pThread->SetApartment(Thread::AS_InMTA, TRUE) != Thread::AS_InMTA)
                {
                    // @todo: should we log the failure
                    goto Exit;
                }
#endif // FEATURE_COMINTEROP

                fThreadInit = TRUE;
            }
        }

        GCX_PREEMP_NO_DTOR();

        //
        // We're about to wait on the IOCP; mark ourselves as no longer "working."
        //
        while (true)
        {
            ThreadCounter::Counts oldCounts = CPThreadCounter.DangerousGetDirtyCounts();
            ThreadCounter::Counts newCounts = oldCounts;
            newCounts.NumWorking--;

            //
            // If we've only got one thread left, it won't be allowed to exit, because we need to keep
            // one thread listening for completions.  So there's no point in having a timeout; it will
            // only use power unnecessarily.
            //
            cpThreadWait = (newCounts.NumActive == 1) ? INFINITE : CP_THREAD_WAIT;

            if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts))
                break;
        }

        errorCode = S_OK;

        if (lpArgs == NULL)
        {
            CONTRACT_VIOLATION(ThrowsViolation);

            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();
                }
            }

            context = NULL;
            fIsCompletionContext = FALSE;
        
            if (pThread == NULL) 
            {    
                pThread = GetThread();
            }

            if (pThread) 
            {
 
                context = (PIOCompletionContext) pThread->GetIOCompletionContext();
            
                if (context->lpOverlapped != NULL) 
                {
                    errorCode = context->ErrorCode;
                    numBytes = context->numBytesTransferred;
                    pOverlapped = context->lpOverlapped;
                    key = context->key;
                    
                    context->lpOverlapped = NULL;
                    fIsCompletionContext = TRUE;
                }
            }

            if((context == NULL) || (!fIsCompletionContext))
            {
                _ASSERTE (context == NULL || context->lpOverlapped == NULL);

                BOOL status = GetQueuedCompletionStatus(
                    GlobalCompletionPort,
                    &numBytes,
                    (PULONG_PTR)&key,
                    &pOverlapped,
                    cpThreadWait
                    );

                if (status == 0)
                    errorCode = GetLastError();
            }
        }
        else
        {
            QueuedStatus *CompletionStatus = (QueuedStatus*)lpArgs;
            numBytes = CompletionStatus->numBytes;
            key = (size_t)CompletionStatus->key;
            pOverlapped = CompletionStatus->pOverlapped;
            errorCode = CompletionStatus->errorCode;
            delete CompletionStatus;
            lpArgs = NULL;  // one-time deal for initial CP packet
        }

        // We fire IODequeue events whether the IO completion was retrieved in the above call to
        // GetQueuedCompletionStatus or during an earlier call (e.g. in GateThreadStart, and passed here in lpArgs, 
        // or in CompletionPortDispatchWorkWithinAppDomain, and passed here through StoreOverlappedInfoInThread)

        // For the purposes of activity correlation we only fire ETW events here, if needed OR if not fired at a higher
        // abstraction level (e.g. ThreadpoolMgr::RegisterWaitForSingleObject)
        // Note: we still fire the event for managed async IO, despite the fact we don't have a paired IOEnqueue event
        // for this case. We do this to "mark" the end of the previous workitem. When we provide full support at the higher
        // abstraction level for managed IO we can remove the IODequeues fired here
        if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolIODequeue)
                && !AreEtwIOQueueEventsSpeciallyHandled((LPOVERLAPPED_COMPLETION_ROUTINE)key) && pOverlapped != NULL)
        {
            FireEtwThreadPoolIODequeue(pOverlapped, OverlappedDataObject::GetOverlappedForTracing(pOverlapped), GetClrInstanceId());
        }

        bool enterRetirement;

        while (true)
        {
            //
            // When we reach this point, this thread is "active" but not "working."  Depending on the result of the call to GetQueuedCompletionStatus, 
            // and the state of the rest of the IOCP threads, we need to figure out whether to de-activate (exit) this thread, retire this thread,
            // or transition to "working."
            //

            // counts volatile read paired with CompareExchangeCounts loop set
            oldCounts = CPThreadCounter.DangerousGetDirtyCounts();
            newCounts = oldCounts;
            enterRetirement = false;

            if (errorCode == WAIT_TIMEOUT)
            {
                //
                // We timed out, and are going to try to exit or retire.
                //
                newCounts.NumActive--;

                //
                // We need at least one free thread, or we have no way of knowing if completions are being queued.
                // 
                if (newCounts.NumWorking == newCounts.NumActive)
                {
                    newCounts = oldCounts;
                    newCounts.NumWorking++; //not really working, but we'll decremented it at the top
                    if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts))
                        goto Top;
                    else
                        continue;
                }

                //
                // We can't exit a thread that has pending I/O - we'll "retire" it instead.
                //
                if (IsIoPending())
                {
                    enterRetirement = true;
                    newCounts.NumRetired++;
                }
            }
            else
            {
                //
                // We have work to do
                //
                newCounts.NumWorking++;
            }

            if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts))
                break;
        }

        if (errorCode == WAIT_TIMEOUT)
        {
            if (!enterRetirement)
            {
                goto Exit;
            }
            else
            {
                // now in "retired mode" waiting for pending io to complete
                FireEtwIOThreadRetire_V1(newCounts.NumActive + newCounts.NumRetired, newCounts.NumRetired, GetClrInstanceId());

                for (;;)
                {
#ifndef FEATURE_PAL
                    if (g_fCompletionPortDrainNeeded && pThread)
                    {
                        // The thread is not going to process IO job now.
                        if (!pThread->IsCompletionPortDrained())
                        {
                            pThread->MarkCompletionPortDrained();
                        }
                    }
#endif // !FEATURE_PAL

                    DWORD status = SafeWait(RetiredCPWakeupEvent,CP_THREAD_PENDINGIO_WAIT,FALSE);
                    _ASSERTE(status == WAIT_TIMEOUT || status == WAIT_OBJECT_0);

                    if (status == WAIT_TIMEOUT)
                    {
                        if (IsIoPending())
                        {
                            continue;
                        }
                        else
                        {
                            // We can now exit; decrement the retired count.
                            while (true)
                            {
                                // counts volatile read paired with CompareExchangeCounts loop set
                                oldCounts = CPThreadCounter.DangerousGetDirtyCounts();
                                newCounts = oldCounts;
                                newCounts.NumRetired--;
                                if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts))
                                    break;
                            }
                            goto Exit;
                        }
                    }
                    else
                    {
                        // put back into rotation -- we need a thread
                        while (true)
                        {
                            // counts volatile read paired with CompareExchangeCounts loop set
                            oldCounts = CPThreadCounter.DangerousGetDirtyCounts();
                            newCounts = oldCounts;
                            newCounts.NumRetired--;
                            newCounts.NumActive++;
                            newCounts.NumWorking++; //we're not really working, but we'll decrement this before waiting for work.
                            if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts))
                                break;
                        }
                        FireEtwIOThreadUnretire_V1(newCounts.NumActive + newCounts.NumRetired, newCounts.NumRetired, GetClrInstanceId());
                        goto Top;
                    }
                }
            }
        }

        // we should not reach this point unless we have work to do
        _ASSERTE(errorCode != WAIT_TIMEOUT && !enterRetirement);

        // if we have no more free threads, start the gate thread
        if (newCounts.NumWorking >= newCounts.NumActive)
            EnsureGateThreadRunning();


        // We can not assert here.  If stdin/stdout/stderr of child process are redirected based on
        // async io, GetQueuedCompletionStatus returns when child process operates on its stdin/stdout/stderr.
        // Parent process does not issue any ReadFile/WriteFile, and hence pOverlapped is going to be NULL.
        //_ASSERTE(pOverlapped != NULL);

        if (pOverlapped != NULL)
        {
            _ASSERTE(key != 0);  // should be a valid function address

            if (key != 0)
            {
                if (GCHeapUtilities::IsGCInProgress(TRUE))
                {
                    //Indicate that this thread is free, and waiting on GC, not doing any user work.
                    //This helps in threads not getting injected when some threads have woken up from the
                    //GC event, and some have not.
                    while (true)
                    {
                        // counts volatile read paired with CompareExchangeCounts loop set
                        oldCounts = CPThreadCounter.DangerousGetDirtyCounts();
                        newCounts = oldCounts;
                        newCounts.NumWorking--;
                        if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts))
                            break;
                    }

                    // GC is imminent, so wait until GC is complete before executing next request.
                    // this reduces in-flight objects allocated right before GC, easing the GC's work
                    GCHeapUtilities::WaitForGCCompletion(TRUE);

                    while (true)
                    {
                        // counts volatile read paired with CompareExchangeCounts loop set
                        oldCounts = CPThreadCounter.DangerousGetDirtyCounts();
                        newCounts = oldCounts;
                        newCounts.NumWorking++;
                        if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts))
                            break;
                    }

                    if (newCounts.NumWorking >= newCounts.NumActive)
                        EnsureGateThreadRunning();
                }
                else
                {
                    GrowCompletionPortThreadpoolIfNeeded();
                }

                {
                    CONTRACT_VIOLATION(ThrowsViolation);

                    ((LPOVERLAPPED_COMPLETION_ROUTINE) key)(errorCode, numBytes, pOverlapped);
                }

                if ((void *)key != CallbackForInitiateDrainageOfCompletionPortQueue &&
                    (void *)key != CallbackForContinueDrainageOfCompletionPortQueue)
                {
                    Thread::IncrementIOThreadPoolCompletionCount(pThread);
                }

                if (pThread == NULL) {
                    pThread = GetThread();
                }
                if (pThread) {
                    if (pThread->IsAbortRequested())
                        pThread->EEResetAbort(Thread::TAR_ALL);
                    pThread->InternalReset();
                }
            }
            else
            {
                // Application bug - can't do much, just ignore it
            }

        }

    }   // for (;;)

Exit:

    oldCounts = CPThreadCounter.GetCleanCounts();

    // we should never destroy or retire all IOCP threads, because then we won't have any threads to notice incoming completions.
    _ASSERTE(oldCounts.NumActive > 0);

    FireEtwIOThreadTerminate_V1(oldCounts.NumActive + oldCounts.NumRetired, oldCounts.NumRetired, GetClrInstanceId());

#ifdef FEATURE_COMINTEROP
    if (pThread) {
        pThread->SetApartment(Thread::AS_Unknown, TRUE);
        pThread->CoUninitialize();
    }
    // Couninit the worker thread
    if (fCoInited)
    {
        CoUninitialize();
    }
#endif

    if (pThread) {
        pThread->ClearThreadCPUGroupAffinity();

        DestroyThread(pThread);
    }

    return 0;
}

LPOVERLAPPED ThreadpoolMgr::CompletionPortDispatchWorkWithinAppDomain(
    Thread* pThread,
    DWORD* pErrorCode, 
    DWORD* pNumBytes,
    size_t* pKey)
//
//This function is called just after dispatching the previous BindIO callback
//to Managed code. This is a perf optimization to do a quick call to 
//GetQueuedCompletionStatus with a timeout of 0 ms. If there is work in the
//same appdomain, dispatch it back immediately. If not stick it in a well known
//place, and reenter the target domain. The timeout of zero is chosen so as to 
//not delay appdomain unloads.
//
{
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_MODE_ANY;

    LPOVERLAPPED lpOverlapped=NULL;

    BOOL status=FALSE;
    OVERLAPPEDDATAREF overlapped=NULL;
    BOOL ManagedCallback=FALSE;

    *pErrorCode = S_OK;


    //Very Very Important!
    //Do not change the timeout for GetQueuedCompletionStatus to a non-zero value.
    //Selecting a non-zero value can cause the thread to block, and lead to expensive context switches.
    //In real life scenarios, we have noticed a packet to be not availabe immediately, but very shortly 
    //(after few 100's of instructions), and falling back to the VM is good in that case as compared to
    //taking a context switch. Changing the timeout to non-zero can lead to perf degrades, that are very
    //hard to diagnose.     

    status = ::GetQueuedCompletionStatus(
                 GlobalCompletionPort,
                 pNumBytes,
                 (PULONG_PTR)pKey,
                 &lpOverlapped,
                 0);

    DWORD lastError = GetLastError();

    if (status == 0) 
    {          
        if (lpOverlapped != NULL) 
        {
            *pErrorCode = lastError;
        } 
        else 
        {
            return NULL;
        }
    } 

    if (((LPOVERLAPPED_COMPLETION_ROUTINE) *pKey) != BindIoCompletionCallbackStub)
    {
        //_ASSERTE(FALSE);
    } 
    else 
    {
        ManagedCallback = TRUE;
        overlapped = ObjectToOVERLAPPEDDATAREF(OverlappedDataObject::GetOverlapped(lpOverlapped));
    }  

    if (ManagedCallback) 
    {           
        _ASSERTE(*pKey != 0);  // should be a valid function address
        
        if (*pKey ==0) 
        {
            //Application Bug.
            return NULL;
        }
    } 
    else 
    {
        //Just retruned back from managed code, a Thread structure should exist.
        _ASSERTE (pThread);
        
        //Oops, this is an overlapped fom a different appdomain. STick it in
        //the thread. We will process it later.

        StoreOverlappedInfoInThread(pThread, *pErrorCode, *pNumBytes, *pKey, lpOverlapped);

        lpOverlapped = NULL;        
    }

#ifndef DACCESS_COMPILE    
    return lpOverlapped;
#endif
}

void ThreadpoolMgr::StoreOverlappedInfoInThread(Thread* pThread, DWORD dwErrorCode, DWORD dwNumBytes, size_t key, LPOVERLAPPED lpOverlapped)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_MODE_ANY;

    _ASSERTE(pThread);

    PIOCompletionContext context;

    context = (PIOCompletionContext) pThread->GetIOCompletionContext();

    _ASSERTE(context);

    context->ErrorCode = dwErrorCode;
    context->numBytesTransferred = dwNumBytes;
    context->lpOverlapped = lpOverlapped;
    context->key = key;
}

BOOL ThreadpoolMgr::ShouldGrowCompletionPortThreadpool(ThreadCounter::Counts counts)
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        NOTHROW;
        MODE_ANY;
    }
    CONTRACTL_END;     

    if (counts.NumWorking >= counts.NumActive 
        && NumCPInfrastructureThreads == 0
        && (counts.NumActive == 0 ||  !GCHeapUtilities::IsGCInProgress(TRUE))
        )
    {
        // adjust limit if needed
        if (counts.NumRetired == 0)
        {
            if (counts.NumActive + counts.NumRetired < MaxLimitTotalCPThreads &&
                (counts.NumActive < MinLimitTotalCPThreads || cpuUtilization < CpuUtilizationLow))
            {
                // add one more check to make sure that we haven't fired off a new
                // thread since the last time time we checked the cpu utilization.
                // However, don't bother if we haven't reached the MinLimit (2*number of cpus)
                if ((counts.NumActive < MinLimitTotalCPThreads) ||
                    SufficientDelaySinceLastSample(LastCPThreadCreation,counts.NumActive))
                {
                    return TRUE;
                }                 
            }
        }

        if (counts.NumRetired > 0)
            return TRUE;
    }
    return FALSE;
}

void ThreadpoolMgr::GrowCompletionPortThreadpoolIfNeeded()
{
    CONTRACTL
    {
        if (GetThread()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        NOTHROW;
        MODE_ANY;
    }
    CONTRACTL_END;    

    ThreadCounter::Counts oldCounts, newCounts;
    while (true)
    {
        oldCounts = CPThreadCounter.GetCleanCounts();
        newCounts = oldCounts;
        
        if(!ShouldGrowCompletionPortThreadpool(oldCounts))
        {
            break;
        }
        else
        {
            if (oldCounts.NumRetired > 0)
            {        
                // wakeup retired thread instead
                RetiredCPWakeupEvent->Set();
                return;
            }
            else 
            {
                // create a new thread.  New IOCP threads start as "active" and "working"
                newCounts.NumActive++;
                newCounts.NumWorking++;
                if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts))
                {
                    if (!CreateCompletionPortThread(NULL))
                    {
                        // if thread creation failed, we have to adjust the counts back down.
                        while (true)
                        {
                            // counts volatile read paired with CompareExchangeCounts loop set
                            oldCounts = CPThreadCounter.DangerousGetDirtyCounts();
                            newCounts = oldCounts;
                            newCounts.NumActive--;
                            newCounts.NumWorking--;
                            if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts))
                                break;
                        }
                    }
                    return;
                }
            }    
        } 
    }
}
#endif // !FEATURE_PAL

// Returns true if there is pending io on the thread.
BOOL ThreadpoolMgr::IsIoPending()
{
    CONTRACTL
    {
        NOTHROW;         
        MODE_ANY;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

#ifndef FEATURE_PAL
    int Status;
    ULONG IsIoPending;

    if (g_pufnNtQueryInformationThread)
    {
        Status =(int) (*g_pufnNtQueryInformationThread)(GetCurrentThread(),
                                          ThreadIsIoPending,
                                          &IsIoPending,
                                          sizeof(IsIoPending),
                                          NULL);


        if ((Status < 0) || IsIoPending)
            return TRUE;
        else
            return FALSE;
    }
    return TRUE;
#else
    return FALSE;
#endif // !FEATURE_PAL
}

#ifndef FEATURE_PAL

#ifdef _WIN64
#pragma warning (disable : 4716)
#else
#pragma warning (disable : 4715)
#endif

int ThreadpoolMgr::GetCPUBusyTime_NT(PROCESS_CPU_INFORMATION* pOldInfo)
{
    LIMITED_METHOD_CONTRACT;

    PROCESS_CPU_INFORMATION newUsage;
    newUsage.idleTime.QuadPart   = 0;
    newUsage.kernelTime.QuadPart = 0;
    newUsage.userTime.QuadPart   = 0;

    if (CPUGroupInfo::CanEnableGCCPUGroups() && CPUGroupInfo::CanEnableThreadUseAllCpuGroups())
    {
#if !defined(FEATURE_REDHAWK) && !defined(FEATURE_PAL)
        FILETIME newIdleTime, newKernelTime, newUserTime;

        CPUGroupInfo::GetSystemTimes(&newIdleTime, &newKernelTime, &newUserTime);
        newUsage.idleTime.u.LowPart    = newIdleTime.dwLowDateTime;
        newUsage.idleTime.u.HighPart   = newIdleTime.dwHighDateTime;
        newUsage.kernelTime.u.LowPart  = newKernelTime.dwLowDateTime;
        newUsage.kernelTime.u.HighPart = newKernelTime.dwHighDateTime;
        newUsage.userTime.u.LowPart    = newUserTime.dwLowDateTime;
        newUsage.userTime.u.HighPart   = newUserTime.dwHighDateTime;
#endif
    }
    else
    {
        (*g_pufnNtQuerySystemInformation)(SystemProcessorPerformanceInformation, 
                        pOldInfo->usageBuffer,
                        pOldInfo->usageBufferSize,
                        NULL);

        SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* pInfoArray = pOldInfo->usageBuffer;
        DWORD_PTR pmask = pOldInfo->affinityMask;

        int proc_no = 0;
        while (pmask)
        {
            if (pmask & 1)
            {   //should be good: 1CPU 28823 years, 256CPUs 100+years
                newUsage.idleTime.QuadPart   += pInfoArray[proc_no].IdleTime.QuadPart;
                newUsage.kernelTime.QuadPart += pInfoArray[proc_no].KernelTime.QuadPart;
                newUsage.userTime.QuadPart   += pInfoArray[proc_no].UserTime.QuadPart;
            }

            pmask >>=1;
            proc_no++;
        }
    }

    __int64 cpuTotalTime, cpuBusyTime;

    cpuTotalTime  = (newUsage.userTime.QuadPart   - pOldInfo->userTime.QuadPart) +
                    (newUsage.kernelTime.QuadPart - pOldInfo->kernelTime.QuadPart);
    cpuBusyTime   = cpuTotalTime - 
                    (newUsage.idleTime.QuadPart   - pOldInfo->idleTime.QuadPart);

    // Preserve reading
    pOldInfo->idleTime   = newUsage.idleTime;
    pOldInfo->kernelTime = newUsage.kernelTime;
    pOldInfo->userTime   = newUsage.userTime;

    __int64 reading = 0;

    if (cpuTotalTime > 0)
        reading = ((cpuBusyTime * 100) / cpuTotalTime);

    _ASSERTE(FitsIn<int>(reading));
    return (int)reading;
}

#else // !FEATURE_PAL

int ThreadpoolMgr::GetCPUBusyTime_NT(PAL_IOCP_CPU_INFORMATION* pOldInfo)
{
    return PAL_GetCPUBusyTime(pOldInfo);
}

#endif // !FEATURE_PAL

//
// A timer that ticks every GATE_THREAD_DELAY milliseconds.  
// On platforms that support it, we use a coalescable waitable timer object.
// For other platforms, we use Sleep, via __SwitchToThread.
//
class GateThreadTimer
{
#ifndef FEATURE_PAL
    HANDLE m_hTimer;

public:
    GateThreadTimer()
        : m_hTimer(NULL)
    {
        CONTRACTL
        {
            NOTHROW;
            MODE_PREEMPTIVE;
        }
        CONTRACTL_END;

        if (g_pufnCreateWaitableTimerEx && g_pufnSetWaitableTimerEx)
        {
            m_hTimer = g_pufnCreateWaitableTimerEx(NULL, NULL, 0, TIMER_ALL_ACCESS);
            if (m_hTimer)
            {
                //
                // Set the timer to fire GATE_THREAD_DELAY milliseconds from now, then every GATE_THREAD_DELAY milliseconds thereafter.
                // We also set the tolerance to GET_THREAD_DELAY_TOLERANCE, allowing the OS to coalesce this timer.
                //
                LARGE_INTEGER dueTime;
                dueTime.QuadPart = MILLI_TO_100NANO(-(LONGLONG)GATE_THREAD_DELAY); //negative value indicates relative time
                if (!g_pufnSetWaitableTimerEx(m_hTimer, &dueTime, GATE_THREAD_DELAY, NULL, NULL, NULL, GATE_THREAD_DELAY_TOLERANCE))
                {
                    CloseHandle(m_hTimer);
                    m_hTimer = NULL;
                }
            }
        }
    }

    ~GateThreadTimer()
    {
        CONTRACTL
        {
            NOTHROW;
            MODE_PREEMPTIVE;
        }
        CONTRACTL_END;

        if (m_hTimer)
        {
            CloseHandle(m_hTimer);
            m_hTimer = NULL;
        }
    }

#endif // !FEATURE_PAL

public:
    void Wait()
    {
        CONTRACTL
        {
            NOTHROW;
            MODE_PREEMPTIVE;
        }
        CONTRACTL_END;

#ifndef FEATURE_PAL
        if (m_hTimer)
            WaitForSingleObject(m_hTimer, INFINITE);
        else
#endif // !FEATURE_PAL
            __SwitchToThread(GATE_THREAD_DELAY, CALLER_LIMITS_SPINNING);
    }
};


DWORD WINAPI ThreadpoolMgr::GateThreadStart(LPVOID lpArgs)
{
    ClrFlsSetThreadType (ThreadType_Gate);

    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

    _ASSERTE(GateThreadStatus == GATE_THREAD_STATUS_REQUESTED);

    GateThreadTimer timer;

    // TODO: do we need to do this?
    timer.Wait(); // delay getting initial CPU reading

#ifndef FEATURE_PAL
    PROCESS_CPU_INFORMATION prevCPUInfo;

    if (!g_pufnNtQuerySystemInformation)
    {
        _ASSERT(!"NtQuerySystemInformation API not available!");
        return 0;
    }

#ifndef FEATURE_PAL
    //GateThread can start before EESetup, so ensure CPU group information is initialized;
    CPUGroupInfo::EnsureInitialized();
#endif // !FEATURE_PAL
    // initialize CPU usage information structure;
    prevCPUInfo.idleTime.QuadPart   = 0;
    prevCPUInfo.kernelTime.QuadPart = 0;
    prevCPUInfo.userTime.QuadPart   = 0;

    PREFIX_ASSUME(NumberOfProcessors < 65536);
    prevCPUInfo.numberOfProcessors = NumberOfProcessors;

    /* In following cases, affinity mask can be zero
     * 1. hosted, the hosted process already uses multiple cpu groups.
     *    thus, during CLR initialization, GetCurrentProcessCpuCount() returns 64, and GC threads
     *    are created to fill up the initial CPU group. ==> use g_SystemInfo.dwNumberOfProcessors
     * 2. GCCpuGroups=1, CLR creates GC threads for all processors in all CPU groups
     *    thus, the threadpool thread would use a whole CPU group (if Thread_UseAllCpuGroups is not set).
     *    ==> use g_SystemInfo.dwNumberOfProcessors.
     * 3. !defined(FEATURE_PAL) but defined(FEATURE_CORESYSTEM), GetCurrentProcessCpuCount()
     *    returns g_SystemInfo.dwNumberOfProcessors ==> use g_SystemInfo.dwNumberOfProcessors;
     * Other cases:
     * 1. Normal case: the mask is all or a subset of all processors in a CPU group;
     * 2. GCCpuGroups=1 && Thread_UseAllCpuGroups = 1, the mask is not used
     */
    prevCPUInfo.affinityMask = GetCurrentProcessCpuMask();
    if (prevCPUInfo.affinityMask == 0) 
    {   // create a mask that has g_SystemInfo.dwNumberOfProcessors;
        DWORD_PTR mask = 0, maskpos = 1;
        for (unsigned int i=0; i < g_SystemInfo.dwNumberOfProcessors; i++)
        {
             mask |= maskpos;
             maskpos <<= 1;
        }
        prevCPUInfo.affinityMask = mask;
    }

    // in some cases GetCurrentProcessCpuCount() returns a number larger than
    // g_SystemInfo.dwNumberOfProcessor when there are CPU groups, use the larger
    // one to create buffer. This buffer must be cleared with 0's to get correct
    // CPU usage statistics
    int elementsNeeded = NumberOfProcessors > g_SystemInfo.dwNumberOfProcessors ?
                                                  NumberOfProcessors : g_SystemInfo.dwNumberOfProcessors;
    if (!ClrSafeInt<int>::multiply(elementsNeeded, sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION), 
                                                  prevCPUInfo.usageBufferSize))
        return 0;

    prevCPUInfo.usageBuffer = (SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *)alloca(prevCPUInfo.usageBufferSize);
    if (prevCPUInfo.usageBuffer == NULL)
        return 0;

    memset((void *)prevCPUInfo.usageBuffer, 0, prevCPUInfo.usageBufferSize); //must clear it with 0s

    GetCPUBusyTime_NT(&prevCPUInfo);
#else // !FEATURE_PAL
    PAL_IOCP_CPU_INFORMATION prevCPUInfo;
    GetCPUBusyTime_NT(&prevCPUInfo);                  // ignore return value the first time
#endif // !FEATURE_PAL
    
    BOOL IgnoreNextSample = FALSE;

    do
    {
        timer.Wait();

        if(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_EnableWorkerTracking))
            FireEtwThreadPoolWorkingThreadCount(TakeMaxWorkingThreadCount(), GetClrInstanceId());

#ifdef DEBUGGING_SUPPORTED
        // if we are stopped at a debug breakpoint, go back to sleep
        if (CORDebuggerAttached() && g_pDebugInterface->IsStopped())
            continue;
#endif // DEBUGGING_SUPPORTED

        if (!GCHeapUtilities::IsGCInProgress(FALSE) )
        {
            if (IgnoreNextSample)
            {
                IgnoreNextSample = FALSE;
                int cpuUtilizationTemp = GetCPUBusyTime_NT(&prevCPUInfo);            // updates prevCPUInfo as side effect
                // don't artificially drive down average if cpu is high
                if (cpuUtilizationTemp <= CpuUtilizationLow)
                    cpuUtilization = CpuUtilizationLow + 1;
                else
                    cpuUtilization = cpuUtilizationTemp;
            }
            else
            {
                cpuUtilization = GetCPUBusyTime_NT(&prevCPUInfo);            // updates prevCPUInfo as side effect
            }
        }
        else
        {
            int cpuUtilizationTemp = GetCPUBusyTime_NT(&prevCPUInfo);            // updates prevCPUInfo as side effect
            // don't artificially drive down average if cpu is high
            if (cpuUtilizationTemp <= CpuUtilizationLow)
                cpuUtilization = CpuUtilizationLow + 1;
            else
                cpuUtilization = cpuUtilizationTemp;
            IgnoreNextSample = TRUE;
        }

#ifndef FEATURE_PAL
        // don't mess with CP thread pool settings if not initialized yet
        if (InitCompletionPortThreadpool)
        {
            ThreadCounter::Counts oldCounts, newCounts;
            oldCounts = CPThreadCounter.GetCleanCounts();

            if (oldCounts.NumActive == oldCounts.NumWorking &&
                oldCounts.NumRetired == 0 &&
                oldCounts.NumActive < MaxLimitTotalCPThreads &&
                !g_fCompletionPortDrainNeeded &&
                NumCPInfrastructureThreads == 0 &&       // infrastructure threads count as "to be free as needed"
                !GCHeapUtilities::IsGCInProgress(TRUE))

            {
                BOOL status;
                DWORD numBytes;
                size_t key;
                LPOVERLAPPED pOverlapped;
                DWORD errorCode;

                errorCode = S_OK;

                status = GetQueuedCompletionStatus(
                            GlobalCompletionPort,
                            &numBytes,
                            (PULONG_PTR)&key,
                            &pOverlapped,
                            0 // immediate return
                            );

                if (status == 0)
                {
                    errorCode = GetLastError();
                }

                if(pOverlapped == &overlappedForContinueCleanup)
                {
                    // if we picked up a "Continue Drainage" notification DO NOT create a new CP thread
                }
                else 
                if (errorCode != WAIT_TIMEOUT)
                {
                    QueuedStatus *CompletionStatus = NULL;

                    // loop, retrying until memory is allocated.  Under such conditions the gate
                    // thread is not useful anyway, so I feel comfortable with this behavior
                    do
                    {
                        // make sure to free mem later in thread
                        CompletionStatus = new (nothrow) QueuedStatus;
                        if (CompletionStatus == NULL)
                        {
                            __SwitchToThread(GATE_THREAD_DELAY, CALLER_LIMITS_SPINNING);
                        }
                    }
                    while (CompletionStatus == NULL);

                    CompletionStatus->numBytes = numBytes;
                    CompletionStatus->key = (PULONG_PTR)key;
                    CompletionStatus->pOverlapped = pOverlapped;
                    CompletionStatus->errorCode = errorCode;

                    // IOCP threads are created as "active" and "working"
                    while (true)
                    {
                        // counts volatile read paired with CompareExchangeCounts loop set
                        oldCounts = CPThreadCounter.DangerousGetDirtyCounts();
                        newCounts = oldCounts;
                        newCounts.NumActive++;
                        newCounts.NumWorking++;
                        if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts))
                            break;
                    }

                    // loop, retrying until thread is created.
                    while (!CreateCompletionPortThread((LPVOID)CompletionStatus))
                    {
                        __SwitchToThread(GATE_THREAD_DELAY, CALLER_LIMITS_SPINNING);
                    }
                }
            }
            else if (cpuUtilization < CpuUtilizationLow)
            {
                // this could be an indication that threads might be getting blocked or there is no work
                if (oldCounts.NumWorking == oldCounts.NumActive &&                // don't bump the limit if there are already free threads
                    oldCounts.NumRetired > 0) 
                {
                    RetiredCPWakeupEvent->Set();
                }
            }
        }
#endif // !FEATURE_PAL

        if (0 == CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_DisableStarvationDetection))
        {
            if (PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains() && SufficientDelaySinceLastDequeue())
            {
                DangerousNonHostedSpinLockHolder tal(&ThreadAdjustmentLock);

                ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts();
                while (counts.NumActive < MaxLimitTotalWorkerThreads && //don't add a thread if we're at the max
                       counts.NumActive >= counts.MaxWorking)            //don't add a thread if we're already in the process of adding threads
                {
                    bool breakIntoDebugger = (0 != CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_DebugBreakOnWorkerStarvation));
                    if (breakIntoDebugger)
                    {
                        OutputDebugStringW(W("The CLR ThreadPool detected work queue starvation!"));
                        DebugBreak();
                    }

                    ThreadCounter::Counts newCounts = counts;
                    newCounts.MaxWorking = newCounts.NumActive + 1;

                    ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts);
                    if (oldCounts == counts)
                    {
                        HillClimbingInstance.ForceChange(newCounts.MaxWorking, Starvation);
                        MaybeAddWorkingWorker();
                        break;
                    }
                    else
                    {
                        counts = oldCounts;
                    }
                }
            }
        }
    }
    while (ShouldGateThreadKeepRunning());

    return 0;
}

// called by logic to spawn a new completion port thread.
// return false if not enough time has elapsed since the last
// time we sampled the cpu utilization.
BOOL ThreadpoolMgr::SufficientDelaySinceLastSample(unsigned int LastThreadCreationTime,
                                                   unsigned NumThreads,   // total number of threads of that type (worker or CP)
                                                   double    throttleRate // the delay is increased by this percentage for each extra thread
                                                   )
{
    LIMITED_METHOD_CONTRACT;

    unsigned dwCurrentTickCount =  GetTickCount();

    unsigned delaySinceLastThreadCreation = dwCurrentTickCount - LastThreadCreationTime;

    unsigned minWaitBetweenThreadCreation =  GATE_THREAD_DELAY;

    if (throttleRate > 0.0)
    {
        _ASSERTE(throttleRate <= 1.0);

        unsigned adjustedThreadCount = NumThreads > NumberOfProcessors ? (NumThreads - NumberOfProcessors) : 0;

        minWaitBetweenThreadCreation = (unsigned) (GATE_THREAD_DELAY * pow((1.0 + throttleRate),(double)adjustedThreadCount));
    }
    // the amount of time to wait should grow up as the number of threads is increased

    return (delaySinceLastThreadCreation > minWaitBetweenThreadCreation);

}


// called by logic to spawn new worker threads, return true if it's been too long
// since the last dequeue operation - takes number of worker threads into account
// in deciding "too long"
BOOL ThreadpoolMgr::SufficientDelaySinceLastDequeue()
{
    LIMITED_METHOD_CONTRACT;

    #define DEQUEUE_DELAY_THRESHOLD (GATE_THREAD_DELAY * 2)

    unsigned delay = GetTickCount() - VolatileLoad(&LastDequeueTime);
    unsigned tooLong;

    if(cpuUtilization < CpuUtilizationLow)
    {
        tooLong = GATE_THREAD_DELAY;
    }
    else       
    {
        ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts();
        unsigned numThreads = counts.MaxWorking;
        tooLong = numThreads * DEQUEUE_DELAY_THRESHOLD;
    }

    return (delay > tooLong);

}


#ifdef _MSC_VER
#ifdef _WIN64
#pragma warning (default : 4716)
#else
#pragma warning (default : 4715)
#endif
#endif

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

struct CreateTimerThreadParams {
    CLREvent    event;
    BOOL        setupSucceeded;
};

BOOL ThreadpoolMgr::CreateTimerQueueTimer(PHANDLE phNewTimer,
                                          WAITORTIMERCALLBACK Callback,
                                          PVOID Parameter,
                                          DWORD DueTime,
                                          DWORD Period,
                                          ULONG Flag)
{
    CONTRACTL
    {
        THROWS;     // EnsureInitialized, CreateAutoEvent can throw
        if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}  // There can be calls thru ICorThreadpool
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END;

    EnsureInitialized();

    // For now we use just one timer thread. Consider using multiple timer threads if
    // number of timers in the queue exceeds a certain threshold. The logic and code
    // would be similar to the one for creating wait threads.
    if (NULL == TimerThread)
    {
        CrstHolder csh(&TimerQueueCriticalSection);

        // check again
        if (NULL == TimerThread)
        {
            CreateTimerThreadParams params;
            params.event.CreateAutoEvent(FALSE);

            params.setupSucceeded = FALSE;

            HANDLE TimerThreadHandle = Thread::CreateUtilityThread(Thread::StackSize_Small, TimerThreadStart, &params, W(".NET Timer"));

            if (TimerThreadHandle == NULL)
            {
                params.event.CloseEvent();
                ThrowOutOfMemory();
            }

            {
                GCX_PREEMP();
                for(;;)
                {
                    // if a host throws because it couldnt allocate another thread,
                    // just retry the wait.
                    if (SafeWait(&params.event,INFINITE, FALSE) != WAIT_TIMEOUT)
                        break;
                }
            }
            params.event.CloseEvent();

            if (!params.setupSucceeded)
            {
                CloseHandle(TimerThreadHandle);
                return FALSE;
            }

            TimerThread = TimerThreadHandle;
        }

    }


    NewHolder<TimerInfo> timerInfoHolder;
    TimerInfo * timerInfo = new (nothrow) TimerInfo;
    *phNewTimer = (HANDLE) timerInfo;

    if (NULL == timerInfo)
        ThrowOutOfMemory();

    timerInfoHolder.Assign(timerInfo);

    timerInfo->FiringTime = DueTime;
    timerInfo->Function = Callback;
    timerInfo->Context = Parameter;
    timerInfo->Period = Period;
    timerInfo->state = 0;
    timerInfo->flag = Flag;
    timerInfo->ExternalCompletionEvent = INVALID_HANDLE;
    timerInfo->ExternalEventSafeHandle = NULL;

    BOOL status = QueueUserAPC((PAPCFUNC)InsertNewTimer,TimerThread,(size_t)timerInfo);
    if (FALSE == status)
    {
        return FALSE;
    }

    timerInfoHolder.SuppressRelease();
    return TRUE;
}

#ifdef _MSC_VER
#ifdef _WIN64
#pragma warning (disable : 4716)
#else
#pragma warning (disable : 4715)
#endif
#endif
DWORD WINAPI ThreadpoolMgr::TimerThreadStart(LPVOID p)
{
    ClrFlsSetThreadType (ThreadType_Timer);

    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_GC_TRIGGERS;        // due to SetApartment
    STATIC_CONTRACT_MODE_PREEMPTIVE;
    /* cannot use contract because of SEH
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;*/

    CreateTimerThreadParams* params = (CreateTimerThreadParams*)p;

    Thread* pThread = SetupThreadNoThrow();

    params->setupSucceeded = (pThread == NULL) ? 0 : 1;
    params->event.Set();

    if (pThread == NULL)
        return 0;

    pTimerThread = pThread;
    // Timer threads never die

    LastTickCount = GetTickCount();

#ifdef FEATURE_COMINTEROP
    if (pThread->SetApartment(Thread::AS_InMTA, TRUE) != Thread::AS_InMTA)
    {
        // @todo: should we log the failure
        goto Exit;
    }
#endif // FEATURE_COMINTEROP

    for (;;)
    {
         // moved to its own function since EX_TRY consumes stack
#ifdef _MSC_VER
#pragma inline_depth (0) // the function containing EX_TRY can't be inlined here
#endif
        TimerThreadFire();
#ifdef _MSC_VER
#pragma inline_depth (20)
#endif
    }

#ifdef FEATURE_COMINTEROP
// unreachable code
//    if (pThread) {
//        pThread->SetApartment(Thread::AS_Unknown, TRUE);
//    }
Exit:

    // @todo: replace with host provided ExitThread
    return 0;
#endif
}

void ThreadpoolMgr::TimerThreadFire()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

    EX_TRY {
        DWORD timeout = FireTimers();

#undef SleepEx
        SleepEx(timeout, TRUE);
#define SleepEx(a,b) Dont_Use_SleepEx(a,b)

        // the thread could wake up either because an APC completed or the sleep timeout
        // in both case, we need to sweep the timer queue, firing timers, and readjusting
        // the next firing time

    }
    EX_CATCH {
        // Assert on debug builds since a dead timer thread is a fatal error
        _ASSERTE(FALSE);
        if (SwallowUnhandledExceptions())
        {
            // Do nothing to swallow the exception
        }
        else
        {
            EX_RETHROW;
        }
    }
    EX_END_CATCH(SwallowAllExceptions);
}

#ifdef _MSC_VER
#ifdef _WIN64
#pragma warning (default : 4716)
#else
#pragma warning (default : 4715)
#endif
#endif

// Executed as an APC in timer thread
void ThreadpoolMgr::InsertNewTimer(TimerInfo* pArg)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    _ASSERTE(pArg);
    TimerInfo * timerInfo = pArg;

    if (timerInfo->state & TIMER_DELETE)
    {   // timer was deleted before it could be registered
        DeleteTimer(timerInfo);
        return;
    }

    // set the firing time = current time + due time (note initially firing time = due time)
    DWORD currentTime = GetTickCount();
    if (timerInfo->FiringTime == (ULONG) -1)
    {
        timerInfo->state = TIMER_REGISTERED;
        timerInfo->refCount = 1;

    }
    else
    {
        timerInfo->FiringTime += currentTime;

        timerInfo->state = (TIMER_REGISTERED | TIMER_ACTIVE);
        timerInfo->refCount = 1;

        // insert the timer in the queue
        InsertTailList(&TimerQueue,(&timerInfo->link));
    }

    return;
}


// executed by the Timer thread
// sweeps through the list of timers, readjusting the firing times, queueing APCs for
// those that have expired, and returns the next firing time interval
DWORD ThreadpoolMgr::FireTimers()
{
    CONTRACTL
    {
        THROWS;     // QueueUserWorkItem can throw
        if (GetThread()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        if (GetThread()) { MODE_PREEMPTIVE;} else { DISABLED(MODE_ANY);}
    }
    CONTRACTL_END;

    DWORD currentTime = GetTickCount();
    DWORD nextFiringInterval = (DWORD) -1;
    TimerInfo* timerInfo = NULL;
    
    EX_TRY 
    {
        for (LIST_ENTRY* node = (LIST_ENTRY*) TimerQueue.Flink;
             node != &TimerQueue;
            )
        {
            timerInfo = (TimerInfo*) node;
            node = (LIST_ENTRY*) node->Flink;

            if (TimeExpired(LastTickCount, currentTime, timerInfo->FiringTime))
            {
                if (timerInfo->Period == 0 || timerInfo->Period == (ULONG) -1)
                {
                    DeactivateTimer(timerInfo);
                }

                InterlockedIncrement(&timerInfo->refCount);

                QueueUserWorkItem(AsyncTimerCallbackCompletion,
                                  timerInfo,
                                  QUEUE_ONLY /* TimerInfo take care of deleting*/);

                if (timerInfo->Period != 0 && timerInfo->Period != (ULONG)-1)
                {
                    ULONG nextFiringTime = timerInfo->FiringTime + timerInfo->Period;
                    DWORD firingInterval;
                    if (TimeExpired(timerInfo->FiringTime, currentTime, nextFiringTime))
                    {
                        // Enough time has elapsed to fire the timer yet again. The timer is not able to keep up with the short
                        // period, have it fire 1 ms from now to avoid spinning without a delay.
                        timerInfo->FiringTime = currentTime + 1;
                        firingInterval = 1;
                    }
                    else
                    {
                        timerInfo->FiringTime = nextFiringTime;
                        firingInterval = TimeInterval(nextFiringTime, currentTime);
                    }

                    if (firingInterval < nextFiringInterval)
                        nextFiringInterval = firingInterval;
                }
            }
            else
            {
                DWORD firingInterval = TimeInterval(timerInfo->FiringTime, currentTime);
                if (firingInterval < nextFiringInterval)
                    nextFiringInterval = firingInterval;
            }
        }
    } 
    EX_CATCH 
    {
        // If QueueUserWorkItem throws OOM, swallow the exception and retry on
        // the next call to FireTimers(), otherwise retrhow.
        Exception *ex = GET_EXCEPTION();
        // undo the call to DeactivateTimer()
        InterlockedDecrement(&timerInfo->refCount);
        timerInfo->state = timerInfo->state & TIMER_ACTIVE;
        InsertTailList(&TimerQueue, (&timerInfo->link));
        if (ex->GetHR() != E_OUTOFMEMORY)
        {
           EX_RETHROW;
        }
    }
    EX_END_CATCH(RethrowTerminalExceptions);

    LastTickCount = currentTime;

    return nextFiringInterval;
}

DWORD WINAPI ThreadpoolMgr::AsyncTimerCallbackCompletion(PVOID pArgs)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

    Thread* pThread = GetThread();

    if (pThread == NULL)
    {
        HRESULT hr = ERROR_SUCCESS;

        ClrFlsSetThreadType(ThreadType_Threadpool_Worker);
        pThread = SetupThreadNoThrow(&hr);

        if (pThread == NULL)
        {
            return hr;
        }
    }

    {
        TimerInfo* timerInfo = (TimerInfo*) pArgs;
        ((WAITORTIMERCALLBACKFUNC) timerInfo->Function) (timerInfo->Context, TRUE) ;

        if (InterlockedDecrement(&timerInfo->refCount) == 0)
        {
            DeleteTimer(timerInfo);
        }
    }

    return ERROR_SUCCESS;
}


// removes the timer from the timer queue, thereby cancelling it
// there may still be pending callbacks that haven't completed
void ThreadpoolMgr::DeactivateTimer(TimerInfo* timerInfo)
{
    LIMITED_METHOD_CONTRACT;

    RemoveEntryList((LIST_ENTRY*) timerInfo);

    // This timer info could go into another linked list of timer infos
    // waiting to be released. Reinitialize the list pointers
    InitializeListHead(&timerInfo->link);
    timerInfo->state = timerInfo->state & ~TIMER_ACTIVE;
}

DWORD WINAPI ThreadpoolMgr::AsyncDeleteTimer(PVOID pArgs)
{
    CONTRACTL
    {
        THROWS;
        MODE_PREEMPTIVE;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    Thread * pThread = GetThread();

    if (pThread == NULL)
    {
        HRESULT hr = ERROR_SUCCESS;

        ClrFlsSetThreadType(ThreadType_Threadpool_Worker);
        pThread = SetupThreadNoThrow(&hr);

        if (pThread == NULL)
        {
            return hr;
        }
    }

    DeleteTimer((TimerInfo*) pArgs);

    return ERROR_SUCCESS;
}

void ThreadpoolMgr::DeleteTimer(TimerInfo* timerInfo)
{
    CONTRACTL
    {
        if (GetThread() == pTimerThread) { NOTHROW; } else { THROWS; }
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    _ASSERTE((timerInfo->state & TIMER_ACTIVE) == 0);

    _ASSERTE(!(timerInfo->flag & WAIT_FREE_CONTEXT));

    if (timerInfo->flag & WAIT_INTERNAL_COMPLETION)
    {
        timerInfo->InternalCompletionEvent.Set();
        return; // the timerInfo will be deleted by the thread that's waiting on InternalCompletionEvent
    }

    // ExternalCompletionEvent comes from Host, ExternalEventSafeHandle from managed code.
    // They are mutually exclusive.
    _ASSERTE(!(timerInfo->ExternalCompletionEvent != INVALID_HANDLE && 
                        timerInfo->ExternalEventSafeHandle != NULL));

    if (timerInfo->ExternalCompletionEvent != INVALID_HANDLE)
    {
        SetEvent(timerInfo->ExternalCompletionEvent);
        timerInfo->ExternalCompletionEvent = INVALID_HANDLE;
    }

    // We cannot block the timer thread, so some cleanup is deferred to other threads.
    if (GetThread() == pTimerThread)
    {
        // Notify the ExternalEventSafeHandle with an user work item 
        if (timerInfo->ExternalEventSafeHandle != NULL)
        {
            BOOL success = FALSE;
            EX_TRY
            {
                if (QueueUserWorkItem(AsyncDeleteTimer,
                          timerInfo,
                          QUEUE_ONLY) != FALSE)
                {
                    success = TRUE;
                }
            }
            EX_CATCH
            {
            }
            EX_END_CATCH(SwallowAllExceptions);

            // If unable to queue a user work item, fall back to queueing timer for release
            // which will happen *sometime* in the future.
            if (success == FALSE)
            {
                QueueTimerInfoForRelease(timerInfo);
            }    
            
            return;
        }

        // Releasing GC handles can block. So we wont do this on the timer thread.
        // We'll put it in a list which will be processed by a worker thread
        if (timerInfo->Context != NULL)
        {
            QueueTimerInfoForRelease(timerInfo);
            return;
        }
    }

    // To get here we are either not the Timer thread or there is no blocking work to be done
    
    if (timerInfo->Context != NULL)
    {
        GCX_COOP();
        delete (ThreadpoolMgr::TimerInfoContext*)timerInfo->Context;
    }

    if (timerInfo->ExternalEventSafeHandle != NULL)
    {
        ReleaseTimerInfo(timerInfo);
    }

    delete timerInfo;
    
}

// We add TimerInfos from deleted timers into a linked list.
// A worker thread will later release the handles held by the TimerInfo
// and recycle them if possible.
void ThreadpoolMgr::QueueTimerInfoForRelease(TimerInfo *pTimerInfo)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    // The synchronization in this method depends on the fact that
    //  - There is only one timer thread
    //  - The one and only timer thread is executing this method.
    //  - This function wont go into an alertable state. That could trigger another APC.
    // Else two threads can be queueing timerinfos and a race could
    // lead to leaked memory and handles
    _ASSERTE(GetThread());
    _ASSERTE(pTimerThread == GetThread());
    TimerInfo *pHead = NULL;

    // Make sure this timer info has been deactivated and removed from any other lists
    _ASSERTE((pTimerInfo->state & TIMER_ACTIVE) == 0);
    //_ASSERTE(pTimerInfo->link.Blink == &(pTimerInfo->link) &&
    //    pTimerInfo->link.Flink == &(pTimerInfo->link));
    // Make sure "link" is the first field in TimerInfo
    _ASSERTE(pTimerInfo == (PVOID)&pTimerInfo->link);

    // Grab any previously published list
    if ((pHead = InterlockedExchangeT(&TimerInfosToBeRecycled, NULL)) != NULL)
    {
        // If there already is a list, just append
        InsertTailList((LIST_ENTRY *)pHead, &pTimerInfo->link);
        pTimerInfo = pHead;
    }
    else
        // If this is the head, make its next and previous ptrs point to itself
        InitializeListHead((LIST_ENTRY*)&pTimerInfo->link);

    // Publish the list
    (void) InterlockedExchangeT(&TimerInfosToBeRecycled, pTimerInfo);

}

void ThreadpoolMgr::FlushQueueOfTimerInfos()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    TimerInfo *pHeadTimerInfo = NULL, *pCurrTimerInfo = NULL;
    LIST_ENTRY *pNextInfo = NULL;

    if ((pHeadTimerInfo = InterlockedExchangeT(&TimerInfosToBeRecycled, NULL)) == NULL)
        return;

    do
    {
        RemoveHeadList((LIST_ENTRY *)pHeadTimerInfo, pNextInfo);
        _ASSERTE(pNextInfo != NULL);

        pCurrTimerInfo = (TimerInfo *) pNextInfo;

        GCX_COOP();
        if (pCurrTimerInfo->Context != NULL)
        {
            delete (ThreadpoolMgr::TimerInfoContext*)pCurrTimerInfo->Context;
        }

        if (pCurrTimerInfo->ExternalEventSafeHandle != NULL)
        {
            ReleaseTimerInfo(pCurrTimerInfo);
        }

        delete pCurrTimerInfo;

    }
    while ((TimerInfo *)pNextInfo != pHeadTimerInfo);
}

/************************************************************************/
BOOL ThreadpoolMgr::ChangeTimerQueueTimer(
                                        HANDLE Timer,
                                        ULONG DueTime,
                                        ULONG Period)
{
    CONTRACTL
    {
        THROWS;
        MODE_ANY;
        GC_NOTRIGGER;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END;

    _ASSERTE(IsInitialized());
    _ASSERTE(Timer);                    // not possible to give invalid handle in managed code

    NewHolder<TimerUpdateInfo> updateInfoHolder;
    TimerUpdateInfo *updateInfo = new TimerUpdateInfo;
    updateInfoHolder.Assign(updateInfo);

    updateInfo->Timer = (TimerInfo*) Timer;
    updateInfo->DueTime = DueTime;
    updateInfo->Period = Period;

    BOOL status = QueueUserAPC((PAPCFUNC)UpdateTimer,
                               TimerThread,
                               (size_t) updateInfo);

    if (status)
        updateInfoHolder.SuppressRelease();

    return(status);
}

void ThreadpoolMgr::UpdateTimer(TimerUpdateInfo* pArgs)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    TimerUpdateInfo* updateInfo = (TimerUpdateInfo*) pArgs;
    TimerInfo* timerInfo = updateInfo->Timer;

    timerInfo->Period = updateInfo->Period;

    if (updateInfo->DueTime == (ULONG) -1)
    {
        if (timerInfo->state & TIMER_ACTIVE)
        {
            DeactivateTimer(timerInfo);
        }
        // else, noop (the timer was already inactive)
        _ASSERTE((timerInfo->state & TIMER_ACTIVE) == 0);

        delete updateInfo;
        return;
    }

    DWORD currentTime = GetTickCount();
    timerInfo->FiringTime = currentTime + updateInfo->DueTime;

    delete updateInfo;

    if (! (timerInfo->state & TIMER_ACTIVE))
    {
        // timer not active (probably a one shot timer that has expired), so activate it
        timerInfo->state |= TIMER_ACTIVE;
        _ASSERTE(timerInfo->refCount >= 1);
        // insert the timer in the queue
        InsertTailList(&TimerQueue,(&timerInfo->link));

    }

    return;
}

/************************************************************************/
BOOL ThreadpoolMgr::DeleteTimerQueueTimer(
                                        HANDLE Timer,
                                        HANDLE Event)
{
    CONTRACTL
    {
        THROWS;
        MODE_ANY;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    _ASSERTE(IsInitialized());          // cannot call delete before creating timer
    _ASSERTE(Timer);                    // not possible to give invalid handle in managed code

    // make volatile to avoid compiler reordering check after async call.
    // otherwise, DeregisterTimer could delete timerInfo before the comparison.
    VolatilePtr<TimerInfo> timerInfo = (TimerInfo*) Timer;

    if (Event == (HANDLE) -1)
    {
        //CONTRACT_VIOLATION(ThrowsViolation);
        timerInfo->InternalCompletionEvent.CreateAutoEvent(FALSE);
        timerInfo->flag |= WAIT_INTERNAL_COMPLETION;
    }
    else if (Event)
    {
        timerInfo->ExternalCompletionEvent = Event;
    }
#ifdef _DEBUG
    else /* Event == NULL */
    {
        _ASSERTE(timerInfo->ExternalCompletionEvent == INVALID_HANDLE);
    }
#endif

    BOOL isBlocking = timerInfo->flag & WAIT_INTERNAL_COMPLETION;

    BOOL status = QueueUserAPC((PAPCFUNC)DeregisterTimer,
                               TimerThread,
                               (size_t)(TimerInfo*)timerInfo);

    if (FALSE == status)
    {
        if (isBlocking)
            timerInfo->InternalCompletionEvent.CloseEvent();
        return FALSE;
    }

    if (isBlocking)
    {
        _ASSERTE(timerInfo->ExternalEventSafeHandle == NULL);
        _ASSERTE(timerInfo->ExternalCompletionEvent == INVALID_HANDLE);
        _ASSERTE(GetThread() != pTimerThread);

        timerInfo->InternalCompletionEvent.Wait(INFINITE,TRUE /*alertable*/);
        timerInfo->InternalCompletionEvent.CloseEvent();
        // Release handles and delete TimerInfo
        _ASSERTE(timerInfo->refCount == 0);
        // if WAIT_INTERNAL_COMPLETION flag is not set, timerInfo will be deleted in DeleteTimer.
        timerInfo->flag &= ~WAIT_INTERNAL_COMPLETION;
        DeleteTimer(timerInfo);
    }
    return status;
}

void ThreadpoolMgr::DeregisterTimer(TimerInfo* pArgs)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

    TimerInfo* timerInfo = (TimerInfo*) pArgs;

    if (! (timerInfo->state & TIMER_REGISTERED) )
    {
        // set state to deleted, so that it does not get registered
        timerInfo->state |= TIMER_DELETE ;

        // since the timer has not even been registered, we dont need an interlock to decrease the RefCount
        timerInfo->refCount--;

        return;
    }

    if (timerInfo->state & TIMER_ACTIVE)
    {
        DeactivateTimer(timerInfo);
    }

    if (InterlockedDecrement(&timerInfo->refCount) == 0 )
    {
        DeleteTimer(timerInfo);
    }
    return;
}

#endif // !DACCESS_COMPILE