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 DPRINT1("PreviousEntry BlockSize %lu, tag %.4s. Entry PreviousSize %lu, tag %.4s\n",
209 PreviousEntry
->BlockSize
, (char *)&PreviousEntry
->PoolTag
,
210 Entry
->PreviousSize
, (char *)&Entry
->PoolTag
);
211 KeBugCheckEx(BAD_POOL_HEADER
,
213 (ULONG_PTR
)PreviousEntry
,
218 else if (PAGE_ALIGN(Entry
) != Entry
)
220 /* If there's no block before us, we are the first block, so we should be on a page boundary */
221 KeBugCheckEx(BAD_POOL_HEADER
,
228 /* This block must have a size */
229 if (!Entry
->BlockSize
)
231 /* Someone must've corrupted this field */
232 if (Entry
->PreviousSize
)
234 PreviousEntry
= POOL_PREV_BLOCK(Entry
);
235 DPRINT1("PreviousEntry tag %.4s. Entry tag %.4s\n",
236 (char *)&PreviousEntry
->PoolTag
,
237 (char *)&Entry
->PoolTag
);
241 DPRINT1("Entry tag %.4s\n",
242 (char *)&Entry
->PoolTag
);
244 KeBugCheckEx(BAD_POOL_HEADER
,
251 /* Okay, now get the next block */
252 NextEntry
= POOL_NEXT_BLOCK(Entry
);
254 /* If this is the last block, then we'll be page-aligned, otherwise, check this block */
255 if (PAGE_ALIGN(NextEntry
) != NextEntry
)
257 /* The two blocks must be on the same page! */
258 if (PAGE_ALIGN(Entry
) != PAGE_ALIGN(NextEntry
))
260 /* Something is messed up */
261 KeBugCheckEx(BAD_POOL_HEADER
,
263 (ULONG_PTR
)NextEntry
,
268 /* And this block should think we are as large as we truly are */
269 if (NextEntry
->PreviousSize
!= Entry
->BlockSize
)
271 /* Otherwise, someone corrupted the field */
272 DPRINT1("Entry BlockSize %lu, tag %.4s. NextEntry PreviousSize %lu, tag %.4s\n",
273 Entry
->BlockSize
, (char *)&Entry
->PoolTag
,
274 NextEntry
->PreviousSize
, (char *)&NextEntry
->PoolTag
);
275 KeBugCheckEx(BAD_POOL_HEADER
,
277 (ULONG_PTR
)NextEntry
,
286 ExpCheckPoolBlocks(IN PVOID Block
)
288 BOOLEAN FoundBlock
= FALSE
;
292 /* Get the first entry for this page, make sure it really is the first */
293 Entry
= PAGE_ALIGN(Block
);
294 ASSERT(Entry
->PreviousSize
== 0);
296 /* Now scan each entry */
299 /* When we actually found our block, remember this */
300 if (Entry
== Block
) FoundBlock
= TRUE
;
302 /* Now validate this block header */
303 ExpCheckPoolHeader(Entry
);
305 /* And go to the next one, keeping track of our size */
306 Size
+= Entry
->BlockSize
;
307 Entry
= POOL_NEXT_BLOCK(Entry
);
309 /* If we hit the last block, stop */
310 if (Size
>= (PAGE_SIZE
/ POOL_BLOCK_SIZE
)) break;
312 /* If we hit the end of the page, stop */
313 if (PAGE_ALIGN(Entry
) == Entry
) break;
316 /* We must've found our block, and we must have hit the end of the page */
317 if ((PAGE_ALIGN(Entry
) != Entry
) || !(FoundBlock
))
319 /* Otherwise, the blocks are messed up */
320 KeBugCheckEx(BAD_POOL_HEADER
, 10, (ULONG_PTR
)Block
, __LINE__
, (ULONG_PTR
)Entry
);
326 ExpCheckPoolIrqlLevel(IN POOL_TYPE PoolType
,
327 IN SIZE_T NumberOfBytes
,
331 // Validate IRQL: It must be APC_LEVEL or lower for Paged Pool, and it must
332 // be DISPATCH_LEVEL or lower for Non Paged Pool
334 if (((PoolType
& BASE_POOL_TYPE_MASK
) == PagedPool
) ?
335 (KeGetCurrentIrql() > APC_LEVEL
) :
336 (KeGetCurrentIrql() > DISPATCH_LEVEL
))
339 // Take the system down
341 KeBugCheckEx(BAD_POOL_CALLER
,
342 !Entry
? POOL_ALLOC_IRQL_INVALID
: POOL_FREE_IRQL_INVALID
,
345 !Entry
? NumberOfBytes
: (ULONG_PTR
)Entry
);
351 ExpComputeHashForTag(IN ULONG Tag
,
352 IN SIZE_T BucketMask
)
355 // Compute the hash by multiplying with a large prime number and then XORing
356 // with the HIDWORD of the result.
358 // Finally, AND with the bucket mask to generate a valid index/bucket into
361 ULONGLONG Result
= 40543 * Tag
;
362 return (ULONG
)BucketMask
& ((ULONG
)Result
^ (Result
>> 32));
367 ExpComputePartialHashForAddress(IN PVOID BaseAddress
)
371 // Compute the hash by converting the address into a page number, and then
372 // XORing each nibble with the next one.
374 // We do *NOT* AND with the bucket mask at this point because big table expansion
375 // might happen. Therefore, the final step of the hash must be performed
376 // while holding the expansion pushlock, and this is why we call this a
377 // "partial" hash only.
379 Result
= (ULONG
)((ULONG_PTR
)BaseAddress
>> PAGE_SHIFT
);
380 return (Result
>> 24) ^ (Result
>> 16) ^ (Result
>> 8) ^ Result
;
383 /* PRIVATE FUNCTIONS **********************************************************/
390 ULONG i
, Key
, Hash
, Index
;
391 PPOOL_TRACKER_TABLE TrackTable
= PoolTrackTable
;
461 // Loop all 64 hot tags
463 ASSERT((sizeof(TagList
) / sizeof(ULONG
)) == 64);
464 for (i
= 0; i
< sizeof(TagList
) / sizeof(ULONG
); i
++)
467 // Get the current tag, and compute its hash in the tracker table
470 Hash
= ExpComputeHashForTag(Key
, PoolTrackTableMask
);
473 // Loop all the hashes in this index/bucket
479 // Find an empty entry, and make sure this isn't the last hash that
482 // On checked builds, also make sure this is the first time we are
485 ASSERT(TrackTable
[Hash
].Key
!= Key
);
486 if (!(TrackTable
[Hash
].Key
) && (Hash
!= PoolTrackTableSize
- 1))
489 // It has been seeded, move on to the next tag
491 TrackTable
[Hash
].Key
= Key
;
496 // This entry was already taken, compute the next possible hash while
497 // making sure we're not back at our initial index.
499 ASSERT(TrackTable
[Hash
].Key
!= Key
);
500 Hash
= (Hash
+ 1) & PoolTrackTableMask
;
501 if (Hash
== Index
) break;
508 ExpRemovePoolTracker(IN ULONG Key
,
509 IN SIZE_T NumberOfBytes
,
510 IN POOL_TYPE PoolType
)
513 PPOOL_TRACKER_TABLE Table
, TableEntry
;
514 SIZE_T TableMask
, TableSize
;
517 // Remove the PROTECTED_POOL flag which is not part of the tag
519 Key
&= ~PROTECTED_POOL
;
522 // With WinDBG you can set a tag you want to break on when an allocation is
525 if (Key
== PoolHitTag
) DbgBreakPoint();
528 // Why the double indirection? Because normally this function is also used
529 // when doing session pool allocations, which has another set of tables,
530 // sizes, and masks that live in session pool. Now we don't support session
531 // pool so we only ever use the regular tables, but I'm keeping the code this
532 // way so that the day we DO support session pool, it won't require that
535 Table
= PoolTrackTable
;
536 TableMask
= PoolTrackTableMask
;
537 TableSize
= PoolTrackTableSize
;
540 // Compute the hash for this key, and loop all the possible buckets
542 Hash
= ExpComputeHashForTag(Key
, TableMask
);
547 // Have we found the entry for this tag? */
549 TableEntry
= &Table
[Hash
];
550 if (TableEntry
->Key
== Key
)
553 // Decrement the counters depending on if this was paged or nonpaged
556 if ((PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
558 InterlockedIncrement(&TableEntry
->NonPagedFrees
);
559 InterlockedExchangeAddSizeT(&TableEntry
->NonPagedBytes
,
560 -(SSIZE_T
)NumberOfBytes
);
563 InterlockedIncrement(&TableEntry
->PagedFrees
);
564 InterlockedExchangeAddSizeT(&TableEntry
->PagedBytes
,
565 -(SSIZE_T
)NumberOfBytes
);
570 // We should have only ended up with an empty entry if we've reached
573 if (!TableEntry
->Key
) ASSERT(Hash
== TableMask
);
576 // This path is hit when we don't have an entry, and the current bucket
577 // is full, so we simply try the next one
579 Hash
= (Hash
+ 1) & TableMask
;
580 if (Hash
== Index
) break;
584 // And finally this path is hit when all the buckets are full, and we need
585 // some expansion. This path is not yet supported in ReactOS and so we'll
588 DPRINT1("Out of pool tag space, ignoring...\n");
593 ExpInsertPoolTracker(IN ULONG Key
,
594 IN SIZE_T NumberOfBytes
,
595 IN POOL_TYPE PoolType
)
599 PPOOL_TRACKER_TABLE Table
, TableEntry
;
600 SIZE_T TableMask
, TableSize
;
603 // Remove the PROTECTED_POOL flag which is not part of the tag
605 Key
&= ~PROTECTED_POOL
;
608 // With WinDBG you can set a tag you want to break on when an allocation is
611 if (Key
== PoolHitTag
) DbgBreakPoint();
614 // There is also an internal flag you can set to break on malformed tags
616 if (ExStopBadTags
) ASSERT(Key
& 0xFFFFFF00);
619 // ASSERT on ReactOS features not yet supported
621 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
622 ASSERT(KeGetCurrentProcessorNumber() == 0);
625 // Why the double indirection? Because normally this function is also used
626 // when doing session pool allocations, which has another set of tables,
627 // sizes, and masks that live in session pool. Now we don't support session
628 // pool so we only ever use the regular tables, but I'm keeping the code this
629 // way so that the day we DO support session pool, it won't require that
632 Table
= PoolTrackTable
;
633 TableMask
= PoolTrackTableMask
;
634 TableSize
= PoolTrackTableSize
;
637 // Compute the hash for this key, and loop all the possible buckets
639 Hash
= ExpComputeHashForTag(Key
, TableMask
);
644 // Do we already have an entry for this tag? */
646 TableEntry
= &Table
[Hash
];
647 if (TableEntry
->Key
== Key
)
650 // Increment the counters depending on if this was paged or nonpaged
653 if ((PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
655 InterlockedIncrement(&TableEntry
->NonPagedAllocs
);
656 InterlockedExchangeAddSizeT(&TableEntry
->NonPagedBytes
, NumberOfBytes
);
659 InterlockedIncrement(&TableEntry
->PagedAllocs
);
660 InterlockedExchangeAddSizeT(&TableEntry
->PagedBytes
, NumberOfBytes
);
665 // We don't have an entry yet, but we've found a free bucket for it
667 if (!(TableEntry
->Key
) && (Hash
!= PoolTrackTableSize
- 1))
670 // We need to hold the lock while creating a new entry, since other
671 // processors might be in this code path as well
673 ExAcquireSpinLock(&ExpTaggedPoolLock
, &OldIrql
);
674 if (!PoolTrackTable
[Hash
].Key
)
677 // We've won the race, so now create this entry in the bucket
679 ASSERT(Table
[Hash
].Key
== 0);
680 PoolTrackTable
[Hash
].Key
= Key
;
681 TableEntry
->Key
= Key
;
683 ExReleaseSpinLock(&ExpTaggedPoolLock
, OldIrql
);
686 // Now we force the loop to run again, and we should now end up in
687 // the code path above which does the interlocked increments...
693 // This path is hit when we don't have an entry, and the current bucket
694 // is full, so we simply try the next one
696 Hash
= (Hash
+ 1) & TableMask
;
697 if (Hash
== Index
) break;
701 // And finally this path is hit when all the buckets are full, and we need
702 // some expansion. This path is not yet supported in ReactOS and so we'll
705 DPRINT1("Out of pool tag space, ignoring...\n");
711 ExInitializePoolDescriptor(IN PPOOL_DESCRIPTOR PoolDescriptor
,
712 IN POOL_TYPE PoolType
,
717 PLIST_ENTRY NextEntry
, LastEntry
;
720 // Setup the descriptor based on the caller's request
722 PoolDescriptor
->PoolType
= PoolType
;
723 PoolDescriptor
->PoolIndex
= PoolIndex
;
724 PoolDescriptor
->Threshold
= Threshold
;
725 PoolDescriptor
->LockAddress
= PoolLock
;
728 // Initialize accounting data
730 PoolDescriptor
->RunningAllocs
= 0;
731 PoolDescriptor
->RunningDeAllocs
= 0;
732 PoolDescriptor
->TotalPages
= 0;
733 PoolDescriptor
->TotalBytes
= 0;
734 PoolDescriptor
->TotalBigPages
= 0;
737 // Nothing pending for now
739 PoolDescriptor
->PendingFrees
= NULL
;
740 PoolDescriptor
->PendingFreeDepth
= 0;
743 // Loop all the descriptor's allocation lists and initialize them
745 NextEntry
= PoolDescriptor
->ListHeads
;
746 LastEntry
= NextEntry
+ POOL_LISTS_PER_PAGE
;
747 while (NextEntry
< LastEntry
)
749 ExpInitializePoolListHead(NextEntry
);
754 // Note that ReactOS does not support Session Pool Yet
756 ASSERT(PoolType
!= PagedPoolSession
);
762 InitializePool(IN POOL_TYPE PoolType
,
765 PPOOL_DESCRIPTOR Descriptor
;
770 // Check what kind of pool this is
772 if (PoolType
== NonPagedPool
)
775 // Compute the track table size and convert it from a power of two to an
778 // NOTE: On checked builds, we'll assert if the registry table size was
779 // invalid, while on retail builds we'll just break out of the loop at
782 TableSize
= min(PoolTrackTableSize
, MmSizeOfNonPagedPoolInBytes
>> 8);
783 for (i
= 0; i
< 32; i
++)
787 ASSERT((TableSize
& ~1) == 0);
788 if (!(TableSize
& ~1)) break;
794 // If we hit bit 32, than no size was defined in the registry, so
795 // we'll use the default size of 2048 entries.
797 // Otherwise, use the size from the registry, as long as it's not
798 // smaller than 64 entries.
802 PoolTrackTableSize
= 2048;
806 PoolTrackTableSize
= max(1 << i
, 64);
810 // Loop trying with the biggest specified size first, and cut it down
811 // by a power of two each iteration in case not enough memory exist
816 // Do not allow overflow
818 if ((PoolTrackTableSize
+ 1) > (MAXULONG_PTR
/ sizeof(POOL_TRACKER_TABLE
)))
820 PoolTrackTableSize
>>= 1;
825 // Allocate the tracker table and exit the loop if this worked
827 PoolTrackTable
= MiAllocatePoolPages(NonPagedPool
,
828 (PoolTrackTableSize
+ 1) *
829 sizeof(POOL_TRACKER_TABLE
));
830 if (PoolTrackTable
) break;
833 // Otherwise, as long as we're not down to the last bit, keep
836 if (PoolTrackTableSize
== 1)
838 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
844 PoolTrackTableSize
>>= 1;
848 // Finally, add one entry, compute the hash, and zero the table
850 PoolTrackTableSize
++;
851 PoolTrackTableMask
= PoolTrackTableSize
- 2;
853 RtlZeroMemory(PoolTrackTable
,
854 PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
));
857 // We now do the exact same thing with the tracker table for big pages
859 TableSize
= min(PoolBigPageTableSize
, MmSizeOfNonPagedPoolInBytes
>> 8);
860 for (i
= 0; i
< 32; i
++)
864 ASSERT((TableSize
& ~1) == 0);
865 if (!(TableSize
& ~1)) break;
871 // For big pages, the default tracker table is 4096 entries, while the
872 // minimum is still 64
876 PoolBigPageTableSize
= 4096;
880 PoolBigPageTableSize
= max(1 << i
, 64);
884 // Again, run the exact same loop we ran earlier, but this time for the
885 // big pool tracker instead
889 if ((PoolBigPageTableSize
+ 1) > (MAXULONG_PTR
/ sizeof(POOL_TRACKER_BIG_PAGES
)))
891 PoolBigPageTableSize
>>= 1;
895 PoolBigPageTable
= MiAllocatePoolPages(NonPagedPool
,
896 PoolBigPageTableSize
*
897 sizeof(POOL_TRACKER_BIG_PAGES
));
898 if (PoolBigPageTable
) break;
900 if (PoolBigPageTableSize
== 1)
902 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
909 PoolBigPageTableSize
>>= 1;
913 // An extra entry is not needed for for the big pool tracker, so just
914 // compute the hash and zero it
916 PoolBigPageTableHash
= PoolBigPageTableSize
- 1;
917 RtlZeroMemory(PoolBigPageTable
,
918 PoolBigPageTableSize
* sizeof(POOL_TRACKER_BIG_PAGES
));
919 for (i
= 0; i
< PoolBigPageTableSize
; i
++) PoolBigPageTable
[i
].Va
= (PVOID
)1;
922 // During development, print this out so we can see what's happening
924 DPRINT1("EXPOOL: Pool Tracker Table at: 0x%p with 0x%lx bytes\n",
925 PoolTrackTable
, PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
));
926 DPRINT1("EXPOOL: Big Pool Tracker Table at: 0x%p with 0x%lx bytes\n",
927 PoolBigPageTable
, PoolBigPageTableSize
* sizeof(POOL_TRACKER_BIG_PAGES
));
930 // Insert the generic tracker for all of big pool
932 ExpInsertPoolTracker('looP',
933 ROUND_TO_PAGES(PoolBigPageTableSize
*
934 sizeof(POOL_TRACKER_BIG_PAGES
)),
938 // No support for NUMA systems at this time
940 ASSERT(KeNumberNodes
== 1);
943 // Initialize the tag spinlock
945 KeInitializeSpinLock(&ExpTaggedPoolLock
);
948 // Initialize the nonpaged pool descriptor
950 PoolVector
[NonPagedPool
] = &NonPagedPoolDescriptor
;
951 ExInitializePoolDescriptor(PoolVector
[NonPagedPool
],
960 // No support for NUMA systems at this time
962 ASSERT(KeNumberNodes
== 1);
965 // Allocate the pool descriptor
967 Descriptor
= ExAllocatePoolWithTag(NonPagedPool
,
968 sizeof(KGUARDED_MUTEX
) +
969 sizeof(POOL_DESCRIPTOR
),
974 // This is really bad...
976 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
984 // Setup the vector and guarded mutex for paged pool
986 PoolVector
[PagedPool
] = Descriptor
;
987 ExpPagedPoolMutex
= (PKGUARDED_MUTEX
)(Descriptor
+ 1);
988 ExpPagedPoolDescriptor
[0] = Descriptor
;
989 KeInitializeGuardedMutex(ExpPagedPoolMutex
);
990 ExInitializePoolDescriptor(Descriptor
,
997 // Insert the generic tracker for all of nonpaged pool
999 ExpInsertPoolTracker('looP',
1000 ROUND_TO_PAGES(PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
)),
1007 ExLockPool(IN PPOOL_DESCRIPTOR Descriptor
)
1010 // Check if this is nonpaged pool
1012 if ((Descriptor
->PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
1015 // Use the queued spin lock
1017 return KeAcquireQueuedSpinLock(LockQueueNonPagedPoolLock
);
1022 // Use the guarded mutex
1024 KeAcquireGuardedMutex(Descriptor
->LockAddress
);
1031 ExUnlockPool(IN PPOOL_DESCRIPTOR Descriptor
,
1035 // Check if this is nonpaged pool
1037 if ((Descriptor
->PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
1040 // Use the queued spin lock
1042 KeReleaseQueuedSpinLock(LockQueueNonPagedPoolLock
, OldIrql
);
1047 // Use the guarded mutex
1049 KeReleaseGuardedMutex(Descriptor
->LockAddress
);
1055 ExpGetPoolTagInfoTarget(IN PKDPC Dpc
,
1056 IN PVOID DeferredContext
,
1057 IN PVOID SystemArgument1
,
1058 IN PVOID SystemArgument2
)
1060 PPOOL_DPC_CONTEXT Context
= DeferredContext
;
1061 UNREFERENCED_PARAMETER(Dpc
);
1062 ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL
);
1065 // Make sure we win the race, and if we did, copy the data atomically
1067 if (KeSignalCallDpcSynchronize(SystemArgument2
))
1069 RtlCopyMemory(Context
->PoolTrackTable
,
1071 Context
->PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
));
1074 // This is here because ReactOS does not yet support expansion
1076 ASSERT(Context
->PoolTrackTableSizeExpansion
== 0);
1080 // Regardless of whether we won or not, we must now synchronize and then
1081 // decrement the barrier since this is one more processor that has completed
1084 KeSignalCallDpcSynchronize(SystemArgument2
);
1085 KeSignalCallDpcDone(SystemArgument1
);
1090 ExGetPoolTagInfo(IN PSYSTEM_POOLTAG_INFORMATION SystemInformation
,
1091 IN ULONG SystemInformationLength
,
1092 IN OUT PULONG ReturnLength OPTIONAL
)
1094 ULONG TableSize
, CurrentLength
;
1096 NTSTATUS Status
= STATUS_SUCCESS
;
1097 PSYSTEM_POOLTAG TagEntry
;
1098 PPOOL_TRACKER_TABLE Buffer
, TrackerEntry
;
1099 POOL_DPC_CONTEXT Context
;
1100 ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL
);
1103 // Keep track of how much data the caller's buffer must hold
1105 CurrentLength
= FIELD_OFFSET(SYSTEM_POOLTAG_INFORMATION
, TagInfo
);
1108 // Initialize the caller's buffer
1110 TagEntry
= &SystemInformation
->TagInfo
[0];
1111 SystemInformation
->Count
= 0;
1114 // Capture the number of entries, and the total size needed to make a copy
1117 EntryCount
= (ULONG
)PoolTrackTableSize
;
1118 TableSize
= EntryCount
* sizeof(POOL_TRACKER_TABLE
);
1121 // Allocate the "Generic DPC" temporary buffer
1123 Buffer
= ExAllocatePoolWithTag(NonPagedPool
, TableSize
, 'ofnI');
1124 if (!Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
1127 // Do a "Generic DPC" to atomically retrieve the tag and allocation data
1129 Context
.PoolTrackTable
= Buffer
;
1130 Context
.PoolTrackTableSize
= PoolTrackTableSize
;
1131 Context
.PoolTrackTableExpansion
= NULL
;
1132 Context
.PoolTrackTableSizeExpansion
= 0;
1133 KeGenericCallDpc(ExpGetPoolTagInfoTarget
, &Context
);
1136 // Now parse the results
1138 for (TrackerEntry
= Buffer
; TrackerEntry
< (Buffer
+ EntryCount
); TrackerEntry
++)
1141 // If the entry is empty, skip it
1143 if (!TrackerEntry
->Key
) continue;
1146 // Otherwise, add one more entry to the caller's buffer, and ensure that
1147 // enough space has been allocated in it
1149 SystemInformation
->Count
++;
1150 CurrentLength
+= sizeof(*TagEntry
);
1151 if (SystemInformationLength
< CurrentLength
)
1154 // The caller's buffer is too small, so set a failure code. The
1155 // caller will know the count, as well as how much space is needed.
1157 // We do NOT break out of the loop, because we want to keep incrementing
1158 // the Count as well as CurrentLength so that the caller can know the
1161 Status
= STATUS_INFO_LENGTH_MISMATCH
;
1166 // Small sanity check that our accounting is working correctly
1168 ASSERT(TrackerEntry
->PagedAllocs
>= TrackerEntry
->PagedFrees
);
1169 ASSERT(TrackerEntry
->NonPagedAllocs
>= TrackerEntry
->NonPagedFrees
);
1172 // Return the data into the caller's buffer
1174 TagEntry
->TagUlong
= TrackerEntry
->Key
;
1175 TagEntry
->PagedAllocs
= TrackerEntry
->PagedAllocs
;
1176 TagEntry
->PagedFrees
= TrackerEntry
->PagedFrees
;
1177 TagEntry
->PagedUsed
= TrackerEntry
->PagedBytes
;
1178 TagEntry
->NonPagedAllocs
= TrackerEntry
->NonPagedAllocs
;
1179 TagEntry
->NonPagedFrees
= TrackerEntry
->NonPagedFrees
;
1180 TagEntry
->NonPagedUsed
= TrackerEntry
->NonPagedBytes
;
1186 // Free the "Generic DPC" temporary buffer, return the buffer length and status
1189 if (ReturnLength
) *ReturnLength
= CurrentLength
;
1195 ExpAddTagForBigPages(IN PVOID Va
,
1197 IN ULONG NumberOfPages
,
1198 IN POOL_TYPE PoolType
)
1204 PPOOL_TRACKER_BIG_PAGES Entry
, EntryEnd
, EntryStart
;
1205 ASSERT(((ULONG_PTR
)Va
& POOL_BIG_TABLE_ENTRY_FREE
) == 0);
1206 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
1209 // As the table is expandable, these values must only be read after acquiring
1210 // the lock to avoid a teared access during an expansion
1212 Hash
= ExpComputePartialHashForAddress(Va
);
1213 KeAcquireSpinLock(&ExpLargePoolTableLock
, &OldIrql
);
1214 Hash
&= PoolBigPageTableHash
;
1215 TableSize
= PoolBigPageTableSize
;
1218 // We loop from the current hash bucket to the end of the table, and then
1219 // rollover to hash bucket 0 and keep going from there. If we return back
1220 // to the beginning, then we attempt expansion at the bottom of the loop
1222 EntryStart
= Entry
= &PoolBigPageTable
[Hash
];
1223 EntryEnd
= &PoolBigPageTable
[TableSize
];
1227 // Make sure that this is a free entry and attempt to atomically make the
1231 if (((ULONG_PTR
)OldVa
& POOL_BIG_TABLE_ENTRY_FREE
) &&
1232 (InterlockedCompareExchangePointer(&Entry
->Va
, Va
, OldVa
) == OldVa
))
1235 // We now own this entry, write down the size and the pool tag
1238 Entry
->NumberOfPages
= NumberOfPages
;
1241 // Add one more entry to the count, and see if we're getting within
1242 // 25% of the table size, at which point we'll do an expansion now
1243 // to avoid blocking too hard later on.
1245 // Note that we only do this if it's also been the 16th time that we
1246 // keep losing the race or that we are not finding a free entry anymore,
1247 // which implies a massive number of concurrent big pool allocations.
1249 InterlockedIncrement(&ExpPoolBigEntriesInUse
);
1250 if ((i
>= 16) && (ExpPoolBigEntriesInUse
> (TableSize
/ 4)))
1252 DPRINT1("Should attempt expansion since we now have %d entries\n",
1253 ExpPoolBigEntriesInUse
);
1257 // We have our entry, return
1259 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1264 // We don't have our entry yet, so keep trying, making the entry list
1265 // circular if we reach the last entry. We'll eventually break out of
1266 // the loop once we've rolled over and returned back to our original
1270 if (++Entry
>= EntryEnd
) Entry
= &PoolBigPageTable
[0];
1271 } while (Entry
!= EntryStart
);
1274 // This means there's no free hash buckets whatsoever, so we would now have
1275 // to attempt expanding the table
1277 DPRINT1("Big pool expansion needed, not implemented!\n");
1278 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1284 ExpFindAndRemoveTagBigPages(IN PVOID Va
,
1285 OUT PULONG_PTR BigPages
,
1286 IN POOL_TYPE PoolType
)
1288 BOOLEAN FirstTry
= TRUE
;
1291 ULONG PoolTag
, Hash
;
1292 PPOOL_TRACKER_BIG_PAGES Entry
;
1293 ASSERT(((ULONG_PTR
)Va
& POOL_BIG_TABLE_ENTRY_FREE
) == 0);
1294 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
1297 // As the table is expandable, these values must only be read after acquiring
1298 // the lock to avoid a teared access during an expansion
1300 Hash
= ExpComputePartialHashForAddress(Va
);
1301 KeAcquireSpinLock(&ExpLargePoolTableLock
, &OldIrql
);
1302 Hash
&= PoolBigPageTableHash
;
1303 TableSize
= PoolBigPageTableSize
;
1306 // Loop while trying to find this big page allocation
1308 while (PoolBigPageTable
[Hash
].Va
!= Va
)
1311 // Increment the size until we go past the end of the table
1313 if (++Hash
>= TableSize
)
1316 // Is this the second time we've tried?
1321 // This means it was never inserted into the pool table and it
1322 // received the special "BIG" tag -- return that and return 0
1323 // so that the code can ask Mm for the page count instead
1325 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1331 // The first time this happens, reset the hash index and try again
1339 // Now capture all the information we need from the entry, since after we
1340 // release the lock, the data can change
1342 Entry
= &PoolBigPageTable
[Hash
];
1343 *BigPages
= Entry
->NumberOfPages
;
1344 PoolTag
= Entry
->Key
;
1347 // Set the free bit, and decrement the number of allocations. Finally, release
1348 // the lock and return the tag that was located
1350 InterlockedIncrement((PLONG
)&Entry
->Va
);
1351 InterlockedDecrement(&ExpPoolBigEntriesInUse
);
1352 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1358 ExQueryPoolUsage(OUT PULONG PagedPoolPages
,
1359 OUT PULONG NonPagedPoolPages
,
1360 OUT PULONG PagedPoolAllocs
,
1361 OUT PULONG PagedPoolFrees
,
1362 OUT PULONG PagedPoolLookasideHits
,
1363 OUT PULONG NonPagedPoolAllocs
,
1364 OUT PULONG NonPagedPoolFrees
,
1365 OUT PULONG NonPagedPoolLookasideHits
)
1368 PPOOL_DESCRIPTOR PoolDesc
;
1371 // Assume all failures
1373 *PagedPoolPages
= 0;
1374 *PagedPoolAllocs
= 0;
1375 *PagedPoolFrees
= 0;
1378 // Tally up the totals for all the apged pool
1380 for (i
= 0; i
< ExpNumberOfPagedPools
+ 1; i
++)
1382 PoolDesc
= ExpPagedPoolDescriptor
[i
];
1383 *PagedPoolPages
+= PoolDesc
->TotalPages
+ PoolDesc
->TotalBigPages
;
1384 *PagedPoolAllocs
+= PoolDesc
->RunningAllocs
;
1385 *PagedPoolFrees
+= PoolDesc
->RunningDeAllocs
;
1389 // The first non-paged pool has a hardcoded well-known descriptor name
1391 PoolDesc
= &NonPagedPoolDescriptor
;
1392 *NonPagedPoolPages
= PoolDesc
->TotalPages
+ PoolDesc
->TotalBigPages
;
1393 *NonPagedPoolAllocs
= PoolDesc
->RunningAllocs
;
1394 *NonPagedPoolFrees
= PoolDesc
->RunningDeAllocs
;
1397 // If the system has more than one non-paged pool, copy the other descriptor
1401 if (ExpNumberOfNonPagedPools
> 1)
1403 for (i
= 0; i
< ExpNumberOfNonPagedPools
; i
++)
1405 PoolDesc
= ExpNonPagedPoolDescriptor
[i
];
1406 *NonPagedPoolPages
+= PoolDesc
->TotalPages
+ PoolDesc
->TotalBigPages
;
1407 *NonPagedPoolAllocs
+= PoolDesc
->RunningAllocs
;
1408 *NonPagedPoolFrees
+= PoolDesc
->RunningDeAllocs
;
1414 // FIXME: Not yet supported
1416 *NonPagedPoolLookasideHits
+= 0;
1417 *PagedPoolLookasideHits
+= 0;
1420 /* PUBLIC FUNCTIONS ***********************************************************/
1427 ExAllocatePoolWithTag(IN POOL_TYPE PoolType
,
1428 IN SIZE_T NumberOfBytes
,
1431 PPOOL_DESCRIPTOR PoolDesc
;
1432 PLIST_ENTRY ListHead
;
1433 PPOOL_HEADER Entry
, NextEntry
, FragmentEntry
;
1435 USHORT BlockSize
, i
;
1437 PKPRCB Prcb
= KeGetCurrentPrcb();
1438 PGENERAL_LOOKASIDE LookasideList
;
1441 // Some sanity checks
1444 ASSERT(Tag
!= ' GIB');
1445 ASSERT(NumberOfBytes
!= 0);
1446 ExpCheckPoolIrqlLevel(PoolType
, NumberOfBytes
, NULL
);
1449 // Not supported in ReactOS
1451 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
1454 // Check if verifier or special pool is enabled
1456 if (ExpPoolFlags
& (POOL_FLAG_VERIFIER
| POOL_FLAG_SPECIAL_POOL
))
1459 // For verifier, we should call the verification routine
1461 if (ExpPoolFlags
& POOL_FLAG_VERIFIER
)
1463 DPRINT1("Driver Verifier is not yet supported\n");
1467 // For special pool, we check if this is a suitable allocation and do
1468 // the special allocation if needed
1470 if (ExpPoolFlags
& POOL_FLAG_SPECIAL_POOL
)
1473 // Check if this is a special pool allocation
1475 if (MmUseSpecialPool(NumberOfBytes
, Tag
))
1478 // Try to allocate using special pool
1480 Entry
= MmAllocateSpecialPool(NumberOfBytes
, Tag
, PoolType
, 2);
1481 if (Entry
) return Entry
;
1487 // Get the pool type and its corresponding vector for this request
1489 OriginalType
= PoolType
;
1490 PoolType
= PoolType
& BASE_POOL_TYPE_MASK
;
1491 PoolDesc
= PoolVector
[PoolType
];
1492 ASSERT(PoolDesc
!= NULL
);
1495 // Check if this is a big page allocation
1497 if (NumberOfBytes
> POOL_MAX_ALLOC
)
1500 // Allocate pages for it
1502 Entry
= MiAllocatePoolPages(OriginalType
, NumberOfBytes
);
1506 // Must succeed pool is deprecated, but still supported. These allocation
1507 // failures must cause an immediate bugcheck
1509 if (OriginalType
& MUST_SUCCEED_POOL_MASK
)
1511 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
1513 NonPagedPoolDescriptor
.TotalPages
,
1514 NonPagedPoolDescriptor
.TotalBigPages
,
1519 // Internal debugging
1524 // This flag requests printing failures, and can also further specify
1525 // breaking on failures
1527 if (ExpPoolFlags
& POOL_FLAG_DBGPRINT_ON_FAILURE
)
1529 DPRINT1("EX: ExAllocatePool (%p, 0x%x) returning NULL\n",
1532 if (ExpPoolFlags
& POOL_FLAG_CRASH_ON_FAILURE
) DbgBreakPoint();
1536 // Finally, this flag requests an exception, which we are more than
1539 if (OriginalType
& POOL_RAISE_IF_ALLOCATION_FAILURE
)
1541 ExRaiseStatus(STATUS_INSUFFICIENT_RESOURCES
);
1546 // Increment required counters
1548 InterlockedExchangeAdd((PLONG
)&PoolDesc
->TotalBigPages
,
1549 (LONG
)BYTES_TO_PAGES(NumberOfBytes
));
1550 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, NumberOfBytes
);
1551 InterlockedIncrement((PLONG
)&PoolDesc
->RunningAllocs
);
1554 // Add a tag for the big page allocation and switch to the generic "BIG"
1555 // tag if we failed to do so, then insert a tracker for this alloation.
1557 if (!ExpAddTagForBigPages(Entry
,
1559 (ULONG
)BYTES_TO_PAGES(NumberOfBytes
),
1564 ExpInsertPoolTracker(Tag
, ROUND_TO_PAGES(NumberOfBytes
), OriginalType
);
1569 // Should never request 0 bytes from the pool, but since so many drivers do
1570 // it, we'll just assume they want 1 byte, based on NT's similar behavior
1572 if (!NumberOfBytes
) NumberOfBytes
= 1;
1575 // A pool allocation is defined by its data, a linked list to connect it to
1576 // the free list (if necessary), and a pool header to store accounting info.
1577 // Calculate this size, then convert it into a block size (units of pool
1580 // Note that i cannot overflow (past POOL_LISTS_PER_PAGE) because any such
1581 // request would've been treated as a POOL_MAX_ALLOC earlier and resulted in
1582 // the direct allocation of pages.
1584 i
= (USHORT
)((NumberOfBytes
+ sizeof(POOL_HEADER
) + (POOL_BLOCK_SIZE
- 1))
1588 // Handle lookaside list optimization for both paged and nonpaged pool
1590 if (i
<= MAXIMUM_PROCESSORS
)
1593 // Try popping it from the per-CPU lookaside list
1595 LookasideList
= (PoolType
== PagedPool
) ?
1596 Prcb
->PPPagedLookasideList
[i
- 1].P
:
1597 Prcb
->PPNPagedLookasideList
[i
- 1].P
;
1598 LookasideList
->TotalAllocates
++;
1599 Entry
= (PPOOL_HEADER
)InterlockedPopEntrySList(&LookasideList
->ListHead
);
1603 // We failed, try popping it from the global list
1605 LookasideList
= (PoolType
== PagedPool
) ?
1606 Prcb
->PPPagedLookasideList
[i
- 1].L
:
1607 Prcb
->PPNPagedLookasideList
[i
- 1].L
;
1608 LookasideList
->TotalAllocates
++;
1609 Entry
= (PPOOL_HEADER
)InterlockedPopEntrySList(&LookasideList
->ListHead
);
1613 // If we were able to pop it, update the accounting and return the block
1617 LookasideList
->AllocateHits
++;
1620 // Get the real entry, write down its pool type, and track it
1623 Entry
->PoolType
= PoolType
+ 1;
1624 ExpInsertPoolTracker(Tag
,
1625 Entry
->BlockSize
* POOL_BLOCK_SIZE
,
1629 // Return the pool allocation
1631 Entry
->PoolTag
= Tag
;
1632 (POOL_FREE_BLOCK(Entry
))->Flink
= NULL
;
1633 (POOL_FREE_BLOCK(Entry
))->Blink
= NULL
;
1634 return POOL_FREE_BLOCK(Entry
);
1639 // Loop in the free lists looking for a block if this size. Start with the
1640 // list optimized for this kind of size lookup
1642 ListHead
= &PoolDesc
->ListHeads
[i
];
1646 // Are there any free entries available on this list?
1648 if (!ExpIsPoolListEmpty(ListHead
))
1651 // Acquire the pool lock now
1653 OldIrql
= ExLockPool(PoolDesc
);
1656 // And make sure the list still has entries
1658 if (ExpIsPoolListEmpty(ListHead
))
1661 // Someone raced us (and won) before we had a chance to acquire
1666 ExUnlockPool(PoolDesc
, OldIrql
);
1672 // Remove a free entry from the list
1673 // Note that due to the way we insert free blocks into multiple lists
1674 // there is a guarantee that any block on this list will either be
1675 // of the correct size, or perhaps larger.
1677 ExpCheckPoolLinks(ListHead
);
1678 Entry
= POOL_ENTRY(ExpRemovePoolHeadList(ListHead
));
1679 ExpCheckPoolLinks(ListHead
);
1680 ExpCheckPoolBlocks(Entry
);
1681 ASSERT(Entry
->BlockSize
>= i
);
1682 ASSERT(Entry
->PoolType
== 0);
1685 // Check if this block is larger that what we need. The block could
1686 // not possibly be smaller, due to the reason explained above (and
1687 // we would've asserted on a checked build if this was the case).
1689 if (Entry
->BlockSize
!= i
)
1692 // Is there an entry before this one?
1694 if (Entry
->PreviousSize
== 0)
1697 // There isn't anyone before us, so take the next block and
1698 // turn it into a fragment that contains the leftover data
1699 // that we don't need to satisfy the caller's request
1701 FragmentEntry
= POOL_BLOCK(Entry
, i
);
1702 FragmentEntry
->BlockSize
= Entry
->BlockSize
- i
;
1705 // And make it point back to us
1707 FragmentEntry
->PreviousSize
= i
;
1710 // Now get the block that follows the new fragment and check
1711 // if it's still on the same page as us (and not at the end)
1713 NextEntry
= POOL_NEXT_BLOCK(FragmentEntry
);
1714 if (PAGE_ALIGN(NextEntry
) != NextEntry
)
1717 // Adjust this next block to point to our newly created
1720 NextEntry
->PreviousSize
= FragmentEntry
->BlockSize
;
1726 // There is a free entry before us, which we know is smaller
1727 // so we'll make this entry the fragment instead
1729 FragmentEntry
= Entry
;
1732 // And then we'll remove from it the actual size required.
1733 // Now the entry is a leftover free fragment
1735 Entry
->BlockSize
-= i
;
1738 // Now let's go to the next entry after the fragment (which
1739 // used to point to our original free entry) and make it
1740 // reference the new fragment entry instead.
1742 // This is the entry that will actually end up holding the
1745 Entry
= POOL_NEXT_BLOCK(Entry
);
1746 Entry
->PreviousSize
= FragmentEntry
->BlockSize
;
1749 // And now let's go to the entry after that one and check if
1750 // it's still on the same page, and not at the end
1752 NextEntry
= POOL_BLOCK(Entry
, i
);
1753 if (PAGE_ALIGN(NextEntry
) != NextEntry
)
1756 // Make it reference the allocation entry
1758 NextEntry
->PreviousSize
= i
;
1763 // Now our (allocation) entry is the right size
1765 Entry
->BlockSize
= i
;
1768 // And the next entry is now the free fragment which contains
1769 // the remaining difference between how big the original entry
1770 // was, and the actual size the caller needs/requested.
1772 FragmentEntry
->PoolType
= 0;
1773 BlockSize
= FragmentEntry
->BlockSize
;
1776 // Now check if enough free bytes remained for us to have a
1777 // "full" entry, which contains enough bytes for a linked list
1778 // and thus can be used for allocations (up to 8 bytes...)
1780 ExpCheckPoolLinks(&PoolDesc
->ListHeads
[BlockSize
- 1]);
1784 // Insert the free entry into the free list for this size
1786 ExpInsertPoolTailList(&PoolDesc
->ListHeads
[BlockSize
- 1],
1787 POOL_FREE_BLOCK(FragmentEntry
));
1788 ExpCheckPoolLinks(POOL_FREE_BLOCK(FragmentEntry
));
1793 // We have found an entry for this allocation, so set the pool type
1794 // and release the lock since we're done
1796 Entry
->PoolType
= PoolType
+ 1;
1797 ExpCheckPoolBlocks(Entry
);
1798 ExUnlockPool(PoolDesc
, OldIrql
);
1801 // Increment required counters
1803 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, Entry
->BlockSize
* POOL_BLOCK_SIZE
);
1804 InterlockedIncrement((PLONG
)&PoolDesc
->RunningAllocs
);
1807 // Track this allocation
1809 ExpInsertPoolTracker(Tag
,
1810 Entry
->BlockSize
* POOL_BLOCK_SIZE
,
1814 // Return the pool allocation
1816 Entry
->PoolTag
= Tag
;
1817 (POOL_FREE_BLOCK(Entry
))->Flink
= NULL
;
1818 (POOL_FREE_BLOCK(Entry
))->Blink
= NULL
;
1819 return POOL_FREE_BLOCK(Entry
);
1821 } while (++ListHead
!= &PoolDesc
->ListHeads
[POOL_LISTS_PER_PAGE
]);
1824 // There were no free entries left, so we have to allocate a new fresh page
1826 Entry
= MiAllocatePoolPages(PoolType
, PAGE_SIZE
);
1830 // Must succeed pool is deprecated, but still supported. These allocation
1831 // failures must cause an immediate bugcheck
1833 if (OriginalType
& MUST_SUCCEED_POOL_MASK
)
1835 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
1837 NonPagedPoolDescriptor
.TotalPages
,
1838 NonPagedPoolDescriptor
.TotalBigPages
,
1843 // Internal debugging
1848 // This flag requests printing failures, and can also further specify
1849 // breaking on failures
1851 if (ExpPoolFlags
& POOL_FLAG_DBGPRINT_ON_FAILURE
)
1853 DPRINT1("EX: ExAllocatePool (%p, 0x%x) returning NULL\n",
1856 if (ExpPoolFlags
& POOL_FLAG_CRASH_ON_FAILURE
) DbgBreakPoint();
1860 // Finally, this flag requests an exception, which we are more than
1863 if (OriginalType
& POOL_RAISE_IF_ALLOCATION_FAILURE
)
1865 ExRaiseStatus(STATUS_INSUFFICIENT_RESOURCES
);
1869 // Return NULL to the caller in all other cases
1875 // Setup the entry data
1878 Entry
->BlockSize
= i
;
1879 Entry
->PoolType
= PoolType
+ 1;
1882 // This page will have two entries -- one for the allocation (which we just
1883 // created above), and one for the remaining free bytes, which we're about
1884 // to create now. The free bytes are the whole page minus what was allocated
1885 // and then converted into units of block headers.
1887 BlockSize
= (PAGE_SIZE
/ POOL_BLOCK_SIZE
) - i
;
1888 FragmentEntry
= POOL_BLOCK(Entry
, i
);
1889 FragmentEntry
->Ulong1
= 0;
1890 FragmentEntry
->BlockSize
= BlockSize
;
1891 FragmentEntry
->PreviousSize
= i
;
1894 // Increment required counters
1896 InterlockedIncrement((PLONG
)&PoolDesc
->TotalPages
);
1897 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, Entry
->BlockSize
* POOL_BLOCK_SIZE
);
1900 // Now check if enough free bytes remained for us to have a "full" entry,
1901 // which contains enough bytes for a linked list and thus can be used for
1902 // allocations (up to 8 bytes...)
1904 if (FragmentEntry
->BlockSize
!= 1)
1907 // Excellent -- acquire the pool lock
1909 OldIrql
= ExLockPool(PoolDesc
);
1912 // And insert the free entry into the free list for this block size
1914 ExpCheckPoolLinks(&PoolDesc
->ListHeads
[BlockSize
- 1]);
1915 ExpInsertPoolTailList(&PoolDesc
->ListHeads
[BlockSize
- 1],
1916 POOL_FREE_BLOCK(FragmentEntry
));
1917 ExpCheckPoolLinks(POOL_FREE_BLOCK(FragmentEntry
));
1920 // Release the pool lock
1922 ExpCheckPoolBlocks(Entry
);
1923 ExUnlockPool(PoolDesc
, OldIrql
);
1928 // Simply do a sanity check
1930 ExpCheckPoolBlocks(Entry
);
1934 // Increment performance counters and track this allocation
1936 InterlockedIncrement((PLONG
)&PoolDesc
->RunningAllocs
);
1937 ExpInsertPoolTracker(Tag
,
1938 Entry
->BlockSize
* POOL_BLOCK_SIZE
,
1942 // And return the pool allocation
1944 ExpCheckPoolBlocks(Entry
);
1945 Entry
->PoolTag
= Tag
;
1946 return POOL_FREE_BLOCK(Entry
);
1954 ExAllocatePool(POOL_TYPE PoolType
,
1955 SIZE_T NumberOfBytes
)
1958 // Use a default tag of "None"
1960 return ExAllocatePoolWithTag(PoolType
, NumberOfBytes
, TAG_NONE
);
1968 ExFreePoolWithTag(IN PVOID P
,
1971 PPOOL_HEADER Entry
, NextEntry
;
1975 PPOOL_DESCRIPTOR PoolDesc
;
1977 BOOLEAN Combined
= FALSE
;
1978 PFN_NUMBER PageCount
, RealPageCount
;
1979 PKPRCB Prcb
= KeGetCurrentPrcb();
1980 PGENERAL_LOOKASIDE LookasideList
;
1983 // Check if any of the debug flags are enabled
1985 if (ExpPoolFlags
& (POOL_FLAG_CHECK_TIMERS
|
1986 POOL_FLAG_CHECK_WORKERS
|
1987 POOL_FLAG_CHECK_RESOURCES
|
1988 POOL_FLAG_VERIFIER
|
1989 POOL_FLAG_CHECK_DEADLOCK
|
1990 POOL_FLAG_SPECIAL_POOL
))
1993 // Check if special pool is enabled
1995 if (ExpPoolFlags
& POOL_FLAG_SPECIAL_POOL
)
1998 // Check if it was allocated from a special pool
2000 if (MmIsSpecialPoolAddress(P
))
2003 // Was deadlock verification also enabled? We can do some extra
2004 // checks at this point
2006 if (ExpPoolFlags
& POOL_FLAG_CHECK_DEADLOCK
)
2008 DPRINT1("Verifier not yet supported\n");
2012 // It is, so handle it via special pool free routine
2014 MmFreeSpecialPool(P
);
2020 // For non-big page allocations, we'll do a bunch of checks in here
2022 if (PAGE_ALIGN(P
) != P
)
2025 // Get the entry for this pool allocation
2026 // The pointer math here may look wrong or confusing, but it is quite right
2032 // Get the pool type
2034 PoolType
= (Entry
->PoolType
- 1) & BASE_POOL_TYPE_MASK
;
2037 // FIXME: Many other debugging checks go here
2039 ExpCheckPoolIrqlLevel(PoolType
, 0, P
);
2044 // Check if this is a big page allocation
2046 if (PAGE_ALIGN(P
) == P
)
2049 // We need to find the tag for it, so first we need to find out what
2050 // kind of allocation this was (paged or nonpaged), then we can go
2051 // ahead and try finding the tag for it. Remember to get rid of the
2052 // PROTECTED_POOL tag if it's found.
2054 // Note that if at insertion time, we failed to add the tag for a big
2055 // pool allocation, we used a special tag called 'BIG' to identify the
2056 // allocation, and we may get this tag back. In this scenario, we must
2057 // manually get the size of the allocation by actually counting through
2058 // the PFN database.
2060 PoolType
= MmDeterminePoolType(P
);
2061 ExpCheckPoolIrqlLevel(PoolType
, 0, P
);
2062 Tag
= ExpFindAndRemoveTagBigPages(P
, &PageCount
, PoolType
);
2065 DPRINT1("We do not know the size of this allocation. This is not yet supported\n");
2066 ASSERT(Tag
== ' GIB');
2067 PageCount
= 1; // We are going to lie! This might screw up accounting?
2069 else if (Tag
& PROTECTED_POOL
)
2071 Tag
&= ~PROTECTED_POOL
;
2075 // We have our tag and our page count, so we can go ahead and remove this
2078 ExpRemovePoolTracker(Tag
, PageCount
<< PAGE_SHIFT
, PoolType
);
2081 // Check if any of the debug flags are enabled
2083 if (ExpPoolFlags
& (POOL_FLAG_CHECK_TIMERS
|
2084 POOL_FLAG_CHECK_WORKERS
|
2085 POOL_FLAG_CHECK_RESOURCES
|
2086 POOL_FLAG_CHECK_DEADLOCK
))
2089 // Was deadlock verification also enabled? We can do some extra
2090 // checks at this point
2092 if (ExpPoolFlags
& POOL_FLAG_CHECK_DEADLOCK
)
2094 DPRINT1("Verifier not yet supported\n");
2098 // FIXME: Many debugging checks go here
2105 PoolDesc
= PoolVector
[PoolType
];
2106 InterlockedIncrement((PLONG
)&PoolDesc
->RunningDeAllocs
);
2107 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
,
2108 -(LONG_PTR
)(PageCount
<< PAGE_SHIFT
));
2111 // Do the real free now and update the last counter with the big page count
2113 RealPageCount
= MiFreePoolPages(P
);
2114 ASSERT(RealPageCount
== PageCount
);
2115 InterlockedExchangeAdd((PLONG
)&PoolDesc
->TotalBigPages
,
2116 -(LONG
)RealPageCount
);
2121 // Get the entry for this pool allocation
2122 // The pointer math here may look wrong or confusing, but it is quite right
2128 // Get the size of the entry, and it's pool type, then load the descriptor
2129 // for this pool type
2131 BlockSize
= Entry
->BlockSize
;
2132 PoolType
= (Entry
->PoolType
- 1) & BASE_POOL_TYPE_MASK
;
2133 PoolDesc
= PoolVector
[PoolType
];
2136 // Make sure that the IRQL makes sense
2138 ExpCheckPoolIrqlLevel(PoolType
, 0, P
);
2141 // Get the pool tag and get rid of the PROTECTED_POOL flag
2143 Tag
= Entry
->PoolTag
;
2144 if (Tag
& PROTECTED_POOL
) Tag
&= ~PROTECTED_POOL
;
2147 // Stop tracking this allocation
2149 ExpRemovePoolTracker(Tag
,
2150 BlockSize
* POOL_BLOCK_SIZE
,
2151 Entry
->PoolType
- 1);
2156 if (TagToFree
&& TagToFree
!= Tag
)
2158 DPRINT1("Freeing pool - invalid tag specified: %.4s != %.4s\n", (char*)&TagToFree
, (char*)&Tag
);
2159 KeBugCheckEx(BAD_POOL_CALLER
, 0x0A, (ULONG_PTR
)P
, Tag
, TagToFree
);
2163 // Is this allocation small enough to have come from a lookaside list?
2165 if (BlockSize
<= MAXIMUM_PROCESSORS
)
2168 // Try pushing it into the per-CPU lookaside list
2170 LookasideList
= (PoolType
== PagedPool
) ?
2171 Prcb
->PPPagedLookasideList
[BlockSize
- 1].P
:
2172 Prcb
->PPNPagedLookasideList
[BlockSize
- 1].P
;
2173 LookasideList
->TotalFrees
++;
2174 if (ExQueryDepthSList(&LookasideList
->ListHead
) < LookasideList
->Depth
)
2176 LookasideList
->FreeHits
++;
2177 InterlockedPushEntrySList(&LookasideList
->ListHead
, P
);
2182 // We failed, try to push it into the global lookaside list
2184 LookasideList
= (PoolType
== PagedPool
) ?
2185 Prcb
->PPPagedLookasideList
[BlockSize
- 1].L
:
2186 Prcb
->PPNPagedLookasideList
[BlockSize
- 1].L
;
2187 LookasideList
->TotalFrees
++;
2188 if (ExQueryDepthSList(&LookasideList
->ListHead
) < LookasideList
->Depth
)
2190 LookasideList
->FreeHits
++;
2191 InterlockedPushEntrySList(&LookasideList
->ListHead
, P
);
2197 // Get the pointer to the next entry
2199 NextEntry
= POOL_BLOCK(Entry
, BlockSize
);
2202 // Update performance counters
2204 InterlockedIncrement((PLONG
)&PoolDesc
->RunningDeAllocs
);
2205 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, -BlockSize
* POOL_BLOCK_SIZE
);
2208 // Acquire the pool lock
2210 OldIrql
= ExLockPool(PoolDesc
);
2213 // Check if the next allocation is at the end of the page
2215 ExpCheckPoolBlocks(Entry
);
2216 if (PAGE_ALIGN(NextEntry
) != NextEntry
)
2219 // We may be able to combine the block if it's free
2221 if (NextEntry
->PoolType
== 0)
2224 // The next block is free, so we'll do a combine
2229 // Make sure there's actual data in the block -- anything smaller
2230 // than this means we only have the header, so there's no linked list
2233 if ((NextEntry
->BlockSize
!= 1))
2236 // The block is at least big enough to have a linked list, so go
2237 // ahead and remove it
2239 ExpCheckPoolLinks(POOL_FREE_BLOCK(NextEntry
));
2240 ExpRemovePoolEntryList(POOL_FREE_BLOCK(NextEntry
));
2241 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Flink
));
2242 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Blink
));
2246 // Our entry is now combined with the next entry
2248 Entry
->BlockSize
= Entry
->BlockSize
+ NextEntry
->BlockSize
;
2253 // Now check if there was a previous entry on the same page as us
2255 if (Entry
->PreviousSize
)
2258 // Great, grab that entry and check if it's free
2260 NextEntry
= POOL_PREV_BLOCK(Entry
);
2261 if (NextEntry
->PoolType
== 0)
2264 // It is, so we can do a combine
2269 // Make sure there's actual data in the block -- anything smaller
2270 // than this means we only have the header so there's no linked list
2273 if ((NextEntry
->BlockSize
!= 1))
2276 // The block is at least big enough to have a linked list, so go
2277 // ahead and remove it
2279 ExpCheckPoolLinks(POOL_FREE_BLOCK(NextEntry
));
2280 ExpRemovePoolEntryList(POOL_FREE_BLOCK(NextEntry
));
2281 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Flink
));
2282 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Blink
));
2286 // Combine our original block (which might've already been combined
2287 // with the next block), into the previous block
2289 NextEntry
->BlockSize
= NextEntry
->BlockSize
+ Entry
->BlockSize
;
2292 // And now we'll work with the previous block instead
2299 // By now, it may have been possible for our combined blocks to actually
2300 // have made up a full page (if there were only 2-3 allocations on the
2301 // page, they could've all been combined).
2303 if ((PAGE_ALIGN(Entry
) == Entry
) &&
2304 (PAGE_ALIGN(POOL_NEXT_BLOCK(Entry
)) == POOL_NEXT_BLOCK(Entry
)))
2307 // In this case, release the pool lock, update the performance counter,
2308 // and free the page
2310 ExUnlockPool(PoolDesc
, OldIrql
);
2311 InterlockedExchangeAdd((PLONG
)&PoolDesc
->TotalPages
, -1);
2312 MiFreePoolPages(Entry
);
2317 // Otherwise, we now have a free block (or a combination of 2 or 3)
2319 Entry
->PoolType
= 0;
2320 BlockSize
= Entry
->BlockSize
;
2321 ASSERT(BlockSize
!= 1);
2324 // Check if we actually did combine it with anyone
2329 // Get the first combined block (either our original to begin with, or
2330 // the one after the original, depending if we combined with the previous)
2332 NextEntry
= POOL_NEXT_BLOCK(Entry
);
2335 // As long as the next block isn't on a page boundary, have it point
2338 if (PAGE_ALIGN(NextEntry
) != NextEntry
) NextEntry
->PreviousSize
= BlockSize
;
2342 // Insert this new free block, and release the pool lock
2344 ExpInsertPoolHeadList(&PoolDesc
->ListHeads
[BlockSize
- 1], POOL_FREE_BLOCK(Entry
));
2345 ExpCheckPoolLinks(POOL_FREE_BLOCK(Entry
));
2346 ExUnlockPool(PoolDesc
, OldIrql
);
2357 // Just free without checking for the tag
2359 ExFreePoolWithTag(P
, 0);
2367 ExQueryPoolBlockSize(IN PVOID PoolBlock
,
2368 OUT PBOOLEAN QuotaCharged
)
2383 ExAllocatePoolWithQuota(IN POOL_TYPE PoolType
,
2384 IN SIZE_T NumberOfBytes
)
2387 // Allocate the pool
2389 return ExAllocatePoolWithQuotaTag(PoolType
, NumberOfBytes
, 'enoN');
2397 ExAllocatePoolWithTagPriority(IN POOL_TYPE PoolType
,
2398 IN SIZE_T NumberOfBytes
,
2400 IN EX_POOL_PRIORITY Priority
)
2403 // Allocate the pool
2406 return ExAllocatePoolWithTag(PoolType
, NumberOfBytes
, Tag
);
2414 ExAllocatePoolWithQuotaTag(IN POOL_TYPE PoolType
,
2415 IN SIZE_T NumberOfBytes
,
2419 // Allocate the pool
2422 return ExAllocatePoolWithTag(PoolType
, NumberOfBytes
, Tag
);