summaryrefslogtreecommitdiffstats
path: root/private/ntos/mm/sectsup.c
blob: 65856beb3025420d3c846a331d9ba8e74ceaa3dc (plain) (blame)
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
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

   sectsup.c

Abstract:

    This module contains the routines which implement the
    section object.

Author:

    Lou Perazzoli (loup) 22-May-1989

Revision History:

--*/


#include "mi.h"

#ifdef ALLOC_PRAGMA
#pragma alloc_text(INIT,MiSectionInitialization)
#endif

MMEVENT_COUNT_LIST MmEventCountList;

NTSTATUS
MiFlushSectionInternal (
    IN PMMPTE StartingPte,
    IN PMMPTE FinalPte,
    IN PSUBSECTION FirstSubsection,
    IN PSUBSECTION LastSubsection,
    IN ULONG Synchronize,
    OUT PIO_STATUS_BLOCK IoStatus
    );

ULONG
FASTCALL
MiCheckProtoPtePageState (
    IN PMMPTE PrototypePte,
    IN ULONG PfnLockHeld
    );

ULONG MmSharedCommit = 0;
extern ULONG MMCONTROL;

//
// Define segment dereference thread wait object types.
//

typedef enum _SEGMENT_DERFERENCE_OBJECT {
    SegmentDereference,
    UsedSegmentCleanup,
    SegMaximumObject
    } BALANCE_OBJECT;

extern POBJECT_TYPE IoFileObjectType;

GENERIC_MAPPING MiSectionMapping = {
    STANDARD_RIGHTS_READ |
        SECTION_QUERY | SECTION_MAP_READ,
    STANDARD_RIGHTS_WRITE |
        SECTION_MAP_WRITE,
    STANDARD_RIGHTS_EXECUTE |
        SECTION_MAP_EXECUTE,
    SECTION_ALL_ACCESS
};

VOID
VadTreeWalk (
    PMMVAD Start
    );

VOID
MiRemoveUnusedSegments(
    VOID
    );


VOID
FASTCALL
MiInsertBasedSection (
    IN PSECTION Section
    )

/*++

Routine Description:

    This function inserts a virtual address descriptor into the tree and
    reorders the splay tree as appropriate.

Arguments:

    Section - Supplies a pointer to a based section.

Return Value:

    None.

Environment:

    Must be holding the section based mutex.

--*/

{
    PMMADDRESS_NODE *Root;

    ASSERT (Section->Address.EndingVa > Section->Address.StartingVa);

    Root = &MmSectionBasedRoot;

    MiInsertNode ( &Section->Address, Root);
    return;
}


VOID
FASTCALL
MiRemoveBasedSection (
    IN PSECTION Section
    )

/*++

Routine Description:

    This function removes a based section from the tree.

Arguments:

    Section - pointer to the based section object to remove.

Return Value:

    None.

Environment:

    Must be holding the section based mutex.

--*/

{
    PMMADDRESS_NODE *Root;

    Root = &MmSectionBasedRoot;

    MiRemoveNode ( &Section->Address, Root);

    return;
}


PVOID
MiFindEmptySectionBaseDown (
    IN ULONG SizeOfRange,
    IN PVOID HighestAddressToEndAt
    )

/*++

Routine Description:

    The function examines the virtual address descriptors to locate
    an unused range of the specified size and returns the starting
    address of the range.  This routine looks from the top down.

Arguments:

    SizeOfRange - Supplies the size in bytes of the range to locate.

    HighestAddressToEndAt - Supplies the virtual address to begin looking
                            at.

Return Value:

    Returns the starting address of a suitable range.

--*/

{
    return MiFindEmptyAddressRangeDownTree ( SizeOfRange,
                    HighestAddressToEndAt,
                    X64K,
                    MmSectionBasedRoot);
}


VOID
MiSegmentDelete (
    PSEGMENT Segment
    )

/*++

Routine Description:

    This routine is called by the object management procedures whenever
    the last reference to a segment object has been removed.  This routine
    releases the pool allocated for the prototype PTEs and performs
    consistency checks on those PTEs.

    For segments which map files, the file object is dereferenced.

    Note, that for a segment which maps a file, no PTEs may be valid
    or transition, while a segment which is backed by a paging file
    may have transition pages, but no valid pages (there can be no
    PTEs which refer to the segment).


Arguments:

    Segment - a pointer to the segment structure.

Return Value:

    None.

--*/

{
    PMMPTE PointerPte;
    PMMPTE LastPte;
    PMMPFN Pfn1;
    KIRQL OldIrql;
    KIRQL OldIrql2;
    volatile PFILE_OBJECT File;
    volatile PCONTROL_AREA ControlArea;
    PEVENT_COUNTER Event;
    MMPTE PteContents;
    PSUBSECTION Subsection;
    PSUBSECTION NextSubsection;

    PointerPte = Segment->PrototypePte;
    LastPte = PointerPte + Segment->NonExtendedPtes;

#if DBG
    if (MmDebug & MM_DBG_SECTIONS) {
        DbgPrint("MM:deleting segment %lx control %lx\n",Segment, Segment->ControlArea);
    }
#endif

    ControlArea = Segment->ControlArea;
    LOCK_PFN (OldIrql2);
    if (ControlArea->DereferenceList.Flink != NULL) {

        //
        // Remove this from the list of usused segments.
        //

        ExAcquireSpinLock (&MmDereferenceSegmentHeader.Lock, &OldIrql);
        RemoveEntryList (&ControlArea->DereferenceList);
        MmUnusedSegmentCount -= 1;
        ExReleaseSpinLock (&MmDereferenceSegmentHeader.Lock, OldIrql);
    }
    UNLOCK_PFN (OldIrql2);

    if (ControlArea->u.Flags.Image ||
        ControlArea->u.Flags.File ) {

        //
        // If there have been committed pages in this segment, adjust
        // the total commit count.
        //


        //
        // Unload kernel debugger symbols if any where loaded.
        //

        if (ControlArea->u.Flags.DebugSymbolsLoaded != 0) {

            //
            //  TEMP TEMP TEMP rip out when debugger converted
            //

            ANSI_STRING AnsiName;
            NTSTATUS Status;

            Status = RtlUnicodeStringToAnsiString( &AnsiName,
                                                   (PUNICODE_STRING)&Segment->ControlArea->FilePointer->FileName,
                                                   TRUE );

            if (NT_SUCCESS( Status)) {
                DbgUnLoadImageSymbols( &AnsiName,
                                       Segment->BasedAddress,
                                       (ULONG)PsGetCurrentProcess());
                RtlFreeAnsiString( &AnsiName );
            }
            LOCK_PFN (OldIrql);
            ControlArea->u.Flags.DebugSymbolsLoaded = 0;
            UNLOCK_PFN (OldIrql);
        }

        //
        // If the segment was deleted due to a name collision at insertion
        // we don't want to dereference the file pointer.
        //

        if (ControlArea->u.Flags.BeingCreated == FALSE) {

            //
            // Clear the segment context and dereference the file object
            // for this Segment.
            //

            LOCK_PFN (OldIrql);

            MiMakeSystemAddressValidPfn (Segment);
            File = (volatile PFILE_OBJECT)Segment->ControlArea->FilePointer;
            ControlArea = (volatile PCONTROL_AREA)Segment->ControlArea;

            Event = ControlArea->WaitingForDeletion;
            ControlArea->WaitingForDeletion = NULL;

            UNLOCK_PFN (OldIrql);

            if (Event != NULL) {
                KeSetEvent (&Event->Event, 0, FALSE);
            }

#if DBG
            if (ControlArea->u.Flags.Image == 1) {
                ASSERT (ControlArea->FilePointer->SectionObjectPointer->ImageSectionObject != (PVOID)ControlArea);
            } else {
                ASSERT (ControlArea->FilePointer->SectionObjectPointer->DataSectionObject != (PVOID)ControlArea);
            }
#endif //DBG

            ObDereferenceObject (ControlArea->FilePointer);
        }

        if (ControlArea->u.Flags.Image == 0) {

            //
            // This is a mapped data file.  None of the prototype
            // PTEs may be referencing a physical page (valid or transition).
            //

#if DBG
            while (PointerPte < LastPte) {

                //
                // Prototype PTEs for Segments backed by paging file
                // are either in demand zero, page file format, or transition.
                //

                ASSERT (PointerPte->u.Hard.Valid == 0);
                ASSERT ((PointerPte->u.Soft.Prototype == 1) ||
                        (PointerPte->u.Long == 0));
                PointerPte += 1;
            }
#endif //DBG

            //
            // Deallocate the control area and subsections.
            //

            Subsection = (PSUBSECTION)(ControlArea + 1);

            Subsection = Subsection->NextSubsection;

            while (Subsection != NULL) {
                ExFreePool (Subsection->SubsectionBase);
                NextSubsection = Subsection->NextSubsection;
                ExFreePool (Subsection);
                Subsection = NextSubsection;
            }

            if (Segment->NumberOfCommittedPages != 0) {
                MiReturnCommitment (Segment->NumberOfCommittedPages);
                MmSharedCommit -= Segment->NumberOfCommittedPages;
            }

            RtlZeroMemory (Segment->ControlArea, sizeof (CONTROL_AREA)); //fixfix remove
            ExFreePool (Segment->ControlArea);
            RtlZeroMemory (Segment, sizeof (SEGMENT)); //fixfix remove
            ExFreePool (Segment);

            //
            // The file mapped Segment object is now deleted.
            //

            return;
        }
    }

    //
    // This is a page file backed or image Segment.  The Segment is being
    // deleted, remove all references to the paging file and physical memory.
    //

    //
    // The PFN mutex is required for deallocating pages from a paging
    // file and for deleting transition PTEs.
    //

    LOCK_PFN (OldIrql);

    MiMakeSystemAddressValidPfn (PointerPte);

    while (PointerPte < LastPte) {

        if (((ULONG)PointerPte & (PAGE_SIZE - 1)) == 0) {

            //
            // We are on a page boundary, make sure this PTE is resident.
            //

            if (MmIsAddressValid (PointerPte) == FALSE) {

                MiMakeSystemAddressValidPfn (PointerPte);
            }
        }

        PteContents = *PointerPte;

        //
        // Prototype PTEs for Segments backed by paging file
        // are either in demand zero, page file format, or transition.
        //

        ASSERT (PteContents.u.Hard.Valid == 0);

        if (PteContents.u.Soft.Prototype == 0) {

            if (PteContents.u.Soft.Transition == 1) {

                //
                // Prototype PTE in transition, put the page on the free list.
                //

                Pfn1 = MI_PFN_ELEMENT (PteContents.u.Trans.PageFrameNumber);

                MI_SET_PFN_DELETED (Pfn1);

                MiDecrementShareCount (Pfn1->PteFrame);

                //
                // Check the reference count for the page, if the reference
                // count is zero and the page is not on the freelist,
                // move the page to the free list, if the reference
                // count is not zero, ignore this page.
                // When the refernce count goes to zero, it will be placed on the
                // free list.
                //

                if (Pfn1->u3.e2.ReferenceCount == 0) {
                    MiUnlinkPageFromList (Pfn1);
                    MiReleasePageFileSpace (Pfn1->OriginalPte);
                    MiInsertPageInList (MmPageLocationList[FreePageList],
                                        PteContents.u.Trans.PageFrameNumber);
                }

            } else {

                //
                // This is not a prototype PTE, if any paging file
                // space has been allocated, release it.
                //

                if (IS_PTE_NOT_DEMAND_ZERO (PteContents)) {
                    MiReleasePageFileSpace (PteContents);
                }
            }
        }
#if DBG
        *PointerPte = ZeroPte;
#endif
        PointerPte += 1;
    }

    UNLOCK_PFN (OldIrql);

    //
    // If their have been committed pages in this segment, adjust
    // the total commit count.
    //

    if (Segment->NumberOfCommittedPages != 0) {
        MiReturnCommitment (Segment->NumberOfCommittedPages);
        MmSharedCommit -= Segment->NumberOfCommittedPages;
    }

    ExFreePool (Segment->ControlArea);
    ExFreePool (Segment);

    return;
}

