summaryrefslogtreecommitdiffstats
path: root/private/ntos/mm/iosup.c
blob: 4187e96f164c3767ebf28de35b30f41b732633c0 (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
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
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

   iosup.c

Abstract:

    This module contains routines which provide support for the I/O system.

Author:

    Lou Perazzoli (loup) 25-Apr-1989

Revision History:

--*/

#include "mi.h"

#undef MmIsRecursiveIoFault

BOOLEAN
MmIsRecursiveIoFault(
    VOID
    );

BOOLEAN
MiCheckForContiguousMemory (
    IN PVOID BaseAddress,
    IN ULONG SizeInPages,
    IN ULONG HighestPfn
    );

PVOID
MiFindContiguousMemory (
    IN ULONG HighestPfn,
    IN ULONG SizeInPages
    );

PVOID
MiMapLockedPagesInUserSpace (
     IN PMDL MemoryDescriptorList,
     IN PVOID StartingVa
     );

VOID
MiUnmapLockedPagesInUserSpace (
     IN PVOID BaseAddress,
     IN PMDL MemoryDescriptorList
     );

VOID
MiFlushTb (
    VOID
    );


#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, MmLockPagableDataSection)
#pragma alloc_text(PAGE, MiLookupDataTableEntry)
#pragma alloc_text(PAGE, MiMapLockedPagesInUserSpace)
#pragma alloc_text(PAGE, MmSetBankedSection)
#pragma alloc_text(PAGE, MmUnmapIoSpace)
#pragma alloc_text(PAGE, MmMapVideoDisplay)
#pragma alloc_text(PAGE, MmUnmapVideoDisplay)

#pragma alloc_text(PAGELK, MiUnmapLockedPagesInUserSpace)
#pragma alloc_text(PAGELK, MmAllocateNonCachedMemory)
#pragma alloc_text(PAGELK, MmFreeNonCachedMemory)
#pragma alloc_text(PAGELK, MiFindContiguousMemory)
#pragma alloc_text(PAGELK, MmLockPagedPool)
#pragma alloc_text(PAGELK, MmUnlockPagedPool)
#endif

extern POOL_DESCRIPTOR NonPagedPoolDescriptor;

extern ULONG MmAllocatedNonPagedPool;

extern ULONG MmDelayPageFaults;

KEVENT MmCollidedLockEvent;
ULONG MmCollidedLockWait;

ULONG MmLockPagesCount;

ULONG MmLockedCode;

#ifdef LARGE_PAGES
ULONG MmLargeVideoMapped;
#endif

#if DBG
ULONG MmReferenceCountCheck = 75;
#endif //DBG



VOID
MmProbeAndLockPages (
     IN OUT PMDL MemoryDescriptorList,
     IN KPROCESSOR_MODE AccessMode,
     IN LOCK_OPERATION Operation
     )

/*++

Routine Description:

    This routine probes the specified pages, makes the pages resident and
    locks the physical pages mapped by the virtual pages in memory.  The
    Memory descriptor list is updated to describe the physical pages.

Arguments:

    MemoryDescriptorList - Supplies a pointer to a Memory Descriptor List
                            (MDL). The supplied MDL must supply a virtual
                            address, byte offset and length field.  The
                            physical page portion of the MDL is updated when
                            the pages are locked in memory.

    AccessMode - Supplies the access mode in which to probe the arguments.
                 One of KernelMode or UserMode.

    Operation - Supplies the operation type.  One of IoReadAccess, IoWriteAccess
                or IoModifyAccess.

Return Value:

    None - exceptions are raised.

Environment:

    Kernel mode.  APC_LEVEL and below for pageable addresses,
                  DISPATCH_LEVEL and below for non-pageable addresses.

--*/

{
    PULONG Page;
    PMMPTE PointerPte;
    PMMPTE PointerPte1;
    PMMPTE PointerPde;
    PVOID Va;
    PVOID EndVa;
    PMMPFN Pfn1 ;
    ULONG PageFrameIndex;
    PEPROCESS CurrentProcess;
    KIRQL OldIrql;
    ULONG NumberOfPagesToLock;
    NTSTATUS status;

    ASSERT (MemoryDescriptorList->ByteCount != 0);
    ASSERT (((ULONG)MemoryDescriptorList->StartVa & (PAGE_SIZE - 1)) == 0);
    ASSERT (((ULONG)MemoryDescriptorList->ByteOffset & ~(PAGE_SIZE - 1)) == 0);

    ASSERT ((MemoryDescriptorList->MdlFlags & (
                    MDL_PAGES_LOCKED |
                    MDL_MAPPED_TO_SYSTEM_VA |
                    MDL_SOURCE_IS_NONPAGED_POOL |
                    MDL_PARTIAL |
                    MDL_SCATTER_GATHER_VA |
                    MDL_IO_SPACE)) == 0);

    Page = (PULONG)(MemoryDescriptorList + 1);

    Va = (PCHAR) MemoryDescriptorList->StartVa + MemoryDescriptorList->ByteOffset;

    PointerPte = MiGetPteAddress (Va);
    PointerPte1 = PointerPte;

    //
    // Endva is one byte past the end of the buffer, if ACCESS_MODE is not
    // kernel, make sure the EndVa is in user space AND the byte count
    // does not cause it to wrap.
    //

    EndVa = (PVOID)(((PCHAR)MemoryDescriptorList->StartVa +
                            MemoryDescriptorList->ByteOffset) +
                            MemoryDescriptorList->ByteCount);

    if ((AccessMode != KernelMode) &&
        ((EndVa > (PVOID)MM_USER_PROBE_ADDRESS) || (Va >= EndVa))) {
        *Page = MM_EMPTY_LIST;
        ExRaiseStatus (STATUS_ACCESS_VIOLATION);
        return;
    }

    //
    // There is an optimization which could be performed here.  If
    // the operation is for WriteAccess and the complete page is
    // being modified, we can remove the current page, if it is not
    // resident, and substitute a demand zero page.
    // Note, that after analysis by marking the thread and then
    // noting if a page read was done, this rarely occurs.
    //
    //

    MemoryDescriptorList->Process = (PEPROCESS)NULL;

    if (!MI_IS_PHYSICAL_ADDRESS(Va)) {
        do {

            *Page = MM_EMPTY_LIST;
            PointerPde = MiGetPdeAddress (Va);

            //
            // Make sure the page is resident.
            //

            if ((PointerPde->u.Hard.Valid == 0) ||
                (PointerPte1->u.Hard.Valid == 0)) {

                status = MmAccessFault (FALSE, Va, KernelMode);
            }

            //
            // Touch the page in case the previous fault caused
            // an access violation.  This is quicker than checking
            // the status code.
            //

            *(volatile CHAR *)Va;

            if ((Operation != IoReadAccess) &&
                (Va <= MM_HIGHEST_USER_ADDRESS)) {

                //
                // Probe for write access as well.
                //

                ProbeForWriteChar ((PCHAR)Va);
            }

            Va = (PVOID)(((ULONG)(PCHAR)Va + PAGE_SIZE) & ~(PAGE_SIZE - 1));
            Page += 1;
            PointerPte1 += 1;
        } while (Va < EndVa);
    }

    Va = (PVOID)(MemoryDescriptorList->StartVa);
    Page = (PULONG)(MemoryDescriptorList + 1);

    //
    // Indicate that this is a write operation.
    //

    if (Operation != IoReadAccess) {
        MemoryDescriptorList->MdlFlags |= MDL_WRITE_OPERATION;
    } else {
        MemoryDescriptorList->MdlFlags &= ~(MDL_WRITE_OPERATION);
    }

    //
    // Acquire the PFN database lock.
    //

    LOCK_PFN2 (OldIrql);

    if (Va <= MM_HIGHEST_USER_ADDRESS) {

        //
        // These are addresses with user space, check to see if the
        // working set size will allow these pages to be locked.
        //

        CurrentProcess = PsGetCurrentProcess ();
        NumberOfPagesToLock =
                        (((ULONG)EndVa - ((ULONG)Va + 1)) >> PAGE_SHIFT) + 1;

        PageFrameIndex = NumberOfPagesToLock + CurrentProcess->NumberOfLockedPages;

        if ((PageFrameIndex >
           (CurrentProcess->Vm.MaximumWorkingSetSize - MM_FLUID_WORKING_SET))
               &&
            ((MmLockPagesCount + NumberOfPagesToLock) > MmLockPagesLimit)) {

            UNLOCK_PFN (OldIrql);
            ExRaiseStatus (STATUS_WORKING_SET_QUOTA);
            return;
        }

        CurrentProcess->NumberOfLockedPages = PageFrameIndex;
        MmLockPagesCount += NumberOfPagesToLock;
        MemoryDescriptorList->Process = CurrentProcess;
    }

    MemoryDescriptorList->MdlFlags |= MDL_PAGES_LOCKED;

    do {

        PointerPde = MiGetPdeAddress (Va);

        if (MI_IS_PHYSICAL_ADDRESS(Va)) {

            //
            // On certains architectures (e.g., MIPS) virtual addresses
            // may be physical and hence have no corresponding PTE.
            //

            PageFrameIndex = MI_CONVERT_PHYSICAL_TO_PFN (Va);

        } else {

            while ((PointerPde->u.Hard.Valid == 0) ||
                   (PointerPte->u.Hard.Valid == 0)) {

                //
                // PDE is not resident, release PFN lock touch the page and make
                // it appear.
                //

                UNLOCK_PFN (OldIrql);

                status = MmAccessFault (FALSE, Va, KernelMode);

                if (!NT_SUCCESS(status)) {

                    //
                    // An exception occurred.  Unlock the pages locked
                    // so far.
                    //

                    MmUnlockPages (MemoryDescriptorList);

                    //
                    // Raise an exception of access violation to the caller.
                    //

                    ExRaiseStatus (status);
                    return;
                }

                LOCK_PFN (OldIrql);
            }

            PageFrameIndex = PointerPte->u.Hard.PageFrameNumber;
        }

        if (PageFrameIndex > MmHighestPhysicalPage) {

            //
            // This is an I/O space address don't allow operations
            // on addresses not in the PFN database.
            //

            MemoryDescriptorList->MdlFlags |= MDL_IO_SPACE;

        } else {
            ASSERT ((MemoryDescriptorList->MdlFlags & MDL_IO_SPACE) == 0);

            Pfn1 = MI_PFN_ELEMENT (PageFrameIndex);
            Pfn1->u3.e2.ReferenceCount += 1;

            ASSERT (Pfn1->u3.e2.ReferenceCount < MmReferenceCountCheck);
        }

        *Page = PageFrameIndex;

        Page += 1;
        PointerPte += 1;
        Va = (PVOID)((PCHAR)Va + PAGE_SIZE);
    } while (Va < EndVa);

    UNLOCK_PFN2 (OldIrql);

    return;
}

NTKERNELAPI
VOID
MmProbeAndLockSelectedPages (
    IN OUT PMDL MemoryDescriptorList,
    IN PFILE_SEGMENT_ELEMENT SegmentArray,
    IN KPROCESSOR_MODE AccessMode,
    IN LOCK_OPERATION Operation
    )

/*++

Routine Description:

    This routine probes the specified pages, makes the pages resident and
    locks the physical pages mapped by the virtual pages in memory.  The
    Memory descriptor list is updated to describe the physical pages.

Arguments:

    MemoryDescriptorList - Supplies a pointer to a Memory Descriptor List
                            (MDL). The MDL must supply the length. The
                            physical page portion of the MDL is updated when
                            the pages are locked in memory.

    SegmentArray - Supplies a pointer to a list of buffer segments to be 
                   probed and locked.

    AccessMode - Supplies the access mode in which to probe the arguments.
                 One of KernelMode or UserMode.

    Operation - Supplies the operation type.  One of IoReadAccess, IoWriteAccess
                or IoModifyAccess.

Return Value:

    None - exceptions are raised.

Environment:

    Kernel mode.  APC_LEVEL and below.

--*/

{
    PMDL TempMdl;
    ULONG MdlHack[(sizeof(MDL)/4) + 1];
    PULONG Page;
    PFILE_SEGMENT_ELEMENT LastSegment;

    PAGED_CODE();
    ASSERT (MemoryDescriptorList->ByteCount != 0);
    ASSERT (((ULONG)MemoryDescriptorList->ByteOffset & ~(PAGE_SIZE - 1)) == 0);

    ASSERT ((MemoryDescriptorList->MdlFlags & (
                    MDL_PAGES_LOCKED |
                    MDL_MAPPED_TO_SYSTEM_VA |
                    MDL_SOURCE_IS_NONPAGED_POOL |
                    MDL_PARTIAL |
                    MDL_SCATTER_GATHER_VA |
                    MDL_IO_SPACE)) == 0);

    //
    // Initialize TempMdl.
    //

    TempMdl = (PMDL) &MdlHack;
    MmInitializeMdl( TempMdl, NULL, PAGE_SIZE );

    Page = (PULONG) (MemoryDescriptorList + 1);

    //
    // Calculate the end of the segment list.
    //

    LastSegment = SegmentArray + 
                  BYTES_TO_PAGES(MemoryDescriptorList->ByteCount);

    //
    // Build a small Mdl for each segement and call probe and lock pages.
    // Then copy the PFNs to the real mdl.
    //

    while (SegmentArray < LastSegment) {

        TempMdl->MdlFlags = 0;
        TempMdl->StartVa = (PVOID) SegmentArray->Buffer;

        SegmentArray++;
        MmProbeAndLockPages( TempMdl, AccessMode, Operation );

        *Page++ = *((PULONG) (TempMdl + 1));
    }

    //
    // Copy the flags and process fields. 
    //

    MemoryDescriptorList->MdlFlags = TempMdl->MdlFlags;
    MemoryDescriptorList->Process = TempMdl->Process;

#ifdef _MIPS_

    //
    // Becuase the caches are virtual on mips they need to be completely
    // flushed.  Only the first level dcache needs to be swept; however,
    // the only kernel interface to do this with is sweep I-cache range
    // since it sweeps the both the first level I and D caches.
    //

    KeSweepIcacheRange( TRUE, NULL, KeGetPcr()->FirstLevelDcacheSize );

    //
    // Set a flag the MDL to indicate this MDL is a scatter/gather MDL.
    //

    MemoryDescriptorList->MdlFlags |= MDL_SCATTER_GATHER_VA;

#endif
}

VOID
MmUnlockPages (
     IN OUT PMDL MemoryDescriptorList
     )

/*++

Routine Description:

    This routine unlocks physical pages which are described by a Memory
    Descriptor List.

Arguments:

    MemoryDescriptorList - Supplies a pointer to a memory description list
                            (MDL). The supplied MDL must have been supplied
                            to MmLockPages to lock the pages down.  As the
                            pages are unlocked, the MDL is updated.

Return Value:

    None.

Environment:

    Kernel mode, IRQL of DISPATCH_LEVEL or below.

--*/

{
    ULONG NumberOfPages;
    PULONG Page;
    PVOID StartingVa;
    KIRQL OldIrql;
    PMMPFN Pfn1;

    ASSERT ((MemoryDescriptorList->MdlFlags & MDL_PAGES_LOCKED) != 0);
    ASSERT ((MemoryDescriptorList->MdlFlags & MDL_SOURCE_IS_NONPAGED_POOL) == 0);
    ASSERT ((MemoryDescriptorList->MdlFlags & MDL_PARTIAL) == 0);
    ASSERT (MemoryDescriptorList->ByteCount != 0);

    if (MemoryDescriptorList->MdlFlags & MDL_MAPPED_TO_SYSTEM_VA) {

        //
        // This MDL has been mapped into system space, unmap now.
        //

        MmUnmapLockedPages (MemoryDescriptorList->MappedSystemVa,
                            MemoryDescriptorList);
    }

    StartingVa = (PVOID)((PCHAR)MemoryDescriptorList->StartVa +
                        MemoryDescriptorList->ByteOffset);

    Page = (PULONG)(MemoryDescriptorList + 1);
    NumberOfPages = ADDRESS_AND_SIZE_TO_SPAN_PAGES(StartingVa,
                                              MemoryDescriptorList->ByteCount);
    ASSERT (NumberOfPages != 0);

    LOCK_PFN2 (OldIrql);

    if (MemoryDescriptorList->Process != NULL) {
        MemoryDescriptorList->Process->NumberOfLockedPages -= NumberOfPages;
        MmLockPagesCount -= NumberOfPages;
        ASSERT ((LONG)MemoryDescriptorList->Process->NumberOfLockedPages >= 0);
    }

    if ((MemoryDescriptorList->MdlFlags & MDL_IO_SPACE) == 0) {

        //
        // Only unlock if not I/O space.
        //

        do {

            if (*Page == MM_EMPTY_LIST) {

                //
                // There are no more locked pages.
                //

                UNLOCK_PFN2 (OldIrql);
                return;
            }
            ASSERT ((*Page <= MmHighestPhysicalPage) &&
                    (*Page >= MmLowestPhysicalPage));

            //
            // If this was a write operation set the modified bit in the
            // pfn database.
            //

            if (MemoryDescriptorList->MdlFlags & MDL_WRITE_OPERATION) {
                Pfn1 = MI_PFN_ELEMENT (*Page);
                Pfn1->u3.e1.Modified = 1;
                if ((Pfn1->OriginalPte.u.Soft.Prototype == 0) &&
                             (Pfn1->u3.e1.WriteInProgress == 0)) {
                    MiReleasePageFileSpace (Pfn1->OriginalPte);
                    Pfn1->OriginalPte.u.Soft.PageFileHigh = 0;
                }
            }

            MiDecrementReferenceCount (*Page);
            *Page = MM_EMPTY_LIST;
            Page += 1;
            NumberOfPages -= 1;
        } while (NumberOfPages != 0);
    }
    UNLOCK_PFN2 (OldIrql);

    MemoryDescriptorList->MdlFlags &= ~MDL_PAGES_LOCKED;

    return;
}

VOID
MmBuildMdlForNonPagedPool (
    IN OUT PMDL MemoryDescriptorList
    )

/*++

Routine Description:

    This routine fills in the "pages" portion of the MDL using the PFN
    numbers corresponding the the buffers which resides in non-paged pool.

    Unlike MmProbeAndLockPages, there is no corresponding unlock as no
    reference counts are incremented as the buffers being in nonpaged
    pool are always resident.

Arguments:

    MemoryDescriptorList - Supplies a pointer to a Memory Descriptor List
                            (MDL). The supplied MDL must supply a virtual
                            address, byte offset and length field.  The
                            physical page portion of the MDL is updated when
                            the pages are locked in memory.  The virtual
                            address must be within the non-paged portion
                            of the system space.

Return Value:

    None.

Environment:

    Kernel mode, IRQL of DISPATCH_LEVEL or below.

--*/

{
    PULONG Page;
    PMMPTE PointerPte;
    PMMPTE LastPte;
    PVOID EndVa;
    ULONG PageFrameIndex;

    Page = (PULONG)(MemoryDescriptorList + 1);

    ASSERT (MemoryDescriptorList->ByteCount != 0);
    ASSERT ((MemoryDescriptorList->MdlFlags & (
                    MDL_PAGES_LOCKED |
                    MDL_MAPPED_TO_SYSTEM_VA |
                    MDL_SOURCE_IS_NONPAGED_POOL |
                    MDL_PARTIAL)) == 0);

    MemoryDescriptorList->Process = (PEPROCESS)NULL;

    //
    // Endva is last byte of the buffer.
    //

    MemoryDescriptorList->MdlFlags |= MDL_SOURCE_IS_NONPAGED_POOL;

    MemoryDescriptorList->MappedSystemVa =
            (PVOID)((PCHAR)MemoryDescriptorList->StartVa +
                                           MemoryDescriptorList->ByteOffset);

    EndVa = (PVOID)(((PCHAR)MemoryDescriptorList->MappedSystemVa +
                            MemoryDescriptorList->ByteCount - 1));

    LastPte = MiGetPteAddress (EndVa);

    ASSERT (MmIsNonPagedSystemAddressValid (MemoryDescriptorList->StartVa));

    PointerPte = MiGetPteAddress (MemoryDescriptorList->StartVa);

    if (MI_IS_PHYSICAL_ADDRESS(EndVa)) {
        PageFrameIndex = MI_CONVERT_PHYSICAL_TO_PFN (
                                MemoryDescriptorList->StartVa);

        do {
            *Page = PageFrameIndex;
            Page += 1;
            PageFrameIndex += 1;
            PointerPte += 1;
        } while (PointerPte <= LastPte);
    } else {
        do {
            PageFrameIndex = PointerPte->u.Hard.PageFrameNumber;
            *Page = PageFrameIndex;
            Page += 1;
            PointerPte += 1;
        } while (PointerPte <= LastPte);
    }

    return;
}

PVOID
MmMapLockedPages (
     IN PMDL MemoryDescriptorList,
     IN KPROCESSOR_MODE AccessMode
     )

/*++

Routine Description:

    This function maps physical pages described by a memory description
    list into the system virtual address space or the user portion of
    the virtual address space.

Arguments:

    MemoryDescriptorList - Supplies a valid Memory Descriptor List which has
                            been updated by MmProbeAndLockPages.


    AccessMode - Supplies an indicator of where to map the pages;
                 KernelMode indicates that the pages should be mapped in the
                 system part of the address space, UserMode indicates the
                 pages should be mapped in the user part of the address space.

Return Value:

    Returns the base address where the pages are mapped.  The base address
    has the same offset as the virtual address in the MDL.

    This routine will raise an exception if the processor mode is USER_MODE
    and quota limits or VM limits are exceeded.

Environment:

    Kernel mode.  DISPATCH_LEVEL or below if access mode is KernelMode,
                APC_LEVEL or below if access mode is UserMode.

--*/

{
    ULONG NumberOfPages;
    ULONG SavedPageCount;
    PULONG Page;
    PMMPTE PointerPte;
    PVOID BaseVa;
    MMPTE TempPte;
    PVOID StartingVa;
    PMMPFN Pfn2;
    KIRQL OldIrql;

    StartingVa = (PVOID)((PCHAR)MemoryDescriptorList->StartVa +
                        MemoryDescriptorList->ByteOffset);

    ASSERT (MemoryDescriptorList->ByteCount != 0);

    if (AccessMode == KernelMode) {

        Page = (PULONG)(MemoryDescriptorList + 1);
        NumberOfPages = COMPUTE_PAGES_SPANNED (StartingVa,
                                               MemoryDescriptorList->ByteCount);
        SavedPageCount = NumberOfPages;

        //
        // Map the pages into the system part of the address space as
        // kernel read/write.
        //

        ASSERT ((MemoryDescriptorList->MdlFlags & (
                        MDL_MAPPED_TO_SYSTEM_VA |
                        MDL_SOURCE_IS_NONPAGED_POOL |
                        MDL_PARTIAL_HAS_BEEN_MAPPED)) == 0);
        ASSERT ((MemoryDescriptorList->MdlFlags & (
                        MDL_PAGES_LOCKED |
                        MDL_PARTIAL)) != 0);

#if defined(_ALPHA_)

        //
        // See if KSEG0 can be used to map this.
        //

        if ((NumberOfPages == 1) &&
            (*Page < ((1*1024*1024*1024) >> PAGE_SHIFT))) {
            BaseVa = (PVOID)(KSEG0_BASE + (*Page << PAGE_SHIFT) +
                            MemoryDescriptorList->ByteOffset);
            MemoryDescriptorList->MappedSystemVa = BaseVa;
            MemoryDescriptorList->MdlFlags |= MDL_MAPPED_TO_SYSTEM_VA;

            goto Update;
        }
#endif //ALPHA

#if defined(_MIPS_)

        //
        // See if KSEG0 can be used to map this.
        //

        if ((NumberOfPages == 1) &&
            (MI_GET_PAGE_COLOR_FROM_VA (MemoryDescriptorList->StartVa) ==
                (MM_COLOR_MASK & *Page)) &&
            (*Page < ((512*1024*1024) >> PAGE_SHIFT))) {
            BaseVa = (PVOID)(KSEG0_BASE + (*Page << PAGE_SHIFT) +
                            MemoryDescriptorList->ByteOffset);
            MemoryDescriptorList->MappedSystemVa = BaseVa;
            MemoryDescriptorList->MdlFlags |= MDL_MAPPED_TO_SYSTEM_VA;

            goto Update;
        }
#endif //MIPS


#if defined(_X86_)

        //
        // See if KSEG0 can be used to map this.
        //

        if ((NumberOfPages == 1) &&
            (*Page < MmKseg2Frame)) {
            BaseVa = (PVOID)(MM_KSEG0_BASE + (*Page << PAGE_SHIFT) +
                            MemoryDescriptorList->ByteOffset);
            MemoryDescriptorList->MappedSystemVa = BaseVa;
            MemoryDescriptorList->MdlFlags |= MDL_MAPPED_TO_SYSTEM_VA;

            goto Update;
        }
#endif //X86

        PointerPte = MiReserveSystemPtes (
                                    NumberOfPages,
                                    SystemPteSpace,
                                    MM_COLOR_ALIGNMENT,
                                    ((ULONG)MemoryDescriptorList->StartVa &
                                                       MM_COLOR_MASK_VIRTUAL),
                        MemoryDescriptorList->MdlFlags & MDL_MAPPING_CAN_FAIL ? 0 : 1);
        if (PointerPte == NULL) {

            //
            // Not enough system PTES are available.
            //

            return NULL;
        }
        BaseVa = (PVOID)((PCHAR)MiGetVirtualAddressMappedByPte (PointerPte) +
                                MemoryDescriptorList->ByteOffset);

        TempPte = ValidKernelPte;

#if defined(_MIPS_)
        
        //
        // If this is a Scatter/Gather Mdl then disable caching since the
        // page colors will be wrong in the MDL.
        //

        if (MemoryDescriptorList->MdlFlags & MDL_SCATTER_GATHER_VA) {
            MI_DISABLE_CACHING( TempPte );
        }
#endif

#if DBG
        LOCK_PFN2 (OldIrql);
#endif //DBG

        do {

            if (*Page == MM_EMPTY_LIST) {
                break;
            }
            ASSERT (*Page != 0);
            TempPte.u.Hard.PageFrameNumber = *Page;
            ASSERT (PointerPte->u.Hard.Valid == 0);

#if DBG
            if ((MemoryDescriptorList->MdlFlags & MDL_IO_SPACE) == 0) {
                Pfn2 = MI_PFN_ELEMENT (*Page);
                ASSERT (Pfn2->u3.e2.ReferenceCount != 0);
                Pfn2->u3.e2.ReferenceCount += 1;
                ASSERT (Pfn2->u3.e2.ReferenceCount < MmReferenceCountCheck);
                ASSERT ((((ULONG)PointerPte >> PTE_SHIFT) & MM_COLOR_MASK) ==
                     (((ULONG)Pfn2->u3.e1.PageColor)));
            }
#endif //DBG

            *PointerPte = TempPte;
            Page++;
            PointerPte++;
            NumberOfPages -= 1;
        } while (NumberOfPages != 0);
#if DBG
        UNLOCK_PFN2 (OldIrql);
#endif //DBG

        ExAcquireSpinLock ( &MmSystemSpaceLock, &OldIrql );
        if (MemoryDescriptorList->MdlFlags & MDL_MAPPED_TO_SYSTEM_VA) {

            //
            //
            // Another thread must have already mapped this.
            // Clean up the system ptes and release them.
            //

            ExReleaseSpinLock ( &MmSystemSpaceLock, OldIrql );

#if DBG
        if ((MemoryDescriptorList->MdlFlags & MDL_IO_SPACE ) == 0) {
            PMMPFN Pfn3;
            ULONG j;
            PULONG Page1;

            Page1 = (PULONG)(MemoryDescriptorList + 1);
            for (j = 0; j < SavedPageCount ; j++ ) {
                if (*Page == MM_EMPTY_LIST) {
                    break;
                }
                Pfn3 = MI_PFN_ELEMENT (*Page1);
                Page1 += 1;
                ASSERT (Pfn3->u3.e2.ReferenceCount > 1);
                Pfn3->u3.e2.ReferenceCount -= 1;
                ASSERT (Pfn3->u3.e2.ReferenceCount < 256);
            }
        }
#endif //DBG
            PointerPte = MiGetPteAddress (BaseVa);

            MiReleaseSystemPtes (PointerPte,
                                 SavedPageCount,
                                 SystemPteSpace);

            return MemoryDescriptorList->MappedSystemVa;
        }

        MemoryDescriptorList->MappedSystemVa = BaseVa;
        *(volatile ULONG *)&MmLockPagesCount;  //need to force order.
        MemoryDescriptorList->MdlFlags |= MDL_MAPPED_TO_SYSTEM_VA;
        ExReleaseSpinLock ( &MmSystemSpaceLock, OldIrql );


#if defined(_MIPS_) || defined(_ALPHA_) || defined (_X86_)
Update:
#endif

        if ((MemoryDescriptorList->MdlFlags & MDL_PARTIAL) != 0) {
            MemoryDescriptorList->MdlFlags |= MDL_PARTIAL_HAS_BEEN_MAPPED;
        }

        return BaseVa;

    } else {

        return MiMapLockedPagesInUserSpace (MemoryDescriptorList, StartingVa);
    }
}


PVOID
MiMapLockedPagesInUserSpace (
     IN PMDL MemoryDescriptorList,
     IN PVOID StartingVa
     )

/*++

Routine Description:

    This function maps physical pages described by a memory description
    list into the system virtual address space or the user portion of
    the virtual address space.

Arguments:

    MemoryDescriptorList - Supplies a valid Memory Descriptor List which has
                            been updated by MmProbeAndLockPages.


    StartingVa - Supplies the starting address.

Return Value:

    Returns the base address where the pages are mapped.  The base address
    has the same offset as the virtual address in the MDL.

    This routine will raise an exception if the processor mode is USER_MODE
    and quota limits or VM limits are exceeded.

Environment:

    Kernel mode.  APC_LEVEL or below.

--*/

{
    ULONG NumberOfPages;
    PULONG Page;
    PMMPTE PointerPte;
    PMMPTE PointerPde;
    PVOID BaseVa;
    MMPTE TempPte;
    PVOID EndingAddress;
    PMMVAD Vad;
    PEPROCESS Process;
    PMMPFN Pfn2;

    PAGED_CODE ();
    Page = (PULONG)(MemoryDescriptorList + 1);
    NumberOfPages = COMPUTE_PAGES_SPANNED (StartingVa,
                                           MemoryDescriptorList->ByteCount);

    if (MemoryDescriptorList->MdlFlags & MDL_IO_SPACE) {
        ExRaiseStatus (STATUS_INVALID_ADDRESS);
    }

    //
    // Map the pages into the user part of the address as user
    // read/write no-delete.
    //

    TempPte = ValidUserPte;

    Process = PsGetCurrentProcess ();

    //
    // Get the working set mutex and address creation mutex.
    //

    LOCK_WS_AND_ADDRESS_SPACE (Process);

    try {

        Vad = (PMMVAD)NULL;
        BaseVa = MiFindEmptyAddressRange ( (NumberOfPages * PAGE_SIZE),
                                            X64K,
                                            0 );

        EndingAddress = (PVOID)((PCHAR)BaseVa + (NumberOfPages * PAGE_SIZE) - 1);

        Vad = ExAllocatePoolWithTag (NonPagedPool, sizeof(MMVAD), ' daV');

        if (Vad == NULL) {
            BaseVa = NULL;
            goto Done;
        }

        Vad->StartingVa = BaseVa;
        Vad->EndingVa = EndingAddress;
        Vad->ControlArea = NULL;
        Vad->FirstPrototypePte = NULL;
        Vad->u.LongFlags = 0;
        Vad->u.VadFlags.Protection = MM_READWRITE;
        Vad->u.VadFlags.PhysicalMapping = 1;
        Vad->u.VadFlags.PrivateMemory = 1;
        Vad->Banked = NULL;
        MiInsertVad (Vad);

    } except (EXCEPTION_EXECUTE_HANDLER) {
        if (Vad != (PMMVAD)NULL) {
            ExFreePool (Vad);
        }
        BaseVa = NULL;
        goto Done;
    }

    //
    // Get the working set mutex and address creation mutex.
    //

    PointerPte = MiGetPteAddress (BaseVa);

    do {

        if (*Page == MM_EMPTY_LIST) {
            break;
        }

        ASSERT (*Page != 0);
        ASSERT ((*Page <= MmHighestPhysicalPage) &&
                (*Page >= MmLowestPhysicalPage));

        PointerPde = MiGetPteAddress (PointerPte);
        MiMakePdeExistAndMakeValid(PointerPde, Process, FALSE);

        ASSERT (PointerPte->u.Hard.Valid == 0);
        TempPte.u.Hard.PageFrameNumber = *Page;
        *PointerPte = TempPte;

        //
        // A PTE just went from not present, not transition to
        // present.  The share count and valid count must be
        // updated in the page table page which contains this
        // Pte.
        //

        Pfn2 = MI_PFN_ELEMENT(PointerPde->u.Hard.PageFrameNumber);
        Pfn2->u2.ShareCount += 1;

        //
        // Another zeroed PTE has become non-zero.
        //

        MmWorkingSetList->UsedPageTableEntries
                            [MiGetPteOffset(PointerPte)] += 1;

        ASSERT (MmWorkingSetList->UsedPageTableEntries
                            [MiGetPteOffset(PointerPte)] <= PTE_PER_PAGE);

        Page++;
        PointerPte++;
        NumberOfPages -= 1;
    } while (NumberOfPages != 0);

Done:
    UNLOCK_WS (Process);
    UNLOCK_ADDRESS_SPACE (Process);
    if (BaseVa == NULL) {
        ExRaiseStatus (STATUS_INSUFFICIENT_RESOURCES);
    }

    return BaseVa;
}


VOID
MmUnmapLockedPages (
     IN PVOID BaseAddress,
     IN PMDL MemoryDescriptorList
     )

/*++

Routine Description:

    This routine unmaps locked pages which were previously mapped via
    a MmMapLockedPages function.

Arguments:

    BaseAddress - Supplies the base address where the pages were previously
                  mapped.

    MemoryDescriptorList - Supplies a valid Memory Descriptor List which has
                            been updated by MmProbeAndLockPages.

Return Value:

    None.

Environment:

    Kernel mode.  DISPATCH_LEVEL or below if base address is within system space;
                APC_LEVEL or below if base address is user space.

--*/

{
    ULONG NumberOfPages;
    ULONG i;
    PULONG Page;
    PMMPTE PointerPte;
    PMMPTE PointerBase;
    PVOID StartingVa;
    KIRQL OldIrql;

    ASSERT (MemoryDescriptorList->ByteCount != 0);
    ASSERT ((MemoryDescriptorList->MdlFlags & MDL_PARENT_MAPPED_SYSTEM_VA) == 0);

    if (MI_IS_PHYSICAL_ADDRESS (BaseAddress)) {

        //
        // MDL is not mapped into virtual space, just clear the fields
        // and return.
        //

        MemoryDescriptorList->MdlFlags &= ~(MDL_MAPPED_TO_SYSTEM_VA |
                                            MDL_PARTIAL_HAS_BEEN_MAPPED);
        return;
    }

    if (BaseAddress > MM_HIGHEST_USER_ADDRESS) {

        StartingVa = (PVOID)((PCHAR)MemoryDescriptorList->StartVa +
                            MemoryDescriptorList->ByteOffset);

        NumberOfPages = COMPUTE_PAGES_SPANNED (StartingVa,
                                               MemoryDescriptorList->ByteCount);

        PointerBase = MiGetPteAddress (BaseAddress);


        ASSERT ((MemoryDescriptorList->MdlFlags & MDL_MAPPED_TO_SYSTEM_VA) != 0);


#if DBG
        PointerPte = PointerBase;
        i = NumberOfPages;
        Page = (PULONG)(MemoryDescriptorList + 1);
        if ((MemoryDescriptorList->MdlFlags & MDL_LOCK_HELD) == 0) {
            LOCK_PFN2 (OldIrql);
        }

        while (i != 0) {
            ASSERT (PointerPte->u.Hard.Valid == 1);
            ASSERT (*Page == PointerPte->u.Hard.PageFrameNumber);
            if ((MemoryDescriptorList->MdlFlags & MDL_IO_SPACE ) == 0) {
                PMMPFN Pfn3;
                Pfn3 = MI_PFN_ELEMENT (*Page);
                ASSERT (Pfn3->u3.e2.ReferenceCount > 1);
                Pfn3->u3.e2.ReferenceCount -= 1;
                ASSERT (Pfn3->u3.e2.ReferenceCount < 256);
            }

            Page += 1;
            PointerPte++;
            i -= 1;
        }

        if ((MemoryDescriptorList->MdlFlags & MDL_LOCK_HELD) == 0) {
            UNLOCK_PFN2 (OldIrql);
        }
#endif //DBG

        MemoryDescriptorList->MdlFlags &= ~(MDL_MAPPED_TO_SYSTEM_VA |
                                            MDL_PARTIAL_HAS_BEEN_MAPPED);

        MiReleaseSystemPtes (PointerBase, NumberOfPages, SystemPteSpace);
        return;

    } else {

        MiUnmapLockedPagesInUserSpace (BaseAddress,
                                   MemoryDescriptorList);
    }
}


VOID
MiUnmapLockedPagesInUserSpace (
     IN PVOID BaseAddress,
     IN PMDL MemoryDescriptorList
     )

/*++

Routine Description:

    This routine unmaps locked pages which were previously mapped via
    a MmMapLockedPages function.

Arguments:

    BaseAddress - Supplies the base address where the pages were previously
                  mapped.

    MemoryDescriptorList - Supplies a valid Memory Descriptor List which has
                            been updated by MmProbeAndLockPages.

Return Value:

    None.

Environment:

    Kernel mode.  DISPATCH_LEVEL or below if base address is within system space;
                APC_LEVEL or below if base address is user space.

--*/

{
    ULONG NumberOfPages;
    PULONG Page;
    PMMPTE PointerPte;
    PMMPTE PointerBase;
    PMMPTE PointerPde;
    PVOID StartingVa;
    KIRQL OldIrql;
    PMMVAD Vad;
    PVOID TempVa;
    PEPROCESS Process;
    CSHORT PageTableOffset;

    MmLockPagableSectionByHandle (ExPageLockHandle);

    StartingVa = (PVOID)((PCHAR)MemoryDescriptorList->StartVa +
                        MemoryDescriptorList->ByteOffset);

    Page = (PULONG)(MemoryDescriptorList + 1);
    NumberOfPages = COMPUTE_PAGES_SPANNED (StartingVa,
                                           MemoryDescriptorList->ByteCount);

    PointerPte = MiGetPteAddress (BaseAddress);
    PointerBase = PointerPte;

    //
    // This was mapped into the user portion of the address space and
    // the corresponding virtual address descriptor must be deleted.
    //

    //
    // Get the working set mutex and address creation mutex.
    //

    Process = PsGetCurrentProcess ();

    LOCK_WS_AND_ADDRESS_SPACE (Process);

    Vad = MiLocateAddress (BaseAddress);
    ASSERT (Vad != NULL);
    MiRemoveVad (Vad);

    //
    // Get the PFN mutex so we can safely decrement share and valid
    // counts on page table pages.
    //

    LOCK_PFN (OldIrql);

    do {

        if (*Page == MM_EMPTY_LIST) {
            break;
        }

        ASSERT (PointerPte->u.Hard.Valid == 1);

        (VOID)KeFlushSingleTb (BaseAddress,
                               TRUE,
                               FALSE,
                               (PHARDWARE_PTE)PointerPte,
                               ZeroPte.u.Flush);

        PointerPde = MiGetPteAddress(PointerPte);
        MiDecrementShareAndValidCount (PointerPde->u.Hard.PageFrameNumber);

        //
        // Another Pte has become zero.
        //

        PageTableOffset = (CSHORT)MiGetPteOffset( PointerPte );
        MmWorkingSetList->UsedPageTableEntries[PageTableOffset] -= 1;
        ASSERT (MmWorkingSetList->UsedPageTableEntries[PageTableOffset]
                            < PTE_PER_PAGE);

        //
        // If all the entries have been eliminated from the previous
        // page table page, delete the page table page itself.
        //

        if (MmWorkingSetList->UsedPageTableEntries[PageTableOffset] == 0) {

            TempVa = MiGetVirtualAddressMappedByPte (PointerPde);
            MiDeletePte (PointerPde,
                         TempVa,
                         FALSE,
                         Process,
                         (PMMPTE)NULL,
                         NULL);
        }

        Page++;
        PointerPte++;
        NumberOfPages -= 1;
        BaseAddress = (PVOID)((PCHAR)BaseAddress + PAGE_SIZE);
    } while (NumberOfPages != 0);

    UNLOCK_PFN (OldIrql);
    UNLOCK_WS (Process);
    UNLOCK_ADDRESS_SPACE (Process);
    ExFreePool (Vad);
    MmUnlockPagableImageSection(ExPageLockHandle);
    return;
}


PVOID
MmMapIoSpace (
     IN PHYSICAL_ADDRESS PhysicalAddress,
     IN ULONG NumberOfBytes,
     IN MEMORY_CACHING_TYPE CacheType
     )

/*++

Routine Description:

    This function maps the specified physical address into the non-pageable
    portion of the system address space.

Arguments:

    PhysicalAddress - Supplies the starting physical address to map.

    NumberOfBytes - Supplies the number of bytes to map.

    CacheType - Supplies MmNonCached if the phyiscal address is to be mapped
                as non-cached, MmCached if the address should be cached, and
                MmCacheFrameBuffer if the address should be cached as a frame
                buffer. For I/O device registers, this is usually specified
                as MmNonCached.

Return Value:

    Returns the virtual address which maps the specified physical addresses.
    The value NULL is returned if sufficient virtual address space for
    the mapping could not be found.

Environment:

    Kernel mode, IRQL of APC_LEVEL or below.

--*/

{
    ULONG NumberOfPages;
    ULONG PageFrameIndex;
    PMMPTE PointerPte;
    PVOID BaseVa;
    MMPTE TempPte;
    NTSTATUS Status;

    //
    // For compatibility for when CacheType used to be passed as a BOOLEAN
    // mask off the upper bits (TRUE == MmCached, FALSE == MmNonCached).
    //

    CacheType &= 0xFF;

    if (CacheType >= MmMaximumCacheType) {
        return (NULL);
    }

#ifdef i386
    ASSERT (PhysicalAddress.HighPart == 0);
#endif
#ifdef R4000
    ASSERT (PhysicalAddress.HighPart < 16);
#endif

    //PAGED_CODE();


    ASSERT (NumberOfBytes != 0);
    NumberOfPages = COMPUTE_PAGES_SPANNED (PhysicalAddress.LowPart,
                                           NumberOfBytes);

    PointerPte = MiReserveSystemPtes(NumberOfPages,
                                     SystemPteSpace,
                                     MM_COLOR_ALIGNMENT,
                                     (PhysicalAddress.LowPart &
                                                       MM_COLOR_MASK_VIRTUAL),
                                     FALSE);
    if (PointerPte == NULL) {
        return(NULL);
    }

    BaseVa = (PVOID)MiGetVirtualAddressMappedByPte (PointerPte);
    BaseVa = (PVOID)((PCHAR)BaseVa + BYTE_OFFSET(PhysicalAddress.LowPart));

    TempPte = ValidKernelPte;

#ifdef i386
    //
    // Set physical range to proper caching type.
    //

    Status = KeSetPhysicalCacheTypeRange(
                PhysicalAddress,
                NumberOfBytes,
                CacheType
                );

    //
    // If range could not be set, determine what to do
    //

    if (!NT_SUCCESS(Status)) {

        if ((Status == STATUS_NOT_SUPPORTED) &&
            ((CacheType == MmNonCached) || (CacheType == MmCached))) {

            //
            // The range may not have been set into the proper cache
            // type.  If the range is either MmNonCached or MmCached just
            // continue as the PTE will be marked properly.
            //

        } else if (Status == STATUS_UNSUCCESSFUL  &&  CacheType == MmCached) {

            //
            // If setting a range to Cached was unsuccessful things are not
            // optimal, but not fatal.  The range can be returned to the
            // caller and it will have whatever caching type it has - possibly
            // something below fully cached.
            //

#if DBG
            DbgPrint("MmMapIoSpace: Failed to set range to MmCached\n");
#endif

        } else {

            //
            // If there's still a problem, fail the request.
            //
#if DBG
            DbgPrint("MmMapIoSpace: KeSetPhysicalCacheTypeRange failed\n");
#endif

            MiReleaseSystemPtes(PointerPte, NumberOfPages, SystemPteSpace);

            return(NULL);
         }
    }
#endif

    if (CacheType == MmNonCached) {
        MI_DISABLE_CACHING (TempPte);
    }

    PageFrameIndex = (ULONG)(PhysicalAddress.QuadPart >> PAGE_SHIFT);

    do {
        ASSERT (PointerPte->u.Hard.Valid == 0);
        TempPte.u.Hard.PageFrameNumber = PageFrameIndex;
        *PointerPte = TempPte;
        PointerPte++;
        PageFrameIndex += 1;
        NumberOfPages -= 1;
    } while (NumberOfPages != 0);

    return BaseVa;
}

VOID
MmUnmapIoSpace (
     IN PVOID BaseAddress,
     IN ULONG NumberOfBytes
     )

/*++

Routine Description:

    This function unmaps a range of physical address which were previously
    mapped via an MmMapIoSpace function call.

Arguments:

    BaseAddress - Supplies the base virtual address where the physical
                  address was previously mapped.

    NumberOfBytes - Supplies the number of bytes which were mapped.

Return Value:

    None.

Environment:

    Kernel mode, IRQL of APC_LEVEL or below.

--*/

{
    ULONG NumberOfPages;
    ULONG i;
    PMMPTE FirstPte;

    PAGED_CODE();
    ASSERT (NumberOfBytes != 0);
    NumberOfPages = COMPUTE_PAGES_SPANNED (BaseAddress, NumberOfBytes);
    FirstPte = MiGetPteAddress (BaseAddress);
    MiReleaseSystemPtes(FirstPte, NumberOfPages, SystemPteSpace);

    return;
}

PVOID
MmAllocateContiguousMemory (
    IN ULONG NumberOfBytes,
    IN PHYSICAL_ADDRESS HighestAcceptableAddress
    )

/*++

Routine Description:

    This function allocates a range of physically contiguous non-paged
    pool.  It relies on the fact that non-paged pool is built at
    system initialization time from a contiguous range of phyiscal
    memory.  It allocates the specified size of non-paged pool and
    then checks to ensure it is contiguous as pool expansion does
    not maintain the contiguous nature of non-paged pool.

    This routine is designed to be used by a driver's initialization
    routine to allocate a contiguous block of physical memory for
    issuing DMA requests from.

Arguments:

    NumberOfBytes - Supplies the number of bytes to allocate.

    HighestAcceptableAddress - Supplies the highest physical address
                               which is valid for the allocation.  For
                               example, if the device can only reference
                               phyiscal memory in the lower 16MB this
                               value would be set to 0xFFFFFF (16Mb - 1).

Return Value:

    NULL - a contiguous range could not be found to satisfy the request.

    NON-NULL - Returns a pointer (virtual address in the nonpaged portion
               of the system) to the allocated phyiscally contiguous
               memory.

Environment:

    Kernel mode, IRQL of APC_LEVEL or below.

--*/

{
    PMMPTE PointerPte;
    PMMPFN Pfn1;
    PVOID BaseAddress;
    ULONG SizeInPages;
    ULONG HighestPfn;
    ULONG i;

    PAGED_CODE();

    ASSERT (NumberOfBytes != 0);
    BaseAddress = ExAllocatePoolWithTag (NonPagedPoolCacheAligned,
                                         NumberOfBytes,
                                         'mCmM');

    SizeInPages = BYTES_TO_PAGES (NumberOfBytes);
    HighestPfn = (ULONG)(HighestAcceptableAddress.QuadPart >> PAGE_SHIFT);
    if (BaseAddress != NULL) {
        if (MiCheckForContiguousMemory( BaseAddress,
                                        SizeInPages,
                                        HighestPfn)) {

            return BaseAddress;
        } else {

            //
            // The allocation from pool does not meet the contingious
            // requirements. Free the page and see if any of the free
            // pool pages meet the requirement.
            //

            ExFreePool (BaseAddress);
        }
    } else {

        //
        // No pool was available, return NULL.
        //

        return NULL;
    }

    if (KeGetCurrentIrql() > APC_LEVEL) {
        return NULL;
    }

    BaseAddress = NULL;

    i = 3;
    for (; ; ) {
        BaseAddress = MiFindContiguousMemory (HighestPfn, SizeInPages);
        if ((BaseAddress != NULL) || (i == 0)) {
            break;
        }

        MmDelayPageFaults = TRUE;

        //
        // Attempt to move pages to the standby list.
        //

        MiEmptyAllWorkingSets ();
        MiFlushAllPages();

        KeDelayExecutionThread (KernelMode,
                                FALSE,
                                &Mm30Milliseconds);

        i -= 1;
    }
    MmDelayPageFaults = FALSE;
    return BaseAddress;
}

PVOID
MiFindContiguousMemory (
    IN ULONG HighestPfn,
    IN ULONG SizeInPages
    )

/*++

Routine Description:

    This function search nonpaged pool and the free, zeroed,
    and standby lists for contiguous pages that satisfy the
    request.

Arguments:

    HighestPfn - Supplies the highest acceptible physical page number.

    SizeInPages - Supplies the number of pages to allocate.


Return Value:

    NULL - a contiguous range could not be found to satisfy the request.

    NON-NULL - Returns a pointer (virtual address in the nonpaged portion
               of the system) to the allocated phyiscally contiguous
               memory.

Environment:

    Kernel mode, IRQL of APC_LEVEL or below.

--*/
{
    PMMPTE PointerPte;
    PMMPFN Pfn1;
    PVOID BaseAddress = NULL;
    KIRQL OldIrql;
    KIRQL OldIrql2;
    PMMFREE_POOL_ENTRY FreePageInfo;
    PLIST_ENTRY Entry;
    ULONG start;
    ULONG count;
    ULONG Page;
    ULONG found;
    MMPTE TempPte;
    ULONG PageColor;

    PAGED_CODE ();

    //
    // A suitable pool page was not allocated via the pool allocator.
    // Grab the pool lock and manually search of a page which meets
    // the requirements.
    //

    MmLockPagableSectionByHandle (ExPageLockHandle);
    OldIrql = ExLockPool (NonPagedPool);

    //
    // Trace through the page allocators pool headers for a page which
    // meets the requirements.
    //

    //
    // NonPaged pool is linked together through the pages themselves.
    //

    Entry = MmNonPagedPoolFreeListHead.Flink;

    while (Entry != &MmNonPagedPoolFreeListHead) {

        //
        // The list is not empty, see if this one meets the physical
        // requirements.
        //

        FreePageInfo = CONTAINING_RECORD(Entry,
                                         MMFREE_POOL_ENTRY,
                                         List);

        ASSERT (FreePageInfo->Signature == MM_FREE_POOL_SIGNATURE);
        if (FreePageInfo->Size >= SizeInPages) {

            //
            // This entry has sufficient space, check to see if the
            // pages meet the pysical requirements.
            //

            if (MiCheckForContiguousMemory( Entry,
                                            SizeInPages,
                                            HighestPfn)) {

                //
                // These page meet the requirements, note that
                // pages are being removed from the front of
                // the list entry and the whole list entry
                // will be removed and then the remainder inserted.
                //

                RemoveEntryList (&FreePageInfo->List);

                //
                // Adjust the number of free pages remaining in the pool.
                //

                MmNumberOfFreeNonPagedPool -= FreePageInfo->Size;
                ASSERT ((LONG)MmNumberOfFreeNonPagedPool >= 0);
                NonPagedPoolDescriptor.TotalBigPages += FreePageInfo->Size;

                //
                // Mark start and end for the block at the top of the
                // list.
                //

                Entry = PAGE_ALIGN(Entry);
                if (MI_IS_PHYSICAL_ADDRESS(Entry)) {

                    //
                    // On certains architectures (e.g., MIPS) virtual addresses
                    // may be physical and hence have no corresponding PTE.
                    //

                    Pfn1 = MI_PFN_ELEMENT (MI_CONVERT_PHYSICAL_TO_PFN (Entry));
                } else {
                    PointerPte = MiGetPteAddress(Entry);
                    ASSERT (PointerPte->u.Hard.Valid == 1);
                    Pfn1 = MI_PFN_ELEMENT (PointerPte->u.Hard.PageFrameNumber);
                }

                ASSERT (Pfn1->u3.e1.StartOfAllocation == 0);
                Pfn1->u3.e1.StartOfAllocation = 1;

                //
                // Calculate the ending PFN address, note that since
                // these pages are contiguous, just add to the PFN.
                //

                Pfn1 += SizeInPages - 1;
                ASSERT (Pfn1->u3.e1.EndOfAllocation == 0);
                Pfn1->u3.e1.EndOfAllocation = 1;

                MmAllocatedNonPagedPool += FreePageInfo->Size;
                NonPagedPoolDescriptor.TotalBigPages += FreePageInfo->Size;

                if (SizeInPages == FreePageInfo->Size) {

                    //
                    // Unlock the pool and return.
                    //
                    BaseAddress = (PVOID)Entry;
                    goto Done;
                }

                BaseAddress = (PVOID)((PCHAR)Entry + (SizeInPages  << PAGE_SHIFT));

                //
                // Mark start and end of allocation in the PFN database.
                //

                if (MI_IS_PHYSICAL_ADDRESS(BaseAddress)) {

                    //
                    // On certains architectures (e.g., MIPS) virtual addresses
                    // may be physical and hence have no corresponding PTE.
                    //

                    Pfn1 = MI_PFN_ELEMENT (MI_CONVERT_PHYSICAL_TO_PFN (BaseAddress));
                } else {
                    PointerPte = MiGetPteAddress(BaseAddress);
                    ASSERT (PointerPte->u.Hard.Valid == 1);
                    Pfn1 = MI_PFN_ELEMENT (PointerPte->u.Hard.PageFrameNumber);
                }

                ASSERT (Pfn1->u3.e1.StartOfAllocation == 0);
                Pfn1->u3.e1.StartOfAllocation = 1;

                //
                // Calculate the ending PTE's address, can't depend on
                // these pages being physically contiguous.
                //

                if (MI_IS_PHYSICAL_ADDRESS(BaseAddress)) {
                    Pfn1 += FreePageInfo->Size - (SizeInPages + 1);
                } else {
                    PointerPte += FreePageInfo->Size - (SizeInPages + 1);
                    ASSERT (PointerPte->u.Hard.Valid == 1);
                    Pfn1 = MI_PFN_ELEMENT (PointerPte->u.Hard.PageFrameNumber);
                }
                ASSERT (Pfn1->u3.e1.EndOfAllocation == 0);
                Pfn1->u3.e1.EndOfAllocation = 1;

                ASSERT (((ULONG)BaseAddress & (PAGE_SIZE -1)) == 0);

                //
                // Unlock the pool.
                //

                ExUnlockPool (NonPagedPool, OldIrql);

                //
                // Free the entry at BaseAddress back into the pool.
                //

                ExFreePool (BaseAddress);
                BaseAddress = (PVOID)Entry;
                goto Done1;
            }
        }
        Entry = FreePageInfo->List.Flink;
    }

    //
    // No entry was found that meets the requirements.
    // Search the PFN database for pages that meet the
    // requirements.
    //

    start = 0;
    do {

        count = MmPhysicalMemoryBlock->Run[start].PageCount;
        Page = MmPhysicalMemoryBlock->Run[start].BasePage;

        if ((Page <= (1 + HighestPfn - SizeInPages)) &&
            (count >= SizeInPages)) {

            //
            // Check to see if these pages are on the right list.
            //

            found = 0;

            Pfn1 = MI_PFN_ELEMENT (Page);
            LOCK_PFN2 (OldIrql2);
            do {

                if ((Pfn1->u3.e1.PageLocation == ZeroedPageList) ||
                    (Pfn1->u3.e1.PageLocation == FreePageList) ||
                    (Pfn1->u3.e1.PageLocation == StandbyPageList)) {

                    if ((Pfn1->u1.Flink != 0) && (Pfn1->u2.Blink != 0)) {
                        found += 1;
                        if (found == SizeInPages) {

                            //
                            // A match has been found, remove these
                            // pages, add them to the free pool and
                            // return.
                            //

                            Page = 1 + Page - found;

                            //
                            // Try to find system ptes to expand the pool into.
                            //

                            PointerPte = MiReserveSystemPtes (SizeInPages,
                                                              NonPagedPoolExpansion,
                                                              0,
                                                              0,
                                                              FALSE);

                            if (PointerPte == NULL) {
                                UNLOCK_PFN2 (OldIrql2);
                                goto Done;
                            }

                            MmResidentAvailablePages -= SizeInPages;
                            MiChargeCommitmentCantExpand (SizeInPages, TRUE);
                            BaseAddress = MiGetVirtualAddressMappedByPte (PointerPte);
                            PageColor = MI_GET_PAGE_COLOR_FROM_VA(BaseAddress);
                            TempPte = ValidKernelPte;
                            MmAllocatedNonPagedPool += SizeInPages;
                            NonPagedPoolDescriptor.TotalBigPages += SizeInPages;
                            Pfn1 = MI_PFN_ELEMENT (Page - 1);

                            do {
                                Pfn1 += 1;
                                if (Pfn1->u3.e1.PageLocation == StandbyPageList) {
                                    MiUnlinkPageFromList (Pfn1);
                                    MiRestoreTransitionPte (Page);
                                } else {
                                    MiUnlinkFreeOrZeroedPage (Page);
                                }

                                MI_CHECK_PAGE_ALIGNMENT(Page,
                                                        PageColor & MM_COLOR_MASK);
                                Pfn1->u3.e1.PageColor = PageColor & MM_COLOR_MASK;
                                PageColor += 1;
                                TempPte.u.Hard.PageFrameNumber = Page;
                                *PointerPte = TempPte;

                                Pfn1->u3.e2.ReferenceCount = 1;
                                Pfn1->u2.ShareCount = 1;
                                Pfn1->PteAddress = PointerPte;
                                Pfn1->OriginalPte.u.Long = MM_DEMAND_ZERO_WRITE_PTE;
                                Pfn1->PteFrame = MiGetPteAddress(PointerPte)->u.Hard.PageFrameNumber;
                                Pfn1->u3.e1.PageLocation = ActiveAndValid;

                                if (found == SizeInPages) {
                                    Pfn1->u3.e1.StartOfAllocation = 1;
                                }
                                PointerPte += 1;
                                Page += 1;
                                found -= 1;
                            } while (found);

                            Pfn1->u3.e1.EndOfAllocation = 1;
                            UNLOCK_PFN2 (OldIrql2);
                            goto Done;
                        }
                    } else {
                        found = 0;
                    }
                } else {
                    found = 0;
                }
                Page += 1;
                Pfn1 += 1;
                count -= 1;

            } while (count && (Page <= HighestPfn));
            UNLOCK_PFN2 (OldIrql2);
        }
        start += 1;
    } while (start != MmPhysicalMemoryBlock->NumberOfRuns);

Done:

    ExUnlockPool (NonPagedPool, OldIrql);

Done1:

    MmUnlockPagableImageSection (ExPageLockHandle);
    return BaseAddress;
}

VOID
MmFreeContiguousMemory (
    IN PVOID BaseAddress
    )

/*++

Routine Description:

    This function deallocates a range of physically contiguous non-paged
    pool which was allocated with the MmAllocateContiguousMemory function.

Arguments:

    BaseAddress - Supplies the base virtual address where the physical
                  address was previously mapped.

Return Value:

    None.

Environment:

    Kernel mode, IRQL of APC_LEVEL or below.

--*/

{
    PAGED_CODE();
    ExFreePool (BaseAddress);
    return;
}

PHYSICAL_ADDRESS
MmGetPhysicalAddress (
     IN PVOID BaseAddress
     )

/*++

Routine Description:

    This function returns the corresponding physical address for a
    valid virtual address.

Arguments:

    BaseAddress - Supplies the virtual address for which to return the
                  physical address.

Return Value:

    Returns the corresponding physical address.

Environment:

    Kernel mode.  Any IRQL level.

--*/

{
    PMMPTE PointerPte;
    PHYSICAL_ADDRESS PhysicalAddress;

    if (MI_IS_PHYSICAL_ADDRESS(BaseAddress)) {
        PhysicalAddress.LowPart = MI_CONVERT_PHYSICAL_TO_PFN (BaseAddress);
    } else {

        PointerPte = MiGetPteAddress(BaseAddress);

        if (PointerPte->u.Hard.Valid == 0) {
            KdPrint(("MM:MmGetPhysicalAddressFailed base address was %lx",
                      BaseAddress));
            ZERO_LARGE (PhysicalAddress);
            return PhysicalAddress;
        }
        PhysicalAddress.LowPart = PointerPte->u.Hard.PageFrameNumber;
    }

    PhysicalAddress.HighPart = 0;
    PhysicalAddress.QuadPart = PhysicalAddress.QuadPart << PAGE_SHIFT;
    PhysicalAddress.LowPart += BYTE_OFFSET(BaseAddress);

    return PhysicalAddress;
}

PVOID
MmGetVirtualForPhysical (
    IN PHYSICAL_ADDRESS PhysicalAddress
     )

/*++

Routine Description:

    This function returns the corresponding virtual address for a physical
    address whose primary virtual address is in system space.

Arguments:

    PhysicalAddress - Supplies the physical address for which to return the
                  virtual address.

Return Value:

    Returns the corresponding virtual address.

Environment:

    Kernel mode.  Any IRQL level.

--*/

{
    ULONG PageFrameIndex;
    PMMPFN Pfn;

    PageFrameIndex = (ULONG)(PhysicalAddress.QuadPart >> PAGE_SHIFT);

    Pfn = MI_PFN_ELEMENT (PageFrameIndex);

    return (PVOID)((PCHAR)MiGetVirtualAddressMappedByPte (Pfn->PteAddress) +
                    BYTE_OFFSET (PhysicalAddress.LowPart));
}

PVOID
MmAllocateNonCachedMemory (
    IN ULONG NumberOfBytes
    )

/*++

Routine Description:

    This function allocates a range of noncached memory in
    the non-paged portion of the system address space.

    This routine is designed to be used by a driver's initialization
    routine to allocate a noncached block of virtual memory for
    various device specific buffers.

Arguments:

    NumberOfBytes - Supplies the number of bytes to allocate.

Return Value:

    NULL - the specified request could not be satisfied.

    NON-NULL - Returns a pointer (virtual address in the nonpaged portion
               of the system) to the allocated phyiscally contiguous
               memory.

Environment:

    Kernel mode, IRQL of APC_LEVEL or below.

--*/

{
    PMMPTE PointerPte;
    MMPTE TempPte;
    ULONG NumberOfPages;
    ULONG PageFrameIndex;
    PVOID BaseAddress;
    KIRQL OldIrql;

    MmLockPagableSectionByHandle (ExPageLockHandle);

    ASSERT (NumberOfBytes != 0);

    //
    // Acquire the PFN mutex to synchronize access to the pfn database.
    //

    LOCK_PFN (OldIrql);

    //
    // Obtain enough pages to contain the allocation.
    // the system PTE pool.  The system PTE pool contains non-paged PTEs
    // which are currently empty.
    //

    NumberOfPages = BYTES_TO_PAGES(NumberOfBytes);

    //
    // Check to make sure the phyiscal pages are available.
    //

    if (MmResidentAvailablePages <= (LONG)NumberOfPages) {
        BaseAddress = NULL;
        goto Done;
    }

    PointerPte = MiReserveSystemPtes (NumberOfPages,
                                      SystemPteSpace,
                                      0,
                                      0,
                                      FALSE);
    if (PointerPte == NULL) {
        BaseAddress = NULL;
        goto Done;
    }

    MmResidentAvailablePages -= (LONG)NumberOfPages;
    MiChargeCommitmentCantExpand (NumberOfPages, TRUE);

    BaseAddress = (PVOID)MiGetVirtualAddressMappedByPte (PointerPte);

    do {
        ASSERT (PointerPte->u.Hard.Valid == 0);
        MiEnsureAvailablePageOrWait (NULL, NULL);
        PageFrameIndex = MiRemoveAnyPage (MI_GET_PAGE_COLOR_FROM_PTE (PointerPte));

        MI_MAKE_VALID_PTE (TempPte,
                           PageFrameIndex,
                           MM_READWRITE,
                           PointerPte);

        MI_SET_PTE_DIRTY (TempPte);
        MI_DISABLE_CACHING (TempPte);
        *PointerPte = TempPte;
        MiInitializePfn (PageFrameIndex, PointerPte, 1);
        PointerPte += 1;
        NumberOfPages -= 1;
    } while (NumberOfPages != 0);

    //
    // Flush any data for this page out of the dcaches.
    //

    KeSweepDcache (TRUE);

Done:
    UNLOCK_PFN (OldIrql);
    MmUnlockPagableImageSection (ExPageLockHandle);

    return BaseAddress;
}

VOID
MmFreeNonCachedMemory (
    IN PVOID BaseAddress,
    IN ULONG NumberOfBytes
    )

/*++

Routine Description:

    This function deallocates a range of noncached memory in
    the non-paged portion of the system address space.

Arguments:

    BaseAddress - Supplies the base virtual address where the noncached
                  memory resides.

    NumberOfBytes - Supplies the number of bytes allocated to the requst.
                    This must be the same number that was obtained with
                    the MmAllocateNonCachedMemory call.

Return Value:

    None.

Environment:

    Kernel mode, IRQL of APC_LEVEL or below.

--*/

{

    PMMPTE PointerPte;
    PMMPFN Pfn1;
    ULONG NumberOfPages;
    ULONG i;
    ULONG PageFrameIndex;
    KIRQL OldIrql;

    ASSERT (NumberOfBytes != 0);
    ASSERT (PAGE_ALIGN (BaseAddress) == BaseAddress);
    MI_MAKING_MULTIPLE_PTES_INVALID (TRUE);

    NumberOfPages = BYTES_TO_PAGES(NumberOfBytes);

    PointerPte = MiGetPteAddress (BaseAddress);

    MmLockPagableSectionByHandle (ExPageLockHandle);

    LOCK_PFN (OldIrql);

    i = NumberOfPages;

    do {


        PageFrameIndex = PointerPte->u.Hard.PageFrameNumber;

        //
        // Set the pointer to PTE as empty so the page
        // is deleted when the reference count goes to zero.
        //

        Pfn1 = MI_PFN_ELEMENT (PageFrameIndex);
        ASSERT (Pfn1->u2.ShareCount == 1);
        MiDecrementShareAndValidCount (Pfn1->PteFrame);
        MI_SET_PFN_DELETED (Pfn1);
        MiDecrementShareCountOnly (PageFrameIndex);
        PointerPte += 1;
        i -= 1;
    } while (i != 0);

    PointerPte -= NumberOfPages;

    MiReleaseSystemPtes (PointerPte, NumberOfPages, SystemPteSpace);

    //
    // Update the count of available resident pages.
    //

    MmResidentAvailablePages += NumberOfPages;
    MiReturnCommitment (NumberOfPages);

    UNLOCK_PFN (OldIrql);

    MmUnlockPagableImageSection (ExPageLockHandle);
    return;
}

ULONG
MmSizeOfMdl (
    IN PVOID Base,
    IN ULONG Length
    )

/*++

Routine Description:

    This function returns the number of bytes required for an MDL for a
    given buffer and size.

Arguments:

    Base - Supplies the base virtual address for the buffer.

    Length - Supplies the size of the buffer in bytes.

Return Value:

    Returns the number of bytes required to contain the MDL.

Environment:

    Kernel mode.  Any IRQL level.

--*/

{
    return( sizeof( MDL ) +
                (ADDRESS_AND_SIZE_TO_SPAN_PAGES( Base, Length ) *
                 sizeof( ULONG ))
          );
}



PMDL
MmCreateMdl (
    IN PMDL MemoryDescriptorList OPTIONAL,
    IN PVOID Base,
    IN ULONG Length
    )

/*++

Routine Description:

    This function optionally allocates and initializes an MDL.

Arguments:

    MemoryDescriptorList - Optionally supplies the address of the MDL
        to initialize.  If this address is supplied as NULL an MDL is
        allocated from non-paged pool and initialized.

    Base - Supplies the base virtual address for the buffer.

    Length - Supplies the size of the buffer in bytes.

Return Value:

    Returns the address of the initialized MDL.

Environment:

    Kernel mode, IRQL of DISPATCH_LEVEL or below.

--*/

{
    ULONG MdlSize;

    MdlSize = MmSizeOfMdl( Base, Length );

    if (!ARGUMENT_PRESENT( MemoryDescriptorList )) {
        MemoryDescriptorList = (PMDL)ExAllocatePoolWithTag (
                                                     NonPagedPoolMustSucceed,
                                                     MdlSize,
                                                     'ldmM');
    }

    MmInitializeMdl( MemoryDescriptorList, Base, Length );
    return ( MemoryDescriptorList );
}

BOOLEAN
MmSetAddressRangeModified (
    IN PVOID Address,
    IN ULONG Length
    )

/*++

Routine Description:

    This routine sets the modified bit in the PFN database for the
    pages that correspond to the specified address range.

    Note that the dirty bit in the PTE is cleared by this operation.

Arguments:

    Address - Supplies the address of the start of the range.  This
              range must reside within the system cache.

    Length - Supplies the length of the range.

Return Value:

    TRUE if at least one PTE was dirty in the range, FALSE otherwise.

Environment:

    Kernel mode.  APC_LEVEL and below for pageable addresses,
                  DISPATCH_LEVEL and below for non-pageable addresses.

--*/

{
    PMMPTE PointerPte;
    PMMPTE LastPte;
    PMMPFN Pfn1;
    PMMPTE FlushPte;
    MMPTE PteContents;
    MMPTE FlushContents;
    KIRQL OldIrql;
    PVOID VaFlushList[MM_MAXIMUM_FLUSH_COUNT];
    ULONG Count = 0;
    BOOLEAN Result = FALSE;

    //
    // Loop on the copy on write case until the page is only
    // writable.
    //

    PointerPte = MiGetPteAddress (Address);
    LastPte = MiGetPteAddress ((PVOID)((PCHAR)Address + Length - 1));

    LOCK_PFN2 (OldIrql);

    do {


        PteContents = *PointerPte;

        if (PteContents.u.Hard.Valid == 1) {

            Pfn1 = MI_PFN_ELEMENT (PteContents.u.Hard.PageFrameNumber);
            Pfn1->u3.e1.Modified = 1;

            if ((Pfn1->OriginalPte.u.Soft.Prototype == 0) &&
                         (Pfn1->u3.e1.WriteInProgress == 0)) {
                MiReleasePageFileSpace (Pfn1->OriginalPte);
                Pfn1->OriginalPte.u.Soft.PageFileHigh = 0;
            }

#ifdef NT_UP
            //
            // On uniprocessor systems no need to flush if this processor
            // doesn't think the PTE is dirty.
            //

            if (MI_IS_PTE_DIRTY (PteContents)) {
                Result = TRUE;
#else  //NT_UP
                Result |= (BOOLEAN)(MI_IS_PTE_DIRTY (PteContents));
#endif //NT_UP
                MI_SET_PTE_CLEAN (PteContents);
                *PointerPte = PteContents;
                FlushContents = PteContents;
                FlushPte = PointerPte;

                //
                // Clear the write bit in the PTE so new writes can be tracked.
                //

                if (Count != MM_MAXIMUM_FLUSH_COUNT) {
                    VaFlushList[Count] = Address;
                    Count += 1;
                }
#ifdef NT_UP
            }
#endif //NT_UP
        }
        PointerPte += 1;
        Address = (PVOID)((PCHAR)Address + PAGE_SIZE);
    } while (PointerPte <= LastPte);

    if (Count != 0) {
        if (Count == 1) {

            (VOID)KeFlushSingleTb (VaFlushList[0],
                                   FALSE,
                                   TRUE,
                                   (PHARDWARE_PTE)FlushPte,
                                   FlushContents.u.Flush);

        } else if (Count != MM_MAXIMUM_FLUSH_COUNT) {

            KeFlushMultipleTb (Count,
                               &VaFlushList[0],
                               FALSE,
                               TRUE,
                               NULL,
                               ZeroPte.u.Flush);

        } else {
            KeFlushEntireTb (FALSE, TRUE);
        }
    }
    UNLOCK_PFN2 (OldIrql);
    return Result;
}


BOOLEAN
MiCheckForContiguousMemory (
    IN PVOID BaseAddress,
    IN ULONG SizeInPages,
    IN ULONG HighestPfn
    )

/*++

Routine Description:

    This routine checks to see if the physical memory mapped
    by the specified BaseAddress for the specified size is
    contiguous and the last page of the physical memory is
    less than or equal to the specified HighestPfn.

Arguments:

    BaseAddress - Supplies the base address to start checking at.

    SizeInPages - Supplies the number of pages in the range.

    HighestPfn  - Supplies the highest PFN acceptable as a physical page.

Return Value:

    Returns TRUE if the physical memory is contiguous and less than
    or equal to the HighestPfn, FALSE otherwise.

Environment:

    Kernel mode, memory mangement internal.

--*/

{
    PMMPTE PointerPte;
    PMMPTE LastPte;
    ULONG PageFrameIndex;

    if (MI_IS_PHYSICAL_ADDRESS (BaseAddress)) {
        if (HighestPfn >=
                (MI_CONVERT_PHYSICAL_TO_PFN(BaseAddress) + SizeInPages - 1)) {
            return TRUE;
        } else {
            return FALSE;
        }
    } else {
        PointerPte = MiGetPteAddress (BaseAddress);
        LastPte = PointerPte + SizeInPages;
        PageFrameIndex = PointerPte->u.Hard.PageFrameNumber + 1;
        PointerPte += 1;

        //
        // Check to see if the range of physical addresses is contiguous.
        //

        while (PointerPte < LastPte) {
            if (PointerPte->u.Hard.PageFrameNumber != PageFrameIndex) {

                //
                // Memory is not physically contiguous.
                //

                return FALSE;
            }
            PageFrameIndex += 1;
            PointerPte += 1;
        }
    }

    if (PageFrameIndex <= HighestPfn) {
        return TRUE;
    }
    return FALSE;
}


VOID
MmLockPagableSectionByHandle (
    IN PVOID ImageSectionHandle
    )


/*++

Routine Description:

    This routine checks to see if the specified pages are resident in
    the process's working set and if so the reference count for the
    page is incremented.  The allows the virtual address to be accessed
    without getting a hard page fault (have to go to the disk... except
    for extremely rare case when the page table page is removed from the
    working set and migrates to the disk.

    If the virtual address is that of the system wide global "cache" the
    virtual adderss of the "locked" pages is always guarenteed to
    be valid.

    NOTE: This routine is not to be used for general locking of user
    addresses - use MmProbeAndLockPages.  This routine is intended for
    well behaved system code like the file system caches which allocates
    virtual addresses for mapping files AND guarantees that the mapping
    will not be modified (deleted or changed) while the pages are locked.

Arguments:

    ImageSectionHandle - Supplies the value returned by a previous call
        to MmLockPagableDataSection.  This is a pointer to the Section
        header for the image.

Return Value:

    None.

Environment:

    Kernel mode, IRQL of DISPATCH_LEVEL or below.

--*/

{
    PIMAGE_SECTION_HEADER NtSection;
    PVOID BaseAddress;
    ULONG SizeToLock;
    PMMPTE PointerPte;
    PMMPTE LastPte;
    KIRQL OldIrql;
    ULONG Collision;

    if (MI_IS_PHYSICAL_ADDRESS(ImageSectionHandle)) {

        //
        // No need to lock physical addresses.
        //

        return;
    }

    NtSection = (PIMAGE_SECTION_HEADER)ImageSectionHandle;

    BaseAddress = (PVOID)NtSection->PointerToLinenumbers;

    ASSERT ((BaseAddress < (PVOID)MM_SYSTEM_CACHE_START) ||
        (BaseAddress >= (PVOID)MM_SYSTEM_CACHE_END));
    ASSERT (BaseAddress >= (PVOID)MM_SYSTEM_RANGE_START);

    SizeToLock = NtSection->SizeOfRawData;
    PointerPte = MiGetPteAddress(BaseAddress);
    LastPte = MiGetPteAddress((PCHAR)BaseAddress + SizeToLock - 1);

    ASSERT (SizeToLock != 0);

    //
    // The address must be within the system space.
    //

RetryLock:

    LOCK_PFN2 (OldIrql);

    MiMakeSystemAddressValidPfn (&NtSection->NumberOfLinenumbers);

    //
    // The NumberOfLinenumbers field is used to store the
    // lock count.
    //
    //  Value of 0 means unlocked,
    //  Value of 1 means lock in progress by another thread.
    //  Value of 2 or more means locked.
    //
    //  If the value is 1, this thread must block until the other thread's
    //  lock operation is complete.
    //

    NtSection->NumberOfLinenumbers += 1;

    if (NtSection->NumberOfLinenumbers >= 3) {

        //
        // Already locked, increment counter and return.
        //

        UNLOCK_PFN2 (OldIrql);
        return;

    }

    if (NtSection->NumberOfLinenumbers == 2) {

        //
        // A lock is in progress.
        // Reset to back to 1 and wait.
        //

        NtSection->NumberOfLinenumbers = 1;
        MmCollidedLockWait = TRUE;

        KeEnterCriticalRegion();
        UNLOCK_PFN_AND_THEN_WAIT (OldIrql);

        KeWaitForSingleObject(&MmCollidedLockEvent,
                              WrVirtualMemory,
                              KernelMode,
                              FALSE,
                              (PLARGE_INTEGER)NULL);
        KeLeaveCriticalRegion();
        goto RetryLock;
    }

    //
    // Value was 0 when the lock was obtained.  It is now 1 indicating
    // a lock is in progress.
    //

    MiLockCode (PointerPte, LastPte, MM_LOCK_BY_REFCOUNT);

    //
    // Set lock count to 2 (it was 1 when this started) and check
    // to see if any other threads tried to lock while this was happening.
    //

    MiMakeSystemAddressValidPfn (&NtSection->NumberOfLinenumbers);
    NtSection->NumberOfLinenumbers += 1;

    ASSERT (NtSection->NumberOfLinenumbers == 2);

    Collision = MmCollidedLockWait;
    MmCollidedLockWait = FALSE;

    UNLOCK_PFN2 (OldIrql);

    if (Collision) {

        //
        // Wake up all waiters.
        //

        KePulseEvent (&MmCollidedLockEvent, 0, FALSE);
    }

    return;
}


VOID
MiLockCode (
    IN PMMPTE FirstPte,
    IN PMMPTE LastPte,
    IN ULONG LockType
    )

/*++

Routine Description:

    This routine checks to see if the specified pages are resident in
    the process's working set and if so the reference count for the
    page is incremented.  The allows the virtual address to be accessed
    without getting a hard page fault (have to go to the disk... except
    for extremely rare case when the page table page is removed from the
    working set and migrates to the disk.

    If the virtual address is that of the system wide global "cache" the
    virtual adderss of the "locked" pages is always guarenteed to
    be valid.

    NOTE: This routine is not to be used for general locking of user
    addresses - use MmProbeAndLockPages.  This routine is intended for
    well behaved system code like the file system caches which allocates
    virtual addresses for mapping files AND guarantees that the mapping
    will not be modified (deleted or changed) while the pages are locked.

Arguments:

    FirstPte - Supplies the base address to begin locking.

    LastPte - The last PTE to lock.

    LockType - Supplies either MM_LOCK_BY_REFCOUNT or MM_LOCK_NONPAGE.
               LOCK_BY_REFCOUNT increments the reference count to keep
               the page in memory, LOCK_NONPAGE removes the page from
               the working set so it's locked just like nonpaged pool.

Return Value:

    None.

Environment:

    Kernel mode, PFN LOCK held.

--*/

{
    PMMPFN Pfn1;
    PMMPTE PointerPte;
    MMPTE TempPte;
    MMPTE PteContents;
    ULONG WorkingSetIndex;
    ULONG PageFrameIndex;
    KIRQL OldIrql1;
    KIRQL OldIrql;

    MM_PFN_LOCK_ASSERT();

    ASSERT (!MI_IS_PHYSICAL_ADDRESS(MiGetVirtualAddressMappedByPte(FirstPte)));
    PointerPte = FirstPte;

    MmLockedCode += 1 + LastPte - FirstPte;

    do {

        PteContents = *PointerPte;
        ASSERT (PteContents.u.Long != ZeroKernelPte.u.Long);
        if (PteContents.u.Hard.Valid == 0) {

            ASSERT (PteContents.u.Soft.Prototype != 1);

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

                PageFrameIndex = PteContents.u.Trans.PageFrameNumber;
                Pfn1 = MI_PFN_ELEMENT (PageFrameIndex);
                if ((Pfn1->u3.e1.ReadInProgress) ||
                    (Pfn1->u3.e1.InPageError)) {

                    //
                    // Page read is ongoing, wait for the read to
                    // complete then retest.
                    //

                    OldIrql = APC_LEVEL;
                    KeEnterCriticalRegion();
                    UNLOCK_PFN_AND_THEN_WAIT (OldIrql);
                    KeWaitForSingleObject( Pfn1->u1.Event,
                                           WrPageIn,
                                           KernelMode,
                                           FALSE,
                                           (PLARGE_INTEGER)NULL);
                    KeLeaveCriticalRegion();

                    //
                    // Need to delay so the faulting thread can
                    // perform the inpage completion.
                    //

                    KeDelayExecutionThread (KernelMode,
                                            FALSE,
                                            &MmShortTime);

                    LOCK_PFN (OldIrql);
                    continue;
                }

                MiUnlinkPageFromList (Pfn1);

                //
                // Set the reference count and share counts to 1.
                //

                Pfn1->u3.e2.ReferenceCount += 1;
                Pfn1->u2.ShareCount = 1;
                Pfn1->u3.e1.PageLocation = ActiveAndValid;

                MI_MAKE_VALID_PTE (TempPte,
                               PageFrameIndex,
                               Pfn1->OriginalPte.u.Soft.Protection,
                               PointerPte );

                *PointerPte = TempPte;

                //
                // Increment the reference count one for putting it the
                // working set list and one for locking it for I/O.
                //

                if (LockType == MM_LOCK_BY_REFCOUNT) {

                    //
                    // Lock the page in the working set by upping the
                    // refernece count.
                    //

                    Pfn1->u3.e2.ReferenceCount += 1;
                    Pfn1->u1.WsIndex = (ULONG)PsGetCurrentThread();

                    UNLOCK_PFN (APC_LEVEL);
                    LOCK_SYSTEM_WS (OldIrql);
                    WorkingSetIndex = MiLocateAndReserveWsle (&MmSystemCacheWs);

                    MiUpdateWsle (&WorkingSetIndex,
                                  MiGetVirtualAddressMappedByPte (PointerPte),
                                  MmSystemCacheWorkingSetList,
                                  Pfn1);
                    UNLOCK_SYSTEM_WS (OldIrql);
                    LOCK_PFN (OldIrql);
                } else {

                    //
                    // Set the wsindex field to zero, indicating that the
                    // page is not in the system working set.
                    //

                    ASSERT (Pfn1->u1.WsIndex == 0);
                }

            } else {

                //
                // Page is not in memory.
                //

                MiMakeSystemAddressValidPfn (
                        MiGetVirtualAddressMappedByPte(PointerPte));

                continue;
            }

        } else {

            //
            // This address is already in the system working set.
            //

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

            //
            // Up the reference count so the page cannot be released.
            //

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

            if (LockType != MM_LOCK_BY_REFCOUNT) {

                //
                // If the page is in the system working set, remove it.
                // The system working set lock MUST be owned to check to
                // see if this page is in the working set or not.  This
                // is because the pager may have just release the PFN lock,
                // acquired the system lock and is now trying to add the
                // page to the system working set.
                //

                UNLOCK_PFN (APC_LEVEL);
                LOCK_SYSTEM_WS (OldIrql1);

                if (Pfn1->u1.WsIndex != 0) {
                    MiRemoveWsle (Pfn1->u1.WsIndex,
                                  MmSystemCacheWorkingSetList );
                    MiReleaseWsle (Pfn1->u1.WsIndex, &MmSystemCacheWs);
                    Pfn1->u1.WsIndex = 0;
                }
                UNLOCK_SYSTEM_WS (OldIrql1);
                LOCK_PFN (OldIrql);
                ASSERT (Pfn1->u3.e2.ReferenceCount > 1);
                Pfn1->u3.e2.ReferenceCount -= 1;
            }
        }

        PointerPte += 1;
    } while (PointerPte <= LastPte);

    return;
}


