summaryrefslogblamecommitdiffstats
path: root/private/ntos/mm/sysptes.c
blob: d117890aeac6a40ee26f79c29ce5e4f6642e0dae (plain) (tree)
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































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                          
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

   sysptes.c

Abstract:

    This module contains the routines which reserve and release
    system wide PTEs reserved within the non paged portion of the
    system space.  These PTEs are used for mapping I/O devices
    and mapping kernel stacks for threads.

Author:

    Lou Perazzoli (loup) 6-Apr-1989

Revision History:

--*/

#include "mi.h"

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


ULONG MmTotalFreeSystemPtes[MaximumPtePoolTypes];
ULONG MmSystemPtesStart[MaximumPtePoolTypes];
ULONG MmSystemPtesEnd[MaximumPtePoolTypes];

#define MM_MIN_SYSPTE_FREE 500
#define MM_MAX_SYSPTE_FREE 3000

PMMPTE MmFlushPte1;

MMPTE MmFlushCounter;

//
// PTEs are binned at sizes 1, 2, 4, 8, and 16.
//

#ifdef _ALPHA_

//
// alpha has 8k pages size and stacks consume 9 pages (including guard page).
//

ULONG MmSysPteIndex[MM_SYS_PTE_TABLES_MAX] = {1,2,4,9,16};

UCHAR MmSysPteTables[17] = {0,0,1,2,2,3,3,3,3,3,4,4,4,4,4,4,4};

#else

ULONG MmSysPteIndex[MM_SYS_PTE_TABLES_MAX] = {1,2,4,8,16};

UCHAR MmSysPteTables[17] = {0,0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4};
#endif

MMPTE MmFreeSysPteListBySize [MM_SYS_PTE_TABLES_MAX];
PMMPTE MmLastSysPteListBySize [MM_SYS_PTE_TABLES_MAX];
ULONG MmSysPteListBySizeCount [MM_SYS_PTE_TABLES_MAX];
ULONG MmSysPteMinimumFree [MM_SYS_PTE_TABLES_MAX] = {100,50,30,20,20};

//
// Initial sizes for PTE lists.
//

#define MM_PTE_LIST_1  400
#define MM_PTE_LIST_2  100
#define MM_PTE_LIST_4   60
#define MM_PTE_LIST_8   50
#define MM_PTE_LIST_16  40

#define MM_PTE_TABLE_LIMIT 16

PMMPTE
MiReserveSystemPtes2 (
    IN ULONG NumberOfPtes,
    IN MMSYSTEM_PTE_POOL_TYPE SystemPtePoolType,
    IN ULONG Alignment,
    IN ULONG Offset,
    IN ULONG BugCheckOnFailure
    );

VOID
MiFeedSysPtePool (
    IN ULONG Index
    );

VOID
MiDumpSystemPtes (
    IN MMSYSTEM_PTE_POOL_TYPE SystemPtePoolType
    );

ULONG
MiCountFreeSystemPtes (
    IN MMSYSTEM_PTE_POOL_TYPE SystemPtePoolType
    );


PMMPTE
MiReserveSystemPtes (
    IN ULONG NumberOfPtes,
    IN MMSYSTEM_PTE_POOL_TYPE SystemPtePoolType,
    IN ULONG Alignment,
    IN ULONG Offset,
    IN ULONG BugCheckOnFailure
    )

/*++

Routine Description:

    This function locates the specified number of unused PTEs to locate
    within the non paged portion of system space.

Arguments:

    NumberOfPtes - Supplies the number of PTEs to locate.

    SystemPtePoolType - Supplies the PTE type of the pool to expand, one of
                        SystemPteSpace or NonPagedPoolExpansion.

    Alignment - Supplies the virtual address alignment for the address
                the returned PTE maps. For example, if the value is 64K,
                the returned PTE will map an address on a 64K boundary.
                An alignment of zero means to align on a page boundary.

    Offset - Supplies the offset into the alignment for the virtual address.
             For example, if the Alignment is 64k and the Offset is 4k,
             the returned address will be 4k above a 64k boundary.

    BugCheckOnFailure - Supplies FALSE if NULL should be returned if
                        the request cannot be satisfied, TRUE if
                        a bugcheck should be issued.

Return Value:

    Returns the address of the first PTE located.
    NULL if no system PTEs can be located and BugCheckOnFailure is FALSE.

Environment:

    Kernel mode, DISPATCH_LEVEL or below.

--*/