VOID
MiSectionDelete (
    PVOID Object
    )

/*++

Routine Description:


    This routine is called by the object management procedures whenever
    the last reference to a section object has been removed.  This routine
    dereferences the associated segment object and checks to see if
    the segment object should be deleted by queueing the segment to the
    segment deletion thread.

Arguments:

    Object - a pointer to the body of the section object.

Return Value:

    None.

--*/

{
    PSECTION Section;
    volatile PCONTROL_AREA ControlArea;
    ULONG DereferenceSegment = FALSE;
    KIRQL OldIrql;
    ULONG UserRef;

    Section = (PSECTION)Object;

    if (Section->Segment == (PSEGMENT)NULL) {

        //
        // The section was never initialized, no need to remove
        // any structures.
        //
        return;
    }

    UserRef = Section->u.Flags.UserReference;
    ControlArea = (volatile PCONTROL_AREA)Section->Segment->ControlArea;

#if DBG
    if (MmDebug & MM_DBG_SECTIONS) {
        DbgPrint("MM:deleting section %lx control %lx\n",Section, ControlArea);
    }
#endif

    if (Section->Address.StartingVa != NULL) {

        //
        // This section is based, remove the base address from the
        // treee.
        //

        //
        // Get the allocation base mutex.
        //

        ExAcquireFastMutex (&MmSectionBasedMutex);

        MiRemoveBasedSection (Section);

        ExReleaseFastMutex (&MmSectionBasedMutex);

    }

    //
    // Decrement the number of section references to the segment for this
    // section.  This requires APCs to be blocked and the PfnMutex to
    // synchonize upon.
    //

    LOCK_PFN (OldIrql);

    ControlArea->NumberOfSectionReferences -= 1;
    ControlArea->NumberOfUserReferences -= UserRef;

    //
    // This routine returns with the PFN lock released.
    //

    MiCheckControlArea (ControlArea, NULL, OldIrql);

    return;
}


VOID
MiDereferenceSegmentThread (
    IN PVOID StartContext
    )

/*++

Routine Description:

    This routine is the thread for derefencing segments which have
    no references from any sections or mapped views AND there are
    no prototype PTEs within the segment which are in the transition
    state (i.e., no PFN database references to the segment).

    It also does double duty and is used for expansion of paging files.

Arguments:

    StartContext - Not used.

Return Value:

    None.

--*/

{
    PCONTROL_AREA ControlArea;
    PMMPAGE_FILE_EXPANSION PageExpand;
    PLIST_ENTRY NextEntry;
    KIRQL OldIrql;
    static KWAIT_BLOCK WaitBlockArray[SegMaximumObject];
    PVOID WaitObjects[SegMaximumObject];
    NTSTATUS Status;

    StartContext;  //avoid compiler warning.

    //
    // Make this a real time thread.
    //

    (VOID) KeSetPriorityThread (&PsGetCurrentThread()->Tcb,
                                LOW_REALTIME_PRIORITY + 2);

    WaitObjects[SegmentDereference] = (PVOID)&MmDereferenceSegmentHeader.Semaphore;
    WaitObjects[UsedSegmentCleanup] = (PVOID)&MmUnusedSegmentCleanup;

    for (;;) {

        Status = KeWaitForMultipleObjects(SegMaximumObject,
                                          &WaitObjects[0],
                                          WaitAny,
                                          WrVirtualMemory,
                                          UserMode,
                                          FALSE,
                                          NULL,
                                          &WaitBlockArray[0]);

        //
        // Switch on the wait status.
        //

        switch (Status) {

        case SegmentDereference:

            //
            // An entry is available to deference, acquire the spinlock
            // and remove the entry.
            //

            ExAcquireSpinLock (&MmDereferenceSegmentHeader.Lock, &OldIrql);

            if (IsListEmpty(&MmDereferenceSegmentHeader.ListHead)) {

                //
                // There is nothing in the list, rewait.
                //

                ExReleaseSpinLock (&MmDereferenceSegmentHeader.Lock, OldIrql);
                break;
            }

            NextEntry = RemoveHeadList(&MmDereferenceSegmentHeader.ListHead);

            ExReleaseSpinLock (&MmDereferenceSegmentHeader.Lock, OldIrql);

            ASSERT (KeGetCurrentIrql() < DISPATCH_LEVEL);

            ControlArea = CONTAINING_RECORD( NextEntry,
                                             CONTROL_AREA,
                                             DereferenceList );

            if (ControlArea->Segment != NULL) {

                //
                // This is a control area, delete it.
                //

#if DBG
                if (MmDebug & MM_DBG_SECTIONS) {
                    DbgPrint("MM:dereferencing segment %lx control %lx\n",
                        ControlArea->Segment, ControlArea);
                }
#endif

                //
                // Indicate this entry is not on any list.
                //

                ControlArea->DereferenceList.Flink = NULL;

                ASSERT (ControlArea->u.Flags.FilePointerNull == 1);
                MiSegmentDelete (ControlArea->Segment);

            } else {

                //
                // This is a request to expand or reduce the paging files.
                //

                PageExpand = (PMMPAGE_FILE_EXPANSION)ControlArea;

                if (PageExpand->RequestedExpansionSize == 0xFFFFFFFF) {

                    //
                    // Attempt to reduce the size of the paging files.
                    //

                    ExFreePool (PageExpand);

                    MiAttemptPageFileReduction ();
                } else {

                    //
                    // Attempt to expand the size of the paging files.
                    //

                    PageExpand->ActualExpansion = MiExtendPagingFiles (
                                                PageExpand->RequestedExpansionSize);

                    KeSetEvent (&PageExpand->Event, 0, FALSE);
                    MiRemoveUnusedSegments();
                }
            }
            break;

        case UsedSegmentCleanup:

            MiRemoveUnusedSegments();

            KeClearEvent (&MmUnusedSegmentCleanup);

            break;

        default:

            KdPrint(("MMSegmentderef: Illegal wait status, %lx =\n", Status));
            break;
        } // end switch

    } //end for

    return;
}