PVOID
MmLockPagableDataSection(
    IN PVOID AddressWithinSection
    )

/*++

Routine Description:

    This functions locks the entire section that contains the specified
    section in memory.  This allows pagable code to be brought into
    memory and to be used as if the code was not really pagable.  This
    should not be done with a high degree of frequency.

Arguments:

    AddressWithinSection - Supplies the address of a function
        contained within a section that should be brought in and locked
        in memory.

Return Value:

    This function returns a value to be used in a subsequent call to
    MmUnlockPagableImageSection.

--*/

{
    PLDR_DATA_TABLE_ENTRY DataTableEntry;
    ULONG i;
    PIMAGE_NT_HEADERS NtHeaders;
    PIMAGE_SECTION_HEADER NtSection;
    PIMAGE_SECTION_HEADER FoundSection;
    ULONG Rva;

    PAGED_CODE();

    if (MI_IS_PHYSICAL_ADDRESS(AddressWithinSection)) {

        //
        // Physical address, just return that as the handle.
        //

        return AddressWithinSection;
    }

    //
    // Search the loaded module list for the data table entry that describes
    // the DLL that was just unloaded. It is possible an entry is not in the
    // list if a failure occured at a point in loading the DLL just before
    // the data table entry was generated.
    //

    FoundSection = NULL;

    KeEnterCriticalRegion();
    ExAcquireResourceShared (&PsLoadedModuleResource, TRUE);

    DataTableEntry = MiLookupDataTableEntry (AddressWithinSection, TRUE);

    Rva = (ULONG)((PUCHAR)AddressWithinSection - (ULONG)DataTableEntry->DllBase);

    NtHeaders = (PIMAGE_NT_HEADERS)RtlImageNtHeader(DataTableEntry->DllBase);

    NtSection = (PIMAGE_SECTION_HEADER)((ULONG)NtHeaders +
                        sizeof(ULONG) +
                        sizeof(IMAGE_FILE_HEADER) +
                        NtHeaders->FileHeader.SizeOfOptionalHeader
                        );

    for (i = 0; i < NtHeaders->FileHeader.NumberOfSections; i++) {

        if ( Rva >= NtSection->VirtualAddress &&
             Rva < NtSection->VirtualAddress + NtSection->SizeOfRawData ) {
            FoundSection = NtSection;

            if (NtSection->PointerToLinenumbers != (ULONG)((PUCHAR)DataTableEntry->DllBase +
                            NtSection->VirtualAddress)) {

                //
                // Stomp on the PointerToLineNumbers field so that it contains
                // the Va of this section and NumberOFLinenumbers so it contains
                // the Lock Count for the section.
                //

                NtSection->PointerToLinenumbers = (ULONG)((PUCHAR)DataTableEntry->DllBase +
                                        NtSection->VirtualAddress);
                NtSection->NumberOfLinenumbers = 0;
            }

            //
            // Now lock in the code
            //

#if DBG
            if (MmDebug & MM_DBG_LOCK_CODE) {
                DbgPrint("MM Lock %wZ %8s 0x%08x -> 0x%8x : 0x%08x %3ld.\n",
                        &DataTableEntry->BaseDllName,
                        NtSection->Name,
                        AddressWithinSection,
                        NtSection,
                        NtSection->PointerToLinenumbers,
                        NtSection->NumberOfLinenumbers);
            }
#endif //DBG

            MmLockPagableSectionByHandle ((PVOID)NtSection);

            goto found_the_section;
        }
        NtSection++;
    }

found_the_section:

    ExReleaseResource (&PsLoadedModuleResource);
    KeLeaveCriticalRegion();
    if (!FoundSection) {
        KeBugCheckEx (MEMORY_MANAGEMENT,
                      0x1234,
                      (ULONG)AddressWithinSection,
                      0,
                      0);
    }
    return (PVOID)FoundSection;
}


