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 <mm/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 ULONG 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 ExpCheckPoolAllocation(
294 POOL_TYPE RealPoolType
;
296 /* Get the pool header */
297 Entry
= ((PPOOL_HEADER
)P
) - 1;
299 /* Check if this is a large allocation */
300 if (PAGE_ALIGN(P
) == P
)
302 /* Lock the pool table */
303 KeAcquireSpinLock(&ExpLargePoolTableLock
, &OldIrql
);
305 /* Find the pool tag */
306 for (i
= 0; i
< PoolBigPageTableSize
; i
++)
308 /* Check if this is our allocation */
309 if (PoolBigPageTable
[i
].Va
== P
)
311 /* Make sure the tag is ok */
312 if (PoolBigPageTable
[i
].Key
!= Tag
)
314 KeBugCheckEx(BAD_POOL_CALLER
, 0x0A, (ULONG_PTR
)P
, PoolBigPageTable
[i
].Key
, Tag
);
321 /* Release the lock */
322 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
324 if (i
== PoolBigPageTableSize
)
326 /* Did not find the allocation */
330 /* Get Pool type by address */
331 RealPoolType
= MmDeterminePoolType(P
);
336 if (Entry
->PoolTag
!= Tag
)
338 DPRINT1("Allocation has wrong pool tag! Expected '%.4s', got '%.4s' (0x%08lx)\n",
339 &Tag
, &Entry
->PoolTag
, Entry
->PoolTag
);
340 KeBugCheckEx(BAD_POOL_CALLER
, 0x0A, (ULONG_PTR
)P
, Entry
->PoolTag
, Tag
);
343 /* Check the rest of the header */
344 ExpCheckPoolHeader(Entry
);
346 /* Get Pool type from entry */
347 RealPoolType
= (Entry
->PoolType
- 1);
350 /* Should we check the pool type? */
353 /* Verify the pool type */
354 if (RealPoolType
!= PoolType
)
356 DPRINT1("Wrong pool type! Expected %s, got %s\n",
357 PoolType
& BASE_POOL_TYPE_MASK
? "PagedPool" : "NonPagedPool",
358 (Entry
->PoolType
- 1) & BASE_POOL_TYPE_MASK
? "PagedPool" : "NonPagedPool");
359 KeBugCheckEx(BAD_POOL_CALLER
, 0xCC, (ULONG_PTR
)P
, Entry
->PoolTag
, Tag
);
366 ExpCheckPoolBlocks(IN PVOID Block
)
368 BOOLEAN FoundBlock
= FALSE
;
372 /* Get the first entry for this page, make sure it really is the first */
373 Entry
= PAGE_ALIGN(Block
);
374 ASSERT(Entry
->PreviousSize
== 0);
376 /* Now scan each entry */
379 /* When we actually found our block, remember this */
380 if (Entry
== Block
) FoundBlock
= TRUE
;
382 /* Now validate this block header */
383 ExpCheckPoolHeader(Entry
);
385 /* And go to the next one, keeping track of our size */
386 Size
+= Entry
->BlockSize
;
387 Entry
= POOL_NEXT_BLOCK(Entry
);
389 /* If we hit the last block, stop */
390 if (Size
>= (PAGE_SIZE
/ POOL_BLOCK_SIZE
)) break;
392 /* If we hit the end of the page, stop */
393 if (PAGE_ALIGN(Entry
) == Entry
) break;
396 /* We must've found our block, and we must have hit the end of the page */
397 if ((PAGE_ALIGN(Entry
) != Entry
) || !(FoundBlock
))
399 /* Otherwise, the blocks are messed up */
400 KeBugCheckEx(BAD_POOL_HEADER
, 10, (ULONG_PTR
)Block
, __LINE__
, (ULONG_PTR
)Entry
);
406 ExpCheckPoolIrqlLevel(IN POOL_TYPE PoolType
,
407 IN SIZE_T NumberOfBytes
,
411 // Validate IRQL: It must be APC_LEVEL or lower for Paged Pool, and it must
412 // be DISPATCH_LEVEL or lower for Non Paged Pool
414 if (((PoolType
& BASE_POOL_TYPE_MASK
) == PagedPool
) ?
415 (KeGetCurrentIrql() > APC_LEVEL
) :
416 (KeGetCurrentIrql() > DISPATCH_LEVEL
))
419 // Take the system down
421 KeBugCheckEx(BAD_POOL_CALLER
,
422 !Entry
? POOL_ALLOC_IRQL_INVALID
: POOL_FREE_IRQL_INVALID
,
425 !Entry
? NumberOfBytes
: (ULONG_PTR
)Entry
);
431 ExpComputeHashForTag(IN ULONG Tag
,
432 IN SIZE_T BucketMask
)
435 // Compute the hash by multiplying with a large prime number and then XORing
436 // with the HIDWORD of the result.
438 // Finally, AND with the bucket mask to generate a valid index/bucket into
441 ULONGLONG Result
= (ULONGLONG
)40543 * Tag
;
442 return (ULONG
)BucketMask
& ((ULONG
)Result
^ (Result
>> 32));
447 ExpComputePartialHashForAddress(IN PVOID BaseAddress
)
451 // Compute the hash by converting the address into a page number, and then
452 // XORing each nibble with the next one.
454 // We do *NOT* AND with the bucket mask at this point because big table expansion
455 // might happen. Therefore, the final step of the hash must be performed
456 // while holding the expansion pushlock, and this is why we call this a
457 // "partial" hash only.
459 Result
= (ULONG
)((ULONG_PTR
)BaseAddress
>> PAGE_SHIFT
);
460 return (Result
>> 24) ^ (Result
>> 16) ^ (Result
>> 8) ^ Result
;
465 ExpTagAllowPrint(CHAR Tag
)
467 if ((Tag
>= 'a' && Tag
<= 'z') ||
468 (Tag
>= 'A' && Tag
<= 'Z') ||
478 MiDumpNonPagedPoolConsumers(VOID
)
482 DPRINT1("---------------------\n");
483 DPRINT1("Out of memory dumper!\n");
486 // We'll extract allocations for all the tracked pools
488 for (i
= 0; i
< PoolTrackTableSize
; ++i
)
490 PPOOL_TRACKER_TABLE TableEntry
;
492 TableEntry
= &PoolTrackTable
[i
];
495 // We only care about non paged
497 if (TableEntry
->NonPagedBytes
!= 0)
500 // If there's a tag, attempt to do a pretty print
502 if (TableEntry
->Key
!= 0 && TableEntry
->Key
!= TAG_NONE
)
507 // Extract each 'component' and check whether they are printable
509 Tag
[0] = TableEntry
->Key
& 0xFF;
510 Tag
[1] = TableEntry
->Key
>> 8 & 0xFF;
511 Tag
[2] = TableEntry
->Key
>> 16 & 0xFF;
512 Tag
[3] = TableEntry
->Key
>> 24 & 0xFF;
514 if (ExpTagAllowPrint(Tag
[0]) && ExpTagAllowPrint(Tag
[1]) && ExpTagAllowPrint(Tag
[2]) && ExpTagAllowPrint(Tag
[3]))
517 // Print in reversed order to match what is in source code
519 DPRINT1("Tag: '%c%c%c%c', Size: %ld\n", Tag
[3], Tag
[2], Tag
[1], Tag
[0], TableEntry
->NonPagedBytes
);
523 DPRINT1("Tag: %x, Size: %ld\n", TableEntry
->Key
, TableEntry
->NonPagedBytes
);
528 DPRINT1("Anon, Size: %ld\n", TableEntry
->NonPagedBytes
);
533 DPRINT1("---------------------\n");
536 /* PRIVATE FUNCTIONS **********************************************************/
543 ULONG i
, Key
, Hash
, Index
;
544 PPOOL_TRACKER_TABLE TrackTable
= PoolTrackTable
;
614 // Loop all 64 hot tags
616 ASSERT((sizeof(TagList
) / sizeof(ULONG
)) == 64);
617 for (i
= 0; i
< sizeof(TagList
) / sizeof(ULONG
); i
++)
620 // Get the current tag, and compute its hash in the tracker table
623 Hash
= ExpComputeHashForTag(Key
, PoolTrackTableMask
);
626 // Loop all the hashes in this index/bucket
632 // Find an empty entry, and make sure this isn't the last hash that
635 // On checked builds, also make sure this is the first time we are
638 ASSERT(TrackTable
[Hash
].Key
!= Key
);
639 if (!(TrackTable
[Hash
].Key
) && (Hash
!= PoolTrackTableSize
- 1))
642 // It has been seeded, move on to the next tag
644 TrackTable
[Hash
].Key
= Key
;
649 // This entry was already taken, compute the next possible hash while
650 // making sure we're not back at our initial index.
652 ASSERT(TrackTable
[Hash
].Key
!= Key
);
653 Hash
= (Hash
+ 1) & PoolTrackTableMask
;
654 if (Hash
== Index
) break;
661 ExpRemovePoolTracker(IN ULONG Key
,
662 IN SIZE_T NumberOfBytes
,
663 IN POOL_TYPE PoolType
)
666 PPOOL_TRACKER_TABLE Table
, TableEntry
;
667 SIZE_T TableMask
, TableSize
;
670 // Remove the PROTECTED_POOL flag which is not part of the tag
672 Key
&= ~PROTECTED_POOL
;
675 // With WinDBG you can set a tag you want to break on when an allocation is
678 if (Key
== PoolHitTag
) DbgBreakPoint();
681 // Why the double indirection? Because normally this function is also used
682 // when doing session pool allocations, which has another set of tables,
683 // sizes, and masks that live in session pool. Now we don't support session
684 // pool so we only ever use the regular tables, but I'm keeping the code this
685 // way so that the day we DO support session pool, it won't require that
688 Table
= PoolTrackTable
;
689 TableMask
= PoolTrackTableMask
;
690 TableSize
= PoolTrackTableSize
;
691 DBG_UNREFERENCED_LOCAL_VARIABLE(TableSize
);
694 // Compute the hash for this key, and loop all the possible buckets
696 Hash
= ExpComputeHashForTag(Key
, TableMask
);
701 // Have we found the entry for this tag? */
703 TableEntry
= &Table
[Hash
];
704 if (TableEntry
->Key
== Key
)
707 // Decrement the counters depending on if this was paged or nonpaged
710 if ((PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
712 InterlockedIncrement(&TableEntry
->NonPagedFrees
);
713 InterlockedExchangeAddSizeT(&TableEntry
->NonPagedBytes
,
714 -(SSIZE_T
)NumberOfBytes
);
717 InterlockedIncrement(&TableEntry
->PagedFrees
);
718 InterlockedExchangeAddSizeT(&TableEntry
->PagedBytes
,
719 -(SSIZE_T
)NumberOfBytes
);
724 // We should have only ended up with an empty entry if we've reached
727 if (!TableEntry
->Key
)
729 DPRINT1("Empty item reached in tracker table. Hash=0x%lx, TableMask=0x%lx, Tag=0x%08lx, NumberOfBytes=%lu, PoolType=%d\n",
730 Hash
, TableMask
, Key
, (ULONG
)NumberOfBytes
, PoolType
);
731 ASSERT(Hash
== TableMask
);
735 // This path is hit when we don't have an entry, and the current bucket
736 // is full, so we simply try the next one
738 Hash
= (Hash
+ 1) & TableMask
;
739 if (Hash
== Index
) break;
743 // And finally this path is hit when all the buckets are full, and we need
744 // some expansion. This path is not yet supported in ReactOS and so we'll
747 DPRINT1("Out of pool tag space, ignoring...\n");
752 ExpInsertPoolTracker(IN ULONG Key
,
753 IN SIZE_T NumberOfBytes
,
754 IN POOL_TYPE PoolType
)
758 PPOOL_TRACKER_TABLE Table
, TableEntry
;
759 SIZE_T TableMask
, TableSize
;
762 // Remove the PROTECTED_POOL flag which is not part of the tag
764 Key
&= ~PROTECTED_POOL
;
767 // With WinDBG you can set a tag you want to break on when an allocation is
770 if (Key
== PoolHitTag
) DbgBreakPoint();
773 // There is also an internal flag you can set to break on malformed tags
775 if (ExStopBadTags
) ASSERT(Key
& 0xFFFFFF00);
778 // ASSERT on ReactOS features not yet supported
780 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
781 ASSERT(KeGetCurrentProcessorNumber() == 0);
784 // Why the double indirection? Because normally this function is also used
785 // when doing session pool allocations, which has another set of tables,
786 // sizes, and masks that live in session pool. Now we don't support session
787 // pool so we only ever use the regular tables, but I'm keeping the code this
788 // way so that the day we DO support session pool, it won't require that
791 Table
= PoolTrackTable
;
792 TableMask
= PoolTrackTableMask
;
793 TableSize
= PoolTrackTableSize
;
794 DBG_UNREFERENCED_LOCAL_VARIABLE(TableSize
);
797 // Compute the hash for this key, and loop all the possible buckets
799 Hash
= ExpComputeHashForTag(Key
, TableMask
);
804 // Do we already have an entry for this tag? */
806 TableEntry
= &Table
[Hash
];
807 if (TableEntry
->Key
== Key
)
810 // Increment the counters depending on if this was paged or nonpaged
813 if ((PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
815 InterlockedIncrement(&TableEntry
->NonPagedAllocs
);
816 InterlockedExchangeAddSizeT(&TableEntry
->NonPagedBytes
, NumberOfBytes
);
819 InterlockedIncrement(&TableEntry
->PagedAllocs
);
820 InterlockedExchangeAddSizeT(&TableEntry
->PagedBytes
, NumberOfBytes
);
825 // We don't have an entry yet, but we've found a free bucket for it
827 if (!(TableEntry
->Key
) && (Hash
!= PoolTrackTableSize
- 1))
830 // We need to hold the lock while creating a new entry, since other
831 // processors might be in this code path as well
833 ExAcquireSpinLock(&ExpTaggedPoolLock
, &OldIrql
);
834 if (!PoolTrackTable
[Hash
].Key
)
837 // We've won the race, so now create this entry in the bucket
839 ASSERT(Table
[Hash
].Key
== 0);
840 PoolTrackTable
[Hash
].Key
= Key
;
841 TableEntry
->Key
= Key
;
843 ExReleaseSpinLock(&ExpTaggedPoolLock
, OldIrql
);
846 // Now we force the loop to run again, and we should now end up in
847 // the code path above which does the interlocked increments...
853 // This path is hit when we don't have an entry, and the current bucket
854 // is full, so we simply try the next one
856 Hash
= (Hash
+ 1) & TableMask
;
857 if (Hash
== Index
) break;
861 // And finally this path is hit when all the buckets are full, and we need
862 // some expansion. This path is not yet supported in ReactOS and so we'll
865 DPRINT1("Out of pool tag space, ignoring...\n");
871 ExInitializePoolDescriptor(IN PPOOL_DESCRIPTOR PoolDescriptor
,
872 IN POOL_TYPE PoolType
,
877 PLIST_ENTRY NextEntry
, LastEntry
;
880 // Setup the descriptor based on the caller's request
882 PoolDescriptor
->PoolType
= PoolType
;
883 PoolDescriptor
->PoolIndex
= PoolIndex
;
884 PoolDescriptor
->Threshold
= Threshold
;
885 PoolDescriptor
->LockAddress
= PoolLock
;
888 // Initialize accounting data
890 PoolDescriptor
->RunningAllocs
= 0;
891 PoolDescriptor
->RunningDeAllocs
= 0;
892 PoolDescriptor
->TotalPages
= 0;
893 PoolDescriptor
->TotalBytes
= 0;
894 PoolDescriptor
->TotalBigPages
= 0;
897 // Nothing pending for now
899 PoolDescriptor
->PendingFrees
= NULL
;
900 PoolDescriptor
->PendingFreeDepth
= 0;
903 // Loop all the descriptor's allocation lists and initialize them
905 NextEntry
= PoolDescriptor
->ListHeads
;
906 LastEntry
= NextEntry
+ POOL_LISTS_PER_PAGE
;
907 while (NextEntry
< LastEntry
)
909 ExpInitializePoolListHead(NextEntry
);
914 // Note that ReactOS does not support Session Pool Yet
916 ASSERT(PoolType
!= PagedPoolSession
);
922 InitializePool(IN POOL_TYPE PoolType
,
925 PPOOL_DESCRIPTOR Descriptor
;
930 // Check what kind of pool this is
932 if (PoolType
== NonPagedPool
)
935 // Compute the track table size and convert it from a power of two to an
938 // NOTE: On checked builds, we'll assert if the registry table size was
939 // invalid, while on retail builds we'll just break out of the loop at
942 TableSize
= min(PoolTrackTableSize
, MmSizeOfNonPagedPoolInBytes
>> 8);
943 for (i
= 0; i
< 32; i
++)
947 ASSERT((TableSize
& ~1) == 0);
948 if (!(TableSize
& ~1)) break;
954 // If we hit bit 32, than no size was defined in the registry, so
955 // we'll use the default size of 2048 entries.
957 // Otherwise, use the size from the registry, as long as it's not
958 // smaller than 64 entries.
962 PoolTrackTableSize
= 2048;
966 PoolTrackTableSize
= max(1 << i
, 64);
970 // Loop trying with the biggest specified size first, and cut it down
971 // by a power of two each iteration in case not enough memory exist
976 // Do not allow overflow
978 if ((PoolTrackTableSize
+ 1) > (MAXULONG_PTR
/ sizeof(POOL_TRACKER_TABLE
)))
980 PoolTrackTableSize
>>= 1;
985 // Allocate the tracker table and exit the loop if this worked
987 PoolTrackTable
= MiAllocatePoolPages(NonPagedPool
,
988 (PoolTrackTableSize
+ 1) *
989 sizeof(POOL_TRACKER_TABLE
));
990 if (PoolTrackTable
) break;
993 // Otherwise, as long as we're not down to the last bit, keep
996 if (PoolTrackTableSize
== 1)
998 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
1004 PoolTrackTableSize
>>= 1;
1008 // Add one entry, compute the hash, and zero the table
1010 PoolTrackTableSize
++;
1011 PoolTrackTableMask
= PoolTrackTableSize
- 2;
1013 RtlZeroMemory(PoolTrackTable
,
1014 PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
));
1017 // Finally, add the most used tags to speed up those allocations
1022 // We now do the exact same thing with the tracker table for big pages
1024 TableSize
= min(PoolBigPageTableSize
, MmSizeOfNonPagedPoolInBytes
>> 8);
1025 for (i
= 0; i
< 32; i
++)
1029 ASSERT((TableSize
& ~1) == 0);
1030 if (!(TableSize
& ~1)) break;
1036 // For big pages, the default tracker table is 4096 entries, while the
1037 // minimum is still 64
1041 PoolBigPageTableSize
= 4096;
1045 PoolBigPageTableSize
= max(1 << i
, 64);
1049 // Again, run the exact same loop we ran earlier, but this time for the
1050 // big pool tracker instead
1054 if ((PoolBigPageTableSize
+ 1) > (MAXULONG_PTR
/ sizeof(POOL_TRACKER_BIG_PAGES
)))
1056 PoolBigPageTableSize
>>= 1;
1060 PoolBigPageTable
= MiAllocatePoolPages(NonPagedPool
,
1061 PoolBigPageTableSize
*
1062 sizeof(POOL_TRACKER_BIG_PAGES
));
1063 if (PoolBigPageTable
) break;
1065 if (PoolBigPageTableSize
== 1)
1067 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
1074 PoolBigPageTableSize
>>= 1;
1078 // An extra entry is not needed for for the big pool tracker, so just
1079 // compute the hash and zero it
1081 PoolBigPageTableHash
= PoolBigPageTableSize
- 1;
1082 RtlZeroMemory(PoolBigPageTable
,
1083 PoolBigPageTableSize
* sizeof(POOL_TRACKER_BIG_PAGES
));
1084 for (i
= 0; i
< PoolBigPageTableSize
; i
++) PoolBigPageTable
[i
].Va
= (PVOID
)1;
1087 // During development, print this out so we can see what's happening
1089 DPRINT("EXPOOL: Pool Tracker Table at: 0x%p with 0x%lx bytes\n",
1090 PoolTrackTable
, PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
));
1091 DPRINT("EXPOOL: Big Pool Tracker Table at: 0x%p with 0x%lx bytes\n",
1092 PoolBigPageTable
, PoolBigPageTableSize
* sizeof(POOL_TRACKER_BIG_PAGES
));
1095 // Insert the generic tracker for all of big pool
1097 ExpInsertPoolTracker('looP',
1098 ROUND_TO_PAGES(PoolBigPageTableSize
*
1099 sizeof(POOL_TRACKER_BIG_PAGES
)),
1103 // No support for NUMA systems at this time
1105 ASSERT(KeNumberNodes
== 1);
1108 // Initialize the tag spinlock
1110 KeInitializeSpinLock(&ExpTaggedPoolLock
);
1113 // Initialize the nonpaged pool descriptor
1115 PoolVector
[NonPagedPool
] = &NonPagedPoolDescriptor
;
1116 ExInitializePoolDescriptor(PoolVector
[NonPagedPool
],
1125 // No support for NUMA systems at this time
1127 ASSERT(KeNumberNodes
== 1);
1130 // Allocate the pool descriptor
1132 Descriptor
= ExAllocatePoolWithTag(NonPagedPool
,
1133 sizeof(KGUARDED_MUTEX
) +
1134 sizeof(POOL_DESCRIPTOR
),
1139 // This is really bad...
1141 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
1149 // Setup the vector and guarded mutex for paged pool
1151 PoolVector
[PagedPool
] = Descriptor
;
1152 ExpPagedPoolMutex
= (PKGUARDED_MUTEX
)(Descriptor
+ 1);
1153 ExpPagedPoolDescriptor
[0] = Descriptor
;
1154 KeInitializeGuardedMutex(ExpPagedPoolMutex
);
1155 ExInitializePoolDescriptor(Descriptor
,
1162 // Insert the generic tracker for all of nonpaged pool
1164 ExpInsertPoolTracker('looP',
1165 ROUND_TO_PAGES(PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
)),
1172 ExLockPool(IN PPOOL_DESCRIPTOR Descriptor
)
1175 // Check if this is nonpaged pool
1177 if ((Descriptor
->PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
1180 // Use the queued spin lock
1182 return KeAcquireQueuedSpinLock(LockQueueNonPagedPoolLock
);
1187 // Use the guarded mutex
1189 KeAcquireGuardedMutex(Descriptor
->LockAddress
);
1196 ExUnlockPool(IN PPOOL_DESCRIPTOR Descriptor
,
1200 // Check if this is nonpaged pool
1202 if ((Descriptor
->PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
1205 // Use the queued spin lock
1207 KeReleaseQueuedSpinLock(LockQueueNonPagedPoolLock
, OldIrql
);
1212 // Use the guarded mutex
1214 KeReleaseGuardedMutex(Descriptor
->LockAddress
);
1220 ExpGetPoolTagInfoTarget(IN PKDPC Dpc
,
1221 IN PVOID DeferredContext
,
1222 IN PVOID SystemArgument1
,
1223 IN PVOID SystemArgument2
)
1225 PPOOL_DPC_CONTEXT Context
= DeferredContext
;
1226 UNREFERENCED_PARAMETER(Dpc
);
1227 ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL
);
1230 // Make sure we win the race, and if we did, copy the data atomically
1232 if (KeSignalCallDpcSynchronize(SystemArgument2
))
1234 RtlCopyMemory(Context
->PoolTrackTable
,
1236 Context
->PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
));
1239 // This is here because ReactOS does not yet support expansion
1241 ASSERT(Context
->PoolTrackTableSizeExpansion
== 0);
1245 // Regardless of whether we won or not, we must now synchronize and then
1246 // decrement the barrier since this is one more processor that has completed
1249 KeSignalCallDpcSynchronize(SystemArgument2
);
1250 KeSignalCallDpcDone(SystemArgument1
);
1255 ExGetPoolTagInfo(IN PSYSTEM_POOLTAG_INFORMATION SystemInformation
,
1256 IN ULONG SystemInformationLength
,
1257 IN OUT PULONG ReturnLength OPTIONAL
)
1259 ULONG TableSize
, CurrentLength
;
1261 NTSTATUS Status
= STATUS_SUCCESS
;
1262 PSYSTEM_POOLTAG TagEntry
;
1263 PPOOL_TRACKER_TABLE Buffer
, TrackerEntry
;
1264 POOL_DPC_CONTEXT Context
;
1265 ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL
);
1268 // Keep track of how much data the caller's buffer must hold
1270 CurrentLength
= FIELD_OFFSET(SYSTEM_POOLTAG_INFORMATION
, TagInfo
);
1273 // Initialize the caller's buffer
1275 TagEntry
= &SystemInformation
->TagInfo
[0];
1276 SystemInformation
->Count
= 0;
1279 // Capture the number of entries, and the total size needed to make a copy
1282 EntryCount
= (ULONG
)PoolTrackTableSize
;
1283 TableSize
= EntryCount
* sizeof(POOL_TRACKER_TABLE
);
1286 // Allocate the "Generic DPC" temporary buffer
1288 Buffer
= ExAllocatePoolWithTag(NonPagedPool
, TableSize
, 'ofnI');
1289 if (!Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
1292 // Do a "Generic DPC" to atomically retrieve the tag and allocation data
1294 Context
.PoolTrackTable
= Buffer
;
1295 Context
.PoolTrackTableSize
= PoolTrackTableSize
;
1296 Context
.PoolTrackTableExpansion
= NULL
;
1297 Context
.PoolTrackTableSizeExpansion
= 0;
1298 KeGenericCallDpc(ExpGetPoolTagInfoTarget
, &Context
);
1301 // Now parse the results
1303 for (TrackerEntry
= Buffer
; TrackerEntry
< (Buffer
+ EntryCount
); TrackerEntry
++)
1306 // If the entry is empty, skip it
1308 if (!TrackerEntry
->Key
) continue;
1311 // Otherwise, add one more entry to the caller's buffer, and ensure that
1312 // enough space has been allocated in it
1314 SystemInformation
->Count
++;
1315 CurrentLength
+= sizeof(*TagEntry
);
1316 if (SystemInformationLength
< CurrentLength
)
1319 // The caller's buffer is too small, so set a failure code. The
1320 // caller will know the count, as well as how much space is needed.
1322 // We do NOT break out of the loop, because we want to keep incrementing
1323 // the Count as well as CurrentLength so that the caller can know the
1326 Status
= STATUS_INFO_LENGTH_MISMATCH
;
1331 // Small sanity check that our accounting is working correctly
1333 ASSERT(TrackerEntry
->PagedAllocs
>= TrackerEntry
->PagedFrees
);
1334 ASSERT(TrackerEntry
->NonPagedAllocs
>= TrackerEntry
->NonPagedFrees
);
1337 // Return the data into the caller's buffer
1339 TagEntry
->TagUlong
= TrackerEntry
->Key
;
1340 TagEntry
->PagedAllocs
= TrackerEntry
->PagedAllocs
;
1341 TagEntry
->PagedFrees
= TrackerEntry
->PagedFrees
;
1342 TagEntry
->PagedUsed
= TrackerEntry
->PagedBytes
;
1343 TagEntry
->NonPagedAllocs
= TrackerEntry
->NonPagedAllocs
;
1344 TagEntry
->NonPagedFrees
= TrackerEntry
->NonPagedFrees
;
1345 TagEntry
->NonPagedUsed
= TrackerEntry
->NonPagedBytes
;
1351 // Free the "Generic DPC" temporary buffer, return the buffer length and status
1353 ExFreePoolWithTag(Buffer
, 'ofnI');
1354 if (ReturnLength
) *ReturnLength
= CurrentLength
;
1360 ExpAddTagForBigPages(IN PVOID Va
,
1362 IN ULONG NumberOfPages
,
1363 IN POOL_TYPE PoolType
)
1369 PPOOL_TRACKER_BIG_PAGES Entry
, EntryEnd
, EntryStart
;
1370 ASSERT(((ULONG_PTR
)Va
& POOL_BIG_TABLE_ENTRY_FREE
) == 0);
1371 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
1374 // As the table is expandable, these values must only be read after acquiring
1375 // the lock to avoid a teared access during an expansion
1377 Hash
= ExpComputePartialHashForAddress(Va
);
1378 KeAcquireSpinLock(&ExpLargePoolTableLock
, &OldIrql
);
1379 Hash
&= PoolBigPageTableHash
;
1380 TableSize
= PoolBigPageTableSize
;
1383 // We loop from the current hash bucket to the end of the table, and then
1384 // rollover to hash bucket 0 and keep going from there. If we return back
1385 // to the beginning, then we attempt expansion at the bottom of the loop
1387 EntryStart
= Entry
= &PoolBigPageTable
[Hash
];
1388 EntryEnd
= &PoolBigPageTable
[TableSize
];
1392 // Make sure that this is a free entry and attempt to atomically make the
1396 if (((ULONG_PTR
)OldVa
& POOL_BIG_TABLE_ENTRY_FREE
) &&
1397 (InterlockedCompareExchangePointer(&Entry
->Va
, Va
, OldVa
) == OldVa
))
1400 // We now own this entry, write down the size and the pool tag
1403 Entry
->NumberOfPages
= NumberOfPages
;
1406 // Add one more entry to the count, and see if we're getting within
1407 // 25% of the table size, at which point we'll do an expansion now
1408 // to avoid blocking too hard later on.
1410 // Note that we only do this if it's also been the 16th time that we
1411 // keep losing the race or that we are not finding a free entry anymore,
1412 // which implies a massive number of concurrent big pool allocations.
1414 InterlockedIncrementUL(&ExpPoolBigEntriesInUse
);
1415 if ((i
>= 16) && (ExpPoolBigEntriesInUse
> (TableSize
/ 4)))
1417 DPRINT("Should attempt expansion since we now have %lu entries\n",
1418 ExpPoolBigEntriesInUse
);
1422 // We have our entry, return
1424 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1429 // We don't have our entry yet, so keep trying, making the entry list
1430 // circular if we reach the last entry. We'll eventually break out of
1431 // the loop once we've rolled over and returned back to our original
1435 if (++Entry
>= EntryEnd
) Entry
= &PoolBigPageTable
[0];
1436 } while (Entry
!= EntryStart
);
1439 // This means there's no free hash buckets whatsoever, so we would now have
1440 // to attempt expanding the table
1442 DPRINT1("Big pool expansion needed, not implemented!\n");
1443 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1449 ExpFindAndRemoveTagBigPages(IN PVOID Va
,
1450 OUT PULONG_PTR BigPages
,
1451 IN POOL_TYPE PoolType
)
1453 BOOLEAN FirstTry
= TRUE
;
1456 ULONG PoolTag
, Hash
;
1457 PPOOL_TRACKER_BIG_PAGES Entry
;
1458 ASSERT(((ULONG_PTR
)Va
& POOL_BIG_TABLE_ENTRY_FREE
) == 0);
1459 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
1462 // As the table is expandable, these values must only be read after acquiring
1463 // the lock to avoid a teared access during an expansion
1465 Hash
= ExpComputePartialHashForAddress(Va
);
1466 KeAcquireSpinLock(&ExpLargePoolTableLock
, &OldIrql
);
1467 Hash
&= PoolBigPageTableHash
;
1468 TableSize
= PoolBigPageTableSize
;
1471 // Loop while trying to find this big page allocation
1473 while (PoolBigPageTable
[Hash
].Va
!= Va
)
1476 // Increment the size until we go past the end of the table
1478 if (++Hash
>= TableSize
)
1481 // Is this the second time we've tried?
1486 // This means it was never inserted into the pool table and it
1487 // received the special "BIG" tag -- return that and return 0
1488 // so that the code can ask Mm for the page count instead
1490 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1496 // The first time this happens, reset the hash index and try again
1504 // Now capture all the information we need from the entry, since after we
1505 // release the lock, the data can change
1507 Entry
= &PoolBigPageTable
[Hash
];
1508 *BigPages
= Entry
->NumberOfPages
;
1509 PoolTag
= Entry
->Key
;
1512 // Set the free bit, and decrement the number of allocations. Finally, release
1513 // the lock and return the tag that was located
1515 InterlockedIncrement((PLONG
)&Entry
->Va
);
1516 InterlockedDecrementUL(&ExpPoolBigEntriesInUse
);
1517 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1523 ExQueryPoolUsage(OUT PULONG PagedPoolPages
,
1524 OUT PULONG NonPagedPoolPages
,
1525 OUT PULONG PagedPoolAllocs
,
1526 OUT PULONG PagedPoolFrees
,
1527 OUT PULONG PagedPoolLookasideHits
,
1528 OUT PULONG NonPagedPoolAllocs
,
1529 OUT PULONG NonPagedPoolFrees
,
1530 OUT PULONG NonPagedPoolLookasideHits
)
1533 PPOOL_DESCRIPTOR PoolDesc
;
1536 // Assume all failures
1538 *PagedPoolPages
= 0;
1539 *PagedPoolAllocs
= 0;
1540 *PagedPoolFrees
= 0;
1543 // Tally up the totals for all the apged pool
1545 for (i
= 0; i
< ExpNumberOfPagedPools
+ 1; i
++)
1547 PoolDesc
= ExpPagedPoolDescriptor
[i
];
1548 *PagedPoolPages
+= PoolDesc
->TotalPages
+ PoolDesc
->TotalBigPages
;
1549 *PagedPoolAllocs
+= PoolDesc
->RunningAllocs
;
1550 *PagedPoolFrees
+= PoolDesc
->RunningDeAllocs
;
1554 // The first non-paged pool has a hardcoded well-known descriptor name
1556 PoolDesc
= &NonPagedPoolDescriptor
;
1557 *NonPagedPoolPages
= PoolDesc
->TotalPages
+ PoolDesc
->TotalBigPages
;
1558 *NonPagedPoolAllocs
= PoolDesc
->RunningAllocs
;
1559 *NonPagedPoolFrees
= PoolDesc
->RunningDeAllocs
;
1562 // If the system has more than one non-paged pool, copy the other descriptor
1566 if (ExpNumberOfNonPagedPools
> 1)
1568 for (i
= 0; i
< ExpNumberOfNonPagedPools
; i
++)
1570 PoolDesc
= ExpNonPagedPoolDescriptor
[i
];
1571 *NonPagedPoolPages
+= PoolDesc
->TotalPages
+ PoolDesc
->TotalBigPages
;
1572 *NonPagedPoolAllocs
+= PoolDesc
->RunningAllocs
;
1573 *NonPagedPoolFrees
+= PoolDesc
->RunningDeAllocs
;
1579 // FIXME: Not yet supported
1581 *NonPagedPoolLookasideHits
+= 0;
1582 *PagedPoolLookasideHits
+= 0;
1587 ExReturnPoolQuota(IN PVOID P
)
1594 if ((ExpPoolFlags
& POOL_FLAG_SPECIAL_POOL
) &&
1595 (MmIsSpecialPoolAddress(P
)))
1602 ASSERT((ULONG_PTR
)Entry
% POOL_BLOCK_SIZE
== 0);
1604 PoolType
= Entry
->PoolType
- 1;
1605 BlockSize
= Entry
->BlockSize
;
1607 if (PoolType
& QUOTA_POOL_MASK
)
1609 Process
= ((PVOID
*)POOL_NEXT_BLOCK(Entry
))[-1];
1610 ASSERT(Process
!= NULL
);
1613 if (Process
->Pcb
.Header
.Type
!= ProcessObject
)
1615 DPRINT1("Object %p is not a process. Type %u, pool type 0x%x, block size %u\n",
1616 Process
, Process
->Pcb
.Header
.Type
, Entry
->PoolType
, BlockSize
);
1617 KeBugCheckEx(BAD_POOL_CALLER
,
1621 (ULONG_PTR
)Process
);
1623 ((PVOID
*)POOL_NEXT_BLOCK(Entry
))[-1] = NULL
;
1624 PsReturnPoolQuota(Process
,
1625 PoolType
& BASE_POOL_TYPE_MASK
,
1626 BlockSize
* POOL_BLOCK_SIZE
);
1627 ObDereferenceObject(Process
);
1632 /* PUBLIC FUNCTIONS ***********************************************************/
1639 ExAllocatePoolWithTag(IN POOL_TYPE PoolType
,
1640 IN SIZE_T NumberOfBytes
,
1643 PPOOL_DESCRIPTOR PoolDesc
;
1644 PLIST_ENTRY ListHead
;
1645 PPOOL_HEADER Entry
, NextEntry
, FragmentEntry
;
1647 USHORT BlockSize
, i
;
1649 PKPRCB Prcb
= KeGetCurrentPrcb();
1650 PGENERAL_LOOKASIDE LookasideList
;
1653 // Some sanity checks
1656 ASSERT(Tag
!= ' GIB');
1657 ASSERT(NumberOfBytes
!= 0);
1658 ExpCheckPoolIrqlLevel(PoolType
, NumberOfBytes
, NULL
);
1661 // Not supported in ReactOS
1663 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
1666 // Check if verifier or special pool is enabled
1668 if (ExpPoolFlags
& (POOL_FLAG_VERIFIER
| POOL_FLAG_SPECIAL_POOL
))
1671 // For verifier, we should call the verification routine
1673 if (ExpPoolFlags
& POOL_FLAG_VERIFIER
)
1675 DPRINT1("Driver Verifier is not yet supported\n");
1679 // For special pool, we check if this is a suitable allocation and do
1680 // the special allocation if needed
1682 if (ExpPoolFlags
& POOL_FLAG_SPECIAL_POOL
)
1685 // Check if this is a special pool allocation
1687 if (MmUseSpecialPool(NumberOfBytes
, Tag
))
1690 // Try to allocate using special pool
1692 Entry
= MmAllocateSpecialPool(NumberOfBytes
, Tag
, PoolType
, 2);
1693 if (Entry
) return Entry
;
1699 // Get the pool type and its corresponding vector for this request
1701 OriginalType
= PoolType
;
1702 PoolType
= PoolType
& BASE_POOL_TYPE_MASK
;
1703 PoolDesc
= PoolVector
[PoolType
];
1704 ASSERT(PoolDesc
!= NULL
);
1707 // Check if this is a big page allocation
1709 if (NumberOfBytes
> POOL_MAX_ALLOC
)
1712 // Allocate pages for it
1714 Entry
= MiAllocatePoolPages(OriginalType
, NumberOfBytes
);
1718 // If non paged backed, display current consumption
1720 if ((OriginalType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
1722 MiDumpNonPagedPoolConsumers();
1726 // Must succeed pool is deprecated, but still supported. These allocation
1727 // failures must cause an immediate bugcheck
1729 if (OriginalType
& MUST_SUCCEED_POOL_MASK
)
1731 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
1733 NonPagedPoolDescriptor
.TotalPages
,
1734 NonPagedPoolDescriptor
.TotalBigPages
,
1739 // Internal debugging
1744 // This flag requests printing failures, and can also further specify
1745 // breaking on failures
1747 if (ExpPoolFlags
& POOL_FLAG_DBGPRINT_ON_FAILURE
)
1749 DPRINT1("EX: ExAllocatePool (%lu, 0x%x) returning NULL\n",
1752 if (ExpPoolFlags
& POOL_FLAG_CRASH_ON_FAILURE
) DbgBreakPoint();
1756 // Finally, this flag requests an exception, which we are more than
1759 if (OriginalType
& POOL_RAISE_IF_ALLOCATION_FAILURE
)
1761 ExRaiseStatus(STATUS_INSUFFICIENT_RESOURCES
);
1768 // Increment required counters
1770 InterlockedExchangeAdd((PLONG
)&PoolDesc
->TotalBigPages
,
1771 (LONG
)BYTES_TO_PAGES(NumberOfBytes
));
1772 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, NumberOfBytes
);
1773 InterlockedIncrement((PLONG
)&PoolDesc
->RunningAllocs
);
1776 // Add a tag for the big page allocation and switch to the generic "BIG"
1777 // tag if we failed to do so, then insert a tracker for this alloation.
1779 if (!ExpAddTagForBigPages(Entry
,
1781 (ULONG
)BYTES_TO_PAGES(NumberOfBytes
),
1786 ExpInsertPoolTracker(Tag
, ROUND_TO_PAGES(NumberOfBytes
), OriginalType
);
1791 // Should never request 0 bytes from the pool, but since so many drivers do
1792 // it, we'll just assume they want 1 byte, based on NT's similar behavior
1794 if (!NumberOfBytes
) NumberOfBytes
= 1;
1797 // A pool allocation is defined by its data, a linked list to connect it to
1798 // the free list (if necessary), and a pool header to store accounting info.
1799 // Calculate this size, then convert it into a block size (units of pool
1802 // Note that i cannot overflow (past POOL_LISTS_PER_PAGE) because any such
1803 // request would've been treated as a POOL_MAX_ALLOC earlier and resulted in
1804 // the direct allocation of pages.
1806 i
= (USHORT
)((NumberOfBytes
+ sizeof(POOL_HEADER
) + (POOL_BLOCK_SIZE
- 1))
1808 ASSERT(i
< POOL_LISTS_PER_PAGE
);
1811 // Handle lookaside list optimization for both paged and nonpaged pool
1813 if (i
<= NUMBER_POOL_LOOKASIDE_LISTS
)
1816 // Try popping it from the per-CPU lookaside list
1818 LookasideList
= (PoolType
== PagedPool
) ?
1819 Prcb
->PPPagedLookasideList
[i
- 1].P
:
1820 Prcb
->PPNPagedLookasideList
[i
- 1].P
;
1821 LookasideList
->TotalAllocates
++;
1822 Entry
= (PPOOL_HEADER
)InterlockedPopEntrySList(&LookasideList
->ListHead
);
1826 // We failed, try popping it from the global list
1828 LookasideList
= (PoolType
== PagedPool
) ?
1829 Prcb
->PPPagedLookasideList
[i
- 1].L
:
1830 Prcb
->PPNPagedLookasideList
[i
- 1].L
;
1831 LookasideList
->TotalAllocates
++;
1832 Entry
= (PPOOL_HEADER
)InterlockedPopEntrySList(&LookasideList
->ListHead
);
1836 // If we were able to pop it, update the accounting and return the block
1840 LookasideList
->AllocateHits
++;
1843 // Get the real entry, write down its pool type, and track it
1846 Entry
->PoolType
= OriginalType
+ 1;
1847 ExpInsertPoolTracker(Tag
,
1848 Entry
->BlockSize
* POOL_BLOCK_SIZE
,
1852 // Return the pool allocation
1854 Entry
->PoolTag
= Tag
;
1855 (POOL_FREE_BLOCK(Entry
))->Flink
= NULL
;
1856 (POOL_FREE_BLOCK(Entry
))->Blink
= NULL
;
1857 return POOL_FREE_BLOCK(Entry
);
1862 // Loop in the free lists looking for a block if this size. Start with the
1863 // list optimized for this kind of size lookup
1865 ListHead
= &PoolDesc
->ListHeads
[i
];
1869 // Are there any free entries available on this list?
1871 if (!ExpIsPoolListEmpty(ListHead
))
1874 // Acquire the pool lock now
1876 OldIrql
= ExLockPool(PoolDesc
);
1879 // And make sure the list still has entries
1881 if (ExpIsPoolListEmpty(ListHead
))
1884 // Someone raced us (and won) before we had a chance to acquire
1889 ExUnlockPool(PoolDesc
, OldIrql
);
1894 // Remove a free entry from the list
1895 // Note that due to the way we insert free blocks into multiple lists
1896 // there is a guarantee that any block on this list will either be
1897 // of the correct size, or perhaps larger.
1899 ExpCheckPoolLinks(ListHead
);
1900 Entry
= POOL_ENTRY(ExpRemovePoolHeadList(ListHead
));
1901 ExpCheckPoolLinks(ListHead
);
1902 ExpCheckPoolBlocks(Entry
);
1903 ASSERT(Entry
->BlockSize
>= i
);
1904 ASSERT(Entry
->PoolType
== 0);
1907 // Check if this block is larger that what we need. The block could
1908 // not possibly be smaller, due to the reason explained above (and
1909 // we would've asserted on a checked build if this was the case).
1911 if (Entry
->BlockSize
!= i
)
1914 // Is there an entry before this one?
1916 if (Entry
->PreviousSize
== 0)
1919 // There isn't anyone before us, so take the next block and
1920 // turn it into a fragment that contains the leftover data
1921 // that we don't need to satisfy the caller's request
1923 FragmentEntry
= POOL_BLOCK(Entry
, i
);
1924 FragmentEntry
->BlockSize
= Entry
->BlockSize
- i
;
1927 // And make it point back to us
1929 FragmentEntry
->PreviousSize
= i
;
1932 // Now get the block that follows the new fragment and check
1933 // if it's still on the same page as us (and not at the end)
1935 NextEntry
= POOL_NEXT_BLOCK(FragmentEntry
);
1936 if (PAGE_ALIGN(NextEntry
) != NextEntry
)
1939 // Adjust this next block to point to our newly created
1942 NextEntry
->PreviousSize
= FragmentEntry
->BlockSize
;
1948 // There is a free entry before us, which we know is smaller
1949 // so we'll make this entry the fragment instead
1951 FragmentEntry
= Entry
;
1954 // And then we'll remove from it the actual size required.
1955 // Now the entry is a leftover free fragment
1957 Entry
->BlockSize
-= i
;
1960 // Now let's go to the next entry after the fragment (which
1961 // used to point to our original free entry) and make it
1962 // reference the new fragment entry instead.
1964 // This is the entry that will actually end up holding the
1967 Entry
= POOL_NEXT_BLOCK(Entry
);
1968 Entry
->PreviousSize
= FragmentEntry
->BlockSize
;
1971 // And now let's go to the entry after that one and check if
1972 // it's still on the same page, and not at the end
1974 NextEntry
= POOL_BLOCK(Entry
, i
);
1975 if (PAGE_ALIGN(NextEntry
) != NextEntry
)
1978 // Make it reference the allocation entry
1980 NextEntry
->PreviousSize
= i
;
1985 // Now our (allocation) entry is the right size
1987 Entry
->BlockSize
= i
;
1990 // And the next entry is now the free fragment which contains
1991 // the remaining difference between how big the original entry
1992 // was, and the actual size the caller needs/requested.
1994 FragmentEntry
->PoolType
= 0;
1995 BlockSize
= FragmentEntry
->BlockSize
;
1998 // Now check if enough free bytes remained for us to have a
1999 // "full" entry, which contains enough bytes for a linked list
2000 // and thus can be used for allocations (up to 8 bytes...)
2002 ExpCheckPoolLinks(&PoolDesc
->ListHeads
[BlockSize
- 1]);
2006 // Insert the free entry into the free list for this size
2008 ExpInsertPoolTailList(&PoolDesc
->ListHeads
[BlockSize
- 1],
2009 POOL_FREE_BLOCK(FragmentEntry
));
2010 ExpCheckPoolLinks(POOL_FREE_BLOCK(FragmentEntry
));
2015 // We have found an entry for this allocation, so set the pool type
2016 // and release the lock since we're done
2018 Entry
->PoolType
= OriginalType
+ 1;
2019 ExpCheckPoolBlocks(Entry
);
2020 ExUnlockPool(PoolDesc
, OldIrql
);
2023 // Increment required counters
2025 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, Entry
->BlockSize
* POOL_BLOCK_SIZE
);
2026 InterlockedIncrement((PLONG
)&PoolDesc
->RunningAllocs
);
2029 // Track this allocation
2031 ExpInsertPoolTracker(Tag
,
2032 Entry
->BlockSize
* POOL_BLOCK_SIZE
,
2036 // Return the pool allocation
2038 Entry
->PoolTag
= Tag
;
2039 (POOL_FREE_BLOCK(Entry
))->Flink
= NULL
;
2040 (POOL_FREE_BLOCK(Entry
))->Blink
= NULL
;
2041 return POOL_FREE_BLOCK(Entry
);
2043 } while (++ListHead
!= &PoolDesc
->ListHeads
[POOL_LISTS_PER_PAGE
]);
2046 // There were no free entries left, so we have to allocate a new fresh page
2048 Entry
= MiAllocatePoolPages(OriginalType
, PAGE_SIZE
);
2052 // If non paged backed, display current consumption
2054 if ((OriginalType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
2056 MiDumpNonPagedPoolConsumers();
2060 // Must succeed pool is deprecated, but still supported. These allocation
2061 // failures must cause an immediate bugcheck
2063 if (OriginalType
& MUST_SUCCEED_POOL_MASK
)
2065 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
2067 NonPagedPoolDescriptor
.TotalPages
,
2068 NonPagedPoolDescriptor
.TotalBigPages
,
2073 // Internal debugging
2078 // This flag requests printing failures, and can also further specify
2079 // breaking on failures
2081 if (ExpPoolFlags
& POOL_FLAG_DBGPRINT_ON_FAILURE
)
2083 DPRINT1("EX: ExAllocatePool (%lu, 0x%x) returning NULL\n",
2086 if (ExpPoolFlags
& POOL_FLAG_CRASH_ON_FAILURE
) DbgBreakPoint();
2090 // Finally, this flag requests an exception, which we are more than
2093 if (OriginalType
& POOL_RAISE_IF_ALLOCATION_FAILURE
)
2095 ExRaiseStatus(STATUS_INSUFFICIENT_RESOURCES
);
2099 // Return NULL to the caller in all other cases
2105 // Setup the entry data
2108 Entry
->BlockSize
= i
;
2109 Entry
->PoolType
= OriginalType
+ 1;
2112 // This page will have two entries -- one for the allocation (which we just
2113 // created above), and one for the remaining free bytes, which we're about
2114 // to create now. The free bytes are the whole page minus what was allocated
2115 // and then converted into units of block headers.
2117 BlockSize
= (PAGE_SIZE
/ POOL_BLOCK_SIZE
) - i
;
2118 FragmentEntry
= POOL_BLOCK(Entry
, i
);
2119 FragmentEntry
->Ulong1
= 0;
2120 FragmentEntry
->BlockSize
= BlockSize
;
2121 FragmentEntry
->PreviousSize
= i
;
2124 // Increment required counters
2126 InterlockedIncrement((PLONG
)&PoolDesc
->TotalPages
);
2127 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, Entry
->BlockSize
* POOL_BLOCK_SIZE
);
2130 // Now check if enough free bytes remained for us to have a "full" entry,
2131 // which contains enough bytes for a linked list and thus can be used for
2132 // allocations (up to 8 bytes...)
2134 if (FragmentEntry
->BlockSize
!= 1)
2137 // Excellent -- acquire the pool lock
2139 OldIrql
= ExLockPool(PoolDesc
);
2142 // And insert the free entry into the free list for this block size
2144 ExpCheckPoolLinks(&PoolDesc
->ListHeads
[BlockSize
- 1]);
2145 ExpInsertPoolTailList(&PoolDesc
->ListHeads
[BlockSize
- 1],
2146 POOL_FREE_BLOCK(FragmentEntry
));
2147 ExpCheckPoolLinks(POOL_FREE_BLOCK(FragmentEntry
));
2150 // Release the pool lock
2152 ExpCheckPoolBlocks(Entry
);
2153 ExUnlockPool(PoolDesc
, OldIrql
);
2158 // Simply do a sanity check
2160 ExpCheckPoolBlocks(Entry
);
2164 // Increment performance counters and track this allocation
2166 InterlockedIncrement((PLONG
)&PoolDesc
->RunningAllocs
);
2167 ExpInsertPoolTracker(Tag
,
2168 Entry
->BlockSize
* POOL_BLOCK_SIZE
,
2172 // And return the pool allocation
2174 ExpCheckPoolBlocks(Entry
);
2175 Entry
->PoolTag
= Tag
;
2176 return POOL_FREE_BLOCK(Entry
);
2184 ExAllocatePool(POOL_TYPE PoolType
,
2185 SIZE_T NumberOfBytes
)
2187 ULONG Tag
= TAG_NONE
;
2189 PLDR_DATA_TABLE_ENTRY LdrEntry
;
2191 /* Use the first four letters of the driver name, or "None" if unavailable */
2192 LdrEntry
= KeGetCurrentIrql() <= APC_LEVEL
2193 ? MiLookupDataTableEntry(_ReturnAddress())
2199 for (i
= 0; i
< min(4, LdrEntry
->BaseDllName
.Length
/ sizeof(WCHAR
)); i
++)
2200 Tag
= Tag
>> 8 | (LdrEntry
->BaseDllName
.Buffer
[i
] & 0xff) << 24;
2202 Tag
= Tag
>> 8 | ' ' << 24;
2205 return ExAllocatePoolWithTag(PoolType
, NumberOfBytes
, Tag
);
2213 ExFreePoolWithTag(IN PVOID P
,
2216 PPOOL_HEADER Entry
, NextEntry
;
2220 PPOOL_DESCRIPTOR PoolDesc
;
2222 BOOLEAN Combined
= FALSE
;
2223 PFN_NUMBER PageCount
, RealPageCount
;
2224 PKPRCB Prcb
= KeGetCurrentPrcb();
2225 PGENERAL_LOOKASIDE LookasideList
;
2229 // Check if any of the debug flags are enabled
2231 if (ExpPoolFlags
& (POOL_FLAG_CHECK_TIMERS
|
2232 POOL_FLAG_CHECK_WORKERS
|
2233 POOL_FLAG_CHECK_RESOURCES
|
2234 POOL_FLAG_VERIFIER
|
2235 POOL_FLAG_CHECK_DEADLOCK
|
2236 POOL_FLAG_SPECIAL_POOL
))
2239 // Check if special pool is enabled
2241 if (ExpPoolFlags
& POOL_FLAG_SPECIAL_POOL
)
2244 // Check if it was allocated from a special pool
2246 if (MmIsSpecialPoolAddress(P
))
2249 // Was deadlock verification also enabled? We can do some extra
2250 // checks at this point
2252 if (ExpPoolFlags
& POOL_FLAG_CHECK_DEADLOCK
)
2254 DPRINT1("Verifier not yet supported\n");
2258 // It is, so handle it via special pool free routine
2260 MmFreeSpecialPool(P
);
2266 // For non-big page allocations, we'll do a bunch of checks in here
2268 if (PAGE_ALIGN(P
) != P
)
2271 // Get the entry for this pool allocation
2272 // The pointer math here may look wrong or confusing, but it is quite right
2278 // Get the pool type
2280 PoolType
= (Entry
->PoolType
- 1) & BASE_POOL_TYPE_MASK
;
2283 // FIXME: Many other debugging checks go here
2285 ExpCheckPoolIrqlLevel(PoolType
, 0, P
);
2290 // Check if this is a big page allocation
2292 if (PAGE_ALIGN(P
) == P
)
2295 // We need to find the tag for it, so first we need to find out what
2296 // kind of allocation this was (paged or nonpaged), then we can go
2297 // ahead and try finding the tag for it. Remember to get rid of the
2298 // PROTECTED_POOL tag if it's found.
2300 // Note that if at insertion time, we failed to add the tag for a big
2301 // pool allocation, we used a special tag called 'BIG' to identify the
2302 // allocation, and we may get this tag back. In this scenario, we must
2303 // manually get the size of the allocation by actually counting through
2304 // the PFN database.
2306 PoolType
= MmDeterminePoolType(P
);
2307 ExpCheckPoolIrqlLevel(PoolType
, 0, P
);
2308 Tag
= ExpFindAndRemoveTagBigPages(P
, &PageCount
, PoolType
);
2311 DPRINT1("We do not know the size of this allocation. This is not yet supported\n");
2312 ASSERT(Tag
== ' GIB');
2313 PageCount
= 1; // We are going to lie! This might screw up accounting?
2315 else if (Tag
& PROTECTED_POOL
)
2317 Tag
&= ~PROTECTED_POOL
;
2323 if (TagToFree
&& TagToFree
!= Tag
)
2325 DPRINT1("Freeing pool - invalid tag specified: %.4s != %.4s\n", (char*)&TagToFree
, (char*)&Tag
);
2326 KeBugCheckEx(BAD_POOL_CALLER
, 0x0A, (ULONG_PTR
)P
, Tag
, TagToFree
);
2330 // We have our tag and our page count, so we can go ahead and remove this
2333 ExpRemovePoolTracker(Tag
, PageCount
<< PAGE_SHIFT
, PoolType
);
2336 // Check if any of the debug flags are enabled
2338 if (ExpPoolFlags
& (POOL_FLAG_CHECK_TIMERS
|
2339 POOL_FLAG_CHECK_WORKERS
|
2340 POOL_FLAG_CHECK_RESOURCES
|
2341 POOL_FLAG_CHECK_DEADLOCK
))
2344 // Was deadlock verification also enabled? We can do some extra
2345 // checks at this point
2347 if (ExpPoolFlags
& POOL_FLAG_CHECK_DEADLOCK
)
2349 DPRINT1("Verifier not yet supported\n");
2353 // FIXME: Many debugging checks go here
2360 PoolDesc
= PoolVector
[PoolType
];
2361 InterlockedIncrement((PLONG
)&PoolDesc
->RunningDeAllocs
);
2362 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
,
2363 -(LONG_PTR
)(PageCount
<< PAGE_SHIFT
));
2366 // Do the real free now and update the last counter with the big page count
2368 RealPageCount
= MiFreePoolPages(P
);
2369 ASSERT(RealPageCount
== PageCount
);
2370 InterlockedExchangeAdd((PLONG
)&PoolDesc
->TotalBigPages
,
2371 -(LONG
)RealPageCount
);
2376 // Get the entry for this pool allocation
2377 // The pointer math here may look wrong or confusing, but it is quite right
2381 ASSERT((ULONG_PTR
)Entry
% POOL_BLOCK_SIZE
== 0);
2384 // Get the size of the entry, and it's pool type, then load the descriptor
2385 // for this pool type
2387 BlockSize
= Entry
->BlockSize
;
2388 PoolType
= (Entry
->PoolType
- 1) & BASE_POOL_TYPE_MASK
;
2389 PoolDesc
= PoolVector
[PoolType
];
2392 // Make sure that the IRQL makes sense
2394 ExpCheckPoolIrqlLevel(PoolType
, 0, P
);
2397 // Get the pool tag and get rid of the PROTECTED_POOL flag
2399 Tag
= Entry
->PoolTag
;
2400 if (Tag
& PROTECTED_POOL
) Tag
&= ~PROTECTED_POOL
;
2405 if (TagToFree
&& TagToFree
!= Tag
)
2407 DPRINT1("Freeing pool - invalid tag specified: %.4s != %.4s\n", (char*)&TagToFree
, (char*)&Tag
);
2408 KeBugCheckEx(BAD_POOL_CALLER
, 0x0A, (ULONG_PTR
)P
, Tag
, TagToFree
);
2412 // Track the removal of this allocation
2414 ExpRemovePoolTracker(Tag
,
2415 BlockSize
* POOL_BLOCK_SIZE
,
2416 Entry
->PoolType
- 1);
2419 // Release pool quota, if any
2421 if ((Entry
->PoolType
- 1) & QUOTA_POOL_MASK
)
2423 Process
= ((PVOID
*)POOL_NEXT_BLOCK(Entry
))[-1];
2426 if (Process
->Pcb
.Header
.Type
!= ProcessObject
)
2428 DPRINT1("Object %p is not a process. Type %u, pool type 0x%x, block size %u\n",
2429 Process
, Process
->Pcb
.Header
.Type
, Entry
->PoolType
, BlockSize
);
2430 KeBugCheckEx(BAD_POOL_CALLER
,
2434 (ULONG_PTR
)Process
);
2436 PsReturnPoolQuota(Process
, PoolType
, BlockSize
* POOL_BLOCK_SIZE
);
2437 ObDereferenceObject(Process
);
2442 // Is this allocation small enough to have come from a lookaside list?
2444 if (BlockSize
<= NUMBER_POOL_LOOKASIDE_LISTS
)
2447 // Try pushing it into the per-CPU lookaside list
2449 LookasideList
= (PoolType
== PagedPool
) ?
2450 Prcb
->PPPagedLookasideList
[BlockSize
- 1].P
:
2451 Prcb
->PPNPagedLookasideList
[BlockSize
- 1].P
;
2452 LookasideList
->TotalFrees
++;
2453 if (ExQueryDepthSList(&LookasideList
->ListHead
) < LookasideList
->Depth
)
2455 LookasideList
->FreeHits
++;
2456 InterlockedPushEntrySList(&LookasideList
->ListHead
, P
);
2461 // We failed, try to push it into the global lookaside list
2463 LookasideList
= (PoolType
== PagedPool
) ?
2464 Prcb
->PPPagedLookasideList
[BlockSize
- 1].L
:
2465 Prcb
->PPNPagedLookasideList
[BlockSize
- 1].L
;
2466 LookasideList
->TotalFrees
++;
2467 if (ExQueryDepthSList(&LookasideList
->ListHead
) < LookasideList
->Depth
)
2469 LookasideList
->FreeHits
++;
2470 InterlockedPushEntrySList(&LookasideList
->ListHead
, P
);
2476 // Get the pointer to the next entry
2478 NextEntry
= POOL_BLOCK(Entry
, BlockSize
);
2481 // Update performance counters
2483 InterlockedIncrement((PLONG
)&PoolDesc
->RunningDeAllocs
);
2484 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, -BlockSize
* POOL_BLOCK_SIZE
);
2487 // Acquire the pool lock
2489 OldIrql
= ExLockPool(PoolDesc
);
2492 // Check if the next allocation is at the end of the page
2494 ExpCheckPoolBlocks(Entry
);
2495 if (PAGE_ALIGN(NextEntry
) != NextEntry
)
2498 // We may be able to combine the block if it's free
2500 if (NextEntry
->PoolType
== 0)
2503 // The next block is free, so we'll do a combine
2508 // Make sure there's actual data in the block -- anything smaller
2509 // than this means we only have the header, so there's no linked list
2512 if ((NextEntry
->BlockSize
!= 1))
2515 // The block is at least big enough to have a linked list, so go
2516 // ahead and remove it
2518 ExpCheckPoolLinks(POOL_FREE_BLOCK(NextEntry
));
2519 ExpRemovePoolEntryList(POOL_FREE_BLOCK(NextEntry
));
2520 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Flink
));
2521 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Blink
));
2525 // Our entry is now combined with the next entry
2527 Entry
->BlockSize
= Entry
->BlockSize
+ NextEntry
->BlockSize
;
2532 // Now check if there was a previous entry on the same page as us
2534 if (Entry
->PreviousSize
)
2537 // Great, grab that entry and check if it's free
2539 NextEntry
= POOL_PREV_BLOCK(Entry
);
2540 if (NextEntry
->PoolType
== 0)
2543 // It is, so we can do a combine
2548 // Make sure there's actual data in the block -- anything smaller
2549 // than this means we only have the header so there's no linked list
2552 if ((NextEntry
->BlockSize
!= 1))
2555 // The block is at least big enough to have a linked list, so go
2556 // ahead and remove it
2558 ExpCheckPoolLinks(POOL_FREE_BLOCK(NextEntry
));
2559 ExpRemovePoolEntryList(POOL_FREE_BLOCK(NextEntry
));
2560 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Flink
));
2561 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Blink
));
2565 // Combine our original block (which might've already been combined
2566 // with the next block), into the previous block
2568 NextEntry
->BlockSize
= NextEntry
->BlockSize
+ Entry
->BlockSize
;
2571 // And now we'll work with the previous block instead
2578 // By now, it may have been possible for our combined blocks to actually
2579 // have made up a full page (if there were only 2-3 allocations on the
2580 // page, they could've all been combined).
2582 if ((PAGE_ALIGN(Entry
) == Entry
) &&
2583 (PAGE_ALIGN(POOL_NEXT_BLOCK(Entry
)) == POOL_NEXT_BLOCK(Entry
)))
2586 // In this case, release the pool lock, update the performance counter,
2587 // and free the page
2589 ExUnlockPool(PoolDesc
, OldIrql
);
2590 InterlockedExchangeAdd((PLONG
)&PoolDesc
->TotalPages
, -1);
2591 MiFreePoolPages(Entry
);
2596 // Otherwise, we now have a free block (or a combination of 2 or 3)
2598 Entry
->PoolType
= 0;
2599 BlockSize
= Entry
->BlockSize
;
2600 ASSERT(BlockSize
!= 1);
2603 // Check if we actually did combine it with anyone
2608 // Get the first combined block (either our original to begin with, or
2609 // the one after the original, depending if we combined with the previous)
2611 NextEntry
= POOL_NEXT_BLOCK(Entry
);
2614 // As long as the next block isn't on a page boundary, have it point
2617 if (PAGE_ALIGN(NextEntry
) != NextEntry
) NextEntry
->PreviousSize
= BlockSize
;
2621 // Insert this new free block, and release the pool lock
2623 ExpInsertPoolHeadList(&PoolDesc
->ListHeads
[BlockSize
- 1], POOL_FREE_BLOCK(Entry
));
2624 ExpCheckPoolLinks(POOL_FREE_BLOCK(Entry
));
2625 ExUnlockPool(PoolDesc
, OldIrql
);
2636 // Just free without checking for the tag
2638 ExFreePoolWithTag(P
, 0);
2646 ExQueryPoolBlockSize(IN PVOID PoolBlock
,
2647 OUT PBOOLEAN QuotaCharged
)
2662 ExAllocatePoolWithQuota(IN POOL_TYPE PoolType
,
2663 IN SIZE_T NumberOfBytes
)
2666 // Allocate the pool
2668 return ExAllocatePoolWithQuotaTag(PoolType
, NumberOfBytes
, TAG_NONE
);
2676 ExAllocatePoolWithTagPriority(IN POOL_TYPE PoolType
,
2677 IN SIZE_T NumberOfBytes
,
2679 IN EX_POOL_PRIORITY Priority
)
2684 // Allocate the pool
2686 Buffer
= ExAllocatePoolWithTag(PoolType
, NumberOfBytes
, Tag
);
2700 ExAllocatePoolWithQuotaTag(IN POOL_TYPE PoolType
,
2701 IN SIZE_T NumberOfBytes
,
2704 BOOLEAN Raise
= TRUE
;
2708 PEPROCESS Process
= PsGetCurrentProcess();
2711 // Check if we should fail instead of raising an exception
2713 if (PoolType
& POOL_QUOTA_FAIL_INSTEAD_OF_RAISE
)
2716 PoolType
&= ~POOL_QUOTA_FAIL_INSTEAD_OF_RAISE
;
2720 // Inject the pool quota mask
2722 PoolType
+= QUOTA_POOL_MASK
;
2725 // Check if we have enough space to add the quota owner process, as long as
2726 // this isn't the system process, which never gets charged quota
2728 ASSERT(NumberOfBytes
!= 0);
2729 if ((NumberOfBytes
<= (PAGE_SIZE
- POOL_BLOCK_SIZE
- sizeof(PVOID
))) &&
2730 (Process
!= PsInitialSystemProcess
))
2733 // Add space for our EPROCESS pointer
2735 NumberOfBytes
+= sizeof(PEPROCESS
);
2740 // We won't be able to store the pointer, so don't use quota for this
2742 PoolType
-= QUOTA_POOL_MASK
;
2746 // Allocate the pool buffer now
2748 Buffer
= ExAllocatePoolWithTag(PoolType
, NumberOfBytes
, Tag
);
2751 // If the buffer is page-aligned, this is a large page allocation and we
2754 if (PAGE_ALIGN(Buffer
) != Buffer
)
2757 // Also if special pool is enabled, and this was allocated from there,
2758 // we won't touch it either
2760 if ((ExpPoolFlags
& POOL_FLAG_SPECIAL_POOL
) &&
2761 (MmIsSpecialPoolAddress(Buffer
)))
2767 // If it wasn't actually allocated with quota charges, ignore it too
2769 if (!(PoolType
& QUOTA_POOL_MASK
)) return Buffer
;
2772 // If this is the system process, we don't charge quota, so ignore
2774 if (Process
== PsInitialSystemProcess
) return Buffer
;
2777 // Actually go and charge quota for the process now
2779 Entry
= POOL_ENTRY(Buffer
);
2780 Status
= PsChargeProcessPoolQuota(Process
,
2781 PoolType
& BASE_POOL_TYPE_MASK
,
2782 Entry
->BlockSize
* POOL_BLOCK_SIZE
);
2783 if (!NT_SUCCESS(Status
))
2786 // Quota failed, back out the allocation, clear the owner, and fail
2788 ((PVOID
*)POOL_NEXT_BLOCK(Entry
))[-1] = NULL
;
2789 ExFreePoolWithTag(Buffer
, Tag
);
2790 if (Raise
) RtlRaiseStatus(Status
);
2795 // Quota worked, write the owner and then reference it before returning
2797 ((PVOID
*)POOL_NEXT_BLOCK(Entry
))[-1] = Process
;
2798 ObReferenceObject(Process
);
2800 else if (!(Buffer
) && (Raise
))
2803 // The allocation failed, raise an error if we are in raise mode
2805 RtlRaiseStatus(STATUS_INSUFFICIENT_RESOURCES
);
2809 // Return the allocated buffer
2814 #if DBG && defined(KDBG)
2821 ULONG_PTR Address
= 0, Flags
= 0;
2830 if (!KdbpGetHexNumber(Argv
[1], &Address
))
2832 KdbpPrint("Invalid parameter: %s\n", Argv
[0]);
2840 if (!KdbpGetHexNumber(Argv
[1], &Flags
))
2842 KdbpPrint("Invalid parameter: %s\n", Argv
[0]);
2847 /* Check if we got an address */
2850 /* Get the base page */
2851 PoolPage
= PAGE_ALIGN(Address
);
2855 KdbpPrint("Heap is unimplemented\n");
2859 /* No paging support! */
2860 if (!MmIsAddressValid(PoolPage
))
2862 KdbpPrint("Address not accessible!\n");
2867 if ((Address
>= (ULONG_PTR
)MmPagedPoolStart
) && (Address
<= (ULONG_PTR
)MmPagedPoolEnd
))
2868 KdbpPrint("Allocation is from PagedPool region\n");
2869 else if ((Address
>= (ULONG_PTR
)MmNonPagedPoolStart
) && (Address
<= (ULONG_PTR
)MmNonPagedPoolEnd
))
2870 KdbpPrint("Allocation is from NonPagedPool region\n");
2873 KdbpPrint("Address 0x%p is not within any pool!\n", (PVOID
)Address
);
2877 /* Loop all entries of that page */
2881 /* Check if the address is within that entry */
2882 ThisOne
= ((Address
>= (ULONG_PTR
)Entry
) &&
2883 (Address
< (ULONG_PTR
)(Entry
+ Entry
->BlockSize
)));
2885 if (!(Flags
& 1) || ThisOne
)
2887 /* Print the line */
2888 KdbpPrint("%c%p size: %4d previous size: %4d %s %.4s\n",
2889 ThisOne
? '*' : ' ', Entry
, Entry
->BlockSize
, Entry
->PreviousSize
,
2890 (Flags
& 0x80000000) ? "" : (Entry
->PoolType
? "(Allocated)" : "(Free) "),
2891 (Flags
& 0x80000000) ? "" : (PCHAR
)&Entry
->PoolTag
);
2896 Data
= (PULONG
)(Entry
+ 1);
2897 KdbpPrint(" %p %08lx %08lx %08lx %08lx\n"
2898 " %p %08lx %08lx %08lx %08lx\n",
2899 &Data
[0], Data
[0], Data
[1], Data
[2], Data
[3],
2900 &Data
[4], Data
[4], Data
[5], Data
[6], Data
[7]);
2903 /* Go to next entry */
2904 Entry
= POOL_BLOCK(Entry
, Entry
->BlockSize
);
2906 while ((Entry
->BlockSize
!= 0) && ((ULONG_PTR
)Entry
< (ULONG_PTR
)PoolPage
+ PAGE_SIZE
));
2911 #endif // DBG && KDBG