{
    PMMPTE PointerPte;
    PMMPTE Previous;
    KIRQL OldIrql;
    ULONG PteMask;
    ULONG MaskSize;
    ULONG Index;

    if (SystemPtePoolType == SystemPteSpace) {

        MaskSize = (Alignment - 1) >> (PAGE_SHIFT - PTE_SHIFT);
        PteMask = MaskSize & (Offset >> (PAGE_SHIFT - PTE_SHIFT));

        //
        // Acquire the system space lock to synchronize access to this
        // routine.
        //

        ExAcquireSpinLock ( &MmSystemSpaceLock, &OldIrql );

        if (NumberOfPtes <= MM_PTE_TABLE_LIMIT) {
            Index = MmSysPteTables [NumberOfPtes];
            ASSERT (NumberOfPtes <= MmSysPteIndex[Index]);
            PointerPte = &MmFreeSysPteListBySize[Index];
#if DBG
            if (MmDebug & MM_DBG_SYS_PTES) {
                PMMPTE PointerPte1;
                PointerPte1 = &MmFreeSysPteListBySize[Index];
                while (PointerPte1->u.List.NextEntry != MM_EMPTY_PTE_LIST) {
                    PMMPTE PointerFreedPte;
                    ULONG j;

                    PointerPte1 = MmSystemPteBase + PointerPte1->u.List.NextEntry;
                    PointerFreedPte = PointerPte1;
                    for (j = 0; j < MmSysPteIndex[Index]; j++) {
                        ASSERT (PointerFreedPte->u.Hard.Valid == 0);
                        PointerFreedPte++;
                    }
                }
            }
#endif //DBG

            Previous = PointerPte;

            while (PointerPte->u.List.NextEntry != MM_EMPTY_PTE_LIST) {

                //
                //  Try to find suitable PTEs with the proper alignment.
                //

                Previous = PointerPte;
                PointerPte = MmSystemPteBase + PointerPte->u.List.NextEntry;
                if (PointerPte == MmFlushPte1) {
                    KeFlushEntireTb (TRUE, TRUE);
                    MmFlushCounter.u.List.NextEntry += 1;
                    MmFlushPte1 = NULL;
                }
                if ((Alignment == 0) ||
                    (((ULONG)PointerPte & MaskSize) == PteMask)) {

                    //
                    // Proper alignment and offset, update list index.
                    //

                    ASSERT ((ULONG)(PointerPte->u.List.NextEntry + MmSystemPteBase) >=
                             MmSystemPtesStart[SystemPtePoolType] ||
                             PointerPte->u.List.NextEntry == MM_EMPTY_PTE_LIST);
                    ASSERT ((ULONG)(PointerPte->u.List.NextEntry + MmSystemPteBase) <=
                             MmSystemPtesEnd[SystemPtePoolType] ||
                             PointerPte->u.List.NextEntry == MM_EMPTY_PTE_LIST);

                    Previous->u.List.NextEntry = PointerPte->u.List.NextEntry;
                    MmSysPteListBySizeCount [Index] -= 1;

                    if (NumberOfPtes != 1) {

                        //
                        // Check to see if the TB should be flushed.
                        //

                        if ((PointerPte + 1)->u.List.NextEntry == MmFlushCounter.u.List.NextEntry) {
                            KeFlushEntireTb (TRUE, TRUE);
                            MmFlushCounter.u.List.NextEntry += 1;
                            MmFlushPte1 = NULL;
                        }
                    }
                    if (PointerPte->u.List.NextEntry == MM_EMPTY_PTE_LIST) {
                        MmLastSysPteListBySize[Index] = Previous;
                    }
#if DBG

                    if (MmDebug & MM_DBG_SYS_PTES) {
                        PMMPTE PointerPte1;
                        PointerPte1 = &MmFreeSysPteListBySize[Index];
                        while (PointerPte1->u.List.NextEntry != MM_EMPTY_PTE_LIST) {
                            PMMPTE PointerFreedPte;
                            ULONG j;

                            PointerPte1 = MmSystemPteBase + PointerPte1->u.List.NextEntry;
                            PointerFreedPte = PointerPte1;
                            for (j = 0; j < MmSysPteIndex[Index]; j++) {
                                ASSERT (PointerFreedPte->u.Hard.Valid == 0);
                                PointerFreedPte++;
                            }
                        }
                    }
#endif //DBG
                    ExReleaseSpinLock ( &MmSystemSpaceLock, OldIrql);

#if DBG
                    PointerPte->u.List.NextEntry = 0xABCDE;
                    if (MmDebug & MM_DBG_SYS_PTES) {

                        PMMPTE PointerFreedPte;
                        ULONG j;

                        PointerFreedPte = PointerPte;
                        for (j = 0; j < MmSysPteIndex[Index]; j++) {
                            ASSERT (PointerFreedPte->u.Hard.Valid == 0);
                            PointerFreedPte++;
                        }
                    }
                    if (!((ULONG)PointerPte >= MmSystemPtesStart[SystemPtePoolType])) {
                        KeBugCheckEx (MEMORY_MANAGEMENT,
                                      0x652,(ULONG)PointerPte,
                                      NumberOfPtes,
                                      SystemPtePoolType);
                    }
                    if (!((ULONG)PointerPte <= MmSystemPtesEnd[SystemPtePoolType])) {
                        KeBugCheckEx (MEMORY_MANAGEMENT,
                                      0x653,(ULONG)PointerPte,
                                      NumberOfPtes,
                                      SystemPtePoolType); //fixfix make assert
                    }
#endif //DBG

                    if (MmSysPteListBySizeCount[Index] <
                                            MmSysPteMinimumFree[Index]) {
                        MiFeedSysPtePool (Index);
                    }
                    return PointerPte;
                }
            }
            NumberOfPtes = MmSysPteIndex [Index];
        }
        ExReleaseSpinLock ( &MmSystemSpaceLock, OldIrql);
    }
    PointerPte = MiReserveSystemPtes2 (NumberOfPtes,
                                       SystemPtePoolType,
                                       Alignment,
                                       Offset,
                                       BugCheckOnFailure);
#if DBG
    if (MmDebug & MM_DBG_SYS_PTES) {

        PMMPTE PointerFreedPte;
        ULONG j;

        PointerFreedPte = PointerPte;
        for (j = 0; j < NumberOfPtes; j++) {
            ASSERT (PointerFreedPte->u.Hard.Valid == 0);
            PointerFreedPte++;
        }
    }
#endif //DBG
    return PointerPte;
}