PLDR_DATA_TABLE_ENTRY
MiLookupDataTableEntry (
    IN PVOID AddressWithinSection,
    IN ULONG ResourceHeld
    )

/*++

Routine Description:

    This functions locks the entire section that contains the specified
    section in memory.  This allows pagable code to be brought into
    memory and to be used as if the code was not really pagable.  This
    should not be done with a high degree of frequency.

Arguments:

    AddressWithinSection - Supplies the address of a function
        contained within a section that should be brought in and locked
        in memory.

    ResourceHeld - Supplies true if the data table resource lock is
                   already held.

Return Value:

    This function returns a value to be used in a subsequent call to
    MmUnlockPagableImageSection.

--*/

{
    PLDR_DATA_TABLE_ENTRY DataTableEntry;
    PLDR_DATA_TABLE_ENTRY FoundEntry = NULL;
    PLIST_ENTRY NextEntry;

    PAGED_CODE();

    //
    // Search the loaded module list for the data table entry that describes
    // the DLL that was just unloaded. It is possible an entry is not in the
    // list if a failure occured at a point in loading the DLL just before
    // the data table entry was generated.
    //

    if (!ResourceHeld) {
        KeEnterCriticalRegion();
        ExAcquireResourceShared (&PsLoadedModuleResource, TRUE);
    }

    NextEntry = PsLoadedModuleList.Flink;
    do {

        DataTableEntry = CONTAINING_RECORD(NextEntry,
                                           LDR_DATA_TABLE_ENTRY,
                                           InLoadOrderLinks);

        //
        // Locate the loaded module that contains this address.
        //

        if ( AddressWithinSection >= DataTableEntry->DllBase &&
             AddressWithinSection < (PVOID)((PUCHAR)DataTableEntry->DllBase+DataTableEntry->SizeOfImage) ) {

            FoundEntry = DataTableEntry;
            break;
        }

        NextEntry = NextEntry->Flink;
    } while (NextEntry != &PsLoadedModuleList);

    if (!ResourceHeld) {
        ExReleaseResource (&PsLoadedModuleResource);
        KeLeaveCriticalRegion();
    }
    return FoundEntry;
}