ULONG
MiSectionInitialization (
    )

/*++

Routine Description:

    This function creates the section object type descriptor at system
    initialization and stores the address of the object type descriptor
    in global storage.

Arguments:

    None.

Return Value:

    TRUE - Initialization was successful.

    FALSE - Initialization Failed.



--*/

{
    OBJECT_TYPE_INITIALIZER ObjectTypeInitializer;
    UNICODE_STRING TypeName;
    HANDLE ThreadHandle;
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING SectionName;
    PSECTION Section;
    HANDLE Handle;
    PSEGMENT Segment;
    PCONTROL_AREA ControlArea;
    NTSTATUS Status;

    MmSectionBasedRoot = (PMMADDRESS_NODE)NULL;

    //
    // Initialize the common fields of the Object Type Initializer record
    //

    RtlZeroMemory( &ObjectTypeInitializer, sizeof( ObjectTypeInitializer ) );
    ObjectTypeInitializer.Length = sizeof( ObjectTypeInitializer );
    ObjectTypeInitializer.InvalidAttributes = OBJ_OPENLINK;
    ObjectTypeInitializer.GenericMapping = MiSectionMapping;
    ObjectTypeInitializer.PoolType = PagedPool;
    ObjectTypeInitializer.DefaultPagedPoolCharge = sizeof(SECTION);

    //
    // Initialize string descriptor.
    //

    RtlInitUnicodeString (&TypeName, L"Section");

    //
    // Create the section object type descriptor
    //

    ObjectTypeInitializer.ValidAccessMask = SECTION_ALL_ACCESS;
    ObjectTypeInitializer.DeleteProcedure = MiSectionDelete;
    ObjectTypeInitializer.GenericMapping = MiSectionMapping;
    ObjectTypeInitializer.UseDefaultObject = TRUE;
    if ( !NT_SUCCESS(ObCreateObjectType(&TypeName,
                                     &ObjectTypeInitializer,
                                     (PSECURITY_DESCRIPTOR) NULL,
                                     &MmSectionObjectType
                                     )) ) {
        return FALSE;
    }

    //
    // Initialize listhead, spinlock and semaphore for
    // segment dereferencing thread.
    //

    KeInitializeSpinLock (&MmDereferenceSegmentHeader.Lock);
    InitializeListHead (&MmDereferenceSegmentHeader.ListHead);
    KeInitializeSemaphore (&MmDereferenceSegmentHeader.Semaphore, 0, MAXLONG);

    InitializeListHead (&MmUnusedSegmentList);
    KeInitializeEvent (&MmUnusedSegmentCleanup, NotificationEvent, FALSE);

    //
    // Create the Segment deferencing thread.
    //

    InitializeObjectAttributes( &ObjectAttributes,
                                NULL,
                                0,
                                NULL,
                                NULL );

    if ( !NT_SUCCESS(PsCreateSystemThread(
                    &ThreadHandle,
                    THREAD_ALL_ACCESS,
                    &ObjectAttributes,
                    0,
                    NULL,
                    MiDereferenceSegmentThread,
                    NULL
                    )) ) {
        return FALSE;
    }
    ZwClose (ThreadHandle);

    //
    // Create the permanent section which maps physical memory.
    //

    Segment = (PSEGMENT)ExAllocatePoolWithTag (PagedPool,
                                               sizeof(SEGMENT),
                                               'gSmM');
    if (Segment == NULL) {
        return FALSE;
    }

    ControlArea = ExAllocatePoolWithTag (NonPagedPool,
                                         (ULONG)sizeof(CONTROL_AREA),
                                         MMCONTROL);
    if (ControlArea == NULL) {
        return FALSE;
    }

    RtlZeroMemory (Segment, sizeof(SEGMENT));
    RtlZeroMemory (ControlArea, sizeof(CONTROL_AREA));

    ControlArea->Segment = Segment;
    ControlArea->NumberOfSectionReferences = 1;
    ControlArea->u.Flags.PhysicalMemory = 1;

    Segment->ControlArea = ControlArea;
    Segment->SegmentPteTemplate = ZeroPte;

    //
    // Now that the segment object is created, create a section object
    // which refers to the segment object.
    //

    RtlInitUnicodeString (&SectionName, L"\\Device\\PhysicalMemory");

    InitializeObjectAttributes( &ObjectAttributes,
                                &SectionName,
                                OBJ_PERMANENT,
                                NULL,
                                NULL
                              );

    Status = ObCreateObject (KernelMode,
                             MmSectionObjectType,
                             &ObjectAttributes,
                             KernelMode,
                             NULL,
                             sizeof(SECTION),
                             sizeof(SECTION),
                             0,
                             (PVOID *)&Section);
    if (!NT_SUCCESS(Status)) {
        return FALSE;
    }

    Section->Segment = Segment;
    Section->SizeOfSection.QuadPart = ((LONGLONG)1 << PHYSICAL_ADDRESS_BITS) - 1;
    Section->u.LongFlags = 0;
    Section->InitialPageProtection = PAGE_READWRITE;

    Status = ObInsertObject ((PVOID)Section,
                                    NULL,
                                    SECTION_MAP_READ,
                                    0,
                                    (PVOID *)NULL,
                                    &Handle);

    if (!NT_SUCCESS( Status )) {
        return FALSE;
    }

    if ( !NT_SUCCESS (NtClose ( Handle))) {
        return FALSE;
    }

    return TRUE;
}

BOOLEAN
MmForceSectionClosed (
    IN PSECTION_OBJECT_POINTERS SectionObjectPointer,
    IN BOOLEAN DelayClose
    )

/*++

Routine Description:

    This function examines the Section object pointers.  If they are NULL,
    no further action is taken and the value TRUE is returned.

    If the Section object pointer is not NULL, the section reference count
    and the map view count are checked. If both counts are zero, the
    segment associated with the file is deleted and the file closed.
    If one of the counts is non-zero, no action is taken and the
    value FALSE is returned.

Arguments:

    SectionObjectPointer - Supplies a pointer to a section object.

    DelayClose - Supplies the value TRUE if the close operation should
                 occur as soon as possible in the event this section
                 cannot be closed now due to outstanding references.

Return Value:

    TRUE - the segment was deleted and the file closed or no segment was
           located.

    FALSE - the segment was not deleted and no action was performed OR
            an I/O error occurred trying to write the pages.

--*/

{
    PCONTROL_AREA ControlArea;
    KIRQL OldIrql;
    ULONG state;

    //
    // Check the status of the control area, if the control area is in use
    // or the control area is being deleted, this operation cannot continue.
    //

    state = MiCheckControlAreaStatus (CheckBothSection,
                                      SectionObjectPointer,
                                      DelayClose,
                                      &ControlArea,
                                      &OldIrql);

    if (ControlArea == NULL) {
        return (BOOLEAN)state;
    }

    //
    // PFN LOCK IS NOW HELD!
    //

    //
    // Set the being deleted flag and up the number of mapped views
    // for the segment.  Upping the number of mapped views prevents
    // the segment from being deleted and passed to the deletion thread
    // while we are forcing a delete.
    //

    ControlArea->u.Flags.BeingDeleted = 1;
    ASSERT (ControlArea->NumberOfMappedViews == 0);
    ControlArea->NumberOfMappedViews = 1;

    //
    // This is a page file backed or image Segment.  The Segment is being
    // deleted, remove all references to the paging file and physical memory.
    //

    UNLOCK_PFN (OldIrql);

    //
    // Delete the section by flushing all modified pages back to the section
    // if it is a file and freeing up the pages such that the PfnReferenceCount
    // goes to zero.
    //

    MiCleanSection (ControlArea);
    return TRUE;
}

VOID
MiCleanSection (
    IN PCONTROL_AREA ControlArea
    )

/*++

Routine Description:

    This function examines each prototype PTE in the section and
    takes the appropriate action to "delete" the prototype PTE.

    If the PTE is dirty and is backed by a file (not a paging file),
    the corresponding page is written to the file.

    At the completion of this service, the section which was
    operated upon is no longer usable.

    NOTE - ALL I/O ERRORS ARE IGNORED.  IF ANY WRITES FAIL, THE
           DIRTY PAGES ARE MARKED CLEAN AND THE SECTION IS DELETED.

Arguments:

    ControlArea - Supplies a pointer to the control area for the section.

Return Value:

    None.

--*/