VOID
MiFeedSysPtePool (
    IN ULONG Index
    )

/*++

Routine Description:

    This routine adds PTEs to the look aside lists.

Arguments:

    Index - Supplies the index for the look aside list to fill.

Return Value:

    None.


Environment:

    Kernel mode, internal to SysPtes.

--*/

{
    ULONG i;
    PMMPTE PointerPte;

    if (MmTotalFreeSystemPtes[SystemPteSpace] < MM_MIN_SYSPTE_FREE) {
        return;
    }

    for (i = 0; i < 10 ; i++ ) {
        PointerPte = MiReserveSystemPtes2 (MmSysPteIndex [Index],
                                           SystemPteSpace,
                                           0,
                                           0,
                                           FALSE);
        if (PointerPte == NULL) {
            return;
        }
        MiReleaseSystemPtes (PointerPte,
                             MmSysPteIndex [Index],
                             SystemPteSpace);
    }
    return;
}


PMMPTE
MiReserveSystemPtes2 (
    IN ULONG NumberOfPtes,
    IN MMSYSTEM_PTE_POOL_TYPE SystemPtePoolType,
    IN ULONG Alignment,
    IN ULONG Offset,
    IN ULONG BugCheckOnFailure
    )

/*++

Routine Description:

    This function locates the specified number of unused PTEs to locate
    within the non paged portion of system space.

Arguments:

    NumberOfPtes - Supplies the number of PTEs to locate.

    SystemPtePoolType - Supplies the PTE type of the pool to expand, one of
                        SystemPteSpace or NonPagedPoolExpansion.

    Alignment - Supplies the virtual address alignment for the address
                the returned PTE maps. For example, if the value is 64K,
                the returned PTE will map an address on a 64K boundary.
                An alignment of zero means to align on a page boundary.

    Offset - Supplies the offset into the alignment for the virtual address.
             For example, if the Alignment is 64k and the Offset is 4k,
             the returned address will be 4k above a 64k boundary.

    BugCheckOnFailure - Supplies FALSE if NULL should be returned if
                        the request cannot be satisfied, TRUE if
                        a bugcheck should be issued.

Return Value:

    Returns the address of the first PTE located.
    NULL if no system PTEs can be located and BugCheckOnFailure is FALSE.

Environment:

    Kernel mode, DISPATCH_LEVEL or below.

--*/