VOID
MmUnlockPagableImageSection(
    IN PVOID ImageSectionHandle
    )

/*++

Routine Description:

    This function unlocks from memory, the pages locked by a preceding call to
    MmLockPagableDataSection.

Arguments:

    ImageSectionHandle - Supplies the value returned by a previous call
        to MmLockPagableDataSection.

Return Value:

    None.

--*/

{
    PIMAGE_SECTION_HEADER NtSection;
    PMMPTE PointerPte;
    PMMPTE LastPte;
    KIRQL OldIrql;
    PVOID BaseAddress;
    ULONG SizeToUnlock;
    ULONG Collision;

    if (MI_IS_PHYSICAL_ADDRESS(ImageSectionHandle)) {

        //
        // No need to lock physical addresses.
        //

        return;
    }

    NtSection = (PIMAGE_SECTION_HEADER)ImageSectionHandle;

    BaseAddress = (PVOID)NtSection->PointerToLinenumbers;
    SizeToUnlock = NtSection->SizeOfRawData;

    //DbgPrint("MM Unlock %s 0x%08x\n",NtSection->Name,NtSection->PointerToLinenumbers);

    PointerPte = MiGetPteAddress(BaseAddress);
    LastPte = MiGetPteAddress((PCHAR)BaseAddress + SizeToUnlock - 1);

    //
    // Address must be within the system cache.
    //

    LOCK_PFN2 (OldIrql);

    //
    // The NumberOfLinenumbers field is used to store the
    // lock count.
    //

    ASSERT (NtSection->NumberOfLinenumbers >= 2);
    NtSection->NumberOfLinenumbers -= 1;

    if (NtSection->NumberOfLinenumbers != 1) {
        UNLOCK_PFN2 (OldIrql);
        return;
    }

    do {

#if DBG
        {   PMMPFN Pfn;
            ASSERT (PointerPte->u.Hard.Valid == 1);
            Pfn = MI_PFN_ELEMENT (PointerPte->u.Hard.PageFrameNumber);
            ASSERT (Pfn->u3.e2.ReferenceCount > 1);
        }
#endif //DBG

        MiDecrementReferenceCount (PointerPte->u.Hard.PageFrameNumber);
        PointerPte += 1;
    } while (PointerPte <= LastPte);

    NtSection->NumberOfLinenumbers -= 1;
    ASSERT (NtSection->NumberOfLinenumbers == 0);
    Collision = MmCollidedLockWait;
    MmCollidedLockWait = FALSE;
    MmLockedCode -= SizeToUnlock;

    UNLOCK_PFN2 (OldIrql);

    if (Collision) {
        KePulseEvent (&MmCollidedLockEvent, 0, FALSE);
    }

    return;
}