{
    PMMPTE PointerPte;
    PMMPTE LastPte;
    PMMPTE LastWritten;
    MMPTE PteContents;
    PMMPFN Pfn1;
    PMMPFN Pfn2;
    PMMPTE WrittenPte;
    MMPTE WrittenContents;
    KIRQL OldIrql;
    PMDL Mdl;
    PKEVENT IoEvent;
    PSUBSECTION Subsection;
    PULONG Page;
    PULONG LastPage;
    PULONG EndingPage;
    LARGE_INTEGER StartingOffset;
    LARGE_INTEGER TempOffset;
    NTSTATUS Status;
    IO_STATUS_BLOCK IoStatus;
    ULONG WriteNow = FALSE;
    ULONG ImageSection = FALSE;
    ULONG DelayCount = 0;
    ULONG First;

    if (ControlArea->u.Flags.Image) {
        ImageSection = TRUE;
    }
    ASSERT (ControlArea->FilePointer);

    PointerPte = ControlArea->Segment->PrototypePte;
    LastPte = PointerPte + ControlArea->Segment->NonExtendedPtes;

    IoEvent = ExAllocatePoolWithTag (NonPagedPoolMustSucceed,
                              MmSizeOfMdl(NULL, PAGE_SIZE *
                                                    MmModifiedWriteClusterSize)
                                                    + sizeof(KEVENT),
                                                    'ldmM');

    Mdl = (PMDL)(IoEvent + 1);

    KeInitializeEvent (IoEvent, NotificationEvent, FALSE);

    LastWritten = NULL;
    EndingPage = (PULONG)(Mdl + 1) + MmModifiedWriteClusterSize;
    LastPage = NULL;

    Subsection = (PSUBSECTION)(ControlArea + 1);

    //
    // The PFN mutex is required for deallocating pages from a paging
    // file and for deleting transition PTEs.
    //

    LOCK_PFN (OldIrql);

    //
    // Stop the modified page writer from writting pages to this
    // file, and if any paging I/O is in progress, wait for it
    // to complete.
    //

    ControlArea->u.Flags.NoModifiedWriting = 1;

    while (ControlArea->ModifiedWriteCount != 0) {

        //
        // There is modified page writting in progess.  Set the
        // flag in the control area indicating the modified page
        // writer should signal when a write to this control area
        // is complete.  Release the PFN LOCK and wait in an
        // atomic operation.  Once the wait is satified, recheck
        // to make sure it was this file's I/O that was written.
        //

        ControlArea->u.Flags.SetMappedFileIoComplete = 1;
        KeEnterCriticalRegion();
        UNLOCK_PFN_AND_THEN_WAIT(OldIrql);

        KeWaitForSingleObject(&MmMappedFileIoComplete,
                              WrPageOut,
                              KernelMode,
                              FALSE,
                              (PLARGE_INTEGER)NULL);
        KeLeaveCriticalRegion();
        LOCK_PFN (OldIrql);
    }

 for (;;) {

    First = TRUE;
    while (PointerPte < LastPte) {

        if ((((ULONG)PointerPte & (PAGE_SIZE - 1)) == 0) || First) {
            First = FALSE;

            if ((ImageSection) ||
                (MiCheckProtoPtePageState(PointerPte, FALSE))) {
                MiMakeSystemAddressValidPfn (PointerPte);
            } else {

                //
                // Paged pool page is not resident, hence no transition or valid
                // prototype PTEs can be present in it.  Skip it.
                //

                PointerPte = (PMMPTE)((((ULONG)PointerPte | PAGE_SIZE - 1)) + 1);
                if (LastWritten != NULL) {
                    WriteNow = TRUE;
                }
                goto WriteItOut;
            }
        }

        PteContents = *PointerPte;

        //
        // Prototype PTEs for Segments backed by paging file
        // are either in demand zero, page file format, or transition.
        //

        ASSERT (PteContents.u.Hard.Valid == 0);

        if (PteContents.u.Soft.Prototype == 0) {

            if (PteContents.u.Soft.Transition == 1) {

                //
                // Prototype PTE in transition, there are 3 possible cases:
                //  1. The page is part of an image which is shareable and
                //     refers to the paging file - dereference page file
                //     space and free the physical page.
                //  2. The page refers to the segment but is not modified -
                //     free the phyisical page.
                //  3. The page refers to the segment and is modified -
                //     write the page to the file and free the physical page.
                //

                Pfn1 = MI_PFN_ELEMENT (PteContents.u.Trans.PageFrameNumber);

                if (Pfn1->u3.e2.ReferenceCount != 0) {
                    if (DelayCount < 20) {

                        //
                        // There must be an I/O in progress on this
                        // page.  Wait for the I/O operation to complete.
                        //

                        UNLOCK_PFN (OldIrql);

                        KeDelayExecutionThread (KernelMode, FALSE, &MmShortTime);

                        DelayCount += 1;

                        //
                        // Redo the loop, if the delay count is greater than
                        // 20, assume that this thread is deadlocked and
                        // don't purge this page.  The file system can deal
                        // with the write operation in progress.
                        //

                        LOCK_PFN (OldIrql);
                        MiMakeSystemAddressValidPfn (PointerPte);
                        continue;
#if DBG
                    } else {

                        //
                        // The I/O still has not completed, just ignore the fact
                        // that the i/o is in progress and delete the page.
                        //

                        KdPrint(("MM:CLEAN - page number %lx has i/o outstanding\n",
                                  PteContents.u.Trans.PageFrameNumber));
#endif //DBG
                    }
                }

                if (Pfn1->OriginalPte.u.Soft.Prototype == 0) {

                    //
                    // Paging file reference (case 1).
                    //

                    MI_SET_PFN_DELETED (Pfn1);
                    if (!ImageSection) {

                        //
                        // This is not an image section, it must be a
                        // page file backed section, therefore decrement
                        // the PFN reference count for the control area.
                        //

                        ControlArea->NumberOfPfnReferences -= 1;
                        ASSERT ((LONG)ControlArea->NumberOfPfnReferences >= 0);
                    }

                    MiDecrementShareCount (Pfn1->PteFrame);

                    //
                    // Check the reference count for the page, if the reference
                    // count is zero and the page is not on the freelist,
                    // move the page to the free list, if the reference
                    // count is not zero, ignore this page.
                    // When the refernce count goes to zero, it will be placed
                    // on the free list.
                    //

                    if ((Pfn1->u3.e2.ReferenceCount == 0) &&
                         (Pfn1->u3.e1.PageLocation != FreePageList)) {

                        MiUnlinkPageFromList (Pfn1);
                        MiReleasePageFileSpace (Pfn1->OriginalPte);
                        MiInsertPageInList (MmPageLocationList[FreePageList],
                                    PteContents.u.Trans.PageFrameNumber);

                    }
                    PointerPte->u.Long = 0;

                    //
                    // If a cluster of pages to write has been completed,
                    // set the WriteNow flag.
                    //

                    if (LastWritten != NULL) {
                        WriteNow = TRUE;
                    }

                } else {

                    if ((Pfn1->u3.e1.Modified == 0) || (ImageSection)) {

                        //
                        // Non modified or image file page (case 2).
                        //

                        MI_SET_PFN_DELETED (Pfn1);
                        ControlArea->NumberOfPfnReferences -= 1;
                        ASSERT ((LONG)ControlArea->NumberOfPfnReferences >= 0);

                        MiDecrementShareCount (Pfn1->PteFrame);

                        //
                        // Check the reference count for the page, if the reference
                        // count is zero and the page is not on the freelist,
                        // move the page to the free list, if the reference
                        // count is not zero, ignore this page.
                        // When the refernce count goes to zero, it will be placed on the
                        // free list.
                        //

                        if ((Pfn1->u3.e2.ReferenceCount == 0) &&
                             (Pfn1->u3.e1.PageLocation != FreePageList)) {

                            MiUnlinkPageFromList (Pfn1);
                            MiReleasePageFileSpace (Pfn1->OriginalPte);
                            MiInsertPageInList (MmPageLocationList[FreePageList],
                                            PteContents.u.Trans.PageFrameNumber);
                        }

                        PointerPte->u.Long = 0;

                        //
                        // If a cluster of pages to write has been completed,
                        // set the WriteNow flag.
                        //

                        if (LastWritten != NULL) {
                            WriteNow = TRUE;
                        }

                    } else {

                        //
                        // Check to see if this is the first page of a cluster.
                        //

                        if (LastWritten == NULL) {
                            LastPage = (PULONG)(Mdl + 1);
                            ASSERT (MiGetSubsectionAddress(&Pfn1->OriginalPte) ==
                                                                    Subsection);

                            //
                            // Calculate the offset to read into the file.
                            //  offset = base + ((thispte - basepte) << PAGE_SHIFT)
                            //

                            StartingOffset.QuadPart = MI_STARTING_OFFSET (
                                                             Subsection,
                                                             Pfn1->PteAddress);

                            MI_INITIALIZE_ZERO_MDL (Mdl);
                            Mdl->MdlFlags |= MDL_PAGES_LOCKED;

                            Mdl->StartVa =
                                   (PVOID)(Pfn1->u3.e1.PageColor << PAGE_SHIFT);
                            Mdl->Size = (CSHORT)(sizeof(MDL) +
                                       (sizeof(ULONG) * MmModifiedWriteClusterSize));
                        }

                        LastWritten = PointerPte;
                        Mdl->ByteCount += PAGE_SIZE;

                        //
                        // If the cluster is now full, set the write now flag.
                        //

                        if (Mdl->ByteCount == (PAGE_SIZE * MmModifiedWriteClusterSize)) {
                            WriteNow = TRUE;
                        }

                        MiUnlinkPageFromList (Pfn1);
                        Pfn1->u3.e1.Modified = 0;

                        //
                        // Up the reference count for the physical page as there
                        // is I/O in progress.
                        //

                        Pfn1->u3.e2.ReferenceCount += 1;

                        //
                        // Clear the modified bit for the page and set the write
                        // in progress bit.
                        //

                        *LastPage = PteContents.u.Trans.PageFrameNumber;

                        LastPage += 1;
                    }
                }
            } else {

                if (IS_PTE_NOT_DEMAND_ZERO (PteContents)) {
                    MiReleasePageFileSpace (PteContents);
                }
                PointerPte->u.Long = 0;

                //
                // If a cluster of pages to write has been completed,
                // set the WriteNow flag.
                //

                if (LastWritten != NULL) {
                    WriteNow = TRUE;
                }
            }
        } else {

            //
            // This is a normal prototype PTE in mapped file format.
            //

            if (LastWritten != NULL) {
                WriteNow = TRUE;
            }
        }

        //
        // Write the current cluster if it is complete,
        // full, or the loop is now complete.
        //

        PointerPte += 1;
        DelayCount = 0;

WriteItOut:

        if ((WriteNow) ||
            ((PointerPte == LastPte) && (LastWritten != NULL))) {

            //
            // Issue the write request.
            //

            UNLOCK_PFN (OldIrql);

            WriteNow = FALSE;

            KeClearEvent (IoEvent);

            //
            // Make sure the write does not go past the
            // end of file. (segment size).
            //

            TempOffset.QuadPart = ((LONGLONG)Subsection->EndingSector <<
                                        MMSECTOR_SHIFT) +
                            Subsection->u.SubsectionFlags.SectorEndOffset;

            if ((StartingOffset.QuadPart + Mdl->ByteCount) >
                         TempOffset.QuadPart) {

                ASSERT ((ULONG)(TempOffset.QuadPart -
                                    StartingOffset.QuadPart) >
                         (Mdl->ByteCount - PAGE_SIZE));

                Mdl->ByteCount = (ULONG)(TempOffset.QuadPart -
                                        StartingOffset.QuadPart);
            }

#if DBG
            if (MmDebug & MM_DBG_FLUSH_SECTION) {
                DbgPrint("MM:flush page write begun %lx\n",
                        Mdl->ByteCount);
            }
#endif //DBG

            Status = IoSynchronousPageWrite (
                                    ControlArea->FilePointer,
                                    Mdl,
                                    &StartingOffset,
                                    IoEvent,
                                    &IoStatus );

            if (NT_SUCCESS(Status)) {

                KeWaitForSingleObject( IoEvent,
                                       WrPageOut,
                                       KernelMode,
                                       FALSE,
                                       (PLARGE_INTEGER)NULL);
            }

            if (Mdl->MdlFlags & MDL_MAPPED_TO_SYSTEM_VA) {
                MmUnmapLockedPages (Mdl->MappedSystemVa, Mdl);
            }

            Page = (PULONG)(Mdl + 1);

            LOCK_PFN (OldIrql);

            if (((ULONG)PointerPte & (PAGE_SIZE - 1)) != 0) {

                //
                // The next PTE is not in a different page, make
                // sure this page did not leave memory when the
                // I/O was in progress.
                //

                MiMakeSystemAddressValidPfn (PointerPte);
            }

            //
            // I/O complete unlock pages.
            //
            // NOTE that the error status is ignored.
            //

            while (Page < LastPage) {

                Pfn2 = MI_PFN_ELEMENT (*Page);

                //
                // Make sure the page is still transition.
                //

                WrittenPte = Pfn2->PteAddress;

                MiDecrementReferenceCount (*Page);

                if (!MI_IS_PFN_DELETED (Pfn2)) {

                    //
                    // Make sure the prototype PTE is
                    // still in the working set.
                    //

                    MiMakeSystemAddressValidPfn (WrittenPte);

                    if (Pfn2->PteAddress != WrittenPte) {

                        //
                        // The PFN mutex was released to make the
                        // page table page valid, and while it
                        // was released, the phyiscal page
                        // was reused.  Go onto the next one.
                        //

                        Page += 1;
                        continue;
                    }

                    WrittenContents = *WrittenPte;

                    if ((WrittenContents.u.Soft.Prototype == 0) &&
                         (WrittenContents.u.Soft.Transition == 1)) {

                        MI_SET_PFN_DELETED (Pfn2);
                        ControlArea->NumberOfPfnReferences -= 1;
                        ASSERT ((LONG)ControlArea->NumberOfPfnReferences >= 0);

                        MiDecrementShareCount (Pfn2->PteFrame);

                        //
                        // Check the reference count for the page,
                        // if the reference count is zero and the
                        // page is not on the freelist, move the page
                        // to the free list, if the reference
                        // count is not zero, ignore this page.
                        // When the refernce count goes to zero,
                        // it will be placed on the free list.
                        //

                        if ((Pfn2->u3.e2.ReferenceCount == 0) &&
                           (Pfn2->u3.e1.PageLocation != FreePageList)) {

                            MiUnlinkPageFromList (Pfn2);
                            MiReleasePageFileSpace (Pfn2->OriginalPte);
                            MiInsertPageInList (
                                MmPageLocationList[FreePageList],
                                *Page);
                        }
                    }
                    WrittenPte->u.Long = 0;
                }
                Page += 1;
            }

            //
            // Indicate that there is no current cluster being built.
            //

            LastWritten = NULL;
        }

    } // end while

    //
    // Get the next subsection if any.
    //

    if (Subsection->NextSubsection == (PSUBSECTION)NULL) {
        break;
    }
    Subsection = Subsection->NextSubsection;
    PointerPte = Subsection->SubsectionBase;
    LastPte = PointerPte + Subsection->PtesInSubsection;


 } // end for

    ControlArea->NumberOfMappedViews = 0;

    ASSERT (ControlArea->NumberOfPfnReferences == 0);

    if (ControlArea->u.Flags.FilePointerNull == 0) {
        ControlArea->u.Flags.FilePointerNull = 1;
        if (ControlArea->u.Flags.Image) {
            ((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->ImageSectionObject)) =
                                                        NULL;
        } else {
            ASSERT (((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->DataSectionObject)) != NULL);
            ((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->DataSectionObject)) =
                                                        NULL;
        }
    }
    UNLOCK_PFN (OldIrql);

    ExFreePool (IoEvent);

    //
    // Delete the segment structure.
    //

    MiSegmentDelete (ControlArea->Segment);

    return;
}