{
    PMMPTE PointerPte;
    PMMPTE PointerFollowingPte;
    PMMPTE Previous;
    ULONG SizeInSet;
    KIRQL OldIrql;
    ULONG MaskSize;
    ULONG NumberOfRequiredPtes;
    ULONG OffsetSum;
    ULONG PtesToObtainAlignment;
    PMMPTE NextSetPointer;
    ULONG LeftInSet;
    ULONG PteOffset;
    MMPTE_FLUSH_LIST PteFlushList;

    MaskSize = (Alignment - 1) >> (PAGE_SHIFT - PTE_SHIFT);

    OffsetSum = (Offset >> (PAGE_SHIFT - PTE_SHIFT)) |
                            (Alignment >> (PAGE_SHIFT - PTE_SHIFT));

    ExAcquireSpinLock ( &MmSystemSpaceLock, &OldIrql );

    //
    // The nonpaged PTE pool use the invalid PTEs to define the pool
    // structure.   A global pointer points to the first free set
    // in the list, each free set contains the number free and a pointer
    // to the next free set.  The free sets are kept in an ordered list
    // such that the pointer to the next free set is always greater
    // than the address of the current free set.
    //
    // As to not limit the size of this pool, a two PTEs are used
    // to define a free region.  If the region is a single PTE, the
    // Prototype field within the PTE is set indicating the set
    // consists of a single PTE.
    //
    // The page frame number field is used to define the next set
    // and the number free.  The two flavors are:
    //
    //                           o          V
    //                           n          l
    //                           e          d
    //  +-----------------------+-+----------+
    //  |  next set             |0|0        0|
    //  +-----------------------+-+----------+
    //  |  number in this set   |0|0        0|
    //  +-----------------------+-+----------+
    //
    //
    //  +-----------------------+-+----------+
    //  |  next set             |1|0        0|
    //  +-----------------------+-+----------+
    //  ...
    //

    //
    // Acquire the system space lock to synchronize access to this
    // routine.
    //

    PointerPte = &MmFirstFreeSystemPte[SystemPtePoolType];
    Previous = PointerPte;

    if (PointerPte->u.List.NextEntry == MM_EMPTY_PTE_LIST) {

        //
        // End of list and none found, return NULL or bugcheck.
        //

        if (BugCheckOnFailure) {
            KeBugCheckEx (NO_MORE_SYSTEM_PTES,
                          (ULONG)SystemPtePoolType,
                          NumberOfPtes,
                          MmTotalFreeSystemPtes[SystemPtePoolType],
                          MmNumberOfSystemPtes);
        }

        ExReleaseSpinLock ( &MmSystemSpaceLock, OldIrql );
        return NULL;
    }

    PointerPte = MmSystemPteBase + PointerPte->u.List.NextEntry;

    if (Alignment <= PAGE_SIZE) {

        //
        // Don't deal with aligment issues.
        //

        while (TRUE) {

            if (PointerPte->u.List.OneEntry) {
                SizeInSet = 1;

            } else {

                PointerFollowingPte = PointerPte + 1;
                SizeInSet = PointerFollowingPte->u.List.NextEntry;
            }

            if (NumberOfPtes < SizeInSet) {

                //
                // Get the PTEs from this set and reduce the size of the
                // set.  Note that the size of the current set cannot be 1.
                //

                if ((SizeInSet - NumberOfPtes) == 1) {

                    //
                    // Collapse to the single PTE format.
                    //

                    PointerPte->u.List.OneEntry = 1;

                } else {

                    PointerFollowingPte->u.List.NextEntry = SizeInSet - NumberOfPtes;

                    //
                    // Get the required PTEs from the end of the set.
                    //

#if DBG
                    if (MmDebug & MM_DBG_SYS_PTES) {
                        MiDumpSystemPtes(SystemPtePoolType);
                        PointerFollowingPte = PointerPte + (SizeInSet - NumberOfPtes);
                        DbgPrint("allocated 0x%lx Ptes at %lx\n",NumberOfPtes,PointerFollowingPte);
                    }
#endif //DBG
                }

                MmTotalFreeSystemPtes[SystemPtePoolType] -= NumberOfPtes;
#if DBG
                if (MmDebug & MM_DBG_SYS_PTES) {
                    ASSERT (MmTotalFreeSystemPtes[SystemPtePoolType] ==
                             MiCountFreeSystemPtes (SystemPtePoolType));
                }
#endif //DBG

                ExReleaseSpinLock ( &MmSystemSpaceLock, OldIrql );

                PointerPte =  PointerPte + (SizeInSet - NumberOfPtes);
                goto Flush;
            }

            if (NumberOfPtes == SizeInSet) {

                //
                // Satisfy the request with this complete set and change
                // the list to reflect the fact that this set is gone.
                //

                Previous->u.List.NextEntry = PointerPte->u.List.NextEntry;

                //
                // Release the system PTE lock.
                //

#if DBG
                if (MmDebug & MM_DBG_SYS_PTES) {
                        MiDumpSystemPtes(SystemPtePoolType);
                        PointerFollowingPte = PointerPte + (SizeInSet - NumberOfPtes);
                        DbgPrint("allocated 0x%lx Ptes at %lx\n",NumberOfPtes,PointerFollowingPte);
                }
#endif

                MmTotalFreeSystemPtes[SystemPtePoolType] -= NumberOfPtes;
#if DBG
                if (MmDebug & MM_DBG_SYS_PTES) {
                    ASSERT (MmTotalFreeSystemPtes[SystemPtePoolType] ==
                             MiCountFreeSystemPtes (SystemPtePoolType));
                }
#endif //DBG
                ExReleaseSpinLock ( &MmSystemSpaceLock, OldIrql );
                goto Flush;
            }

            //
            // Point to the next set and try again
            //

            if (PointerPte->u.List.NextEntry == MM_EMPTY_PTE_LIST) {

                //
                // End of list and none found, return NULL or bugcheck.
                //

                if (BugCheckOnFailure) {
                    KeBugCheckEx (NO_MORE_SYSTEM_PTES,
                                  (ULONG)SystemPtePoolType,
                                  NumberOfPtes,
                                  MmTotalFreeSystemPtes[SystemPtePoolType],
                                  MmNumberOfSystemPtes);
                }

                ExReleaseSpinLock ( &MmSystemSpaceLock, OldIrql );
                return NULL;
            }
            Previous = PointerPte;
            PointerPte = MmSystemPteBase + PointerPte->u.List.NextEntry;
            ASSERT (PointerPte > Previous);
        }

    } else {

        //
        // Deal with the alignment issues.
        //

        while (TRUE) {

            if (PointerPte->u.List.OneEntry) {
                SizeInSet = 1;

            } else {

                PointerFollowingPte = PointerPte + 1;
                SizeInSet = PointerFollowingPte->u.List.NextEntry;
            }

            PtesToObtainAlignment =
                (((OffsetSum - ((ULONG)PointerPte & MaskSize)) & MaskSize) >>
                    PTE_SHIFT);

            NumberOfRequiredPtes = NumberOfPtes + PtesToObtainAlignment;

            if (NumberOfRequiredPtes < SizeInSet) {

                //
                // Get the PTEs from this set and reduce the size of the
                // set.  Note that the size of the current set cannot be 1.
                //
                // This current block will be slit into 2 blocks if
                // the PointerPte does not match the aligment.
                //

                //
                // Check to see if the first PTE is on the proper
                // alignment, if so, eliminate this block.
                //

                LeftInSet = SizeInSet - NumberOfRequiredPtes;

                //
                // Set up the new set at the end of this block.
                //

                NextSetPointer = PointerPte + NumberOfRequiredPtes;
                NextSetPointer->u.List.NextEntry =
                                       PointerPte->u.List.NextEntry;

                PteOffset = NextSetPointer - MmSystemPteBase;

                if (PtesToObtainAlignment == 0) {

                    Previous->u.List.NextEntry += NumberOfRequiredPtes;

                } else {

                    //
                    // Point to the new set at the end of the block
                    // we are giving away.
                    //

                    PointerPte->u.List.NextEntry = PteOffset;

                    //
                    // Update the size of the current set.
                    //

                    if (PtesToObtainAlignment == 1) {

                        //
                        // Collapse to the single PTE format.
                        //

                        PointerPte->u.List.OneEntry = 1;

                    } else {

                        //
                        // Set the set size in the next PTE.
                        //

                        PointerFollowingPte->u.List.NextEntry =
                                                        PtesToObtainAlignment;
                    }
                }

                //
                // Set up the new set at the end of the block.
                //

                if (LeftInSet == 1) {
                    NextSetPointer->u.List.OneEntry = 1;
                } else {
                    NextSetPointer->u.List.OneEntry = 0;
                    NextSetPointer += 1;
                    NextSetPointer->u.List.NextEntry = LeftInSet;
                }
                MmTotalFreeSystemPtes[SystemPtePoolType] -= NumberOfPtes;
#if DBG
                if (MmDebug & MM_DBG_SYS_PTES) {
                    ASSERT (MmTotalFreeSystemPtes[SystemPtePoolType] ==
                             MiCountFreeSystemPtes (SystemPtePoolType));
                }
#endif //DBG
                ExReleaseSpinLock ( &MmSystemSpaceLock, OldIrql );

                PointerPte = PointerPte + PtesToObtainAlignment;
                goto Flush;
            }

            if (NumberOfRequiredPtes == SizeInSet) {

                //
                // Satisfy the request with this complete set and change
                // the list to reflect the fact that this set is gone.
                //

                if (PtesToObtainAlignment == 0) {

                    //
                    // This block exactly satifies the request.
                    //

                    Previous->u.List.NextEntry =
                                            PointerPte->u.List.NextEntry;

                } else {

                    //
                    // A portion at the start of this block remains.
                    //

                    if (PtesToObtainAlignment == 1) {

                        //
                        // Collapse to the single PTE format.
                        //

                        PointerPte->u.List.OneEntry = 1;

                    } else {
                      PointerFollowingPte->u.List.NextEntry =
                                                        PtesToObtainAlignment;

                    }
                }

                MmTotalFreeSystemPtes[SystemPtePoolType] -= NumberOfPtes;
#if DBG
                if (MmDebug & MM_DBG_SYS_PTES) {
                    ASSERT (MmTotalFreeSystemPtes[SystemPtePoolType] ==
                             MiCountFreeSystemPtes (SystemPtePoolType));
                }
#endif //DBG
                ExReleaseSpinLock ( &MmSystemSpaceLock, OldIrql );

                PointerPte = PointerPte + PtesToObtainAlignment;
                goto Flush;
            }

            //
            // Point to the next set and try again
            //

            if (PointerPte->u.List.NextEntry == MM_EMPTY_PTE_LIST) {

                //
                // End of list and none found, return NULL or bugcheck.
                //

                if (BugCheckOnFailure) {
                    KeBugCheckEx (NO_MORE_SYSTEM_PTES,
                                  (ULONG)SystemPtePoolType,
                                  NumberOfPtes,
                                  MmTotalFreeSystemPtes[SystemPtePoolType],
                                  MmNumberOfSystemPtes);
                }

                ExReleaseSpinLock ( &MmSystemSpaceLock, OldIrql );
                return NULL;
            }
            Previous = PointerPte;
            PointerPte = MmSystemPteBase + PointerPte->u.List.NextEntry;
            ASSERT (PointerPte > Previous);
        }
    }
Flush:

    if (SystemPtePoolType == SystemPteSpace) {
        PVOID BaseAddress;
        ULONG j;

        PteFlushList.Count = 0;
        Previous = PointerPte;
        BaseAddress = MiGetVirtualAddressMappedByPte (Previous);

        for (j = 0; j < NumberOfPtes ; j++) {
            if (PteFlushList.Count != MM_MAXIMUM_FLUSH_COUNT) {
                PteFlushList.FlushPte[PteFlushList.Count] = Previous;
                PteFlushList.FlushVa[PteFlushList.Count] = BaseAddress;
                PteFlushList.Count += 1;
            }
            *Previous = ZeroKernelPte;
            BaseAddress = (PVOID)((PCHAR)BaseAddress + PAGE_SIZE);
            Previous++;
        }

        KeRaiseIrql (DISPATCH_LEVEL, &OldIrql);
        MiFlushPteList (&PteFlushList, TRUE, ZeroKernelPte);
        KeLowerIrql (OldIrql);
    }
    return PointerPte;
}

