2 * PROJECT: ReactOS Kernel
3 * LICENSE: BSD - See COPYING.ARM in the top level directory
4 * FILE: ntoskrnl/mm/ARM3/expool.c
5 * PURPOSE: ARM Memory Manager Executive Pool Manager
6 * PROGRAMMERS: ReactOS Portable Systems Group
9 /* INCLUDES *******************************************************************/
15 #define MODULE_INVOLVED_IN_ARM3
16 #include "../ARM3/miarm.h"
18 #undef ExAllocatePoolWithQuota
19 #undef ExAllocatePoolWithQuotaTag
21 /* GLOBALS ********************************************************************/
23 #define POOL_BIG_TABLE_ENTRY_FREE 0x1
25 typedef struct _POOL_DPC_CONTEXT
27 PPOOL_TRACKER_TABLE PoolTrackTable
;
28 SIZE_T PoolTrackTableSize
;
29 PPOOL_TRACKER_TABLE PoolTrackTableExpansion
;
30 SIZE_T PoolTrackTableSizeExpansion
;
31 } POOL_DPC_CONTEXT
, *PPOOL_DPC_CONTEXT
;
33 ULONG ExpNumberOfPagedPools
;
34 POOL_DESCRIPTOR NonPagedPoolDescriptor
;
35 PPOOL_DESCRIPTOR ExpPagedPoolDescriptor
[16 + 1];
36 PPOOL_DESCRIPTOR PoolVector
[2];
37 PKGUARDED_MUTEX ExpPagedPoolMutex
;
38 SIZE_T PoolTrackTableSize
, PoolTrackTableMask
;
39 SIZE_T PoolBigPageTableSize
, PoolBigPageTableHash
;
40 PPOOL_TRACKER_TABLE PoolTrackTable
;
41 PPOOL_TRACKER_BIG_PAGES PoolBigPageTable
;
42 KSPIN_LOCK ExpTaggedPoolLock
;
44 BOOLEAN ExStopBadTags
;
45 KSPIN_LOCK ExpLargePoolTableLock
;
46 LONG ExpPoolBigEntriesInUse
;
50 /* Pool block/header/list access macros */
51 #define POOL_ENTRY(x) (PPOOL_HEADER)((ULONG_PTR)(x) - sizeof(POOL_HEADER))
52 #define POOL_FREE_BLOCK(x) (PLIST_ENTRY)((ULONG_PTR)(x) + sizeof(POOL_HEADER))
53 #define POOL_BLOCK(x, i) (PPOOL_HEADER)((ULONG_PTR)(x) + ((i) * POOL_BLOCK_SIZE))
54 #define POOL_NEXT_BLOCK(x) POOL_BLOCK((x), (x)->BlockSize)
55 #define POOL_PREV_BLOCK(x) POOL_BLOCK((x), -((x)->PreviousSize))
58 * Pool list access debug macros, similar to Arthur's pfnlist.c work.
59 * Microsoft actually implements similar checks in the Windows Server 2003 SP1
60 * pool code, but only for checked builds.
62 * As of Vista, however, an MSDN Blog entry by a Security Team Manager indicates
63 * that these checks are done even on retail builds, due to the increasing
64 * number of kernel-mode attacks which depend on dangling list pointers and other
65 * kinds of list-based attacks.
67 * For now, I will leave these checks on all the time, but later they are likely
68 * to be DBG-only, at least until there are enough kernel-mode security attacks
69 * against ReactOS to warrant the performance hit.
71 * For now, these are not made inline, so we can get good stack traces.
75 ExpDecodePoolLink(IN PLIST_ENTRY Link
)
77 return (PLIST_ENTRY
)((ULONG_PTR
)Link
& ~1);
82 ExpEncodePoolLink(IN PLIST_ENTRY Link
)
84 return (PLIST_ENTRY
)((ULONG_PTR
)Link
| 1);
89 ExpCheckPoolLinks(IN PLIST_ENTRY ListHead
)
91 if ((ExpDecodePoolLink(ExpDecodePoolLink(ListHead
->Flink
)->Blink
) != ListHead
) ||
92 (ExpDecodePoolLink(ExpDecodePoolLink(ListHead
->Blink
)->Flink
) != ListHead
))
94 KeBugCheckEx(BAD_POOL_HEADER
,
97 (ULONG_PTR
)ExpDecodePoolLink(ExpDecodePoolLink(ListHead
->Flink
)->Blink
),
98 (ULONG_PTR
)ExpDecodePoolLink(ExpDecodePoolLink(ListHead
->Blink
)->Flink
));
104 ExpInitializePoolListHead(IN PLIST_ENTRY ListHead
)
106 ListHead
->Flink
= ListHead
->Blink
= ExpEncodePoolLink(ListHead
);
111 ExpIsPoolListEmpty(IN PLIST_ENTRY ListHead
)
113 return (ExpDecodePoolLink(ListHead
->Flink
) == ListHead
);
118 ExpRemovePoolEntryList(IN PLIST_ENTRY Entry
)
120 PLIST_ENTRY Blink
, Flink
;
121 Flink
= ExpDecodePoolLink(Entry
->Flink
);
122 Blink
= ExpDecodePoolLink(Entry
->Blink
);
123 Flink
->Blink
= ExpEncodePoolLink(Blink
);
124 Blink
->Flink
= ExpEncodePoolLink(Flink
);
129 ExpRemovePoolHeadList(IN PLIST_ENTRY ListHead
)
131 PLIST_ENTRY Entry
, Flink
;
132 Entry
= ExpDecodePoolLink(ListHead
->Flink
);
133 Flink
= ExpDecodePoolLink(Entry
->Flink
);
134 ListHead
->Flink
= ExpEncodePoolLink(Flink
);
135 Flink
->Blink
= ExpEncodePoolLink(ListHead
);
141 ExpRemovePoolTailList(IN PLIST_ENTRY ListHead
)
143 PLIST_ENTRY Entry
, Blink
;
144 Entry
= ExpDecodePoolLink(ListHead
->Blink
);
145 Blink
= ExpDecodePoolLink(Entry
->Blink
);
146 ListHead
->Blink
= ExpEncodePoolLink(Blink
);
147 Blink
->Flink
= ExpEncodePoolLink(ListHead
);
153 ExpInsertPoolTailList(IN PLIST_ENTRY ListHead
,
154 IN PLIST_ENTRY Entry
)
157 ExpCheckPoolLinks(ListHead
);
158 Blink
= ExpDecodePoolLink(ListHead
->Blink
);
159 Entry
->Flink
= ExpEncodePoolLink(ListHead
);
160 Entry
->Blink
= ExpEncodePoolLink(Blink
);
161 Blink
->Flink
= ExpEncodePoolLink(Entry
);
162 ListHead
->Blink
= ExpEncodePoolLink(Entry
);
163 ExpCheckPoolLinks(ListHead
);
168 ExpInsertPoolHeadList(IN PLIST_ENTRY ListHead
,
169 IN PLIST_ENTRY Entry
)
172 ExpCheckPoolLinks(ListHead
);
173 Flink
= ExpDecodePoolLink(ListHead
->Flink
);
174 Entry
->Flink
= ExpEncodePoolLink(Flink
);
175 Entry
->Blink
= ExpEncodePoolLink(ListHead
);
176 Flink
->Blink
= ExpEncodePoolLink(Entry
);
177 ListHead
->Flink
= ExpEncodePoolLink(Entry
);
178 ExpCheckPoolLinks(ListHead
);
183 ExpCheckPoolHeader(IN PPOOL_HEADER Entry
)
185 PPOOL_HEADER PreviousEntry
, NextEntry
;
187 /* Is there a block before this one? */
188 if (Entry
->PreviousSize
)
191 PreviousEntry
= POOL_PREV_BLOCK(Entry
);
193 /* The two blocks must be on the same page! */
194 if (PAGE_ALIGN(Entry
) != PAGE_ALIGN(PreviousEntry
))
196 /* Something is awry */
197 KeBugCheckEx(BAD_POOL_HEADER
,
199 (ULONG_PTR
)PreviousEntry
,
204 /* This block should also indicate that it's as large as we think it is */
205 if (PreviousEntry
->BlockSize
!= Entry
->PreviousSize
)
207 /* Otherwise, someone corrupted one of the sizes */
208 KeBugCheckEx(BAD_POOL_HEADER
,
210 (ULONG_PTR
)PreviousEntry
,
215 else if (PAGE_ALIGN(Entry
) != Entry
)
217 /* If there's no block before us, we are the first block, so we should be on a page boundary */
218 KeBugCheckEx(BAD_POOL_HEADER
,
225 /* This block must have a size */
226 if (!Entry
->BlockSize
)
228 /* Someone must've corrupted this field */
229 KeBugCheckEx(BAD_POOL_HEADER
,
236 /* Okay, now get the next block */
237 NextEntry
= POOL_NEXT_BLOCK(Entry
);
239 /* If this is the last block, then we'll be page-aligned, otherwise, check this block */
240 if (PAGE_ALIGN(NextEntry
) != NextEntry
)
242 /* The two blocks must be on the same page! */
243 if (PAGE_ALIGN(Entry
) != PAGE_ALIGN(NextEntry
))
245 /* Something is messed up */
246 KeBugCheckEx(BAD_POOL_HEADER
,
248 (ULONG_PTR
)NextEntry
,
253 /* And this block should think we are as large as we truly are */
254 if (NextEntry
->PreviousSize
!= Entry
->BlockSize
)
256 /* Otherwise, someone corrupted the field */
257 KeBugCheckEx(BAD_POOL_HEADER
,
259 (ULONG_PTR
)NextEntry
,
268 ExpCheckPoolBlocks(IN PVOID Block
)
270 BOOLEAN FoundBlock
= FALSE
;
274 /* Get the first entry for this page, make sure it really is the first */
275 Entry
= PAGE_ALIGN(Block
);
276 ASSERT(Entry
->PreviousSize
== 0);
278 /* Now scan each entry */
281 /* When we actually found our block, remember this */
282 if (Entry
== Block
) FoundBlock
= TRUE
;
284 /* Now validate this block header */
285 ExpCheckPoolHeader(Entry
);
287 /* And go to the next one, keeping track of our size */
288 Size
+= Entry
->BlockSize
;
289 Entry
= POOL_NEXT_BLOCK(Entry
);
291 /* If we hit the last block, stop */
292 if (Size
>= (PAGE_SIZE
/ POOL_BLOCK_SIZE
)) break;
294 /* If we hit the end of the page, stop */
295 if (PAGE_ALIGN(Entry
) == Entry
) break;
298 /* We must've found our block, and we must have hit the end of the page */
299 if ((PAGE_ALIGN(Entry
) != Entry
) || !(FoundBlock
))
301 /* Otherwise, the blocks are messed up */
302 KeBugCheckEx(BAD_POOL_HEADER
, 10, (ULONG_PTR
)Block
, __LINE__
, (ULONG_PTR
)Entry
);
308 ExpCheckPoolIrqlLevel(IN POOL_TYPE PoolType
,
309 IN ULONG NumberOfBytes
,
313 // Validate IRQL: It must be APC_LEVEL or lower for Paged Pool, and it must
314 // be DISPATCH_LEVEL or lower for Non Paged Pool
316 if (((PoolType
& BASE_POOL_TYPE_MASK
) == PagedPool
) ?
317 (KeGetCurrentIrql() > APC_LEVEL
) :
318 (KeGetCurrentIrql() > DISPATCH_LEVEL
))
321 // Take the system down
323 KeBugCheckEx(BAD_POOL_CALLER
,
324 !Entry
? POOL_ALLOC_IRQL_INVALID
: POOL_FREE_IRQL_INVALID
,
327 !Entry
? NumberOfBytes
: (ULONG_PTR
)Entry
);
333 ExpComputeHashForTag(IN ULONG Tag
,
334 IN SIZE_T BucketMask
)
337 // Compute the hash by multiplying with a large prime number and then XORing
338 // with the HIDWORD of the result.
340 // Finally, AND with the bucket mask to generate a valid index/bucket into
343 ULONGLONG Result
= 40543 * Tag
;
344 return BucketMask
& (Result
^ (Result
>> 32));
349 ExpComputePartialHashForAddress(IN PVOID BaseAddress
)
353 // Compute the hash by converting the address into a page number, and then
354 // XORing each nibble with the next one.
356 // We do *NOT* AND with the bucket mask at this point because big table expansion
357 // might happen. Therefore, the final step of the hash must be performed
358 // while holding the expansion pushlock, and this is why we call this a
359 // "partial" hash only.
361 Result
= (ULONG_PTR
)BaseAddress
>> PAGE_SHIFT
;
362 return (Result
>> 24) ^ (Result
>> 16) ^ (Result
>> 8) ^ Result
;
365 /* PRIVATE FUNCTIONS **********************************************************/
372 ULONG i
, Key
, Hash
, Index
;
373 PPOOL_TRACKER_TABLE TrackTable
= PoolTrackTable
;
443 // Loop all 64 hot tags
445 ASSERT((sizeof(TagList
) / sizeof(ULONG
)) == 64);
446 for (i
= 0; i
< sizeof(TagList
) / sizeof(ULONG
); i
++)
449 // Get the current tag, and compute its hash in the tracker table
452 Hash
= ExpComputeHashForTag(Key
, PoolTrackTableMask
);
455 // Loop all the hashes in this index/bucket
461 // Find an empty entry, and make sure this isn't the last hash that
464 // On checked builds, also make sure this is the first time we are
467 ASSERT(TrackTable
[Hash
].Key
!= Key
);
468 if (!(TrackTable
[Hash
].Key
) && (Hash
!= PoolTrackTableSize
- 1))
471 // It has been seeded, move on to the next tag
473 TrackTable
[Hash
].Key
= Key
;
478 // This entry was already taken, compute the next possible hash while
479 // making sure we're not back at our initial index.
481 ASSERT(TrackTable
[Hash
].Key
!= Key
);
482 Hash
= (Hash
+ 1) & PoolTrackTableMask
;
483 if (Hash
== Index
) break;
490 ExpRemovePoolTracker(IN ULONG Key
,
491 IN SIZE_T NumberOfBytes
,
492 IN POOL_TYPE PoolType
)
495 PPOOL_TRACKER_TABLE Table
, TableEntry
;
496 SIZE_T TableMask
, TableSize
;
499 // Remove the PROTECTED_POOL flag which is not part of the tag
501 Key
&= ~PROTECTED_POOL
;
504 // With WinDBG you can set a tag you want to break on when an allocation is
507 if (Key
== PoolHitTag
) DbgBreakPoint();
510 // Why the double indirection? Because normally this function is also used
511 // when doing session pool allocations, which has another set of tables,
512 // sizes, and masks that live in session pool. Now we don't support session
513 // pool so we only ever use the regular tables, but I'm keeping the code this
514 // way so that the day we DO support session pool, it won't require that
517 Table
= PoolTrackTable
;
518 TableMask
= PoolTrackTableMask
;
519 TableSize
= PoolTrackTableSize
;
522 // Compute the hash for this key, and loop all the possible buckets
524 Hash
= ExpComputeHashForTag(Key
, TableMask
);
529 // Have we found the entry for this tag? */
531 TableEntry
= &Table
[Hash
];
532 if (TableEntry
->Key
== Key
)
535 // Decrement the counters depending on if this was paged or nonpaged
538 if ((PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
540 InterlockedIncrement(&TableEntry
->NonPagedFrees
);
541 InterlockedExchangeAddSizeT(&TableEntry
->NonPagedBytes
, -NumberOfBytes
);
544 InterlockedIncrement(&TableEntry
->PagedFrees
);
545 InterlockedExchangeAddSizeT(&TableEntry
->PagedBytes
, -NumberOfBytes
);
550 // We should have only ended up with an empty entry if we've reached
553 if (!TableEntry
->Key
) ASSERT(Hash
== TableMask
);
556 // This path is hit when we don't have an entry, and the current bucket
557 // is full, so we simply try the next one
559 Hash
= (Hash
+ 1) & TableMask
;
560 if (Hash
== Index
) break;
564 // And finally this path is hit when all the buckets are full, and we need
565 // some expansion. This path is not yet supported in ReactOS and so we'll
568 DPRINT1("Out of pool tag space, ignoring...\n");
573 ExpInsertPoolTracker(IN ULONG Key
,
574 IN SIZE_T NumberOfBytes
,
575 IN POOL_TYPE PoolType
)
579 PPOOL_TRACKER_TABLE Table
, TableEntry
;
580 SIZE_T TableMask
, TableSize
;
583 // Remove the PROTECTED_POOL flag which is not part of the tag
585 Key
&= ~PROTECTED_POOL
;
588 // With WinDBG you can set a tag you want to break on when an allocation is
591 if (Key
== PoolHitTag
) DbgBreakPoint();
594 // There is also an internal flag you can set to break on malformed tags
596 if (ExStopBadTags
) ASSERT(Key
& 0xFFFFFF00);
599 // ASSERT on ReactOS features not yet supported
601 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
602 ASSERT(KeGetCurrentProcessorNumber() == 0);
605 // Why the double indirection? Because normally this function is also used
606 // when doing session pool allocations, which has another set of tables,
607 // sizes, and masks that live in session pool. Now we don't support session
608 // pool so we only ever use the regular tables, but I'm keeping the code this
609 // way so that the day we DO support session pool, it won't require that
612 Table
= PoolTrackTable
;
613 TableMask
= PoolTrackTableMask
;
614 TableSize
= PoolTrackTableSize
;
617 // Compute the hash for this key, and loop all the possible buckets
619 Hash
= ExpComputeHashForTag(Key
, TableMask
);
624 // Do we already have an entry for this tag? */
626 TableEntry
= &Table
[Hash
];
627 if (TableEntry
->Key
== Key
)
630 // Increment the counters depending on if this was paged or nonpaged
633 if ((PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
635 InterlockedIncrement(&TableEntry
->NonPagedAllocs
);
636 InterlockedExchangeAddSizeT(&TableEntry
->NonPagedBytes
, NumberOfBytes
);
639 InterlockedIncrement(&TableEntry
->PagedAllocs
);
640 InterlockedExchangeAddSizeT(&TableEntry
->PagedBytes
, NumberOfBytes
);
645 // We don't have an entry yet, but we've found a free bucket for it
647 if (!(TableEntry
->Key
) && (Hash
!= PoolTrackTableSize
- 1))
650 // We need to hold the lock while creating a new entry, since other
651 // processors might be in this code path as well
653 ExAcquireSpinLock(&ExpTaggedPoolLock
, &OldIrql
);
654 if (!PoolTrackTable
[Hash
].Key
)
657 // We've won the race, so now create this entry in the bucket
659 ASSERT(Table
[Hash
].Key
== 0);
660 PoolTrackTable
[Hash
].Key
= Key
;
661 TableEntry
->Key
= Key
;
663 ExReleaseSpinLock(&ExpTaggedPoolLock
, OldIrql
);
666 // Now we force the loop to run again, and we should now end up in
667 // the code path above which does the interlocked increments...
673 // This path is hit when we don't have an entry, and the current bucket
674 // is full, so we simply try the next one
676 Hash
= (Hash
+ 1) & TableMask
;
677 if (Hash
== Index
) break;
681 // And finally this path is hit when all the buckets are full, and we need
682 // some expansion. This path is not yet supported in ReactOS and so we'll
685 DPRINT1("Out of pool tag space, ignoring...\n");
691 ExInitializePoolDescriptor(IN PPOOL_DESCRIPTOR PoolDescriptor
,
692 IN POOL_TYPE PoolType
,
697 PLIST_ENTRY NextEntry
, LastEntry
;
700 // Setup the descriptor based on the caller's request
702 PoolDescriptor
->PoolType
= PoolType
;
703 PoolDescriptor
->PoolIndex
= PoolIndex
;
704 PoolDescriptor
->Threshold
= Threshold
;
705 PoolDescriptor
->LockAddress
= PoolLock
;
708 // Initialize accounting data
710 PoolDescriptor
->RunningAllocs
= 0;
711 PoolDescriptor
->RunningDeAllocs
= 0;
712 PoolDescriptor
->TotalPages
= 0;
713 PoolDescriptor
->TotalBytes
= 0;
714 PoolDescriptor
->TotalBigPages
= 0;
717 // Nothing pending for now
719 PoolDescriptor
->PendingFrees
= NULL
;
720 PoolDescriptor
->PendingFreeDepth
= 0;
723 // Loop all the descriptor's allocation lists and initialize them
725 NextEntry
= PoolDescriptor
->ListHeads
;
726 LastEntry
= NextEntry
+ POOL_LISTS_PER_PAGE
;
727 while (NextEntry
< LastEntry
)
729 ExpInitializePoolListHead(NextEntry
);
734 // Note that ReactOS does not support Session Pool Yet
736 ASSERT(PoolType
!= PagedPoolSession
);
742 InitializePool(IN POOL_TYPE PoolType
,
745 PPOOL_DESCRIPTOR Descriptor
;
750 // Check what kind of pool this is
752 if (PoolType
== NonPagedPool
)
755 // Compute the track table size and convert it from a power of two to an
758 // NOTE: On checked builds, we'll assert if the registry table size was
759 // invalid, while on retail builds we'll just break out of the loop at
762 TableSize
= min(PoolTrackTableSize
, MmSizeOfNonPagedPoolInBytes
>> 8);
763 for (i
= 0; i
< 32; i
++)
767 ASSERT((TableSize
& ~1) == 0);
768 if (!(TableSize
& ~1)) break;
774 // If we hit bit 32, than no size was defined in the registry, so
775 // we'll use the default size of 2048 entries.
777 // Otherwise, use the size from the registry, as long as it's not
778 // smaller than 64 entries.
782 PoolTrackTableSize
= 2048;
786 PoolTrackTableSize
= max(1 << i
, 64);
790 // Loop trying with the biggest specified size first, and cut it down
791 // by a power of two each iteration in case not enough memory exist
796 // Do not allow overflow
798 if ((PoolTrackTableSize
+ 1) > (MAXULONG_PTR
/ sizeof(POOL_TRACKER_TABLE
)))
800 PoolTrackTableSize
>>= 1;
805 // Allocate the tracker table and exit the loop if this worked
807 PoolTrackTable
= MiAllocatePoolPages(NonPagedPool
,
808 (PoolTrackTableSize
+ 1) *
809 sizeof(POOL_TRACKER_TABLE
));
810 if (PoolTrackTable
) break;
813 // Otherwise, as long as we're not down to the last bit, keep
816 if (PoolTrackTableSize
== 1)
818 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
824 PoolTrackTableSize
>>= 1;
828 // Finally, add one entry, compute the hash, and zero the table
830 PoolTrackTableSize
++;
831 PoolTrackTableMask
= PoolTrackTableSize
- 2;
833 RtlZeroMemory(PoolTrackTable
,
834 PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
));
837 // We now do the exact same thing with the tracker table for big pages
839 TableSize
= min(PoolBigPageTableSize
, MmSizeOfNonPagedPoolInBytes
>> 8);
840 for (i
= 0; i
< 32; i
++)
844 ASSERT((TableSize
& ~1) == 0);
845 if (!(TableSize
& ~1)) break;
851 // For big pages, the default tracker table is 4096 entries, while the
852 // minimum is still 64
856 PoolBigPageTableSize
= 4096;
860 PoolBigPageTableSize
= max(1 << i
, 64);
864 // Again, run the exact same loop we ran earlier, but this time for the
865 // big pool tracker instead
869 if ((PoolBigPageTableSize
+ 1) > (MAXULONG_PTR
/ sizeof(POOL_TRACKER_BIG_PAGES
)))
871 PoolBigPageTableSize
>>= 1;
875 PoolBigPageTable
= MiAllocatePoolPages(NonPagedPool
,
876 PoolBigPageTableSize
*
877 sizeof(POOL_TRACKER_BIG_PAGES
));
878 if (PoolBigPageTable
) break;
880 if (PoolBigPageTableSize
== 1)
882 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
889 PoolBigPageTableSize
>>= 1;
893 // An extra entry is not needed for for the big pool tracker, so just
894 // compute the hash and zero it
896 PoolBigPageTableHash
= PoolBigPageTableSize
- 1;
897 RtlZeroMemory(PoolBigPageTable
,
898 PoolBigPageTableSize
* sizeof(POOL_TRACKER_BIG_PAGES
));
899 for (i
= 0; i
< PoolBigPageTableSize
; i
++) PoolBigPageTable
[i
].Va
= (PVOID
)1;
902 // During development, print this out so we can see what's happening
904 DPRINT1("EXPOOL: Pool Tracker Table at: 0x%p with 0x%lx bytes\n",
905 PoolTrackTable
, PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
));
906 DPRINT1("EXPOOL: Big Pool Tracker Table at: 0x%p with 0x%lx bytes\n",
907 PoolBigPageTable
, PoolBigPageTableSize
* sizeof(POOL_TRACKER_BIG_PAGES
));
910 // Insert the generic tracker for all of big pool
912 ExpInsertPoolTracker('looP',
913 ROUND_TO_PAGES(PoolBigPageTableSize
*
914 sizeof(POOL_TRACKER_BIG_PAGES
)),
918 // No support for NUMA systems at this time
920 ASSERT(KeNumberNodes
== 1);
923 // Initialize the tag spinlock
925 KeInitializeSpinLock(&ExpTaggedPoolLock
);
928 // Initialize the nonpaged pool descriptor
930 PoolVector
[NonPagedPool
] = &NonPagedPoolDescriptor
;
931 ExInitializePoolDescriptor(PoolVector
[NonPagedPool
],
940 // No support for NUMA systems at this time
942 ASSERT(KeNumberNodes
== 1);
945 // Allocate the pool descriptor
947 Descriptor
= ExAllocatePoolWithTag(NonPagedPool
,
948 sizeof(KGUARDED_MUTEX
) +
949 sizeof(POOL_DESCRIPTOR
),
954 // This is really bad...
956 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
964 // Setup the vector and guarded mutex for paged pool
966 PoolVector
[PagedPool
] = Descriptor
;
967 ExpPagedPoolMutex
= (PKGUARDED_MUTEX
)(Descriptor
+ 1);
968 ExpPagedPoolDescriptor
[0] = Descriptor
;
969 KeInitializeGuardedMutex(ExpPagedPoolMutex
);
970 ExInitializePoolDescriptor(Descriptor
,
977 // Insert the generic tracker for all of nonpaged pool
979 ExpInsertPoolTracker('looP',
980 ROUND_TO_PAGES(PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
)),
987 ExLockPool(IN PPOOL_DESCRIPTOR Descriptor
)
990 // Check if this is nonpaged pool
992 if ((Descriptor
->PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
995 // Use the queued spin lock
997 return KeAcquireQueuedSpinLock(LockQueueNonPagedPoolLock
);
1002 // Use the guarded mutex
1004 KeAcquireGuardedMutex(Descriptor
->LockAddress
);
1011 ExUnlockPool(IN PPOOL_DESCRIPTOR Descriptor
,
1015 // Check if this is nonpaged pool
1017 if ((Descriptor
->PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
1020 // Use the queued spin lock
1022 KeReleaseQueuedSpinLock(LockQueueNonPagedPoolLock
, OldIrql
);
1027 // Use the guarded mutex
1029 KeReleaseGuardedMutex(Descriptor
->LockAddress
);
1035 ExpGetPoolTagInfoTarget(IN PKDPC Dpc
,
1036 IN PVOID DeferredContext
,
1037 IN PVOID SystemArgument1
,
1038 IN PVOID SystemArgument2
)
1040 PPOOL_DPC_CONTEXT Context
= DeferredContext
;
1041 UNREFERENCED_PARAMETER(Dpc
);
1042 ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL
);
1045 // Make sure we win the race, and if we did, copy the data atomically
1047 if (KeSignalCallDpcSynchronize(SystemArgument2
))
1049 RtlCopyMemory(Context
->PoolTrackTable
,
1051 Context
->PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
));
1054 // This is here because ReactOS does not yet support expansion
1056 ASSERT(Context
->PoolTrackTableSizeExpansion
== 0);
1060 // Regardless of whether we won or not, we must now synchronize and then
1061 // decrement the barrier since this is one more processor that has completed
1064 KeSignalCallDpcSynchronize(SystemArgument2
);
1065 KeSignalCallDpcDone(SystemArgument1
);
1070 ExGetPoolTagInfo(IN PSYSTEM_POOLTAG_INFORMATION SystemInformation
,
1071 IN ULONG SystemInformationLength
,
1072 IN OUT PULONG ReturnLength OPTIONAL
)
1074 SIZE_T TableSize
, CurrentLength
;
1076 NTSTATUS Status
= STATUS_SUCCESS
;
1077 PSYSTEM_POOLTAG TagEntry
;
1078 PPOOL_TRACKER_TABLE Buffer
, TrackerEntry
;
1079 POOL_DPC_CONTEXT Context
;
1080 ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL
);
1083 // Keep track of how much data the caller's buffer must hold
1085 CurrentLength
= FIELD_OFFSET(SYSTEM_POOLTAG_INFORMATION
, TagInfo
);
1088 // Initialize the caller's buffer
1090 TagEntry
= &SystemInformation
->TagInfo
[0];
1091 SystemInformation
->Count
= 0;
1094 // Capture the number of entries, and the total size needed to make a copy
1097 EntryCount
= PoolTrackTableSize
;
1098 TableSize
= EntryCount
* sizeof(POOL_TRACKER_TABLE
);
1101 // Allocate the "Generic DPC" temporary buffer
1103 Buffer
= ExAllocatePoolWithTag(NonPagedPool
, TableSize
, 'ofnI');
1104 if (!Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
1107 // Do a "Generic DPC" to atomically retrieve the tag and allocation data
1109 Context
.PoolTrackTable
= Buffer
;
1110 Context
.PoolTrackTableSize
= PoolTrackTableSize
;
1111 Context
.PoolTrackTableExpansion
= NULL
;
1112 Context
.PoolTrackTableSizeExpansion
= 0;
1113 KeGenericCallDpc(ExpGetPoolTagInfoTarget
, &Context
);
1116 // Now parse the results
1118 for (TrackerEntry
= Buffer
; TrackerEntry
< (Buffer
+ EntryCount
); TrackerEntry
++)
1121 // If the entry is empty, skip it
1123 if (!TrackerEntry
->Key
) continue;
1126 // Otherwise, add one more entry to the caller's buffer, and ensure that
1127 // enough space has been allocated in it
1129 SystemInformation
->Count
++;
1130 CurrentLength
+= sizeof(*TagEntry
);
1131 if (SystemInformationLength
< CurrentLength
)
1134 // The caller's buffer is too small, so set a failure code. The
1135 // caller will know the count, as well as how much space is needed.
1137 // We do NOT break out of the loop, because we want to keep incrementing
1138 // the Count as well as CurrentLength so that the caller can know the
1141 Status
= STATUS_INFO_LENGTH_MISMATCH
;
1146 // Small sanity check that our accounting is working correctly
1148 ASSERT(TrackerEntry
->PagedAllocs
>= TrackerEntry
->PagedFrees
);
1149 ASSERT(TrackerEntry
->NonPagedAllocs
>= TrackerEntry
->NonPagedFrees
);
1152 // Return the data into the caller's buffer
1154 TagEntry
->TagUlong
= TrackerEntry
->Key
;
1155 TagEntry
->PagedAllocs
= TrackerEntry
->PagedAllocs
;
1156 TagEntry
->PagedFrees
= TrackerEntry
->PagedFrees
;
1157 TagEntry
->PagedUsed
= TrackerEntry
->PagedBytes
;
1158 TagEntry
->NonPagedAllocs
= TrackerEntry
->NonPagedAllocs
;
1159 TagEntry
->NonPagedFrees
= TrackerEntry
->NonPagedFrees
;
1160 TagEntry
->NonPagedUsed
= TrackerEntry
->NonPagedBytes
;
1166 // Free the "Generic DPC" temporary buffer, return the buffer length and status
1169 if (ReturnLength
) *ReturnLength
= CurrentLength
;
1175 ExpAddTagForBigPages(IN PVOID Va
,
1177 IN ULONG NumberOfPages
,
1178 IN POOL_TYPE PoolType
)
1184 PPOOL_TRACKER_BIG_PAGES Entry
, EntryEnd
, EntryStart
;
1185 ASSERT(((ULONG_PTR
)Va
& POOL_BIG_TABLE_ENTRY_FREE
) == 0);
1186 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
1189 // As the table is expandable, these values must only be read after acquiring
1190 // the lock to avoid a teared access during an expansion
1192 Hash
= ExpComputePartialHashForAddress(Va
);
1193 KeAcquireSpinLock(&ExpLargePoolTableLock
, &OldIrql
);
1194 Hash
&= PoolBigPageTableHash
;
1195 TableSize
= PoolBigPageTableSize
;
1198 // We loop from the current hash bucket to the end of the table, and then
1199 // rollover to hash bucket 0 and keep going from there. If we return back
1200 // to the beginning, then we attempt expansion at the bottom of the loop
1202 EntryStart
= Entry
= &PoolBigPageTable
[Hash
];
1203 EntryEnd
= &PoolBigPageTable
[TableSize
];
1207 // Make sure that this is a free entry and attempt to atomically make the
1211 if (((ULONG_PTR
)OldVa
& POOL_BIG_TABLE_ENTRY_FREE
) &&
1212 (InterlockedCompareExchangePointer(&Entry
->Va
, Va
, OldVa
) == OldVa
))
1215 // We now own this entry, write down the size and the pool tag
1218 Entry
->NumberOfPages
= NumberOfPages
;
1221 // Add one more entry to the count, and see if we're getting within
1222 // 25% of the table size, at which point we'll do an expansion now
1223 // to avoid blocking too hard later on.
1225 // Note that we only do this if it's also been the 16th time that we
1226 // keep losing the race or that we are not finding a free entry anymore,
1227 // which implies a massive number of concurrent big pool allocations.
1229 InterlockedIncrement(&ExpPoolBigEntriesInUse
);
1230 if ((i
>= 16) && (ExpPoolBigEntriesInUse
> (TableSize
/ 4)))
1232 DPRINT1("Should attempt expansion since we now have %d entries\n",
1233 ExpPoolBigEntriesInUse
);
1237 // We have our entry, return
1239 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1244 // We don't have our entry yet, so keep trying, making the entry list
1245 // circular if we reach the last entry. We'll eventually break out of
1246 // the loop once we've rolled over and returned back to our original
1250 if (++Entry
>= EntryEnd
) Entry
= &PoolBigPageTable
[0];
1251 } while (Entry
!= EntryStart
);
1254 // This means there's no free hash buckets whatsoever, so we would now have
1255 // to attempt expanding the table
1257 DPRINT1("Big pool expansion needed, not implemented!");
1258 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1264 ExpFindAndRemoveTagBigPages(IN PVOID Va
,
1265 OUT PULONG BigPages
,
1266 IN POOL_TYPE PoolType
)
1268 BOOLEAN FirstTry
= TRUE
;
1271 ULONG PoolTag
, Hash
;
1272 PPOOL_TRACKER_BIG_PAGES Entry
;
1273 ASSERT(((ULONG_PTR
)Va
& POOL_BIG_TABLE_ENTRY_FREE
) == 0);
1274 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
1277 // As the table is expandable, these values must only be read after acquiring
1278 // the lock to avoid a teared access during an expansion
1280 Hash
= ExpComputePartialHashForAddress(Va
);
1281 KeAcquireSpinLock(&ExpLargePoolTableLock
, &OldIrql
);
1282 Hash
&= PoolBigPageTableHash
;
1283 TableSize
= PoolBigPageTableSize
;
1286 // Loop while trying to find this big page allocation
1288 while (PoolBigPageTable
[Hash
].Va
!= Va
)
1291 // Increment the size until we go past the end of the table
1293 if (++Hash
>= TableSize
)
1296 // Is this the second time we've tried?
1301 // This means it was never inserted into the pool table and it
1302 // received the special "BIG" tag -- return that and return 0
1303 // so that the code can ask Mm for the page count instead
1305 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1311 // The first time this happens, reset the hash index and try again
1319 // Now capture all the information we need from the entry, since after we
1320 // release the lock, the data can change
1322 Entry
= &PoolBigPageTable
[Hash
];
1323 *BigPages
= Entry
->NumberOfPages
;
1324 PoolTag
= Entry
->Key
;
1327 // Set the free bit, and decrement the number of allocations. Finally, release
1328 // the lock and return the tag that was located
1330 InterlockedIncrement((PLONG
)&Entry
->Va
);
1331 InterlockedDecrement(&ExpPoolBigEntriesInUse
);
1332 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1338 ExQueryPoolUsage(OUT PULONG PagedPoolPages
,
1339 OUT PULONG NonPagedPoolPages
,
1340 OUT PULONG PagedPoolAllocs
,
1341 OUT PULONG PagedPoolFrees
,
1342 OUT PULONG PagedPoolLookasideHits
,
1343 OUT PULONG NonPagedPoolAllocs
,
1344 OUT PULONG NonPagedPoolFrees
,
1345 OUT PULONG NonPagedPoolLookasideHits
)
1348 PPOOL_DESCRIPTOR PoolDesc
;
1351 // Assume all failures
1353 *PagedPoolPages
= 0;
1354 *PagedPoolAllocs
= 0;
1355 *PagedPoolFrees
= 0;
1358 // Tally up the totals for all the apged pool
1360 for (i
= 0; i
< ExpNumberOfPagedPools
+ 1; i
++)
1362 PoolDesc
= ExpPagedPoolDescriptor
[i
];
1363 *PagedPoolPages
+= PoolDesc
->TotalPages
+ PoolDesc
->TotalBigPages
;
1364 *PagedPoolAllocs
+= PoolDesc
->RunningAllocs
;
1365 *PagedPoolFrees
+= PoolDesc
->RunningDeAllocs
;
1369 // The first non-paged pool has a hardcoded well-known descriptor name
1371 PoolDesc
= &NonPagedPoolDescriptor
;
1372 *NonPagedPoolPages
= PoolDesc
->TotalPages
+ PoolDesc
->TotalBigPages
;
1373 *NonPagedPoolAllocs
= PoolDesc
->RunningAllocs
;
1374 *NonPagedPoolFrees
= PoolDesc
->RunningDeAllocs
;
1377 // If the system has more than one non-paged pool, copy the other descriptor
1381 if (ExpNumberOfNonPagedPools
> 1)
1383 for (i
= 0; i
< ExpNumberOfNonPagedPools
; i
++)
1385 PoolDesc
= ExpNonPagedPoolDescriptor
[i
];
1386 *NonPagedPoolPages
+= PoolDesc
->TotalPages
+ PoolDesc
->TotalBigPages
;
1387 *NonPagedPoolAllocs
+= PoolDesc
->RunningAllocs
;
1388 *NonPagedPoolFrees
+= PoolDesc
->RunningDeAllocs
;
1394 // FIXME: Not yet supported
1396 *NonPagedPoolLookasideHits
+= 0;
1397 *PagedPoolLookasideHits
+= 0;
1400 /* PUBLIC FUNCTIONS ***********************************************************/
1407 ExAllocatePoolWithTag(IN POOL_TYPE PoolType
,
1408 IN SIZE_T NumberOfBytes
,
1411 PPOOL_DESCRIPTOR PoolDesc
;
1412 PLIST_ENTRY ListHead
;
1413 PPOOL_HEADER Entry
, NextEntry
, FragmentEntry
;
1415 USHORT BlockSize
, i
;
1417 PKPRCB Prcb
= KeGetCurrentPrcb();
1418 PGENERAL_LOOKASIDE LookasideList
;
1421 // Some sanity checks
1424 ASSERT(Tag
!= ' GIB');
1425 ASSERT(NumberOfBytes
!= 0);
1426 ExpCheckPoolIrqlLevel(PoolType
, NumberOfBytes
, NULL
);
1429 // Not supported in ReactOS
1431 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
1434 // Check if verifier or special pool is enabled
1436 if (ExpPoolFlags
& (POOL_FLAG_VERIFIER
| POOL_FLAG_SPECIAL_POOL
))
1439 // For verifier, we should call the verification routine
1441 if (ExpPoolFlags
& POOL_FLAG_VERIFIER
)
1443 DPRINT1("Driver Verifier is not yet supported\n");
1447 // For special pool, we check if this is a suitable allocation and do
1448 // the special allocation if needed
1450 if (ExpPoolFlags
& POOL_FLAG_SPECIAL_POOL
)
1453 // Check if this is a special pool allocation
1455 if (MmUseSpecialPool(NumberOfBytes
, Tag
))
1458 // Try to allocate using special pool
1460 Entry
= MmAllocateSpecialPool(NumberOfBytes
, Tag
, PoolType
, 2);
1461 if (Entry
) return Entry
;
1467 // Get the pool type and its corresponding vector for this request
1469 OriginalType
= PoolType
;
1470 PoolType
= PoolType
& BASE_POOL_TYPE_MASK
;
1471 PoolDesc
= PoolVector
[PoolType
];
1472 ASSERT(PoolDesc
!= NULL
);
1475 // Check if this is a big page allocation
1477 if (NumberOfBytes
> POOL_MAX_ALLOC
)
1480 // Allocate pages for it
1482 Entry
= MiAllocatePoolPages(OriginalType
, NumberOfBytes
);
1486 // Must succeed pool is deprecated, but still supported. These allocation
1487 // failures must cause an immediate bugcheck
1489 if (OriginalType
& MUST_SUCCEED_POOL_MASK
)
1491 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
1493 NonPagedPoolDescriptor
.TotalPages
,
1494 NonPagedPoolDescriptor
.TotalBigPages
,
1499 // Internal debugging
1504 // This flag requests printing failures, and can also further specify
1505 // breaking on failures
1507 if (ExpPoolFlags
& POOL_FLAG_DBGPRINT_ON_FAILURE
)
1509 DPRINT1("EX: ExAllocatePool (%p, 0x%x) returning NULL\n",
1512 if (ExpPoolFlags
& POOL_FLAG_CRASH_ON_FAILURE
) DbgBreakPoint();
1516 // Finally, this flag requests an exception, which we are more than
1519 if (OriginalType
& POOL_RAISE_IF_ALLOCATION_FAILURE
)
1521 ExRaiseStatus(STATUS_INSUFFICIENT_RESOURCES
);
1526 // Increment required counters
1528 InterlockedExchangeAdd((PLONG
)&PoolDesc
->TotalBigPages
, BYTES_TO_PAGES(NumberOfBytes
));
1529 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, NumberOfBytes
);
1530 InterlockedIncrement((PLONG
)&PoolDesc
->RunningAllocs
);
1533 // Add a tag for the big page allocation and switch to the generic "BIG"
1534 // tag if we failed to do so, then insert a tracker for this alloation.
1536 if (!ExpAddTagForBigPages(Entry
,
1538 BYTES_TO_PAGES(NumberOfBytes
),
1543 ExpInsertPoolTracker(Tag
, ROUND_TO_PAGES(NumberOfBytes
), OriginalType
);
1548 // Should never request 0 bytes from the pool, but since so many drivers do
1549 // it, we'll just assume they want 1 byte, based on NT's similar behavior
1551 if (!NumberOfBytes
) NumberOfBytes
= 1;
1554 // A pool allocation is defined by its data, a linked list to connect it to
1555 // the free list (if necessary), and a pool header to store accounting info.
1556 // Calculate this size, then convert it into a block size (units of pool
1559 // Note that i cannot overflow (past POOL_LISTS_PER_PAGE) because any such
1560 // request would've been treated as a POOL_MAX_ALLOC earlier and resulted in
1561 // the direct allocation of pages.
1563 i
= (USHORT
)((NumberOfBytes
+ sizeof(POOL_HEADER
) + (POOL_BLOCK_SIZE
- 1))
1567 // Handle lookaside list optimization for both paged and nonpaged pool
1569 if (i
<= MAXIMUM_PROCESSORS
)
1572 // Try popping it from the per-CPU lookaside list
1574 LookasideList
= (PoolType
== PagedPool
) ?
1575 Prcb
->PPPagedLookasideList
[i
- 1].P
:
1576 Prcb
->PPNPagedLookasideList
[i
- 1].P
;
1577 LookasideList
->TotalAllocates
++;
1578 Entry
= (PPOOL_HEADER
)InterlockedPopEntrySList(&LookasideList
->ListHead
);
1582 // We failed, try popping it from the global list
1584 LookasideList
= (PoolType
== PagedPool
) ?
1585 Prcb
->PPPagedLookasideList
[i
- 1].L
:
1586 Prcb
->PPNPagedLookasideList
[i
- 1].L
;
1587 LookasideList
->TotalAllocates
++;
1588 Entry
= (PPOOL_HEADER
)InterlockedPopEntrySList(&LookasideList
->ListHead
);
1592 // If we were able to pop it, update the accounting and return the block
1596 LookasideList
->AllocateHits
++;
1599 // Get the real entry, write down its pool type, and track it
1602 Entry
->PoolType
= PoolType
+ 1;
1603 ExpInsertPoolTracker(Tag
,
1604 Entry
->BlockSize
* POOL_BLOCK_SIZE
,
1608 // Return the pool allocation
1610 Entry
->PoolTag
= Tag
;
1611 (POOL_FREE_BLOCK(Entry
))->Flink
= NULL
;
1612 (POOL_FREE_BLOCK(Entry
))->Blink
= NULL
;
1613 return POOL_FREE_BLOCK(Entry
);
1618 // Loop in the free lists looking for a block if this size. Start with the
1619 // list optimized for this kind of size lookup
1621 ListHead
= &PoolDesc
->ListHeads
[i
];
1625 // Are there any free entries available on this list?
1627 if (!ExpIsPoolListEmpty(ListHead
))
1630 // Acquire the pool lock now
1632 OldIrql
= ExLockPool(PoolDesc
);
1635 // And make sure the list still has entries
1637 if (ExpIsPoolListEmpty(ListHead
))
1640 // Someone raced us (and won) before we had a chance to acquire
1645 ExUnlockPool(PoolDesc
, OldIrql
);
1651 // Remove a free entry from the list
1652 // Note that due to the way we insert free blocks into multiple lists
1653 // there is a guarantee that any block on this list will either be
1654 // of the correct size, or perhaps larger.
1656 ExpCheckPoolLinks(ListHead
);
1657 Entry
= POOL_ENTRY(ExpRemovePoolHeadList(ListHead
));
1658 ExpCheckPoolLinks(ListHead
);
1659 ExpCheckPoolBlocks(Entry
);
1660 ASSERT(Entry
->BlockSize
>= i
);
1661 ASSERT(Entry
->PoolType
== 0);
1664 // Check if this block is larger that what we need. The block could
1665 // not possibly be smaller, due to the reason explained above (and
1666 // we would've asserted on a checked build if this was the case).
1668 if (Entry
->BlockSize
!= i
)
1671 // Is there an entry before this one?
1673 if (Entry
->PreviousSize
== 0)
1676 // There isn't anyone before us, so take the next block and
1677 // turn it into a fragment that contains the leftover data
1678 // that we don't need to satisfy the caller's request
1680 FragmentEntry
= POOL_BLOCK(Entry
, i
);
1681 FragmentEntry
->BlockSize
= Entry
->BlockSize
- i
;
1684 // And make it point back to us
1686 FragmentEntry
->PreviousSize
= i
;
1689 // Now get the block that follows the new fragment and check
1690 // if it's still on the same page as us (and not at the end)
1692 NextEntry
= POOL_NEXT_BLOCK(FragmentEntry
);
1693 if (PAGE_ALIGN(NextEntry
) != NextEntry
)
1696 // Adjust this next block to point to our newly created
1699 NextEntry
->PreviousSize
= FragmentEntry
->BlockSize
;
1705 // There is a free entry before us, which we know is smaller
1706 // so we'll make this entry the fragment instead
1708 FragmentEntry
= Entry
;
1711 // And then we'll remove from it the actual size required.
1712 // Now the entry is a leftover free fragment
1714 Entry
->BlockSize
-= i
;
1717 // Now let's go to the next entry after the fragment (which
1718 // used to point to our original free entry) and make it
1719 // reference the new fragment entry instead.
1721 // This is the entry that will actually end up holding the
1724 Entry
= POOL_NEXT_BLOCK(Entry
);
1725 Entry
->PreviousSize
= FragmentEntry
->BlockSize
;
1728 // And now let's go to the entry after that one and check if
1729 // it's still on the same page, and not at the end
1731 NextEntry
= POOL_BLOCK(Entry
, i
);
1732 if (PAGE_ALIGN(NextEntry
) != NextEntry
)
1735 // Make it reference the allocation entry
1737 NextEntry
->PreviousSize
= i
;
1742 // Now our (allocation) entry is the right size
1744 Entry
->BlockSize
= i
;
1747 // And the next entry is now the free fragment which contains
1748 // the remaining difference between how big the original entry
1749 // was, and the actual size the caller needs/requested.
1751 FragmentEntry
->PoolType
= 0;
1752 BlockSize
= FragmentEntry
->BlockSize
;
1755 // Now check if enough free bytes remained for us to have a
1756 // "full" entry, which contains enough bytes for a linked list
1757 // and thus can be used for allocations (up to 8 bytes...)
1759 ExpCheckPoolLinks(&PoolDesc
->ListHeads
[BlockSize
- 1]);
1763 // Insert the free entry into the free list for this size
1765 ExpInsertPoolTailList(&PoolDesc
->ListHeads
[BlockSize
- 1],
1766 POOL_FREE_BLOCK(FragmentEntry
));
1767 ExpCheckPoolLinks(POOL_FREE_BLOCK(FragmentEntry
));
1772 // We have found an entry for this allocation, so set the pool type
1773 // and release the lock since we're done
1775 Entry
->PoolType
= PoolType
+ 1;
1776 ExpCheckPoolBlocks(Entry
);
1777 ExUnlockPool(PoolDesc
, OldIrql
);
1780 // Increment required counters
1782 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, Entry
->BlockSize
* POOL_BLOCK_SIZE
);
1783 InterlockedIncrement((PLONG
)&PoolDesc
->RunningAllocs
);
1786 // Track this allocation
1788 ExpInsertPoolTracker(Tag
,
1789 Entry
->BlockSize
* POOL_BLOCK_SIZE
,
1793 // Return the pool allocation
1795 Entry
->PoolTag
= Tag
;
1796 (POOL_FREE_BLOCK(Entry
))->Flink
= NULL
;
1797 (POOL_FREE_BLOCK(Entry
))->Blink
= NULL
;
1798 return POOL_FREE_BLOCK(Entry
);
1800 } while (++ListHead
!= &PoolDesc
->ListHeads
[POOL_LISTS_PER_PAGE
]);
1803 // There were no free entries left, so we have to allocate a new fresh page
1805 Entry
= MiAllocatePoolPages(PoolType
, PAGE_SIZE
);
1809 // Must succeed pool is deprecated, but still supported. These allocation
1810 // failures must cause an immediate bugcheck
1812 if (OriginalType
& MUST_SUCCEED_POOL_MASK
)
1814 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
1816 NonPagedPoolDescriptor
.TotalPages
,
1817 NonPagedPoolDescriptor
.TotalBigPages
,
1822 // Internal debugging
1827 // This flag requests printing failures, and can also further specify
1828 // breaking on failures
1830 if (ExpPoolFlags
& POOL_FLAG_DBGPRINT_ON_FAILURE
)
1832 DPRINT1("EX: ExAllocatePool (%p, 0x%x) returning NULL\n",
1835 if (ExpPoolFlags
& POOL_FLAG_CRASH_ON_FAILURE
) DbgBreakPoint();
1839 // Finally, this flag requests an exception, which we are more than
1842 if (OriginalType
& POOL_RAISE_IF_ALLOCATION_FAILURE
)
1844 ExRaiseStatus(STATUS_INSUFFICIENT_RESOURCES
);
1848 // Return NULL to the caller in all other cases
1854 // Setup the entry data
1857 Entry
->BlockSize
= i
;
1858 Entry
->PoolType
= PoolType
+ 1;
1861 // This page will have two entries -- one for the allocation (which we just
1862 // created above), and one for the remaining free bytes, which we're about
1863 // to create now. The free bytes are the whole page minus what was allocated
1864 // and then converted into units of block headers.
1866 BlockSize
= (PAGE_SIZE
/ POOL_BLOCK_SIZE
) - i
;
1867 FragmentEntry
= POOL_BLOCK(Entry
, i
);
1868 FragmentEntry
->Ulong1
= 0;
1869 FragmentEntry
->BlockSize
= BlockSize
;
1870 FragmentEntry
->PreviousSize
= i
;
1873 // Increment required counters
1875 InterlockedIncrement((PLONG
)&PoolDesc
->TotalPages
);
1876 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, Entry
->BlockSize
* POOL_BLOCK_SIZE
);
1879 // Now check if enough free bytes remained for us to have a "full" entry,
1880 // which contains enough bytes for a linked list and thus can be used for
1881 // allocations (up to 8 bytes...)
1883 if (FragmentEntry
->BlockSize
!= 1)
1886 // Excellent -- acquire the pool lock
1888 OldIrql
= ExLockPool(PoolDesc
);
1891 // And insert the free entry into the free list for this block size
1893 ExpCheckPoolLinks(&PoolDesc
->ListHeads
[BlockSize
- 1]);
1894 ExpInsertPoolTailList(&PoolDesc
->ListHeads
[BlockSize
- 1],
1895 POOL_FREE_BLOCK(FragmentEntry
));
1896 ExpCheckPoolLinks(POOL_FREE_BLOCK(FragmentEntry
));
1899 // Release the pool lock
1901 ExpCheckPoolBlocks(Entry
);
1902 ExUnlockPool(PoolDesc
, OldIrql
);
1907 // Simply do a sanity check
1909 ExpCheckPoolBlocks(Entry
);
1913 // Increment performance counters and track this allocation
1915 InterlockedIncrement((PLONG
)&PoolDesc
->RunningAllocs
);
1916 ExpInsertPoolTracker(Tag
,
1917 Entry
->BlockSize
* POOL_BLOCK_SIZE
,
1921 // And return the pool allocation
1923 ExpCheckPoolBlocks(Entry
);
1924 Entry
->PoolTag
= Tag
;
1925 return POOL_FREE_BLOCK(Entry
);
1933 ExAllocatePool(POOL_TYPE PoolType
,
1934 SIZE_T NumberOfBytes
)
1937 // Use a default tag of "None"
1939 return ExAllocatePoolWithTag(PoolType
, NumberOfBytes
, TAG_NONE
);
1947 ExFreePoolWithTag(IN PVOID P
,
1950 PPOOL_HEADER Entry
, NextEntry
;
1954 PPOOL_DESCRIPTOR PoolDesc
;
1956 BOOLEAN Combined
= FALSE
;
1957 PFN_NUMBER PageCount
, RealPageCount
;
1958 PKPRCB Prcb
= KeGetCurrentPrcb();
1959 PGENERAL_LOOKASIDE LookasideList
;
1962 // Check if any of the debug flags are enabled
1964 if (ExpPoolFlags
& (POOL_FLAG_CHECK_TIMERS
|
1965 POOL_FLAG_CHECK_WORKERS
|
1966 POOL_FLAG_CHECK_RESOURCES
|
1967 POOL_FLAG_VERIFIER
|
1968 POOL_FLAG_CHECK_DEADLOCK
|
1969 POOL_FLAG_SPECIAL_POOL
))
1972 // Check if special pool is enabled
1974 if (ExpPoolFlags
& POOL_FLAG_SPECIAL_POOL
)
1977 // Check if it was allocated from a special pool
1979 if (MmIsSpecialPoolAddress(P
))
1982 // Was deadlock verification also enabled? We can do some extra
1983 // checks at this point
1985 if (ExpPoolFlags
& POOL_FLAG_CHECK_DEADLOCK
)
1987 DPRINT1("Verifier not yet supported\n");
1991 // It is, so handle it via special pool free routine
1993 MmFreeSpecialPool(P
);
1999 // For non-big page allocations, we'll do a bunch of checks in here
2001 if (PAGE_ALIGN(P
) != P
)
2004 // Get the entry for this pool allocation
2005 // The pointer math here may look wrong or confusing, but it is quite right
2011 // Get the pool type
2013 PoolType
= (Entry
->PoolType
- 1) & BASE_POOL_TYPE_MASK
;
2016 // FIXME: Many other debugging checks go here
2018 ExpCheckPoolIrqlLevel(PoolType
, 0, P
);
2023 // Check if this is a big page allocation
2025 if (PAGE_ALIGN(P
) == P
)
2028 // We need to find the tag for it, so first we need to find out what
2029 // kind of allocation this was (paged or nonpaged), then we can go
2030 // ahead and try finding the tag for it. Remember to get rid of the
2031 // PROTECTED_POOL tag if it's found.
2033 // Note that if at insertion time, we failed to add the tag for a big
2034 // pool allocation, we used a special tag called 'BIG' to identify the
2035 // allocation, and we may get this tag back. In this scenario, we must
2036 // manually get the size of the allocation by actually counting through
2037 // the PFN database.
2039 PoolType
= MmDeterminePoolType(P
);
2040 ExpCheckPoolIrqlLevel(PoolType
, 0, P
);
2041 Tag
= ExpFindAndRemoveTagBigPages(P
, &PageCount
, PoolType
);
2044 DPRINT1("We do not know the size of this allocation. This is not yet supported\n");
2045 ASSERT(Tag
== ' GIB');
2046 PageCount
= 1; // We are going to lie! This might screw up accounting?
2048 else if (Tag
& PROTECTED_POOL
)
2050 Tag
&= ~PROTECTED_POOL
;
2054 // We have our tag and our page count, so we can go ahead and remove this
2057 ExpRemovePoolTracker(Tag
, PageCount
<< PAGE_SHIFT
, PoolType
);
2060 // Check if any of the debug flags are enabled
2062 if (ExpPoolFlags
& (POOL_FLAG_CHECK_TIMERS
|
2063 POOL_FLAG_CHECK_WORKERS
|
2064 POOL_FLAG_CHECK_RESOURCES
|
2065 POOL_FLAG_CHECK_DEADLOCK
))
2068 // Was deadlock verification also enabled? We can do some extra
2069 // checks at this point
2071 if (ExpPoolFlags
& POOL_FLAG_CHECK_DEADLOCK
)
2073 DPRINT1("Verifier not yet supported\n");
2077 // FIXME: Many debugging checks go here
2084 PoolDesc
= PoolVector
[PoolType
];
2085 InterlockedIncrement((PLONG
)&PoolDesc
->RunningDeAllocs
);
2086 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, -PageCount
<< PAGE_SHIFT
);
2089 // Do the real free now and update the last counter with the big page count
2091 RealPageCount
= MiFreePoolPages(P
);
2092 ASSERT(RealPageCount
== PageCount
);
2093 InterlockedExchangeAdd((PLONG
)&PoolDesc
->TotalBigPages
, -RealPageCount
);
2098 // Get the entry for this pool allocation
2099 // The pointer math here may look wrong or confusing, but it is quite right
2105 // Get the size of the entry, and it's pool type, then load the descriptor
2106 // for this pool type
2108 BlockSize
= Entry
->BlockSize
;
2109 PoolType
= (Entry
->PoolType
- 1) & BASE_POOL_TYPE_MASK
;
2110 PoolDesc
= PoolVector
[PoolType
];
2113 // Make sure that the IRQL makes sense
2115 ExpCheckPoolIrqlLevel(PoolType
, 0, P
);
2118 // Get the pool tag and get rid of the PROTECTED_POOL flag
2120 Tag
= Entry
->PoolTag
;
2121 if (Tag
& PROTECTED_POOL
) Tag
&= ~PROTECTED_POOL
;
2124 // Stop tracking this allocation
2126 ExpRemovePoolTracker(Tag
,
2127 BlockSize
* POOL_BLOCK_SIZE
,
2128 Entry
->PoolType
- 1);
2131 // Is this allocation small enough to have come from a lookaside list?
2133 if (BlockSize
<= MAXIMUM_PROCESSORS
)
2136 // Try pushing it into the per-CPU lookaside list
2138 LookasideList
= (PoolType
== PagedPool
) ?
2139 Prcb
->PPPagedLookasideList
[BlockSize
- 1].P
:
2140 Prcb
->PPNPagedLookasideList
[BlockSize
- 1].P
;
2141 LookasideList
->TotalFrees
++;
2142 if (ExQueryDepthSList(&LookasideList
->ListHead
) < LookasideList
->Depth
)
2144 LookasideList
->FreeHits
++;
2145 InterlockedPushEntrySList(&LookasideList
->ListHead
, P
);
2150 // We failed, try to push it into the global lookaside list
2152 LookasideList
= (PoolType
== PagedPool
) ?
2153 Prcb
->PPPagedLookasideList
[BlockSize
- 1].L
:
2154 Prcb
->PPNPagedLookasideList
[BlockSize
- 1].L
;
2155 LookasideList
->TotalFrees
++;
2156 if (ExQueryDepthSList(&LookasideList
->ListHead
) < LookasideList
->Depth
)
2158 LookasideList
->FreeHits
++;
2159 InterlockedPushEntrySList(&LookasideList
->ListHead
, P
);
2165 // Get the pointer to the next entry
2167 NextEntry
= POOL_BLOCK(Entry
, BlockSize
);
2170 // Update performance counters
2172 InterlockedIncrement((PLONG
)&PoolDesc
->RunningDeAllocs
);
2173 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, -BlockSize
* POOL_BLOCK_SIZE
);
2176 // Acquire the pool lock
2178 OldIrql
= ExLockPool(PoolDesc
);
2183 if (TagToFree
&& TagToFree
!= Entry
->PoolTag
)
2185 DPRINT1("Freeing pool - invalid tag specified: %.4s != %.4s\n", (char*)&TagToFree
, (char*)&Entry
->PoolTag
);
2186 KeBugCheckEx(BAD_POOL_CALLER
, 0x0A, (ULONG_PTR
)P
, Entry
->PoolTag
, TagToFree
);
2190 // Check if the next allocation is at the end of the page
2192 ExpCheckPoolBlocks(Entry
);
2193 if (PAGE_ALIGN(NextEntry
) != NextEntry
)
2196 // We may be able to combine the block if it's free
2198 if (NextEntry
->PoolType
== 0)
2201 // The next block is free, so we'll do a combine
2206 // Make sure there's actual data in the block -- anything smaller
2207 // than this means we only have the header, so there's no linked list
2210 if ((NextEntry
->BlockSize
!= 1))
2213 // The block is at least big enough to have a linked list, so go
2214 // ahead and remove it
2216 ExpCheckPoolLinks(POOL_FREE_BLOCK(NextEntry
));
2217 ExpRemovePoolEntryList(POOL_FREE_BLOCK(NextEntry
));
2218 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Flink
));
2219 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Blink
));
2223 // Our entry is now combined with the next entry
2225 Entry
->BlockSize
= Entry
->BlockSize
+ NextEntry
->BlockSize
;
2230 // Now check if there was a previous entry on the same page as us
2232 if (Entry
->PreviousSize
)
2235 // Great, grab that entry and check if it's free
2237 NextEntry
= POOL_PREV_BLOCK(Entry
);
2238 if (NextEntry
->PoolType
== 0)
2241 // It is, so we can do a combine
2246 // Make sure there's actual data in the block -- anything smaller
2247 // than this means we only have the header so there's no linked list
2250 if ((NextEntry
->BlockSize
!= 1))
2253 // The block is at least big enough to have a linked list, so go
2254 // ahead and remove it
2256 ExpCheckPoolLinks(POOL_FREE_BLOCK(NextEntry
));
2257 ExpRemovePoolEntryList(POOL_FREE_BLOCK(NextEntry
));
2258 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Flink
));
2259 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Blink
));
2263 // Combine our original block (which might've already been combined
2264 // with the next block), into the previous block
2266 NextEntry
->BlockSize
= NextEntry
->BlockSize
+ Entry
->BlockSize
;
2269 // And now we'll work with the previous block instead
2276 // By now, it may have been possible for our combined blocks to actually
2277 // have made up a full page (if there were only 2-3 allocations on the
2278 // page, they could've all been combined).
2280 if ((PAGE_ALIGN(Entry
) == Entry
) &&
2281 (PAGE_ALIGN(POOL_NEXT_BLOCK(Entry
)) == POOL_NEXT_BLOCK(Entry
)))
2284 // In this case, release the pool lock, update the performance counter,
2285 // and free the page
2287 ExUnlockPool(PoolDesc
, OldIrql
);
2288 InterlockedExchangeAdd((PLONG
)&PoolDesc
->TotalPages
, -1);
2289 MiFreePoolPages(Entry
);
2294 // Otherwise, we now have a free block (or a combination of 2 or 3)
2296 Entry
->PoolType
= 0;
2297 BlockSize
= Entry
->BlockSize
;
2298 ASSERT(BlockSize
!= 1);
2301 // Check if we actually did combine it with anyone
2306 // Get the first combined block (either our original to begin with, or
2307 // the one after the original, depending if we combined with the previous)
2309 NextEntry
= POOL_NEXT_BLOCK(Entry
);
2312 // As long as the next block isn't on a page boundary, have it point
2315 if (PAGE_ALIGN(NextEntry
) != NextEntry
) NextEntry
->PreviousSize
= BlockSize
;
2319 // Insert this new free block, and release the pool lock
2321 ExpInsertPoolHeadList(&PoolDesc
->ListHeads
[BlockSize
- 1], POOL_FREE_BLOCK(Entry
));
2322 ExpCheckPoolLinks(POOL_FREE_BLOCK(Entry
));
2323 ExUnlockPool(PoolDesc
, OldIrql
);
2334 // Just free without checking for the tag
2336 ExFreePoolWithTag(P
, 0);
2344 ExQueryPoolBlockSize(IN PVOID PoolBlock
,
2345 OUT PBOOLEAN QuotaCharged
)
2360 ExAllocatePoolWithQuota(IN POOL_TYPE PoolType
,
2361 IN SIZE_T NumberOfBytes
)
2364 // Allocate the pool
2366 return ExAllocatePoolWithQuotaTag(PoolType
, NumberOfBytes
, 'enoN');
2374 ExAllocatePoolWithTagPriority(IN POOL_TYPE PoolType
,
2375 IN SIZE_T NumberOfBytes
,
2377 IN EX_POOL_PRIORITY Priority
)
2380 // Allocate the pool
2383 return ExAllocatePoolWithTag(PoolType
, NumberOfBytes
, Tag
);
2391 ExAllocatePoolWithQuotaTag(IN POOL_TYPE PoolType
,
2392 IN SIZE_T NumberOfBytes
,
2396 // Allocate the pool
2399 return ExAllocatePoolWithTag(PoolType
, NumberOfBytes
, Tag
);