NTSTATUS
MmGetFileNameForSection (
    IN HANDLE Section,
    OUT PSTRING FileName
    )

/*++

Routine Description:

    This function returns the file name for the corresponding section.

Arguments:

    Section - Supplies the handle of the section to get the name of.

    FileName - Returns the name of the corresonding section.

Return Value:

    TBS

Environment:

    Kernel mode, APC_LEVEL or below, no mutexes held.

--*/

{

    PSECTION SectionObject;
    POBJECT_NAME_INFORMATION FileNameInfo;
    ULONG whocares;
    NTSTATUS Status;
    ULONG Dereference;

    Dereference = TRUE;
#define xMAX_NAME 1024

    if ( (ULONG)Section & 1 ) {
        SectionObject = (PSECTION)((ULONG)Section & 0xfffffffe);
        Dereference = FALSE;
    } else {
        Status = ObReferenceObjectByHandle ( Section,
                                             0,
                                             MmSectionObjectType,
                                             KernelMode,
                                             (PVOID *)&SectionObject,
                                             NULL );

        if (!NT_SUCCESS(Status)) {
            return Status;
        }
    }
    if (SectionObject->u.Flags.Image == 0) {
        if ( Dereference ) ObDereferenceObject (SectionObject);
        return STATUS_SECTION_NOT_IMAGE;
    }

    FileNameInfo = ExAllocatePoolWithTag (PagedPool, xMAX_NAME, '  mM');
    if ( !FileNameInfo ) {
        if ( Dereference ) ObDereferenceObject (SectionObject);
        return STATUS_NO_MEMORY;
    }

    Status = ObQueryNameString(
                SectionObject->Segment->ControlArea->FilePointer,
                FileNameInfo,
                xMAX_NAME,
                &whocares
                );

    if ( Dereference ) ObDereferenceObject (SectionObject);
    if ( !NT_SUCCESS(Status) ) {
        ExFreePool(FileNameInfo);
        return Status;
        }

    FileName->Length = 0;
    FileName->MaximumLength = (FileNameInfo->Name.Length/sizeof(WCHAR)) + 1;
    FileName->Buffer = ExAllocatePoolWithTag (PagedPool,
                                              FileName->MaximumLength,
                                              '  mM');
    if ( !FileName->Buffer ) {
        ExFreePool(FileNameInfo);
        return STATUS_NO_MEMORY;
    }
    RtlUnicodeStringToAnsiString((PANSI_STRING)FileName,&FileNameInfo->Name,FALSE);
    FileName->Buffer[FileName->Length] = '\0';
    ExFreePool(FileNameInfo);

    return STATUS_SUCCESS;
}

VOID
MiCheckControlArea (
    IN PCONTROL_AREA ControlArea,
    IN PEPROCESS CurrentProcess,
    IN KIRQL PreviousIrql
    )