BOOLEAN
MmIsRecursiveIoFault(
    VOID
    )

/*++

Routine Description:

    This function examines the thread's page fault clustering information
    and determines if the current page fault is occuring during an I/O
    operation.

Arguments:

    None.

Return Value:

    Returns TRUE if the fault is occuring during an I/O operation,
    FALSE otherwise.

--*/

{
    return PsGetCurrentThread()->DisablePageFaultClustering |
           PsGetCurrentThread()->ForwardClusterOnly;
}


VOID
MmMapMemoryDumpMdl(
    IN OUT PMDL MemoryDumpMdl
    )

/*++

Routine Description:

    For use by crash dump routine ONLY.  Maps an MDL into a fixed
    portion of the address space.  Only 1 mdl can be mapped at a
    time.

Arguments:

    MemoryDumpMdl - Supplies the MDL to map.

Return Value:

    None, fields in MDL updated.

--*/

{
    ULONG NumberOfPages;
    PMMPTE PointerPte;
    PCHAR BaseVa;
    MMPTE TempPte;
    PULONG Page;

    NumberOfPages = BYTES_TO_PAGES (MemoryDumpMdl->ByteCount + MemoryDumpMdl->ByteOffset);

    PointerPte = MmCrashDumpPte;
    BaseVa = (PCHAR)MiGetVirtualAddressMappedByPte(PointerPte);
    MemoryDumpMdl->MappedSystemVa = (PCHAR)BaseVa + MemoryDumpMdl->ByteOffset;
    TempPte = ValidKernelPte;
    Page = (PULONG)(MemoryDumpMdl + 1);

    do {

        KiFlushSingleTb (TRUE, BaseVa);
        ASSERT ((*Page <= MmHighestPhysicalPage) &&
                (*Page >= MmLowestPhysicalPage));

        TempPte.u.Hard.PageFrameNumber = *Page;
        *PointerPte = TempPte;

        Page++;
        PointerPte++;
        BaseVa += PAGE_SIZE;
        NumberOfPages -= 1;
    } while (NumberOfPages != 0);

    PointerPte->u.Long = MM_KERNEL_DEMAND_ZERO_PTE;
    return;
}


