summaryrefslogtreecommitdiffstats
path: root/private/ntos/mm/allocpag.c
blob: 2baf5dc4e1c4d85e3fd3fd2a9b51e376d31c6c58 (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
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

   allocpag.c

Abstract:

    This module contains the routines which allocate and deallocate
    one or more pages from paged or nonpaged pool.

Author:

    Lou Perazzoli (loup) 6-Apr-1989

Revision History:

--*/

#include "mi.h"

#ifdef ALLOC_PRAGMA
#pragma alloc_text(INIT,MiInitializeNonPagedPool)
#if DBG || (i386 && !FPO)
#pragma alloc_text(PAGELK, MmSnapShotPool)
#endif // DBG || (i386 && !FPO)
#endif

ULONG MmPagedPoolHint;

ULONG MmPagedPoolCommit;

ULONG MmAllocatedPagedPool;

ULONG MmAllocatedNonPagedPool;

PVOID MmNonPagedPoolExpansionStart;

LIST_ENTRY MmNonPagedPoolFreeListHead;

extern ULONG MmSystemPageDirectory;

extern POOL_DESCRIPTOR NonPagedPoolDescriptor;

#define MM_SMALL_ALLOCATIONS 4


POOL_TYPE
MmDeterminePoolType (
    IN PVOID VirtualAddress
    )

/*++

Routine Description:

    This function determines which pool a virtual address resides within.

Arguments:

    VirtualAddress - Supplies the virtual address to determine which pool
                     it resides within.

Return Value:

    Returns the POOL_TYPE (PagedPool or NonPagedPool), it never returns
            any information about MustSucceed pool types.

Environment:

    Kernel Mode Only.

--*/

{
    if ((VirtualAddress >= MmPagedPoolStart) &&
        (VirtualAddress <= MmPagedPoolEnd)) {
        return PagedPool;
    }
    return NonPagedPool;
}


PVOID
MiAllocatePoolPages (
    IN POOL_TYPE PoolType,
    IN ULONG SizeInBytes
    )

/*++

Routine Description:

    This function allocates a set of pages from the specified pool
    and returns the starting virtual address to the caller.

    For the NonPagedPoolMustSucceed case, the caller must first
    attempt to get NonPagedPool and if and ONLY IF that fails, then
    MiAllocatePoolPages should be called again with the PoolType of
    NonPagedPoolMustSucceed.

Arguments:

    PoolType - Supplies the type of pool from which to obtain pages.

    SizeInBytes - Supplies the size of the request in bytes.  The actual
                  size returned is rounded up to a page boundary.

Return Value:

    Returns a pointer to the allocated pool, or NULL if no more pool is
    available.

Environment:

    These functions are used by the general pool allocation routines
    and should not be called directly.

    Mutexes guarding the pool databases must be held when calling
    these functions.

    Kernel mode, IRQP at DISPATCH_LEVEL.

--*/

{
    ULONG SizeInPages;
    ULONG StartPosition;
    ULONG EndPosition;
    PMMPTE StartingPte;
    PMMPTE PointerPte;
    PMMPFN Pfn1;
    MMPTE TempPte;
    ULONG PageFrameIndex;
    PVOID BaseVa;
    KIRQL OldIrql;
    ULONG i;
    PLIST_ENTRY Entry;
    PMMFREE_POOL_ENTRY FreePageInfo;

    SizeInPages = BYTES_TO_PAGES (SizeInBytes);

    ASSERT (SizeInPages < 10000);

    if (PoolType == NonPagedPoolMustSucceed) {

        //
        // Pool expansion failed, see if any Must Succeed
        // pool is still left.
        //

        if (MmNonPagedMustSucceed == NULL) {

            //
            // No more pool exists.  Bug Check.
            //

            KeBugCheckEx (MUST_SUCCEED_POOL_EMPTY,
                          SizeInBytes,
                          NonPagedPoolDescriptor.TotalPages,
                          NonPagedPoolDescriptor.TotalBigPages,
                          MmAvailablePages);
        }

        //
        // Remove a page from the must succeed pool.
        //

        ASSERT (SizeInBytes <= PAGE_SIZE);

        BaseVa = MmNonPagedMustSucceed;

        MmNonPagedMustSucceed = (PVOID)(*(PULONG)BaseVa);
        return BaseVa;
    }

    if (PoolType == NonPagedPool) {

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

        Entry = MmNonPagedPoolFreeListHead.Flink;

        while (Entry != &MmNonPagedPoolFreeListHead) {

            //
            // The list is not empty, see if this one has enough
            // space.
            //

            FreePageInfo = CONTAINING_RECORD(Entry,
                                             MMFREE_POOL_ENTRY,
                                             List);

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

                //
                // This entry has sufficient space, remove
                // the pages from the end of the allocation.
                //

                FreePageInfo->Size -= SizeInPages;

                if (FreePageInfo->Size == 0) {
                    RemoveEntryList (&FreePageInfo->List);
                }

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

                MmNumberOfFreeNonPagedPool -= SizeInPages;
                ASSERT ((LONG)MmNumberOfFreeNonPagedPool >= 0);

                BaseVa = (PVOID)((PCHAR)FreePageInfo +
                                        (FreePageInfo->Size  << PAGE_SHIFT));

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

                if (MI_IS_PHYSICAL_ADDRESS(BaseVa)) {

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

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

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

                //
                // Calculate the ending PTE's address.
                //

                if (SizeInPages != 1) {

                    if (MI_IS_PHYSICAL_ADDRESS(BaseVa)) {
                        Pfn1 += SizeInPages - 1;
                    } else {
                        PointerPte += SizeInPages - 1;
                        ASSERT (PointerPte->u.Hard.Valid == 1);
                        Pfn1 = MI_PFN_ELEMENT (PointerPte->u.Hard.PageFrameNumber);
                    }

                } else {

#if defined(_ALPHA_)

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

                   if  ((BaseVa > (PVOID)KSEG2_BASE) &&
                        (PageFrameIndex < MmSubsectionTopPage)) {
                       BaseVa = (PVOID)(KSEG0_BASE + (PageFrameIndex << PAGE_SHIFT));
                   }
#endif //ALPHA

#if defined(_MIPS_)

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

                   if  ((BaseVa > (PVOID)KSEG1_BASE) &&
                        (MI_GET_PAGE_COLOR_FROM_VA (BaseVa) ==
                           (MM_COLOR_MASK & PageFrameIndex)) &&
                       (PageFrameIndex < MmSubsectionTopPage)) {
                       BaseVa = (PVOID)(KSEG0_BASE + (PageFrameIndex << PAGE_SHIFT));
                   }
#endif //MIPS

#if defined(_X86_)

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

                   if  ((BaseVa > (PVOID)MM_KSEG2_BASE) &&
                        (PageFrameIndex < MmSubsectionTopPage)) {
                       BaseVa = (PVOID)(MM_KSEG0_BASE + (PageFrameIndex << PAGE_SHIFT));
                   }
#endif //X86

                NOTHING;

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

                MmAllocatedNonPagedPool += SizeInPages;
                return BaseVa;
            }
            Entry = FreePageInfo->List.Flink;
        }

        //
        // No more entries on the list, expand nonpaged pool if
        // possible to satisfy this request.
        //

        //
        // Check to see if there are too many unused segments laying
        // around, and if so, set an event so they get deleted.
        //

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

        LOCK_PFN2 (OldIrql);

        //
        // Make sure we have 1 more than the number of pages
        // requested available.
        //

        if (MmAvailablePages <= SizeInPages) {

            UNLOCK_PFN2 (OldIrql);

            //
            // There are free physical pages to expand
            // nonpaged pool.
            //

            return NULL;
        }

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

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

        if (StartingPte == NULL) {

            UNLOCK_PFN2 (OldIrql);

            //
            // There are no free physical PTEs to expand
            // nonpaged pool.
            //

            return NULL;
        }

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

        MmResidentAvailablePages -= SizeInPages;

        //
        // Charge commitment as non paged pool uses physical memory.
        //

        MiChargeCommitmentCantExpand (SizeInPages, TRUE);

        //
        //  Expand the pool.
        //

        PointerPte = StartingPte;
        TempPte = ValidKernelPte;
        MmAllocatedNonPagedPool += SizeInPages;
        i= SizeInPages;

        do {
            PageFrameIndex = MiRemoveAnyPage (
                                MI_GET_PAGE_COLOR_FROM_PTE (PointerPte));

            Pfn1 = MI_PFN_ELEMENT (PageFrameIndex);

            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;

            TempPte.u.Hard.PageFrameNumber = PageFrameIndex;
            *PointerPte = TempPte;
            PointerPte += 1;
            SizeInPages -= 1;
        } while (SizeInPages > 0);

        Pfn1->u3.e1.EndOfAllocation = 1;
        Pfn1 = MI_PFN_ELEMENT (StartingPte->u.Hard.PageFrameNumber);
        Pfn1->u3.e1.StartOfAllocation = 1;

        UNLOCK_PFN2 (OldIrql);

        BaseVa = MiGetVirtualAddressMappedByPte (StartingPte);

#if defined(_ALPHA_)
        if (i == 1) {

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

            if (PageFrameIndex < MmSubsectionTopPage) {
                 BaseVa = (PVOID)(KSEG0_BASE + (PageFrameIndex << PAGE_SHIFT));
            }
        }
#endif //ALPHA

#if defined(_MIPS_)
        if (i == 1) {

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

            if ((MI_GET_PAGE_COLOR_FROM_VA (BaseVa) ==
                    (MM_COLOR_MASK & PageFrameIndex)) &&
                (PageFrameIndex < MmSubsectionTopPage)) {
                BaseVa = (PVOID)(KSEG0_BASE + (PageFrameIndex << PAGE_SHIFT));
            }
        }
#endif //MIPS

#if defined(_X86_)
       if (i == 1) {
            //
            // See if KSEG0 can be used to map this.
            //

            if (PageFrameIndex < MmSubsectionTopPage) {
                BaseVa = (PVOID)(MM_KSEG0_BASE + (PageFrameIndex << PAGE_SHIFT));
            }
       }
#endif //X86

        return BaseVa;
    }

    //
    // Paged Pool.
    //

    StartPosition = RtlFindClearBitsAndSet (
                               MmPagedPoolAllocationMap,
                               SizeInPages,
                               MmPagedPoolHint
                               );

    if ((StartPosition == 0xFFFFFFFF) &&
        (MmPagedPoolHint != 0)) {

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

        //
        // No free bits were found, check from the start of
        // the bit map.

        StartPosition = RtlFindClearBitsAndSet (
                                   MmPagedPoolAllocationMap,
                                   SizeInPages,
                                   0
                                   );
    }

    //
    // If start position = -1, no room in pool.  Attempt to
    // expand NonPagedPool.
    //

    if (StartPosition == 0xFFFFFFFF) {


        //
        // Attempt to expand the paged pool.
        //

        StartPosition = ((SizeInPages - 1) / PTE_PER_PAGE) + 1;

        //
        // Make sure there are enough space to create the prototype PTEs.
        //

        if (((StartPosition - 1) + MmNextPteForPagedPoolExpansion) >
            MiGetPteAddress (MmLastPteForPagedPool)) {

            //
            // Can't expand pool any more.
            //

            return NULL;
        }

        LOCK_PFN (OldIrql);

        //
        // Make sure we have 1 more than the number of pages
        // requested available.
        //

        if (MmAvailablePages <= StartPosition) {

            UNLOCK_PFN (OldIrql);

            //
            // There are free physical pages to expand
            // paged pool.
            //

            return NULL;
        }

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

        MmResidentAvailablePages -= StartPosition;

        //
        //  Expand the pool.
        //

        EndPosition = (MmNextPteForPagedPoolExpansion -
                          MiGetPteAddress(MmFirstPteForPagedPool)) *
                          PTE_PER_PAGE;

        RtlClearBits (MmPagedPoolAllocationMap,
                      EndPosition,
                      StartPosition * PTE_PER_PAGE);

        PointerPte = MmNextPteForPagedPoolExpansion;
        StartingPte =
                (PMMPTE)MiGetVirtualAddressMappedByPte(PointerPte);
        MmNextPteForPagedPoolExpansion += StartPosition;

        TempPte = ValidKernelPde;

        do {
            ASSERT (PointerPte->u.Hard.Valid == 0);

            MiChargeCommitmentCantExpand (1, TRUE);
            PageFrameIndex = MiRemoveAnyPage (
                                MI_GET_PAGE_COLOR_FROM_PTE (PointerPte));
            TempPte.u.Hard.PageFrameNumber = PageFrameIndex;
            *PointerPte = TempPte;

            //
            // Map valid PDE into system address space as well.
            //

            MmSystemPagePtes [((ULONG)PointerPte &
                    ((sizeof(MMPTE) * PDE_PER_PAGE) - 1)) / sizeof(MMPTE)] =
                                     TempPte;

            MiInitializePfnForOtherProcess (PageFrameIndex,
                                            PointerPte,
                                            MmSystemPageDirectory);

            RtlFillMemoryUlong (StartingPte,
                                PAGE_SIZE,
                                MM_KERNEL_DEMAND_ZERO_PTE);

            PointerPte += 1;
            StartingPte += PAGE_SIZE / sizeof(MMPTE);
            StartPosition -= 1;
        } while (StartPosition > 0);

        UNLOCK_PFN (OldIrql);

        StartPosition = RtlFindClearBitsAndSet (
                                   MmPagedPoolAllocationMap,
                                   SizeInPages,
                                   EndPosition
                                   );
        ASSERT (StartPosition != 0xffffffff);
    }
    MmPagedPoolHint = StartPosition + SizeInPages - 1;

    BaseVa = (PVOID)((PUCHAR)MmPageAlignedPoolBase[PoolType] +
                            (StartPosition * PAGE_SIZE));

    //
    // This is paged pool, the start and end can't be saved
    // in the PFN database as the page isn't always resident
    // in memory.  The ideal place to save the start and end
    // would be in the prototype PTE, but there are no free
    // bits.  To solve this problem, a bitmap which parallels
    // the allocation bitmap exists which contains set bits
    // in the positions where an allocation ends.  This
    // allows pages to be deallocated with only their starting
    // address.
    //
    // For sanity's sake, the starting address can be verified
    // from the 2 bitmaps as well.  If the page before the starting
    // address is not allocated (bit is zero in allocation bitmap)
    // then this page is obviously a start of an allocation block.
    // If the page before is allocated and the other bit map does
    // not indicate the previous page is the end of an allocation,
    // then the starting address is wrong and a bug check should
    // be issued.
    //

    try {

        MiChargeCommitmentCantExpand (SizeInPages, FALSE);
    } except (EXCEPTION_EXECUTE_HANDLER) {

        RtlClearBits (MmPagedPoolAllocationMap,
                      StartPosition,
                      SizeInPages);

        //
        // Could not commit the page, return NULL indicating
        // no pool was allocated.
        //

        return(NULL);
    }

    MmPagedPoolCommit += SizeInPages;
    EndPosition = StartPosition + SizeInPages - 1;
    RtlSetBits (MmEndOfPagedPoolBitmap, EndPosition, 1L);

    MmAllocatedPagedPool += SizeInPages;
    return BaseVa;
}

ULONG
MiFreePoolPages (
    IN PVOID StartingAddress
    )

/*++

Routine Description:

    This function returns a set of pages back to the pool from
    which they were obtained.  Once the pages have been deallocated
    the region provided by the allocation becomes available for
    allocation to other callers, i.e. any data in the region is now
    trashed and cannot be referenced.

Arguments:

    StartingAddress - Supplies the starting address which was returned
                      in a previous call to VmAllocatePages.

Return Value:

    Returns the number of pages deallocated.

Environment:

    These functions are used by the general pool allocation routines
    and should not be called directly.

    Mutexes guarding the pool databases must be held when calling
    these functions.

--*/

{
    ULONG StartPosition;
    ULONG i;
    ULONG NumberOfPages = 1;
    POOL_TYPE PoolType;
    PMMPTE PointerPte;
    PMMPFN Pfn1;
    ULONG PageFrameIndex;
    KIRQL OldIrql;
    PMMFREE_POOL_ENTRY Entry;
    PMMFREE_POOL_ENTRY NextEntry;

    //
    // Determine Pool type base on the virtual address of the block
    // to deallocate.
    //
    // This assumes NonPagedPool starts at a higher virtual address
    // then PagedPool.
    //

    if ((StartingAddress >= MmPagedPoolStart) &&
        (StartingAddress <= MmPagedPoolEnd)) {
        PoolType = PagedPool;
    } else {
        PoolType = NonPagedPool;
    }

    StartPosition = ((ULONG)StartingAddress -
                      (ULONG)MmPageAlignedPoolBase[PoolType]) >> PAGE_SHIFT;

    //
    // Check to insure this page is really a start of allocation.
    //

    if (PoolType == NonPagedPool) {

        if (StartPosition < MmMustSucceedPoolBitPosition) {

            PULONG NextList;

            //
            // This is must succeed pool, don't free it, just
            // add it to the front of the list.
            //
            // Note - only a single page can be released at a time.
            //

            NextList = (PULONG)StartingAddress;
            *NextList = (ULONG)MmNonPagedMustSucceed;
            MmNonPagedMustSucceed = StartingAddress;
            return NumberOfPages;
        }

        if (MI_IS_PHYSICAL_ADDRESS (StartingAddress)) {

            //
            // 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 (StartingAddress));
            if (StartPosition >= MmExpandedPoolBitPosition) {
                PointerPte = Pfn1->PteAddress;
                StartingAddress = MiGetVirtualAddressMappedByPte (PointerPte);
            }
        } else {
            PointerPte = MiGetPteAddress (StartingAddress);
            Pfn1 = MI_PFN_ELEMENT (PointerPte->u.Hard.PageFrameNumber);
        }

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

#if DBG
        if ((Pfn1->u3.e2.ReferenceCount > 1) &&
            (Pfn1->u3.e1.WriteInProgress == 0)) {
            DbgPrint ("MM:ALLOCPAGE - deleting pool locked for I/O %lx\n",
                 PageFrameIndex);
            ASSERT (Pfn1->u3.e2.ReferenceCount == 1);
        }
#endif //DBG

        //
        // Find end of allocation and release the pages.
        //

        while (Pfn1->u3.e1.EndOfAllocation == 0) {
            if (MI_IS_PHYSICAL_ADDRESS(StartingAddress)) {
                Pfn1 += 1;
            } else {
                PointerPte++;
                Pfn1 = MI_PFN_ELEMENT (PointerPte->u.Hard.PageFrameNumber);
            }
            NumberOfPages++;
#if DBG
            if ((Pfn1->u3.e2.ReferenceCount > 1) &&
                (Pfn1->u3.e1.WriteInProgress == 0)) {
                DbgPrint ("MM:ALLOCPAGE - deleting pool locked for I/O %lx\n",
                     PageFrameIndex);
                ASSERT (Pfn1->u3.e2.ReferenceCount == 1);
            }
#endif //DBG
        }

        MmAllocatedNonPagedPool -= NumberOfPages;

        Pfn1->u3.e1.EndOfAllocation = 0;
#if DBG
        RtlFillMemoryUlong (StartingAddress,
                            PAGE_SIZE * NumberOfPages,
                            0x23456789);
#endif //DBG

        if (StartingAddress > MmNonPagedPoolExpansionStart) {

            //
            // This page was from the expanded pool, should
            // it be freed?
            //
            // NOTE: all pages in the expanded pool area have PTEs
            // so no physical address checks need to be performed.
            //

            if ((NumberOfPages > 3) || (MmNumberOfFreeNonPagedPool > 5)) {

                //
                // Free these pages back to the free page list.
                //

                MI_MAKING_MULTIPLE_PTES_INVALID (TRUE);

                PointerPte = MiGetPteAddress (StartingAddress);

                //
                // Return commitment.
                //

                MiReturnCommitment (NumberOfPages);

                LOCK_PFN2 (OldIrql);

                for (i=0; i < NumberOfPages; i++) {

                    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);
                    Pfn1->u2.ShareCount = 0;
                    MI_SET_PFN_DELETED (Pfn1);
#if DBG
                    Pfn1->u3.e1.PageLocation = StandbyPageList;
#endif //DBG
                    MiDecrementReferenceCount (PageFrameIndex);

                    (VOID)KeFlushSingleTb (StartingAddress,
                                           TRUE,
                                           TRUE,
                                           (PHARDWARE_PTE)PointerPte,
                                           ZeroKernelPte.u.Flush);
                    StartingAddress = (PVOID)((ULONG)StartingAddress +
                                                                    PAGE_SIZE);
                    PointerPte += 1;
                }

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

                MmResidentAvailablePages += NumberOfPages;

                UNLOCK_PFN2(OldIrql);

                PointerPte -= NumberOfPages;

                MiReleaseSystemPtes (PointerPte,
                                     NumberOfPages,
                                     NonPagedPoolExpansion);

                return NumberOfPages;
            }
        }

        //
        // Add the pages to the list of free pages.
        //

        MmNumberOfFreeNonPagedPool += NumberOfPages;

        //
        // Check to see if the next allocation is free.
        //

        i = NumberOfPages;

        if (MI_IS_PHYSICAL_ADDRESS(StartingAddress)) {
            Pfn1 += 1;
        } else {
            PointerPte += 1;
            if (PointerPte->u.Hard.Valid == 1) {
                Pfn1 = MI_PFN_ELEMENT (PointerPte->u.Hard.PageFrameNumber);
            } else {
                Pfn1 = NULL;
            }
        }

        if (Pfn1 != NULL) {
            if (Pfn1->u3.e1.StartOfAllocation == 0) {

                //
                // This range of pages is free.  Remove this entry
                // from the list and add these pages to the current
                // range being freed.
                //

                Entry = (PMMFREE_POOL_ENTRY)((PCHAR)StartingAddress
                                            + (NumberOfPages << PAGE_SHIFT));
                ASSERT (Entry->Signature == MM_FREE_POOL_SIGNATURE);
                ASSERT (Entry->Owner == Entry);
#if DBG
                {
                    PMMPTE DebugPte;
                    PMMPFN DebugPfn;
                    if (MI_IS_PHYSICAL_ADDRESS(StartingAddress)) {

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

                        DebugPfn = MI_PFN_ELEMENT (MI_CONVERT_PHYSICAL_TO_PFN (Entry));
                        DebugPfn += Entry->Size;
                        ASSERT (DebugPfn->u3.e1.StartOfAllocation == 1);
                    } else {
                        DebugPte = PointerPte + Entry->Size;
                        if (DebugPte->u.Hard.Valid == 1) {
                            DebugPfn = MI_PFN_ELEMENT (DebugPte->u.Hard.PageFrameNumber);
                            ASSERT (DebugPfn->u3.e1.StartOfAllocation == 1);
                        }
                    }
                }
#endif //DBG

                i += Entry->Size;
                RemoveEntryList (&Entry->List);
            }
        }

        //
        // Check to see if the previous page is the end of an allocation.
        // If it is not then end of an allocation, it must be free and
        // therefore this allocation can be tagged onto the end of
        // that allocation.
        //

        Entry = (PMMFREE_POOL_ENTRY)StartingAddress;

        if (MI_IS_PHYSICAL_ADDRESS(StartingAddress)) {
            Pfn1 = MI_PFN_ELEMENT (MI_CONVERT_PHYSICAL_TO_PFN (
                                        (PVOID)((PCHAR)Entry - PAGE_SIZE)));
        } else {
            PointerPte -= NumberOfPages + 1;
            if (PointerPte->u.Hard.Valid == 1) {
                Pfn1 = MI_PFN_ELEMENT (PointerPte->u.Hard.PageFrameNumber);
            } else {
                Pfn1 = NULL;
            }
        }
        if (Pfn1 != NULL) {
            if (Pfn1->u3.e1.EndOfAllocation == 0) {

                //
                // This range of pages is free, add these pages to
                // this entry.  The owner field points to the address
                // of the list entry which is linked into the free pool
                // pages list.
                //

                Entry = (PMMFREE_POOL_ENTRY)((PCHAR)StartingAddress - PAGE_SIZE);
                ASSERT (Entry->Signature == MM_FREE_POOL_SIGNATURE);
                Entry = Entry->Owner;
                ASSERT (Entry->Owner == Entry);

                //
                // If this entry became larger than MM_SMALL_ALLOCATIONS
                // pages, move it to the tail of the list.  This keeps the
                // small allocations at the front of the list.
                //

                if ((Entry->Size < MM_SMALL_ALLOCATIONS) &&
                    (Entry->Size + i) >= MM_SMALL_ALLOCATIONS) {

                    RemoveEntryList (&Entry->List);
                    InsertTailList (&MmNonPagedPoolFreeListHead, &Entry->List);
                }

                //
                // Add these pages to the previous entry.
                //

                Entry->Size += i;
            }
        }

        if (Entry == (PMMFREE_POOL_ENTRY)StartingAddress) {

            //
            // This entry was not combined with the previous, insert it
            // into the list.
            //

            Entry->Size = i;
            if (Entry->Size < MM_SMALL_ALLOCATIONS) {

                //
                // Small number of pages, insert this at the head of the list.
                //

                InsertHeadList (&MmNonPagedPoolFreeListHead, &Entry->List);
            } else {
                InsertTailList (&MmNonPagedPoolFreeListHead, &Entry->List);
            }
        }

        //
        // Set the owner field in all these pages.
        //

        NextEntry = (PMMFREE_POOL_ENTRY)StartingAddress;
        while (i > 0) {
            NextEntry->Owner = Entry;
#if DBG
            NextEntry->Signature = MM_FREE_POOL_SIGNATURE;
#endif

            NextEntry = (PMMFREE_POOL_ENTRY)((PCHAR)NextEntry + PAGE_SIZE);
            i -= 1;
        }

#if DBG
        NextEntry = Entry;
        for (i=0;i<Entry->Size ;i++ ) {
            {
                PMMPTE DebugPte;
                PMMPFN DebugPfn;
                if (MI_IS_PHYSICAL_ADDRESS(StartingAddress)) {

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

                    DebugPfn = MI_PFN_ELEMENT (MI_CONVERT_PHYSICAL_TO_PFN (NextEntry));
                } else {

                    DebugPte = MiGetPteAddress (NextEntry);
                    DebugPfn = MI_PFN_ELEMENT (DebugPte->u.Hard.PageFrameNumber);
                }
                ASSERT (DebugPfn->u3.e1.StartOfAllocation == 0);
                ASSERT (DebugPfn->u3.e1.EndOfAllocation == 0);
                ASSERT (NextEntry->Owner == Entry);
                NextEntry = (PMMFREE_POOL_ENTRY)((PCHAR)NextEntry + PAGE_SIZE);
            }
        }
#endif

        return NumberOfPages;

    } else {

        //
        // Paged pool.  Need to verify start of allocation using
        // end of allocation bitmap.
        //

        ASSERT (RtlCheckBit (MmPagedPoolAllocationMap, StartPosition));

#if DBG
        if (StartPosition > 0) {
            if (RtlCheckBit (MmPagedPoolAllocationMap, StartPosition - 1)) {
                if (!RtlCheckBit (MmEndOfPagedPoolBitmap, StartPosition - 1)) {

                    //
                    // In the middle of an allocation... bugcheck.
                    //

                    DbgPrint("paged pool in middle of allocation\n");
                    KeBugCheck (MEMORY_MANAGEMENT);
                }
            }
        }
#endif

        i = StartPosition;
        PointerPte = MmFirstPteForPagedPool + i;

        //
        // Find the last allocated page and check to see if any
        // of the pages being deallocated are in the paging file.
        //

        while (!RtlCheckBit (MmEndOfPagedPoolBitmap, i)) {
            NumberOfPages++;
            i++;
        }

        MiDeleteSystemPagableVm (PointerPte,
                                 NumberOfPages,
                                 MM_KERNEL_DEMAND_ZERO_PTE,
                                 &PageFrameIndex);

        //
        // Clear the end of allocation bit in the bit map.
        //

        RtlClearBits (MmEndOfPagedPoolBitmap, i, 1L);
        MiReturnCommitment (NumberOfPages);
        MmPagedPoolCommit -= NumberOfPages;
        MmAllocatedPagedPool -= NumberOfPages;

        //
        // Clear the allocation bits in the bit map.
        //

        RtlClearBits (
                 MmPagedPoolAllocationMap,
                 StartPosition,
                 NumberOfPages
                 );

        MmPagedPoolHint = StartPosition;

        return NumberOfPages;
    }
}

VOID
MiInitializeNonPagedPool (
    PVOID StartOfNonPagedPool
    )

/*++

Routine Description:

    This function initializes the NonPaged pool.

    NonPaged Pool is linked together through the pages.

Arguments:

    None.

Return Value:

    None.

Environment:

    Kernel mode, during initialization.

--*/

{
    ULONG PagesInPool;
    ULONG Size;
    PMMFREE_POOL_ENTRY FreeEntry;
    PMMFREE_POOL_ENTRY FirstEntry;
    PMMPTE PointerPte;
    ULONG i;
    PULONG ThisPage;
    PULONG NextPage;

    //
    // Initialize the list head for free pages.
    //

    InitializeListHead (&MmNonPagedPoolFreeListHead);

    //
    // Initialize the must succeed pool (this occupies the first
    // pages of the pool area).
    //

    //
    // Allocate NonPage pool for the NonPagedPoolMustSucceed pool.
    //

    MmNonPagedMustSucceed = (PCHAR)MmNonPagedPoolStart;

    i = MmSizeOfNonPagedMustSucceed - PAGE_SIZE;

    MmMustSucceedPoolBitPosition = BYTES_TO_PAGES(MmSizeOfNonPagedMustSucceed);

    ThisPage = (PULONG)MmNonPagedMustSucceed;

    while (i > 0) {
        NextPage = (PULONG)((ULONG)ThisPage + PAGE_SIZE);
        *ThisPage = (ULONG)NextPage;
        ThisPage = NextPage;
        i -= PAGE_SIZE;
    }
    *ThisPage = 0;

    //
    // Set up the remaining pages as non paged pool pages.
    // NOTE - that on MIPS the initial nonpaged pool could be physical,
    // so use the NonPagedPoolStart parameter to get the virtual
    // address for building expanded pool.
    //

    ASSERT ((MmSizeOfNonPagedMustSucceed & (PAGE_SIZE - 1)) == 0);
    FreeEntry = (PMMFREE_POOL_ENTRY)((PCHAR)MmNonPagedPoolStart +
                                            MmSizeOfNonPagedMustSucceed);
    FirstEntry = FreeEntry;

    PagesInPool = BYTES_TO_PAGES(MmSizeOfNonPagedPoolInBytes -
                                    MmSizeOfNonPagedMustSucceed);

    //
    // Set the location of expanded pool.
    //

    MmExpandedPoolBitPosition = BYTES_TO_PAGES (MmSizeOfNonPagedPoolInBytes);

    MmNumberOfFreeNonPagedPool = PagesInPool;;

    InsertHeadList (&MmNonPagedPoolFreeListHead, &FreeEntry->List);

    FreeEntry->Size = PagesInPool;
#if DBG
    FreeEntry->Signature = MM_FREE_POOL_SIGNATURE;
#endif
    FreeEntry->Owner = FirstEntry;

    while (PagesInPool > 1) {
        FreeEntry = (PMMFREE_POOL_ENTRY)((PCHAR)FreeEntry + PAGE_SIZE);
#if DBG
        FreeEntry->Signature = MM_FREE_POOL_SIGNATURE;
#endif
        FreeEntry->Owner = FirstEntry;
        PagesInPool -= 1;
    }

    //
    // Set up the system PTEs for nonpaged pool expansion.
    //

    PointerPte = MiGetPteAddress (MmNonPagedPoolExpansionStart);
    ASSERT (PointerPte->u.Hard.Valid == 0);

    Size = BYTES_TO_PAGES(MmMaximumNonPagedPoolInBytes -
                            MmSizeOfNonPagedPoolInBytes) - 1;

    MiInitializeSystemPtes (PointerPte,
                            Size,
                            NonPagedPoolExpansion
                            );

    //
    // Build a guard PTE.
    //

    PointerPte += Size;
    *PointerPte = ZeroKernelPte;

    return;
}

#if DBG || (i386 && !FPO)

//
// This only works on checked builds, because the TraceLargeAllocs array is
// kept in that case to keep track of page size pool allocations.  Otherwise
// we will call ExpSnapShotPoolPages with a page size pool allocation containing
// arbitrary data and it will potentially go off in the weeds trying to interpret
// it as a suballocated pool page.  Ideally, there would be another bit map
// that identified single page pool allocations so ExpSnapShotPoolPages would NOT
// be called for those.
//

NTSTATUS
MmSnapShotPool(
    IN POOL_TYPE PoolType,
    IN PMM_SNAPSHOT_POOL_PAGE SnapShotPoolPage,
    IN PSYSTEM_POOL_INFORMATION PoolInformation,
    IN ULONG Length,
    IN OUT PULONG RequiredLength
    )
{
    NTSTATUS Status;
    NTSTATUS xStatus;
    PCHAR p, pStart;
    PVOID *pp;
    ULONG Size;
    ULONG BusyFlag;
    ULONG CurrentPage, NumberOfPages;
    PSYSTEM_POOL_ENTRY PoolEntryInfo;
    PLIST_ENTRY Entry;
    PMMFREE_POOL_ENTRY FreePageInfo;
    ULONG StartPosition;
    PMMPTE PointerPte;
    PMMPFN Pfn1;

    Status = STATUS_SUCCESS;
    PoolEntryInfo = &PoolInformation->Entries[ 0 ];
    if (PoolType == PagedPool) {
        PoolInformation->TotalSize = (ULONG)MmPagedPoolEnd -
                                     (ULONG)MmPagedPoolStart;
        PoolInformation->FirstEntry = MmPagedPoolStart;
        p = MmPagedPoolStart;
        CurrentPage = 0;
        while (p < (PCHAR)MmPagedPoolEnd) {
            pStart = p;
            BusyFlag = RtlCheckBit( MmPagedPoolAllocationMap, CurrentPage );
            while ( ~(BusyFlag ^ RtlCheckBit( MmPagedPoolAllocationMap, CurrentPage )) ) {
                p += PAGE_SIZE;
                if (RtlCheckBit( MmEndOfPagedPoolBitmap, CurrentPage )) {
                    CurrentPage++;
                    break;
                    }

                CurrentPage++;
                if (p > (PCHAR)MmPagedPoolEnd) {
                   break;
                   }
                }

            Size = p - pStart;
            if (BusyFlag) {
                xStatus = (*SnapShotPoolPage)( pStart,
                                               Size,
                                               PoolInformation,
                                               &PoolEntryInfo,
                                               Length,
                                               RequiredLength
                                             );
                if ( xStatus != STATUS_COMMITMENT_LIMIT ) {
                    Status = xStatus;
                    }
                }
            else {
                PoolInformation->NumberOfEntries += 1;
                *RequiredLength += sizeof( SYSTEM_POOL_ENTRY );
                if (Length < *RequiredLength) {
                    Status = STATUS_INFO_LENGTH_MISMATCH;
                    }
                else {
                    PoolEntryInfo->Allocated = FALSE;
                    PoolEntryInfo->Size = Size;
                    PoolEntryInfo->AllocatorBackTraceIndex = 0;
                    PoolEntryInfo->TagUlong = 0;
                    PoolEntryInfo++;
                    Status = STATUS_SUCCESS;
                    }
                }
            }
        }
    else
    if (PoolType == NonPagedPool) {
        PoolInformation->TotalSize = MmSizeOfNonPagedPoolInBytes;
        PoolInformation->FirstEntry = MmNonPagedPoolStart;

        p = MmNonPagedPoolStart;
        while (p < (PCHAR)MmNonPagedPoolEnd) {

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

            pp = (PVOID *)MmNonPagedMustSucceed;
            while (pp) {
                if (p == (PCHAR)pp) {
                    PoolInformation->NumberOfEntries += 1;
                    *RequiredLength += sizeof( SYSTEM_POOL_ENTRY );
                    if (Length < *RequiredLength) {
                        Status = STATUS_INFO_LENGTH_MISMATCH;
                        }
                    else {
                        PoolEntryInfo->Allocated = FALSE;
                        PoolEntryInfo->Size = PAGE_SIZE;
                        PoolEntryInfo->AllocatorBackTraceIndex = 0;
                        PoolEntryInfo->TagUlong = 0;
                        PoolEntryInfo++;
                        Status = STATUS_SUCCESS;
                        }

                    p += PAGE_SIZE;
                    pp = (PVOID *)MmNonPagedMustSucceed;
                    }
                else {
                    pp = (PVOID *)*pp;
                    }
                }

            Entry = MmNonPagedPoolFreeListHead.Flink;
            while (Entry != &MmNonPagedPoolFreeListHead) {
                FreePageInfo = CONTAINING_RECORD( Entry,
                                                  MMFREE_POOL_ENTRY,
                                                  List
                                                );

                ASSERT (FreePageInfo->Signature == MM_FREE_POOL_SIGNATURE);
                if (p == (PCHAR)FreePageInfo) {
                    Size = (FreePageInfo->Size * PAGE_SIZE);
                    PoolInformation->NumberOfEntries += 1;
                    *RequiredLength += sizeof( SYSTEM_POOL_ENTRY );
                    if (Length < *RequiredLength) {
                        Status = STATUS_INFO_LENGTH_MISMATCH;
                        }
                    else {
                        PoolEntryInfo->Allocated = FALSE;
                        PoolEntryInfo->Size = Size;
                        PoolEntryInfo->AllocatorBackTraceIndex = 0;
                        PoolEntryInfo->TagUlong = 0;
                        PoolEntryInfo++;
                        Status = STATUS_SUCCESS;
                        }

                    p += Size;
                    break;
                    }

                Entry = FreePageInfo->List.Flink;
                }

            StartPosition = BYTES_TO_PAGES((ULONG)p -
                  (ULONG)MmPageAlignedPoolBase[NonPagedPool]);
            if (StartPosition >= MmExpandedPoolBitPosition) {
                break;
                }

            if (StartPosition < MmMustSucceedPoolBitPosition) {
                Size = PAGE_SIZE;
                xStatus = (*SnapShotPoolPage)( p,
                                               Size,
                                               PoolInformation,
                                               &PoolEntryInfo,
                                               Length,
                                               RequiredLength
                                             );
                if ( xStatus != STATUS_COMMITMENT_LIMIT ) {
                    Status = xStatus;
                    }
                }
            else {
                if (MI_IS_PHYSICAL_ADDRESS(p)) {
                    //
                    // On certains architectures (e.g., MIPS) virtual addresses
                    // may be physical and hence have no corresponding PTE.
                    //
                    PointerPte = NULL;
                    Pfn1 = MI_PFN_ELEMENT (MI_CONVERT_PHYSICAL_TO_PFN (p));
                } else {
                    PointerPte = MiGetPteAddress (p);
                    Pfn1 = MI_PFN_ELEMENT (PointerPte->u.Hard.PageFrameNumber);
                }
                ASSERT (Pfn1->u3.e1.StartOfAllocation != 0);

                //
                // Find end of allocation and determine size.
                //

                NumberOfPages = 1;
                while (Pfn1->u3.e1.EndOfAllocation == 0) {
                    NumberOfPages++;
                    if (PointerPte == NULL) {
                        Pfn1 += 1;
                        }
                    else {
                        PointerPte++;
                        Pfn1 = MI_PFN_ELEMENT (PointerPte->u.Hard.PageFrameNumber);
                        }
                    }

                Size = NumberOfPages * PAGE_SIZE;
                xStatus = (*SnapShotPoolPage)( p,
                                               Size,
                                               PoolInformation,
                                               &PoolEntryInfo,
                                               Length,
                                               RequiredLength
                                             );
                if ( xStatus != STATUS_COMMITMENT_LIMIT ) {
                    Status = xStatus;
                    }
                }

            p += Size;
            }
        }
    else {
        Status = STATUS_NOT_IMPLEMENTED;
        }

    return( Status );
}


ULONG MmSpecialPoolTag;
PVOID MmSpecialPoolStart;
PVOID MmSpecialPoolEnd;
PMMPTE SpecialPoolFirstPte;
PMMPTE SpecialPoolLastPte;

VOID
MmInitializeSpecialPool (
    VOID
    )

{
    KIRQL OldIrql;
    PMMPTE pte;

    LOCK_PFN (OldIrql);
    SpecialPoolFirstPte = MiReserveSystemPtes (25000, SystemPteSpace, 0, 0, TRUE);
    UNLOCK_PFN (OldIrql);

    //
    // build list of pte pairs.
    //

    SpecialPoolLastPte = SpecialPoolFirstPte + 25000;
    MmSpecialPoolStart = MiGetVirtualAddressMappedByPte (SpecialPoolFirstPte);

    pte = SpecialPoolFirstPte;
    while (pte < SpecialPoolLastPte) {
        pte->u.List.NextEntry = ((pte+2) - MmSystemPteBase);
        pte += 2;
    }
    pte -= 2;
    pte->u.List.NextEntry = MM_EMPTY_PTE_LIST;
    SpecialPoolLastPte = pte;
    MmSpecialPoolEnd = MiGetVirtualAddressMappedByPte (SpecialPoolLastPte + 1);
}


PVOID
MmAllocateSpecialPool (
    IN ULONG NumberOfBytes,
    IN ULONG Tag
    )

{
    MMPTE TempPte;
    ULONG PageFrameIndex;
    PMMPTE PointerPte;
    KIRQL OldIrql2;
    PULONG Entry;


    TempPte = ValidKernelPte;

    LOCK_PFN2 (OldIrql2);
    if (MmAvailablePages == 0) {
        KeBugCheck (MEMORY_MANAGEMENT);
    }

    PointerPte = SpecialPoolFirstPte;

    ASSERT (SpecialPoolFirstPte->u.List.NextEntry != MM_EMPTY_PTE_LIST);

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

    PageFrameIndex = MiRemoveAnyPage (MI_GET_PAGE_COLOR_FROM_PTE (PointerPte));

    TempPte.u.Hard.PageFrameNumber = PageFrameIndex;
    *PointerPte = TempPte;
    MiInitializePfn (PageFrameIndex, PointerPte, 1);
    UNLOCK_PFN2 (OldIrql2);

    Entry = (PULONG)MiGetVirtualAddressMappedByPte (PointerPte);

    Entry = (PULONG)(PVOID)(((ULONG)Entry + (PAGE_SIZE - (NumberOfBytes + 8))) &
            0xfffffff8L);

    *Entry = MmSpecialPoolTag;
    Entry += 1;
    *Entry = NumberOfBytes;
    Entry += 1;
    return (PVOID)(Entry);
}

VOID
MmFreeSpecialPool (
    IN PVOID P
    )

{
    PMMPTE PointerPte;
    PMMPFN Pfn1;
    PULONG Entry;
    KIRQL OldIrql;

    Entry = (PULONG)((PCH)P - 8);

    PointerPte = MiGetPteAddress (P);

    if (PointerPte->u.Hard.Valid == 0) {
        KeBugCheck (MEMORY_MANAGEMENT);
    }

    ASSERT (*Entry == MmSpecialPoolTag);

    KeSweepDcache(TRUE);

    Pfn1 = MI_PFN_ELEMENT (PointerPte->u.Hard.PageFrameNumber);
    MI_SET_PFN_DELETED (Pfn1);

    LOCK_PFN2 (OldIrql);
    MiDecrementShareCount (PointerPte->u.Hard.PageFrameNumber);
    KeFlushSingleTb (PAGE_ALIGN(P),
                     TRUE,
                     TRUE,
                     (PHARDWARE_PTE)PointerPte,
                     ZeroKernelPte.u.Flush);

    ASSERT (SpecialPoolLastPte->u.List.NextEntry == MM_EMPTY_PTE_LIST);
    SpecialPoolLastPte->u.List.NextEntry = PointerPte - MmSystemPteBase;

    SpecialPoolLastPte = PointerPte;
    SpecialPoolLastPte->u.List.NextEntry = MM_EMPTY_PTE_LIST;

    UNLOCK_PFN2 (OldIrql);

    return;
}

#endif // DBG || (i386 && !FPO)