/*++

Routine Description:

    This routine checks the reference counts for the specified
    control area, and if the counts are all zero, it marks the
    control area for deletion and queues it to the deletion thread.


    *********************** NOTE ********************************
    This routine returns with the PFN LOCK RELEASED!!!!!

Arguments:

    ControlArea - Supplies a pointer to the control area to check.

    CurrentProcess - Supplies a pointer to the current process if and ONLY
                     IF the working set lock is held.

    PreviousIrql - Supplies the previous IRQL.

Return Value:

    NONE.

Environment:

    Kernel mode, PFN lock held, PFN lock release upon return!!!

--*/

{
    PEVENT_COUNTER PurgeEvent = NULL;
    ULONG DeleteOnClose = FALSE;
    ULONG DereferenceSegment = FALSE;


    MM_PFN_LOCK_ASSERT();
    if ((ControlArea->NumberOfMappedViews == 0) &&
         (ControlArea->NumberOfSectionReferences == 0)) {

        ASSERT (ControlArea->NumberOfUserReferences == 0);

        if (ControlArea->FilePointer != (PFILE_OBJECT)NULL) {

            if (ControlArea->NumberOfPfnReferences == 0) {

                //
                // There are no views and no physical pages referenced
                // by the Segment, derferenced the Segment object.
                //

                ControlArea->u.Flags.BeingDeleted = 1;
                DereferenceSegment = TRUE;

                ASSERT (ControlArea->u.Flags.FilePointerNull == 0);
                ControlArea->u.Flags.FilePointerNull = 1;
                if (ControlArea->u.Flags.Image) {
                    ((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->ImageSectionObject)) =
                                                                    NULL;
                } else {
                    ASSERT (((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->DataSectionObject)) != NULL);
                    ((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->DataSectionObject)) =
                                                                    NULL;
                }
            } else {

                //
                // Insert this segment into the unused segment list (unless
                // it is already on the list).
                //

                if (ControlArea->DereferenceList.Flink == NULL) {
                    InsertTailList ( &MmUnusedSegmentList,
                                     &ControlArea->DereferenceList);
                    MmUnusedSegmentCount += 1;
                }

                //
                // Indicate if this section should be deleted now that
                // the reference counts are zero.
                //

                DeleteOnClose = ControlArea->u.Flags.DeleteOnClose;

                //
                // The number of mapped views are zero, the number of
                // section references are zero, but there are some
                // pages of the file still resident.  If this is
                // an image with Global Memory, "purge" the subsections
                // which contian the global memory and reset them to
                // point back to the file.
                //

                if (ControlArea->u.Flags.GlobalMemory == 1) {
                    ASSERT (ControlArea->u.Flags.Image == 1);

                    ControlArea->u.Flags.BeingPurged = 1;
                    ControlArea->NumberOfMappedViews = 1;

                    MiPurgeImageSection (ControlArea, CurrentProcess);

                    ControlArea->u.Flags.BeingPurged = 0;
                    ControlArea->NumberOfMappedViews -= 1;
                    if ((ControlArea->NumberOfMappedViews == 0) &&
                        (ControlArea->NumberOfSectionReferences == 0) &&
                        (ControlArea->NumberOfPfnReferences == 0)) {

                        ControlArea->u.Flags.BeingDeleted = 1;
                        DereferenceSegment = TRUE;
                        ControlArea->u.Flags.FilePointerNull = 1;
                        ((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->ImageSectionObject)) =
                                                                        NULL;
                    } else {

                        PurgeEvent = ControlArea->WaitingForDeletion;
                        ControlArea->WaitingForDeletion = NULL;
                    }
                }

                //
                // If delete on close is set and the segment was
                // not deleted, up the count of mapped views so the
                // control area will not be deleted when the PFN lock
                // is released.
                //

                if (DeleteOnClose && !DereferenceSegment) {
                    ControlArea->NumberOfMappedViews = 1;
                    ControlArea->u.Flags.BeingDeleted = 1;
                }
            }

        } else {

            //
            // This Segment is backed by a paging file, dereference the
            // Segment object when the number of views goes from 1 to 0
            // without regard to the number of PFN references.
            //

            ControlArea->u.Flags.BeingDeleted = 1;
            DereferenceSegment = TRUE;
        }
    }

    UNLOCK_PFN (PreviousIrql);

    if (DereferenceSegment || DeleteOnClose) {

        //
        // Release the working set mutex, if it is held as the object
        // management routines may page fault, ect..
        //

        if (CurrentProcess) {
            UNLOCK_WS (CurrentProcess);
        }

        if (DereferenceSegment) {

            //
            // Delete the segment.
            //

            MiSegmentDelete (ControlArea->Segment);

        } else {

            //
            // The segment should be forced closed now.
            //

            MiCleanSection (ControlArea);
        }

        ASSERT (PurgeEvent == NULL);

        //
        // Reaquire the working set lock, if a process was specified.
        //

        if (CurrentProcess) {
            LOCK_WS (CurrentProcess);
        }

    } else {

        //
        // If any threads are waiting for the segment, indicate the
        // the purge operation has completed.
        //

        if (PurgeEvent != NULL) {
            KeSetEvent (&PurgeEvent->Event, 0, FALSE);
        }

        if (MmUnusedSegmentCount > (MmUnusedSegmentCountMaximum << 2)) {
            KeSetEvent (&MmUnusedSegmentCleanup, 0, FALSE);
        }
    }

    return;
}

VOID
MiCheckForControlAreaDeletion (
    IN PCONTROL_AREA ControlArea
    )

/*++

Routine Description:

    This routine checks the reference counts for the specified
    control area, and if the counts are all zero, it marks the
    control area for deletion and queues it to the deletion thread.

Arguments:

    ControlArea - Supplies a pointer to the control area to check.

    CurrentProcess - Supplies a pointer to the current process IF
                     the working set lock is held.  If the working
                     set lock is NOT HELD, this value is NULL.

Return Value:

    None.

Environment:

    Kernel mode, PFN lock held.

--*/

{
    KIRQL OldIrql;

    MM_PFN_LOCK_ASSERT();
    if ((ControlArea->NumberOfPfnReferences == 0) &&
        (ControlArea->NumberOfMappedViews == 0) &&
        (ControlArea->NumberOfSectionReferences == 0 )) {

        //
        // This segment is no longer mapped in any address space
        // nor are there any prototype PTEs within the segment
        // which are valid or in a transition state.  Queue
        // the segment to the segment-dereferencer thread
        // which will dereference the segment object, potentially
        // causing the segment to be deleted.
        //

        ControlArea->u.Flags.BeingDeleted = 1;
        ASSERT (ControlArea->u.Flags.FilePointerNull == 0);
        ControlArea->u.Flags.FilePointerNull = 1;

        if (ControlArea->u.Flags.Image) {
            ((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->ImageSectionObject)) =
                                                            NULL;
        } else {
            ((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->DataSectionObject)) =
                                                            NULL;
        }

        ExAcquireSpinLock (&MmDereferenceSegmentHeader.Lock, &OldIrql);

        ASSERT (ControlArea->DereferenceList.Flink != NULL);

        //
        // Remove the entry from the unused segment list and put
        // on the dereference list.
        //

        RemoveEntryList (&ControlArea->DereferenceList);
        MmUnusedSegmentCount -= 1;
        InsertTailList (&MmDereferenceSegmentHeader.ListHead,
                        &ControlArea->DereferenceList);
        ExReleaseSpinLock (&MmDereferenceSegmentHeader.Lock, OldIrql);

        KeReleaseSemaphore (&MmDereferenceSegmentHeader.Semaphore,
                            0L,
                            1L,
                            FALSE);
    }
    return;
}


ULONG
MiCheckControlAreaStatus (
    IN SECTION_CHECK_TYPE SectionCheckType,
    IN PSECTION_OBJECT_POINTERS SectionObjectPointers,
    IN ULONG DelayClose,
    OUT PCONTROL_AREA *ControlAreaOut,
    OUT PKIRQL PreviousIrql
    )

/*++

Routine Description:

    This routine checks the status of the control area for the specified
    SectionObjectPointers.  If the control area is in use, that is, the
    number of section references and the number of mapped views are not
    both zero, no action is taken and the function returns FALSE.

    If there is no control area associated with the specified
    SectionObjectPointers or the control area is in the process of being
    created or deleted, no action is taken and the value TRUE is returned.

    If, there are no section objects and the control area is not being
    created or deleted, the address of the control area is returned
    in the ControlArea argument, the address of a pool block to free
    is returned in the SegmentEventOut argument and the PFN_LOCK is
    still held at the return.

Arguments:

    *SegmentEventOut - Returns a pointer to NonPaged Pool which much be
                       freed by the caller when the PFN_LOCK is released.
                       This value is NULL if no pool is allocated and the
                       PFN_LOCK is not held.

    SecionCheckType - Supplies the type of section to check on, one of
                      CheckImageSection, CheckDataSection, CheckBothSection.

    SectionObjectPointers - Supplies the section object pointers through
                            which the control area can be located.

    DelayClose - Supplies a boolean which if TRUE and the control area
                 is being used, the delay on close field should be set
                 in the control area.

    *ControlAreaOut - Returns the addresss of the control area.

    PreviousIrql - Returns, in the case the PFN_LOCK is held, the previous
                   IRQL so the lock can be released properly.

Return Value:

    FALSE if the control area is in use, TRUE if the control area is gone or
    in the process or being created or deleted.

Environment:

    Kernel mode, PFN lock NOT held.

--*/