NTSTATUS
MmSetBankedSection (
    IN HANDLE ProcessHandle,
    IN PVOID VirtualAddress,
    IN ULONG BankLength,
    IN BOOLEAN ReadWriteBank,
    IN PBANKED_SECTION_ROUTINE BankRoutine,
    IN PVOID Context
    )

/*++

Routine Description:

    This function declares a mapped video buffer as a banked
    section.  This allows banked video devices (i.e., even
    though the video controller has a megabyte or so of memory,
    only a small bank (like 64k) can be mapped at any one time.

    In order to overcome this problem, the pager handles faults
    to this memory, unmaps the current bank, calls off to the
    video driver and then maps in the new bank.

    This function creates the neccessary structures to allow the
    video driver to be called from the pager.

 ********************* NOTE NOTE NOTE *************************
    At this time only read/write banks are supported!

Arguments:

    ProcessHandle - Supplies a handle to the process in which to
                    support the banked video function.

    VirtualAddress - Supplies the virtual address where the video
                     buffer is mapped in the specified process.

    BankLength - Supplies the size of the bank.

    ReadWriteBank - Supplies TRUE if the bank is read and write.

    BankRoutine - Supplies a pointer to the routine that should be
                  called by the pager.

    Context - Supplies a context to be passed by the pager to the
              BankRoutine.

Return Value:

    Returns the status of the function.

Environment:

    Kernel mode, APC_LEVEL or below.

--*/