VOID
MiReleaseSystemPtes (
    IN PMMPTE StartingPte,
    IN ULONG NumberOfPtes,
    IN MMSYSTEM_PTE_POOL_TYPE SystemPtePoolType
    )

/*++

Routine Description:

    This function releases the specified number of PTEs
    within the non paged portion of system space.

    Note that the PTEs must be invalid and the page frame number
    must have been set to zero.

Arguments:

    StartingPte - Supplies the address of the first PTE to release.

    NumberOfPtes - Supplies the number of PTEs to release.

Return Value:

    none.

Environment:

    Kernel mode.

--*/

{

    ULONG Size;
    ULONG i;
    ULONG PteOffset;
    PMMPTE PointerPte;
    PMMPTE PointerFollowingPte;
    PMMPTE NextPte;
    KIRQL OldIrql;
    ULONG Index;
    MMPTE TempPte;

    //
    // Check to make sure the PTEs don't map anything.
    //

    ASSERT (NumberOfPtes != 0);
#if DBG
    if (!((ULONG)StartingPte >= MmSystemPtesStart[SystemPtePoolType])) {
        KeBugCheckEx (MEMORY_MANAGEMENT,
                      0x656,(ULONG)StartingPte,
                      NumberOfPtes,
                      SystemPtePoolType);
    }

    if (!((ULONG)StartingPte <= MmSystemPtesEnd[SystemPtePoolType])) {
        KeBugCheckEx (MEMORY_MANAGEMENT,
                      0x657,(ULONG)StartingPte,
                      NumberOfPtes,
                      SystemPtePoolType);
    }
#endif //DBG

#if DBG
    if (MmDebug & MM_DBG_SYS_PTES) {
        DbgPrint("releasing 0x%lx system PTEs at location %lx\n",NumberOfPtes,StartingPte);
    }
#endif

    //
    // Zero PTEs.
    //

    RtlFillMemoryUlong (StartingPte,
                        NumberOfPtes * sizeof (MMPTE),
                        ZeroKernelPte.u.Long);

    //
    // Acquire system space spin lock to synchronize access.
    //

    PteOffset = StartingPte - MmSystemPteBase;

    ExAcquireSpinLock ( &MmSystemSpaceLock, &OldIrql );

    if ((SystemPtePoolType == SystemPteSpace) &&
        (NumberOfPtes <= MM_PTE_TABLE_LIMIT)) {

        Index = MmSysPteTables [NumberOfPtes];
        NumberOfPtes = MmSysPteIndex [Index];

        if (MmTotalFreeSystemPtes[SystemPteSpace] >= MM_MIN_SYSPTE_FREE) {

            //
            // Don't add to the pool if the size is greater than 15 + the minimum.
            //

            i = MmSysPteMinimumFree[Index];
            if (MmTotalFreeSystemPtes[SystemPteSpace] >= MM_MAX_SYSPTE_FREE) {

                //
                // Lots of free PTEs, quadrouple the limit.
                //

                i = i * 4;
            }
            i += 15;
            if (MmSysPteListBySizeCount[Index] <= i) {

#if DBG
                if (MmDebug & MM_DBG_SYS_PTES) {
                    PMMPTE PointerPte1;

                    PointerPte1 = &MmFreeSysPteListBySize[Index];
                    while (PointerPte1->u.List.NextEntry != MM_EMPTY_PTE_LIST) {
                        PMMPTE PointerFreedPte;
                        ULONG j;

                        PointerPte1 = MmSystemPteBase + PointerPte1->u.List.NextEntry;
                        PointerFreedPte = PointerPte1;
                        for (j = 0; j < MmSysPteIndex[Index]; j++) {
                            ASSERT (PointerFreedPte->u.Hard.Valid == 0);
                            PointerFreedPte++;
                        }
                    }
                }
#endif //DBG
                MmSysPteListBySizeCount [Index] += 1;
                PointerPte = MmLastSysPteListBySize[Index];
                ASSERT (PointerPte->u.List.NextEntry == MM_EMPTY_PTE_LIST);
                PointerPte->u.List.NextEntry = PteOffset;
                MmLastSysPteListBySize[Index] = StartingPte;
                StartingPte->u.List.NextEntry = MM_EMPTY_PTE_LIST;

#if DBG
                if (MmDebug & MM_DBG_SYS_PTES) {
                    PMMPTE PointerPte1;
                    PointerPte1 = &MmFreeSysPteListBySize[Index];
                    while (PointerPte1->u.List.NextEntry != MM_EMPTY_PTE_LIST) {
                        PMMPTE PointerFreedPte;
                        ULONG j;

                        PointerPte1 = MmSystemPteBase + PointerPte1->u.List.NextEntry;
                        PointerFreedPte = PointerPte1;
                        for (j = 0; j < MmSysPteIndex[Index]; j++) {
                            ASSERT (PointerFreedPte->u.Hard.Valid == 0);
                            PointerFreedPte++;
                        }
                    }
                }
#endif //DBG
                if (NumberOfPtes == 1) {
                    if (MmFlushPte1 == NULL) {
                        MmFlushPte1 = StartingPte;
                    }
                } else {
                    (StartingPte + 1)->u.List.NextEntry = MmFlushCounter.u.List.NextEntry;
                }

                ExReleaseSpinLock ( &MmSystemSpaceLock, OldIrql);
                return;
            }
        }
    }

    MmTotalFreeSystemPtes[SystemPtePoolType] += NumberOfPtes;

    PteOffset = StartingPte - MmSystemPteBase;
    PointerPte = &MmFirstFreeSystemPte[SystemPtePoolType];

    while (TRUE) {
        NextPte = MmSystemPteBase + PointerPte->u.List.NextEntry;
        if (PteOffset < PointerPte->u.List.NextEntry) {

            //
            // Insert in the list at this point.  The
            // previous one should point to the new freed set and
            // the new freed set should point to the place
            // the previous set points to.
            //
            // Attempt to combine the clusters before we
            // insert.
            //
            // Locate the end of the current structure.
            //

            ASSERT ((StartingPte + NumberOfPtes) <= NextPte);

            PointerFollowingPte = PointerPte + 1;
            if (PointerPte->u.List.OneEntry) {
                Size = 1;
            } else {
                Size = PointerFollowingPte->u.List.NextEntry;
            }
            if ((PointerPte + Size) == StartingPte) {

                //
                // We can combine the clusters.
                //

                NumberOfPtes = Size + NumberOfPtes;
                PointerFollowingPte->u.List.NextEntry = NumberOfPtes;
                PointerPte->u.List.OneEntry = 0;

                //
                // Point the starting PTE to the beginning of
                // the new free set and try to combine with the
                // following free cluster.
                //

                StartingPte = PointerPte;

            } else {

                //
                // Can't combine with previous. Make this Pte the
                // start of a cluster.
                //

                //
                // Point this cluster to the next cluster.
                //

                StartingPte->u.List.NextEntry = PointerPte->u.List.NextEntry;

                //
                // Point the current cluster to this cluster.
                //

                PointerPte->u.List.NextEntry = PteOffset;

                //
                // Set the size of this cluster.
                //

                if (NumberOfPtes == 1) {
                    StartingPte->u.List.OneEntry = 1;

                } else {
                    StartingPte->u.List.OneEntry = 0;
                    PointerFollowingPte = StartingPte + 1;
                    PointerFollowingPte->u.List.NextEntry = NumberOfPtes;
                }
            }

            //
            // Attempt to combine the newly created cluster with
            // the following cluster.
            //

            if ((StartingPte + NumberOfPtes) == NextPte) {

                //
                // Combine with following cluster.
                //

                //
                // Set the next cluster to the value contained in the
                // cluster we are merging into this one.
                //

                StartingPte->u.List.NextEntry = NextPte->u.List.NextEntry;
                StartingPte->u.List.OneEntry = 0;
                PointerFollowingPte = StartingPte + 1;

                if (NextPte->u.List.OneEntry) {
                    Size = 1;

                } else {
                    NextPte++;
                    Size = NextPte->u.List.NextEntry;
                }
                PointerFollowingPte->u.List.NextEntry = NumberOfPtes + Size;
            }
#if DBG
            if (MmDebug & MM_DBG_SYS_PTES) {
                MiDumpSystemPtes(SystemPtePoolType);
            }
#endif

#if DBG
            if (MmDebug & MM_DBG_SYS_PTES) {
                ASSERT (MmTotalFreeSystemPtes[SystemPtePoolType] ==
                         MiCountFreeSystemPtes (SystemPtePoolType));
            }
#endif //DBG
            ExReleaseSpinLock ( &MmSystemSpaceLock, OldIrql );
            return;
        }

        //
        // Point to next freed cluster.
        //

        PointerPte = NextPte;
    }
}