{
    PEVENT_COUNTER IoEvent;
    PEVENT_COUNTER SegmentEvent;
    ULONG DeallocateSegmentEvent = TRUE;
    PCONTROL_AREA ControlArea;
    ULONG SectRef;
    KIRQL OldIrql;

    //
    // Allocate an event to wait on in case the segment is in the
    // process of being deleted.  This event cannot be allocated
    // with the PFN database locked as pool expansion would deadlock.
    //

    *ControlAreaOut = NULL;

    //
    // Acquire the PFN mutex and examine the section object pointer
    // value within the file object.
    //

    //
    // File control blocks live in non-paged pool.
    //

    LOCK_PFN (OldIrql);

    SegmentEvent = MiGetEventCounter ();

    if (SectionCheckType != CheckImageSection) {
        ControlArea = ((PCONTROL_AREA)(SectionObjectPointers->DataSectionObject));
    } else {
        ControlArea = ((PCONTROL_AREA)(SectionObjectPointers->ImageSectionObject));
    }

    if (ControlArea == NULL) {

        if (SectionCheckType != CheckBothSection) {

            //
            // This file no longer has an associated segment.
            //

            MiFreeEventCounter (SegmentEvent, TRUE);
            UNLOCK_PFN (OldIrql);
            return TRUE;
        } else {
            ControlArea = ((PCONTROL_AREA)(SectionObjectPointers->ImageSectionObject));
            if (ControlArea == NULL) {

                //
                // This file no longer has an associated segment.
                //

                MiFreeEventCounter (SegmentEvent, TRUE);
                UNLOCK_PFN (OldIrql);
                return TRUE;
            }
        }
    }

    //
    //  Depending on the type of section, check for the pertinant
    //  reference count being non-zero.
    //

    if (SectionCheckType != CheckUserDataSection) {
        SectRef = ControlArea->NumberOfSectionReferences;
    } else {
        SectRef = ControlArea->NumberOfUserReferences;
    }

    if ((SectRef != 0) ||
        (ControlArea->NumberOfMappedViews != 0) ||
        (ControlArea->u.Flags.BeingCreated)) {


        //
        // The segment is currently in use or being created.
        //

        if (DelayClose) {

            //
            // The section should be deleted when the reference
            // counts are zero, set the delete on close flag.
            //

            ControlArea->u.Flags.DeleteOnClose = 1;
        }

        MiFreeEventCounter (SegmentEvent, TRUE);
        UNLOCK_PFN (OldIrql);
        return FALSE;
    }

    //
    // The segment has no references, delete it.  If the segment
    // is already being deleted, set the event field in the control
    // area and wait on the event.
    //

    if (ControlArea->u.Flags.BeingDeleted) {

        //
        // The segment object is in the process of being deleted.
        // Check to see if another thread is waiting for the deletion,
        // otherwise create and event object to wait upon.
        //

        if (ControlArea->WaitingForDeletion == NULL) {

            //
            // Create an event a put it's address in the control area.
            //

            DeallocateSegmentEvent = FALSE;
            ControlArea->WaitingForDeletion = SegmentEvent;
            IoEvent = SegmentEvent;
        } else {
            IoEvent = ControlArea->WaitingForDeletion;
            IoEvent->RefCount += 1;
        }

        //
        // Release the mutex and wait for the event.
        //

        KeEnterCriticalRegion();
        UNLOCK_PFN_AND_THEN_WAIT(OldIrql);

        KeWaitForSingleObject(&IoEvent->Event,
                              WrPageOut,
                              KernelMode,
                              FALSE,
                              (PLARGE_INTEGER)NULL);
        KeLeaveCriticalRegion();

        LOCK_PFN (OldIrql);
        MiFreeEventCounter (IoEvent, TRUE);
        if (DeallocateSegmentEvent) {
            MiFreeEventCounter (SegmentEvent, TRUE);
        }
        UNLOCK_PFN (OldIrql);
        return TRUE;
    }

    //
    // Return with the PFN database locked.
    //

    MiFreeEventCounter (SegmentEvent, FALSE);
    *ControlAreaOut = ControlArea;
    *PreviousIrql = OldIrql;
    return FALSE;
}


PEVENT_COUNTER
MiGetEventCounter (
    )

/*++

Routine Description:

    This function maintains a list of "events" to allow waiting
    on segment operations (deletion, creation, purging).

Arguments:

    None.

Return Value:

    Event to be used for waiting (stored into the control area).

Environment:

    Kernel mode, PFN lock held.

--*/

{
    KIRQL OldIrql;
    PEVENT_COUNTER Support;
    PLIST_ENTRY NextEntry;

    MM_PFN_LOCK_ASSERT();

    if (MmEventCountList.Count == 0) {
        ASSERT (IsListEmpty(&MmEventCountList.ListHead));
        OldIrql = APC_LEVEL;
        UNLOCK_PFN (OldIrql);
        Support = ExAllocatePoolWithTag (NonPagedPoolMustSucceed,
                                         sizeof(EVENT_COUNTER),
                                         'xEmM');
        KeInitializeEvent (&Support->Event, NotificationEvent, FALSE);
        LOCK_PFN (OldIrql);
    } else {
        ASSERT (!IsListEmpty(&MmEventCountList.ListHead));
        MmEventCountList.Count -= 1;
        NextEntry = RemoveHeadList (&MmEventCountList.ListHead);
        Support = CONTAINING_RECORD (NextEntry,
                                     EVENT_COUNTER,
                                     ListEntry );
        //ASSERT (Support->RefCount == 0);
        KeClearEvent (&Support->Event);
    }
    Support->RefCount = 1;
    Support->ListEntry.Flink = NULL;
    return Support;
}


VOID
MiFreeEventCounter (
    IN PEVENT_COUNTER Support,
    IN ULONG Flush
    )

/*++

Routine Description:

    This routine frees an event counter back to the free list.

Arguments:

    Support - Supplies a pointer to the event counter.

    Flush - Supplies TRUE if the PFN lock can be released and the event
            counter pool block actually freed.  The PFN lock will be
            reacquired before returning.

Return Value:

    None.

Environment:

    Kernel mode, PFN lock held.

--*/

{

    MM_PFN_LOCK_ASSERT();

    ASSERT (Support->RefCount != 0);
    ASSERT (Support->ListEntry.Flink == NULL);
    Support->RefCount -= 1;
    if (Support->RefCount == 0) {
        InsertTailList (&MmEventCountList.ListHead,
                        &Support->ListEntry);
        MmEventCountList.Count += 1;
    }
    if ((Flush) && (MmEventCountList.Count > 4)) {
        MiFlushEventCounter();
    }
    return;
}


VOID
MiFlushEventCounter (
    )

/*++

Routine Description:

    This routine examines the list of event counters and attempts
    to free up to 10 (if there are more than 4).

    It will release and reacquire the PFN lock when it frees the
    event counters!

Arguments:

    None.

Return Value:

    None.

Environment:

    Kernel mode, PFN lock held.

--*/


{
    KIRQL OldIrql;
    PEVENT_COUNTER Support[10];
    ULONG i = 0;
    PLIST_ENTRY NextEntry;

    MM_PFN_LOCK_ASSERT();

    while ((MmEventCountList.Count > 4) && (i < 10)) {
        NextEntry = RemoveHeadList (&MmEventCountList.ListHead);
        Support[i] = CONTAINING_RECORD (NextEntry,
                                        EVENT_COUNTER,
                                        ListEntry );
        Support[i]->ListEntry.Flink = NULL;
        i += 1;
        MmEventCountList.Count -= 1;
    }

    if (i == 0) {
        return;
    }

    OldIrql = APC_LEVEL;
    UNLOCK_PFN (OldIrql);

    do {
        i -= 1;
        ExFreePool(Support[i]);
    } while (i > 0);

    LOCK_PFN (OldIrql);

    return;
}


BOOLEAN
MmCanFileBeTruncated (
    IN PSECTION_OBJECT_POINTERS SectionPointer,
    IN PLARGE_INTEGER NewFileSize
    )

/*++

Routine Description:

    This routine does the following:

        1.  Checks to see if a image section is in use for the file,
            if so it returns FALSE.

        2.  Checks to see if a user section exists for the file, if
            it does, it checks to make sure the new file size is greater
            than the size of the file, if not it returns FALSE.

        3.  If no image section exists, and no user created data section
            exists or the files size is greater, then TRUE is returned.

Arguments:

    SectionPointer - Supplies a pointer to the section object pointers
                     from the file object.

    NewFileSize - Supplies a pointer to the size the file is getting set to.

Return Value:

    TRUE if the file can be truncated, FALSE if it cannot be.

Environment:

    Kernel mode.

--*/