{
    NTSTATUS Status;
    PEPROCESS Process;
    PMMVAD Vad;
    PMMPTE PointerPte;
    PMMPTE LastPte;
    MMPTE TempPte;
    ULONG size;
    LONG count;
    ULONG NumberOfPtes;
    PMMBANKED_SECTION Bank;

    PAGED_CODE ();

    //
    // Reference the specified process handle for VM_OPERATION access.
    //

    Status = ObReferenceObjectByHandle ( ProcessHandle,
                                         PROCESS_VM_OPERATION,
                                         PsProcessType,
                                         KernelMode,
                                         (PVOID *)&Process,
                                         NULL );

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

    KeAttachProcess (&Process->Pcb);

    //
    // Get the address creation mutex to block multiple threads from
    // creating or deleting address space at the same time and
    // get the working set mutex so virtual address descriptors can
    // be inserted and walked.  Block APCs so an APC which takes a page
    // fault does not corrupt various structures.
    //

    LOCK_WS_AND_ADDRESS_SPACE (Process);

    //
    // Make sure the address space was not deleted, if so, return an error.
    //

    if (Process->AddressSpaceDeleted != 0) {
        Status = STATUS_PROCESS_IS_TERMINATING;
        goto ErrorReturn;
    }

    Vad = MiLocateAddress (VirtualAddress);

    if ((Vad == NULL) ||
        (Vad->StartingVa != VirtualAddress) ||
        (Vad->u.VadFlags.PhysicalMapping == 0)) {
        Status = STATUS_NOT_MAPPED_DATA;
        goto ErrorReturn;
    }

    size = 1 + (ULONG)Vad->EndingVa - (ULONG)Vad->StartingVa;
    if ((size % BankLength) != 0) {
        Status = STATUS_INVALID_VIEW_SIZE;
        goto ErrorReturn;
    }

    count = -1;
    NumberOfPtes = BankLength;

    do {
        NumberOfPtes = NumberOfPtes >> 1;
        count += 1;
    } while (NumberOfPtes != 0);

    //
    // Turn VAD into Banked VAD
    //

    NumberOfPtes = BankLength >> PAGE_SHIFT;

    Bank = ExAllocatePoolWithTag (NonPagedPool,
                                    sizeof (MMBANKED_SECTION) +
                                       (NumberOfPtes - 1) * sizeof(MMPTE),
                                    '  mM');
    if (Bank == NULL) {
        Status = STATUS_INSUFFICIENT_RESOURCES;
        goto ErrorReturn;
    }

    Bank->BankShift = PTE_SHIFT + count - PAGE_SHIFT;

    PointerPte = MiGetPteAddress(Vad->StartingVa);
    ASSERT (PointerPte->u.Hard.Valid == 1);

    Vad->Banked = Bank;
    Bank->BasePhysicalPage = PointerPte->u.Hard.PageFrameNumber;
    Bank->BasedPte = PointerPte;
    Bank->BankSize = BankLength;
    Bank->BankedRoutine = BankRoutine;
    Bank->Context = Context;
    Bank->CurrentMappedPte = PointerPte;

    //
    // Build template PTEs the structure.
    //

    count = 0;
    TempPte = ZeroPte;

    MI_MAKE_VALID_PTE (TempPte,
                       Bank->BasePhysicalPage,
                       MM_READWRITE,
                       PointerPte);

    if (TempPte.u.Hard.Write) {
        MI_SET_PTE_DIRTY (TempPte);
    }

    do {
        Bank->BankTemplate[count] = TempPte;
        TempPte.u.Hard.PageFrameNumber += 1;
        count += 1;
    } while ((ULONG)count < NumberOfPtes );

    LastPte = MiGetPteAddress (Vad->EndingVa);

    //
    // Set all PTEs within this range to zero.  Any faults within
    // this range will call the banked routine before making the
    // page valid.
    //

    RtlFillMemory (PointerPte,
                   (size >> (PAGE_SHIFT - PTE_SHIFT)),
                   (UCHAR)ZeroPte.u.Long);

    MiFlushTb ();

    Status = STATUS_SUCCESS;
ErrorReturn:

    UNLOCK_WS (Process);
    UNLOCK_ADDRESS_SPACE (Process);
    KeDetachProcess();
    return Status;
}