VOID
MiInitializeSystemPtes (
    IN PMMPTE StartingPte,
    IN ULONG NumberOfPtes,
    IN MMSYSTEM_PTE_POOL_TYPE SystemPtePoolType
    )

/*++

Routine Description:

    This routine initializes the system PTE pool.

Arguments:

    StartingPte - Supplies the address of the first PTE to put in the pool.

    NumberOfPtes - Supplies the number of PTEs to put in the pool.

Return Value:

    none.

Environment:

    Kernel mode.

--*/

{
    LONG i;
    LONG j;

    //
    // Set the base of the system PTE pool to this PTE.
    //

    MmSystemPteBase = MiGetPteAddress (0xC0000000);
    MmSystemPtesStart[SystemPtePoolType] = (ULONG)StartingPte;
    MmSystemPtesEnd[SystemPtePoolType] = (ULONG)((StartingPte + NumberOfPtes -1));

    if (NumberOfPtes <= 1) {

        //
        // Not enough PTEs to make a valid chain, just indicate
        // not PTEs are free.
        //

        MmFirstFreeSystemPte[SystemPtePoolType] = ZeroKernelPte;
        MmFirstFreeSystemPte[SystemPtePoolType].u.List.NextEntry =
                                                                MM_EMPTY_LIST;
        return;

    }

    //
    // Zero the system pte pool.
    //

    RtlFillMemoryUlong (StartingPte,
                        NumberOfPtes * sizeof (MMPTE),
                        ZeroKernelPte.u.Long);

    //
    // The page frame field points to the next cluster.  As we only
    // have one cluster at initialization time, mark it as the last
    // cluster.
    //

    StartingPte->u.List.NextEntry = MM_EMPTY_LIST;

    MmFirstFreeSystemPte[SystemPtePoolType] = ZeroKernelPte;
    MmFirstFreeSystemPte[SystemPtePoolType].u.List.NextEntry =
                                                StartingPte - MmSystemPteBase;

    //
    // Point to the next PTE to fill in the size of this cluster.
    //

    StartingPte++;
    *StartingPte = ZeroKernelPte;
    StartingPte->u.List.NextEntry = NumberOfPtes;

    MmTotalFreeSystemPtes[SystemPtePoolType] = NumberOfPtes;
    ASSERT (MmTotalFreeSystemPtes[SystemPtePoolType] ==
                         MiCountFreeSystemPtes (SystemPtePoolType));

    if (SystemPtePoolType == SystemPteSpace) {

        ULONG Lists[MM_SYS_PTE_TABLES_MAX] = {MM_PTE_LIST_1, MM_PTE_LIST_2, MM_PTE_LIST_4, MM_PTE_LIST_8, MM_PTE_LIST_16};
        PMMPTE PointerPte;
        ULONG total;

        for (j = 0; j < MM_SYS_PTE_TABLES_MAX ; j++) {
            MmFreeSysPteListBySize [j].u.List.NextEntry = MM_EMPTY_PTE_LIST;
            MmLastSysPteListBySize [j] = &MmFreeSysPteListBySize [j];
        }
        MmFlushCounter.u.List.NextEntry += 1;

        //
        // Initialize the by size lists.
        //

        total = MM_PTE_LIST_1 * MmSysPteIndex[0] +
                MM_PTE_LIST_2 * MmSysPteIndex[1] +
                MM_PTE_LIST_4 * MmSysPteIndex[2] +
                MM_PTE_LIST_8 * MmSysPteIndex[3] +
                MM_PTE_LIST_16 * MmSysPteIndex[4];

        PointerPte = MiReserveSystemPtes (total,
                                          SystemPteSpace,
                                          64*1024,
                                          0,
                                          TRUE);

#ifdef MIPS
        {
            ULONG inserted;

            //
            // For MIPS make sure buffers exist at all alignemnts.
            //

            do {
                inserted = FALSE;
                for (i = 0; i < MM_SYS_PTE_TABLES_MAX; i++) {
                    if (Lists[i]) {
                        Lists[i] -= 1;
                        MiReleaseSystemPtes (PointerPte,
                                             MmSysPteIndex[i],
                                             SystemPteSpace);
                        inserted = TRUE;
                        PointerPte += MmSysPteIndex[i];
                    }
                }
            } while (inserted);
        }

#else
        for (i = (MM_SYS_PTE_TABLES_MAX - 1); i >= 0; i--) {
            do {
                Lists[i] -= 1;
                MiReleaseSystemPtes (PointerPte,
                                     MmSysPteIndex[i],
                                     SystemPteSpace);
                PointerPte += MmSysPteIndex[i];
            } while (Lists[i] != 0  );
        }
#endif //MIPS
        MmFlushCounter.u.List.NextEntry += 1;
        MmFlushPte1 = NULL;
    }

    return;
}