{
    LARGE_INTEGER LocalOffset;
    KIRQL OldIrql;

    //
    //  Capture caller's file size, since we may modify it.
    //

    if (ARGUMENT_PRESENT(NewFileSize)) {

        LocalOffset = *NewFileSize;
        NewFileSize = &LocalOffset;
    }

    if (MmCanFileBeTruncatedInternal( SectionPointer, NewFileSize, &OldIrql )) {

        UNLOCK_PFN (OldIrql);
        return TRUE;
    }

    return FALSE;
}

ULONG
MmCanFileBeTruncatedInternal (
    IN PSECTION_OBJECT_POINTERS SectionPointer,
    IN PLARGE_INTEGER NewFileSize OPTIONAL,
    OUT PKIRQL PreviousIrql
    )

/*++

Routine Description:

    This routine does the following:

        1.  Checks to see if a image section is in use for the file,
            if so it returns FALSE.

        2.  Checks to see if a user section exists for the file, if
            it does, it checks to make sure the new file size is greater
            than the size of the file, if not it returns FALSE.

        3.  If no image section exists, and no user created data section
            exists or the files size is greater, then TRUE is returned.

Arguments:

    SectionPointer - Supplies a pointer to the section object pointers
                     from the file object.

    NewFileSize - Supplies a pointer to the size the file is getting set to.

    PreviousIrql - If returning TRUE, returns Irql to use when unlocking
                   Pfn database.

Return Value:

    TRUE if the file can be truncated (PFN locked).
    FALSE if it cannot be truncated (PFN not locked).

Environment:

    Kernel mode.

--*/

{
    KIRQL OldIrql;
    LARGE_INTEGER SegmentSize;
    PCONTROL_AREA ControlArea;
    PSUBSECTION Subsection;

    if (!MmFlushImageSection (SectionPointer, MmFlushForWrite)) {
        return FALSE;
    }

    LOCK_PFN (OldIrql);

    ControlArea = (PCONTROL_AREA)(SectionPointer->DataSectionObject);

    if (ControlArea != NULL) {

        if (ControlArea->u.Flags.BeingCreated) {
            goto UnlockAndReturn;
        }

        //
        // If there are user references and the size is less than the
        // size of the user view, don't allow the trucation.
        //

        if (ControlArea->NumberOfUserReferences != 0) {

            //
            //  You cannot purge the entire section if there is a user
            //  reference.
            //

            if (!ARGUMENT_PRESENT(NewFileSize)) {
                goto UnlockAndReturn;
            }

            //
            // Locate last subsection and get total size.
            //

            Subsection = (PSUBSECTION)(ControlArea + 1);
            while (Subsection->NextSubsection != NULL) {
                Subsection = Subsection->NextSubsection;
            }

            SegmentSize.QuadPart =
                    ((LONGLONG)Subsection->EndingSector << MMSECTOR_SHIFT) +
                        Subsection->u.SubsectionFlags.SectorEndOffset;

            if (NewFileSize->QuadPart < SegmentSize.QuadPart) {
                goto UnlockAndReturn;
            }

            //
            //  If there are mapped views, we will skip the last page
            //  of the section if the size passed in falls in that page.
            //  The caller (like Cc) may want to clear this fractional page.
            //

            SegmentSize.QuadPart += PAGE_SIZE - 1;
            SegmentSize.LowPart &= ~(PAGE_SIZE - 1);
            if (NewFileSize->QuadPart < SegmentSize.QuadPart) {
                *NewFileSize = SegmentSize;
            }
        }
    }

    *PreviousIrql = OldIrql;
    return TRUE;

UnlockAndReturn:
    UNLOCK_PFN (OldIrql);
    return FALSE;
}


VOID
MiRemoveUnusedSegments (
    VOID
    )

/*++

Routine Description:

    This routine removes unused segments (no section refernces,
    no mapped views only PFN references that are in transition state).

Arguments:

    None.

Return Value:

    None.

Environment:

    Kernel mode.

--*/

{
    KIRQL OldIrql;
    PLIST_ENTRY NextEntry;
    PCONTROL_AREA ControlArea;
    NTSTATUS Status;

    while (MmUnusedSegmentCount > MmUnusedSegmentCountGoal) {

        //
        // Eliminate some of the unused segments which are only
        // kept in memory because they contain transition pages.
        //

        Status = STATUS_SUCCESS;

        LOCK_PFN (OldIrql);

        if (IsListEmpty(&MmUnusedSegmentList)) {

            //
            // There is nothing in the list, rewait.
            //

            ASSERT (MmUnusedSegmentCount == 0);
            UNLOCK_PFN (OldIrql);
            break;
        }

        NextEntry = RemoveHeadList(&MmUnusedSegmentList);
        MmUnusedSegmentCount -= 1;

        ControlArea = CONTAINING_RECORD( NextEntry,
                                         CONTROL_AREA,
                                         DereferenceList );
#if DBG
        if (MmDebug & MM_DBG_SECTIONS) {
            DbgPrint("MM: cleaning segment %lx control %lx\n",
                ControlArea->Segment, ControlArea);
        }
#endif

        //
        // Indicate this entry is not on any list.
        //

#if DBG
        if (ControlArea->u.Flags.BeingDeleted == 0) {
          if (ControlArea->u.Flags.Image) {
            ASSERT (((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->ImageSectionObject)) != NULL);
          } else {
            ASSERT (((PCONTROL_AREA)(ControlArea->FilePointer->SectionObjectPointer->DataSectionObject)) != NULL);
          }
        }
#endif //DBG

        //
        // Set the flink to NULL indicating this control area
        // is not on any lists.
        //

        ControlArea->DereferenceList.Flink = NULL;

        if ((ControlArea->NumberOfMappedViews == 0) &&
            (ControlArea->NumberOfSectionReferences == 0) &&
            (ControlArea->u.Flags.BeingDeleted == 0)) {

            //
            // If there is paging I/O in progress on this
            // segment, just put this at the tail of the list, as
            // the call to MiCleanSegment would block waiting
            // for the I/O to complete.  As this could tie up
            // the thread, don't do it.
            //

            if (ControlArea->ModifiedWriteCount > 0) {
                InsertTailList ( &MmUnusedSegmentList,
                                 &ControlArea->DereferenceList);
                MmUnusedSegmentCount += 1;
                UNLOCK_PFN (OldIrql);
                continue;
            }

            //
            // Up the number of mapped views to prevent other threads
            // from freeing this.
            //

            ControlArea->NumberOfMappedViews = 1;
            UNLOCK_PFN (OldIrql);
            {
                PSUBSECTION Subsection;
                PSUBSECTION LastSubsection;
                PMMPTE PointerPte;
                PMMPTE LastPte;
                IO_STATUS_BLOCK IoStatus;

                Subsection = (PSUBSECTION)(ControlArea + 1);
                PointerPte = &Subsection->SubsectionBase[0];
                LastSubsection = Subsection;
                while (LastSubsection->NextSubsection != NULL) {
                    LastSubsection = LastSubsection->NextSubsection;
                }
                LastPte = &LastSubsection->SubsectionBase
                                    [LastSubsection->PtesInSubsection - 1];

                //
                //  Preacquire the file to prevent deadlocks with other flushers
                //

                FsRtlAcquireFileForCcFlush (ControlArea->FilePointer);

                Status = MiFlushSectionInternal (PointerPte,
                                                 LastPte,
                                                 Subsection,
                                                 LastSubsection,
                                                 FALSE,
                                                 &IoStatus);
                //
                //  Now release the file
                //

                FsRtlReleaseFileForCcFlush (ControlArea->FilePointer);
            }

            LOCK_PFN (OldIrql);

            if (!NT_SUCCESS(Status)) {
                if ((Status == STATUS_FILE_LOCK_CONFLICT) ||
                    (ControlArea->u.Flags.Networked == 0)) {

                    //
                    // If an error occurs, don't flush this section, unless
                    // it's a networked file and the status is not
                    // LOCK_CONFLICT.
                    //

                    ControlArea->NumberOfMappedViews -= 1;
                    UNLOCK_PFN (OldIrql);
                    continue;
                }
            }

            if (!((ControlArea->NumberOfMappedViews == 1) &&
                (ControlArea->NumberOfSectionReferences == 0) &&
                (ControlArea->u.Flags.BeingDeleted == 0))) {
                ControlArea->NumberOfMappedViews -= 1;
                UNLOCK_PFN (OldIrql);
                continue;
            }

            ControlArea->u.Flags.BeingDeleted = 1;

            //
            // Don't let any pages be written by the modified
            // page writer from this point on.
            //

            ControlArea->u.Flags.NoModifiedWriting = 1;
            ASSERT (ControlArea->u.Flags.FilePointerNull == 0);
            UNLOCK_PFN (OldIrql);
            MiCleanSection (ControlArea);
        } else {

            //
            // The segment was not eligible for deletion.  Just
            // leave it off the unused segment list and continue the
            // loop.
            //

            UNLOCK_PFN (OldIrql);
        }

    } //end while
    return;
}