PVOID
MmMapVideoDisplay (
     IN PHYSICAL_ADDRESS PhysicalAddress,
     IN ULONG NumberOfBytes,
     IN MEMORY_CACHING_TYPE CacheType
     )

/*++

Routine Description:

    This function maps the specified physical address into the non-pageable
    portion of the system address space.

Arguments:

    PhysicalAddress - Supplies the starting physical address to map.

    NumberOfBytes - Supplies the number of bytes to map.

    CacheType - Supplies MmNonCached if the phyiscal address is to be mapped
                as non-cached, MmCached if the address should be cached, and
                MmCacheFrameBuffer if the address should be cached as a frame
                buffer. For I/O device registers, this is usually specified
                as MmNonCached.

Return Value:

    Returns the virtual address which maps the specified physical addresses.
    The value NULL is returned if sufficient virtual address space for
    the mapping could not be found.

Environment:

    Kernel mode, IRQL of APC_LEVEL or below.

--*/

{
    ULONG NumberOfPages;
    ULONG PageFrameIndex;
    PMMPTE PointerPte = NULL;
    PVOID BaseVa;
    MMPTE TempPte;
#ifdef LARGE_PAGES
    ULONG size;
    PMMPTE protoPte;
    PMMPTE largePte;
    ULONG pageSize;
    PSUBSECTION Subsection;
    ULONG Alignment;
#endif LARGE_PAGES
    ULONG LargePages = FALSE;

#ifdef i386
    ASSERT (PhysicalAddress.HighPart == 0);
#endif
#ifdef R4000
    ASSERT (PhysicalAddress.HighPart < 16);
#endif

    PAGED_CODE();

    ASSERT (NumberOfBytes != 0);

#ifdef LARGE_PAGES
    NumberOfPages = COMPUTE_PAGES_SPANNED (PhysicalAddress.LowPart,
                                           NumberOfBytes);

    TempPte = ValidKernelPte;
    MI_DISABLE_CACHING (TempPte);
    PageFrameIndex = (ULONG)(PhysicalAddress.QuadPart >> PAGE_SHIFT);
    TempPte.u.Hard.PageFrameNumber = PageFrameIndex;

    if ((NumberOfBytes > X64K) && (!MmLargeVideoMapped)) {
        size = (NumberOfBytes - 1) >> (PAGE_SHIFT + 1);
        pageSize = PAGE_SIZE;

        while (size != 0) {
            size = size >> 2;
            pageSize = pageSize << 2;
        }

        Alignment = pageSize << 1;
        if (Alignment < MM_VA_MAPPED_BY_PDE) {
            Alignment = MM_VA_MAPPED_BY_PDE;
        }
        NumberOfPages = Alignment >> PAGE_SHIFT;
        PointerPte = MiReserveSystemPtes(NumberOfPages,
                                         SystemPteSpace,
                                         Alignment,
                                         0,
                                         FALSE);
        protoPte = ExAllocatePoolWithTag (PagedPool,
                                           sizeof (MMPTE),
                                           'bSmM');
        if ((PointerPte != NULL) && (protoPte != NULL)) {

            RtlFillMemoryUlong (PointerPte,
                                Alignment >> (PAGE_SHIFT - PTE_SHIFT),
                                MM_ZERO_KERNEL_PTE);

            //
            // Build large page descriptor and fill in all the PTEs.
            //

            Subsection = ExAllocatePoolWithTag (NonPagedPoolMustSucceed,
                                         sizeof(SUBSECTION) + (4 * sizeof(MMPTE)),
                                         'bSmM');

            Subsection->StartingSector = pageSize;
            Subsection->EndingSector = (ULONG)NumberOfPages;
            Subsection->u.LongFlags = 0;
            Subsection->u.SubsectionFlags.LargePages = 1;
            Subsection->u.SubsectionFlags.Protection = MM_READWRITE | MM_NOCACHE;
            Subsection->PtesInSubsection = Alignment;
            Subsection->SubsectionBase = PointerPte;

            largePte = (PMMPTE)(Subsection + 1);

            //
            // Build the first 2 ptes as entries for the TLB to
            // map the specified physical address.
            //

            *largePte = TempPte;
            largePte += 1;

            if (NumberOfBytes > pageSize) {
                *largePte = TempPte;
                largePte->u.Hard.PageFrameNumber += (pageSize >> PAGE_SHIFT);
            } else {
                *largePte = ZeroKernelPte;
            }

            //
            // Build the first prototype PTE as a paging file format PTE
            // referring to the subsection.
            //

            protoPte->u.Long = (ULONG)MiGetSubsectionAddressForPte(Subsection);
            protoPte->u.Soft.Prototype = 1;
            protoPte->u.Soft.Protection = MM_READWRITE | MM_NOCACHE;

            //
            // Set the PTE up for all the user's PTE entries, proto pte
            // format pointing to the 3rd prototype PTE.
            //

            TempPte.u.Long = MiProtoAddressForPte (protoPte);
            MI_SET_GLOBAL_STATE (TempPte, 1);
            LargePages = TRUE;
            MmLargeVideoMapped = TRUE;
        }
    }
    BaseVa = (PVOID)MiGetVirtualAddressMappedByPte (PointerPte);
    BaseVa = (PVOID)((PCHAR)BaseVa + BYTE_OFFSET(PhysicalAddress.LowPart));

    if (PointerPte != NULL) {

        do {
            ASSERT (PointerPte->u.Hard.Valid == 0);
            *PointerPte = TempPte;
            PointerPte++;
            NumberOfPages -= 1;
        } while (NumberOfPages != 0);
    } else {
#endif //LARGE_PAGES

        BaseVa = MmMapIoSpace (PhysicalAddress,
                               NumberOfBytes,
                               CacheType);
#ifdef LARGE_PAGES
    }
#endif //LARGE_PAGES

    return BaseVa;
}

VOID
MmUnmapVideoDisplay (
     IN PVOID BaseAddress,
     IN ULONG NumberOfBytes
     )

/*++

Routine Description:

    This function unmaps a range of physical address which were previously
    mapped via an MmMapVideoDisplay function call.

Arguments:

    BaseAddress - Supplies the base virtual address where the physical
                  address was previously mapped.

    NumberOfBytes - Supplies the number of bytes which were mapped.

Return Value:

    None.

Environment:

    Kernel mode, IRQL of APC_LEVEL or below.

--*/

{

#ifdef LARGE_PAGES
    ULONG NumberOfPages;
    ULONG i;
    PMMPTE FirstPte;
    KIRQL OldIrql;
    PMMPTE LargePte;
    PSUBSECTION Subsection;

    PAGED_CODE();

    ASSERT (NumberOfBytes != 0);
    NumberOfPages = COMPUTE_PAGES_SPANNED (BaseAddress, NumberOfBytes);
    FirstPte = MiGetPteAddress (BaseAddress);

    if ((NumberOfBytes > X64K) && (FirstPte->u.Hard.Valid == 0)) {

        ASSERT (MmLargeVideoMapped);
        LargePte = MiPteToProto (FirstPte);
        Subsection = MiGetSubsectionAddress (LargePte);
        ASSERT (Subsection->SubsectionBase == FirstPte);
        NumberOfPages = Subsection->PtesInSubsection;
        ExFreePool (Subsection);
        ExFreePool (LargePte);
        MmLargeVideoMapped = FALSE;
        KeFillFixedEntryTb ((PHARDWARE_PTE)FirstPte, (PVOID)KSEG0_BASE, LARGE_ENTRY);
    }
    MiReleaseSystemPtes(FirstPte, NumberOfPages, SystemPteSpace);
    return;

#else // LARGE_PAGES

    MmUnmapIoSpace (BaseAddress, NumberOfBytes);
    return;
#endif //LARGE_PAGES
}


VOID
MiFlushTb (
    VOID
    )

/*++

Routine Description:

     Nonpagable wrapper.

Arguments:

Return Value:

    None.

Environment:

    Kernel mode, IRQL of APC_LEVEL or below.

--*/

{
    KIRQL OldIrql;

    KeRaiseIrql (DISPATCH_LEVEL, &OldIrql);
    KeFlushEntireTb (TRUE, TRUE);
    KeLowerIrql (OldIrql);
}


VOID
MmLockPagedPool (
    IN PVOID Address,
    IN ULONG Size
    )

/*++

Routine Description:

    Locks the specified address (which MUST reside in paged pool) into
    memory until MmUnlockPagedPool is called.

Arguments:

    Address - Supplies the address in paged pool to lock.

    Size - Supplies the size to lock.

Return Value:

    None.

Environment:

    Kernel mode, IRQL of APC_LEVEL or below.

--*/

{
    PMMPTE PointerPte;
    PMMPTE LastPte;
    KIRQL OldIrql;

    MmLockPagableSectionByHandle(ExPageLockHandle);
    PointerPte = MiGetPteAddress (Address);
    LastPte = MiGetPteAddress ((PVOID)((PCHAR)Address + (Size - 1)));
    LOCK_PFN (OldIrql);
    MiLockCode (PointerPte, LastPte, MM_LOCK_BY_REFCOUNT);
    UNLOCK_PFN (OldIrql);
    MmUnlockPagableImageSection(ExPageLockHandle);
    return;
}

NTKERNELAPI
VOID
MmUnlockPagedPool (
    IN PVOID Address,
    IN ULONG Size
    )

/*++

Routine Description:

    Unlocks paged pool that was locked with MmLockPagedPool.

Arguments:

    Address - Supplies the address in paged pool to unlock.

    Size - Supplies the size to unlock.

Return Value:

    None.

Environment:

    Kernel mode, IRQL of APC_LEVEL or below.

--*/

{
    PMMPTE PointerPte;
    PMMPTE LastPte;
    KIRQL OldIrql;

    MmLockPagableSectionByHandle(ExPageLockHandle);
    PointerPte = MiGetPteAddress (Address);
    LastPte = MiGetPteAddress ((PVOID)((PCHAR)Address + (Size - 1)));
    LOCK_PFN2 (OldIrql);

    do {
#if DBG
        {   PMMPFN Pfn;
            ASSERT (PointerPte->u.Hard.Valid == 1);
            Pfn = MI_PFN_ELEMENT (PointerPte->u.Hard.PageFrameNumber);
            ASSERT (Pfn->u3.e2.ReferenceCount > 1);
        }
#endif //DBG

        MiDecrementReferenceCount (PointerPte->u.Hard.PageFrameNumber);
        PointerPte += 1;
    } while (PointerPte <= LastPte);

    UNLOCK_PFN2 (OldIrql);
    MmUnlockPagableImageSection(ExPageLockHandle);
    return;
}