#if DBG

VOID
MiDumpSystemPtes (
    IN MMSYSTEM_PTE_POOL_TYPE SystemPtePoolType
    )


{
    PMMPTE PointerPte;
    PMMPTE PointerNextPte;
    ULONG ClusterSize;
    PMMPTE EndOfCluster;

    PointerPte = &MmFirstFreeSystemPte[SystemPtePoolType];
    if (PointerPte->u.List.NextEntry == MM_EMPTY_PTE_LIST) {
        return;
    }

    PointerPte = MmSystemPteBase + PointerPte->u.List.NextEntry;

    for (;;) {
        if (PointerPte->u.List.OneEntry) {
            ClusterSize = 1;
        } else {
            PointerNextPte = PointerPte + 1;
            ClusterSize = PointerNextPte->u.List.NextEntry;
        }

        EndOfCluster = PointerPte + (ClusterSize - 1);

        DbgPrint("System Pte at %lx for %lx entries (%lx)\n",PointerPte,
                ClusterSize, EndOfCluster);

        if (PointerPte->u.List.NextEntry == MM_EMPTY_PTE_LIST) {
            break;
        }

        PointerPte = MmSystemPteBase + PointerPte->u.List.NextEntry;
    }
    return;
}

ULONG
MiCountFreeSystemPtes (
    IN MMSYSTEM_PTE_POOL_TYPE SystemPtePoolType
    )

{
    PMMPTE PointerPte;
    PMMPTE PointerNextPte;
    ULONG ClusterSize;
    PMMPTE EndOfCluster;
    ULONG FreeCount = 0;

    PointerPte = &MmFirstFreeSystemPte[SystemPtePoolType];
    if (PointerPte->u.List.NextEntry == MM_EMPTY_PTE_LIST) {
        return 0;
    }

    PointerPte = MmSystemPteBase + PointerPte->u.List.NextEntry;

    for (;;) {
        if (PointerPte->u.List.OneEntry) {
            ClusterSize = 1;
        } else {
            PointerNextPte = PointerPte + 1;
            ClusterSize = PointerNextPte->u.List.NextEntry;
        }

        FreeCount += ClusterSize;

        EndOfCluster = PointerPte + (ClusterSize - 1);

        if (PointerPte->u.List.NextEntry == MM_EMPTY_PTE_LIST) {
            break;
        }

        PointerPte = MmSystemPteBase + PointerPte->u.List.NextEntry;
    }
    return FreeCount;
}

#endif //DBG