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
;
466 ExpTagAllowPrint(CHAR Tag
)
468 if ((Tag
>= 'a' && Tag
<= 'z') ||
469 (Tag
>= 'A' && Tag
<= 'Z') ||
478 #define MiDumperPrint(dbg, fmt, ...) \
479 if (dbg) KdbpPrint(fmt, ##__VA_ARGS__); \
480 else DPRINT1(fmt, ##__VA_ARGS__)
483 MiDumpPoolConsumers(BOOLEAN CalledFromDbg
, ULONG Tag
)
488 // Only print header if called from OOM situation
492 DPRINT1("---------------------\n");
493 DPRINT1("Out of memory dumper!\n");
497 KdbpPrint("Pool Used:\n");
501 // Print table header
503 MiDumperPrint(CalledFromDbg
, "\t\tNonPaged\t\t\tPaged\n");
504 MiDumperPrint(CalledFromDbg
, "Tag\t\tAllocs\t\tUsed\t\tAllocs\t\tUsed\n");
507 // We'll extract allocations for all the tracked pools
509 for (i
= 0; i
< PoolTrackTableSize
; ++i
)
511 PPOOL_TRACKER_TABLE TableEntry
;
513 TableEntry
= &PoolTrackTable
[i
];
516 // We only care about tags which have allocated memory
518 if (TableEntry
->NonPagedBytes
!= 0 || TableEntry
->PagedBytes
!= 0)
521 // If there's a tag, attempt to do a pretty print
522 // only if it matches the caller tag, or if
523 // any tag is allowed
525 if (TableEntry
->Key
!= 0 && TableEntry
->Key
!= TAG_NONE
&& (Tag
== 0 || TableEntry
->Key
== Tag
))
530 // Extract each 'component' and check whether they are printable
532 Tag
[0] = TableEntry
->Key
& 0xFF;
533 Tag
[1] = TableEntry
->Key
>> 8 & 0xFF;
534 Tag
[2] = TableEntry
->Key
>> 16 & 0xFF;
535 Tag
[3] = TableEntry
->Key
>> 24 & 0xFF;
537 if (ExpTagAllowPrint(Tag
[0]) && ExpTagAllowPrint(Tag
[1]) && ExpTagAllowPrint(Tag
[2]) && ExpTagAllowPrint(Tag
[3]))
540 // Print in reversed order to match what is in source code
542 MiDumperPrint(CalledFromDbg
, "'%c%c%c%c'\t\t%ld\t\t%ld\t\t%ld\t\t%ld\n", Tag
[3], Tag
[2], Tag
[1], Tag
[0],
543 TableEntry
->NonPagedAllocs
, TableEntry
->NonPagedBytes
,
544 TableEntry
->PagedAllocs
, TableEntry
->PagedBytes
);
548 MiDumperPrint(CalledFromDbg
, "%x\t%ld\t\t%ld\t\t%ld\t\t%ld\n", TableEntry
->Key
,
549 TableEntry
->NonPagedAllocs
, TableEntry
->NonPagedBytes
,
550 TableEntry
->PagedAllocs
, TableEntry
->PagedBytes
);
553 else if (Tag
== 0 || Tag
== TAG_NONE
)
555 MiDumperPrint(CalledFromDbg
, "Anon\t\t%ld\t\t%ld\t\t%ld\t\t%ld\n",
556 TableEntry
->NonPagedAllocs
, TableEntry
->NonPagedBytes
,
557 TableEntry
->PagedAllocs
, TableEntry
->PagedBytes
);
564 DPRINT1("---------------------\n");
569 /* PRIVATE FUNCTIONS **********************************************************/
576 ULONG i
, Key
, Hash
, Index
;
577 PPOOL_TRACKER_TABLE TrackTable
= PoolTrackTable
;
647 // Loop all 64 hot tags
649 ASSERT((sizeof(TagList
) / sizeof(ULONG
)) == 64);
650 for (i
= 0; i
< sizeof(TagList
) / sizeof(ULONG
); i
++)
653 // Get the current tag, and compute its hash in the tracker table
656 Hash
= ExpComputeHashForTag(Key
, PoolTrackTableMask
);
659 // Loop all the hashes in this index/bucket
665 // Find an empty entry, and make sure this isn't the last hash that
668 // On checked builds, also make sure this is the first time we are
671 ASSERT(TrackTable
[Hash
].Key
!= Key
);
672 if (!(TrackTable
[Hash
].Key
) && (Hash
!= PoolTrackTableSize
- 1))
675 // It has been seeded, move on to the next tag
677 TrackTable
[Hash
].Key
= Key
;
682 // This entry was already taken, compute the next possible hash while
683 // making sure we're not back at our initial index.
685 ASSERT(TrackTable
[Hash
].Key
!= Key
);
686 Hash
= (Hash
+ 1) & PoolTrackTableMask
;
687 if (Hash
== Index
) break;
694 ExpRemovePoolTracker(IN ULONG Key
,
695 IN SIZE_T NumberOfBytes
,
696 IN POOL_TYPE PoolType
)
699 PPOOL_TRACKER_TABLE Table
, TableEntry
;
700 SIZE_T TableMask
, TableSize
;
703 // Remove the PROTECTED_POOL flag which is not part of the tag
705 Key
&= ~PROTECTED_POOL
;
708 // With WinDBG you can set a tag you want to break on when an allocation is
711 if (Key
== PoolHitTag
) DbgBreakPoint();
714 // Why the double indirection? Because normally this function is also used
715 // when doing session pool allocations, which has another set of tables,
716 // sizes, and masks that live in session pool. Now we don't support session
717 // pool so we only ever use the regular tables, but I'm keeping the code this
718 // way so that the day we DO support session pool, it won't require that
721 Table
= PoolTrackTable
;
722 TableMask
= PoolTrackTableMask
;
723 TableSize
= PoolTrackTableSize
;
724 DBG_UNREFERENCED_LOCAL_VARIABLE(TableSize
);
727 // Compute the hash for this key, and loop all the possible buckets
729 Hash
= ExpComputeHashForTag(Key
, TableMask
);
734 // Have we found the entry for this tag? */
736 TableEntry
= &Table
[Hash
];
737 if (TableEntry
->Key
== Key
)
740 // Decrement the counters depending on if this was paged or nonpaged
743 if ((PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
745 InterlockedIncrement(&TableEntry
->NonPagedFrees
);
746 InterlockedExchangeAddSizeT(&TableEntry
->NonPagedBytes
,
747 -(SSIZE_T
)NumberOfBytes
);
750 InterlockedIncrement(&TableEntry
->PagedFrees
);
751 InterlockedExchangeAddSizeT(&TableEntry
->PagedBytes
,
752 -(SSIZE_T
)NumberOfBytes
);
757 // We should have only ended up with an empty entry if we've reached
760 if (!TableEntry
->Key
)
762 DPRINT1("Empty item reached in tracker table. Hash=0x%lx, TableMask=0x%lx, Tag=0x%08lx, NumberOfBytes=%lu, PoolType=%d\n",
763 Hash
, TableMask
, Key
, (ULONG
)NumberOfBytes
, PoolType
);
764 ASSERT(Hash
== TableMask
);
768 // This path is hit when we don't have an entry, and the current bucket
769 // is full, so we simply try the next one
771 Hash
= (Hash
+ 1) & TableMask
;
772 if (Hash
== Index
) break;
776 // And finally this path is hit when all the buckets are full, and we need
777 // some expansion. This path is not yet supported in ReactOS and so we'll
780 DPRINT1("Out of pool tag space, ignoring...\n");
785 ExpInsertPoolTracker(IN ULONG Key
,
786 IN SIZE_T NumberOfBytes
,
787 IN POOL_TYPE PoolType
)
791 PPOOL_TRACKER_TABLE Table
, TableEntry
;
792 SIZE_T TableMask
, TableSize
;
795 // Remove the PROTECTED_POOL flag which is not part of the tag
797 Key
&= ~PROTECTED_POOL
;
800 // With WinDBG you can set a tag you want to break on when an allocation is
803 if (Key
== PoolHitTag
) DbgBreakPoint();
806 // There is also an internal flag you can set to break on malformed tags
808 if (ExStopBadTags
) ASSERT(Key
& 0xFFFFFF00);
811 // ASSERT on ReactOS features not yet supported
813 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
814 ASSERT(KeGetCurrentProcessorNumber() == 0);
817 // Why the double indirection? Because normally this function is also used
818 // when doing session pool allocations, which has another set of tables,
819 // sizes, and masks that live in session pool. Now we don't support session
820 // pool so we only ever use the regular tables, but I'm keeping the code this
821 // way so that the day we DO support session pool, it won't require that
824 Table
= PoolTrackTable
;
825 TableMask
= PoolTrackTableMask
;
826 TableSize
= PoolTrackTableSize
;
827 DBG_UNREFERENCED_LOCAL_VARIABLE(TableSize
);
830 // Compute the hash for this key, and loop all the possible buckets
832 Hash
= ExpComputeHashForTag(Key
, TableMask
);
837 // Do we already have an entry for this tag? */
839 TableEntry
= &Table
[Hash
];
840 if (TableEntry
->Key
== Key
)
843 // Increment the counters depending on if this was paged or nonpaged
846 if ((PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
848 InterlockedIncrement(&TableEntry
->NonPagedAllocs
);
849 InterlockedExchangeAddSizeT(&TableEntry
->NonPagedBytes
, NumberOfBytes
);
852 InterlockedIncrement(&TableEntry
->PagedAllocs
);
853 InterlockedExchangeAddSizeT(&TableEntry
->PagedBytes
, NumberOfBytes
);
858 // We don't have an entry yet, but we've found a free bucket for it
860 if (!(TableEntry
->Key
) && (Hash
!= PoolTrackTableSize
- 1))
863 // We need to hold the lock while creating a new entry, since other
864 // processors might be in this code path as well
866 ExAcquireSpinLock(&ExpTaggedPoolLock
, &OldIrql
);
867 if (!PoolTrackTable
[Hash
].Key
)
870 // We've won the race, so now create this entry in the bucket
872 ASSERT(Table
[Hash
].Key
== 0);
873 PoolTrackTable
[Hash
].Key
= Key
;
874 TableEntry
->Key
= Key
;
876 ExReleaseSpinLock(&ExpTaggedPoolLock
, OldIrql
);
879 // Now we force the loop to run again, and we should now end up in
880 // the code path above which does the interlocked increments...
886 // This path is hit when we don't have an entry, and the current bucket
887 // is full, so we simply try the next one
889 Hash
= (Hash
+ 1) & TableMask
;
890 if (Hash
== Index
) break;
894 // And finally this path is hit when all the buckets are full, and we need
895 // some expansion. This path is not yet supported in ReactOS and so we'll
898 DPRINT1("Out of pool tag space, ignoring...\n");
904 ExInitializePoolDescriptor(IN PPOOL_DESCRIPTOR PoolDescriptor
,
905 IN POOL_TYPE PoolType
,
910 PLIST_ENTRY NextEntry
, LastEntry
;
913 // Setup the descriptor based on the caller's request
915 PoolDescriptor
->PoolType
= PoolType
;
916 PoolDescriptor
->PoolIndex
= PoolIndex
;
917 PoolDescriptor
->Threshold
= Threshold
;
918 PoolDescriptor
->LockAddress
= PoolLock
;
921 // Initialize accounting data
923 PoolDescriptor
->RunningAllocs
= 0;
924 PoolDescriptor
->RunningDeAllocs
= 0;
925 PoolDescriptor
->TotalPages
= 0;
926 PoolDescriptor
->TotalBytes
= 0;
927 PoolDescriptor
->TotalBigPages
= 0;
930 // Nothing pending for now
932 PoolDescriptor
->PendingFrees
= NULL
;
933 PoolDescriptor
->PendingFreeDepth
= 0;
936 // Loop all the descriptor's allocation lists and initialize them
938 NextEntry
= PoolDescriptor
->ListHeads
;
939 LastEntry
= NextEntry
+ POOL_LISTS_PER_PAGE
;
940 while (NextEntry
< LastEntry
)
942 ExpInitializePoolListHead(NextEntry
);
947 // Note that ReactOS does not support Session Pool Yet
949 ASSERT(PoolType
!= PagedPoolSession
);
955 InitializePool(IN POOL_TYPE PoolType
,
958 PPOOL_DESCRIPTOR Descriptor
;
963 // Check what kind of pool this is
965 if (PoolType
== NonPagedPool
)
968 // Compute the track table size and convert it from a power of two to an
971 // NOTE: On checked builds, we'll assert if the registry table size was
972 // invalid, while on retail builds we'll just break out of the loop at
975 TableSize
= min(PoolTrackTableSize
, MmSizeOfNonPagedPoolInBytes
>> 8);
976 for (i
= 0; i
< 32; i
++)
980 ASSERT((TableSize
& ~1) == 0);
981 if (!(TableSize
& ~1)) break;
987 // If we hit bit 32, than no size was defined in the registry, so
988 // we'll use the default size of 2048 entries.
990 // Otherwise, use the size from the registry, as long as it's not
991 // smaller than 64 entries.
995 PoolTrackTableSize
= 2048;
999 PoolTrackTableSize
= max(1 << i
, 64);
1003 // Loop trying with the biggest specified size first, and cut it down
1004 // by a power of two each iteration in case not enough memory exist
1009 // Do not allow overflow
1011 if ((PoolTrackTableSize
+ 1) > (MAXULONG_PTR
/ sizeof(POOL_TRACKER_TABLE
)))
1013 PoolTrackTableSize
>>= 1;
1018 // Allocate the tracker table and exit the loop if this worked
1020 PoolTrackTable
= MiAllocatePoolPages(NonPagedPool
,
1021 (PoolTrackTableSize
+ 1) *
1022 sizeof(POOL_TRACKER_TABLE
));
1023 if (PoolTrackTable
) break;
1026 // Otherwise, as long as we're not down to the last bit, keep
1029 if (PoolTrackTableSize
== 1)
1031 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
1037 PoolTrackTableSize
>>= 1;
1041 // Add one entry, compute the hash, and zero the table
1043 PoolTrackTableSize
++;
1044 PoolTrackTableMask
= PoolTrackTableSize
- 2;
1046 RtlZeroMemory(PoolTrackTable
,
1047 PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
));
1050 // Finally, add the most used tags to speed up those allocations
1055 // We now do the exact same thing with the tracker table for big pages
1057 TableSize
= min(PoolBigPageTableSize
, MmSizeOfNonPagedPoolInBytes
>> 8);
1058 for (i
= 0; i
< 32; i
++)
1062 ASSERT((TableSize
& ~1) == 0);
1063 if (!(TableSize
& ~1)) break;
1069 // For big pages, the default tracker table is 4096 entries, while the
1070 // minimum is still 64
1074 PoolBigPageTableSize
= 4096;
1078 PoolBigPageTableSize
= max(1 << i
, 64);
1082 // Again, run the exact same loop we ran earlier, but this time for the
1083 // big pool tracker instead
1087 if ((PoolBigPageTableSize
+ 1) > (MAXULONG_PTR
/ sizeof(POOL_TRACKER_BIG_PAGES
)))
1089 PoolBigPageTableSize
>>= 1;
1093 PoolBigPageTable
= MiAllocatePoolPages(NonPagedPool
,
1094 PoolBigPageTableSize
*
1095 sizeof(POOL_TRACKER_BIG_PAGES
));
1096 if (PoolBigPageTable
) break;
1098 if (PoolBigPageTableSize
== 1)
1100 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
1107 PoolBigPageTableSize
>>= 1;
1111 // An extra entry is not needed for for the big pool tracker, so just
1112 // compute the hash and zero it
1114 PoolBigPageTableHash
= PoolBigPageTableSize
- 1;
1115 RtlZeroMemory(PoolBigPageTable
,
1116 PoolBigPageTableSize
* sizeof(POOL_TRACKER_BIG_PAGES
));
1117 for (i
= 0; i
< PoolBigPageTableSize
; i
++) PoolBigPageTable
[i
].Va
= (PVOID
)1;
1120 // During development, print this out so we can see what's happening
1122 DPRINT("EXPOOL: Pool Tracker Table at: 0x%p with 0x%lx bytes\n",
1123 PoolTrackTable
, PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
));
1124 DPRINT("EXPOOL: Big Pool Tracker Table at: 0x%p with 0x%lx bytes\n",
1125 PoolBigPageTable
, PoolBigPageTableSize
* sizeof(POOL_TRACKER_BIG_PAGES
));
1128 // Insert the generic tracker for all of big pool
1130 ExpInsertPoolTracker('looP',
1131 ROUND_TO_PAGES(PoolBigPageTableSize
*
1132 sizeof(POOL_TRACKER_BIG_PAGES
)),
1136 // No support for NUMA systems at this time
1138 ASSERT(KeNumberNodes
== 1);
1141 // Initialize the tag spinlock
1143 KeInitializeSpinLock(&ExpTaggedPoolLock
);
1146 // Initialize the nonpaged pool descriptor
1148 PoolVector
[NonPagedPool
] = &NonPagedPoolDescriptor
;
1149 ExInitializePoolDescriptor(PoolVector
[NonPagedPool
],
1158 // No support for NUMA systems at this time
1160 ASSERT(KeNumberNodes
== 1);
1163 // Allocate the pool descriptor
1165 Descriptor
= ExAllocatePoolWithTag(NonPagedPool
,
1166 sizeof(KGUARDED_MUTEX
) +
1167 sizeof(POOL_DESCRIPTOR
),
1172 // This is really bad...
1174 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
1182 // Setup the vector and guarded mutex for paged pool
1184 PoolVector
[PagedPool
] = Descriptor
;
1185 ExpPagedPoolMutex
= (PKGUARDED_MUTEX
)(Descriptor
+ 1);
1186 ExpPagedPoolDescriptor
[0] = Descriptor
;
1187 KeInitializeGuardedMutex(ExpPagedPoolMutex
);
1188 ExInitializePoolDescriptor(Descriptor
,
1195 // Insert the generic tracker for all of nonpaged pool
1197 ExpInsertPoolTracker('looP',
1198 ROUND_TO_PAGES(PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
)),
1205 ExLockPool(IN PPOOL_DESCRIPTOR Descriptor
)
1208 // Check if this is nonpaged pool
1210 if ((Descriptor
->PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
1213 // Use the queued spin lock
1215 return KeAcquireQueuedSpinLock(LockQueueNonPagedPoolLock
);
1220 // Use the guarded mutex
1222 KeAcquireGuardedMutex(Descriptor
->LockAddress
);
1229 ExUnlockPool(IN PPOOL_DESCRIPTOR Descriptor
,
1233 // Check if this is nonpaged pool
1235 if ((Descriptor
->PoolType
& BASE_POOL_TYPE_MASK
) == NonPagedPool
)
1238 // Use the queued spin lock
1240 KeReleaseQueuedSpinLock(LockQueueNonPagedPoolLock
, OldIrql
);
1245 // Use the guarded mutex
1247 KeReleaseGuardedMutex(Descriptor
->LockAddress
);
1253 ExpGetPoolTagInfoTarget(IN PKDPC Dpc
,
1254 IN PVOID DeferredContext
,
1255 IN PVOID SystemArgument1
,
1256 IN PVOID SystemArgument2
)
1258 PPOOL_DPC_CONTEXT Context
= DeferredContext
;
1259 UNREFERENCED_PARAMETER(Dpc
);
1260 ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL
);
1263 // Make sure we win the race, and if we did, copy the data atomically
1265 if (KeSignalCallDpcSynchronize(SystemArgument2
))
1267 RtlCopyMemory(Context
->PoolTrackTable
,
1269 Context
->PoolTrackTableSize
* sizeof(POOL_TRACKER_TABLE
));
1272 // This is here because ReactOS does not yet support expansion
1274 ASSERT(Context
->PoolTrackTableSizeExpansion
== 0);
1278 // Regardless of whether we won or not, we must now synchronize and then
1279 // decrement the barrier since this is one more processor that has completed
1282 KeSignalCallDpcSynchronize(SystemArgument2
);
1283 KeSignalCallDpcDone(SystemArgument1
);
1288 ExGetPoolTagInfo(IN PSYSTEM_POOLTAG_INFORMATION SystemInformation
,
1289 IN ULONG SystemInformationLength
,
1290 IN OUT PULONG ReturnLength OPTIONAL
)
1292 ULONG TableSize
, CurrentLength
;
1294 NTSTATUS Status
= STATUS_SUCCESS
;
1295 PSYSTEM_POOLTAG TagEntry
;
1296 PPOOL_TRACKER_TABLE Buffer
, TrackerEntry
;
1297 POOL_DPC_CONTEXT Context
;
1298 ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL
);
1301 // Keep track of how much data the caller's buffer must hold
1303 CurrentLength
= FIELD_OFFSET(SYSTEM_POOLTAG_INFORMATION
, TagInfo
);
1306 // Initialize the caller's buffer
1308 TagEntry
= &SystemInformation
->TagInfo
[0];
1309 SystemInformation
->Count
= 0;
1312 // Capture the number of entries, and the total size needed to make a copy
1315 EntryCount
= (ULONG
)PoolTrackTableSize
;
1316 TableSize
= EntryCount
* sizeof(POOL_TRACKER_TABLE
);
1319 // Allocate the "Generic DPC" temporary buffer
1321 Buffer
= ExAllocatePoolWithTag(NonPagedPool
, TableSize
, 'ofnI');
1322 if (!Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
1325 // Do a "Generic DPC" to atomically retrieve the tag and allocation data
1327 Context
.PoolTrackTable
= Buffer
;
1328 Context
.PoolTrackTableSize
= PoolTrackTableSize
;
1329 Context
.PoolTrackTableExpansion
= NULL
;
1330 Context
.PoolTrackTableSizeExpansion
= 0;
1331 KeGenericCallDpc(ExpGetPoolTagInfoTarget
, &Context
);
1334 // Now parse the results
1336 for (TrackerEntry
= Buffer
; TrackerEntry
< (Buffer
+ EntryCount
); TrackerEntry
++)
1339 // If the entry is empty, skip it
1341 if (!TrackerEntry
->Key
) continue;
1344 // Otherwise, add one more entry to the caller's buffer, and ensure that
1345 // enough space has been allocated in it
1347 SystemInformation
->Count
++;
1348 CurrentLength
+= sizeof(*TagEntry
);
1349 if (SystemInformationLength
< CurrentLength
)
1352 // The caller's buffer is too small, so set a failure code. The
1353 // caller will know the count, as well as how much space is needed.
1355 // We do NOT break out of the loop, because we want to keep incrementing
1356 // the Count as well as CurrentLength so that the caller can know the
1359 Status
= STATUS_INFO_LENGTH_MISMATCH
;
1364 // Small sanity check that our accounting is working correctly
1366 ASSERT(TrackerEntry
->PagedAllocs
>= TrackerEntry
->PagedFrees
);
1367 ASSERT(TrackerEntry
->NonPagedAllocs
>= TrackerEntry
->NonPagedFrees
);
1370 // Return the data into the caller's buffer
1372 TagEntry
->TagUlong
= TrackerEntry
->Key
;
1373 TagEntry
->PagedAllocs
= TrackerEntry
->PagedAllocs
;
1374 TagEntry
->PagedFrees
= TrackerEntry
->PagedFrees
;
1375 TagEntry
->PagedUsed
= TrackerEntry
->PagedBytes
;
1376 TagEntry
->NonPagedAllocs
= TrackerEntry
->NonPagedAllocs
;
1377 TagEntry
->NonPagedFrees
= TrackerEntry
->NonPagedFrees
;
1378 TagEntry
->NonPagedUsed
= TrackerEntry
->NonPagedBytes
;
1384 // Free the "Generic DPC" temporary buffer, return the buffer length and status
1386 ExFreePoolWithTag(Buffer
, 'ofnI');
1387 if (ReturnLength
) *ReturnLength
= CurrentLength
;
1393 ExpAddTagForBigPages(IN PVOID Va
,
1395 IN ULONG NumberOfPages
,
1396 IN POOL_TYPE PoolType
)
1402 PPOOL_TRACKER_BIG_PAGES Entry
, EntryEnd
, EntryStart
;
1403 ASSERT(((ULONG_PTR
)Va
& POOL_BIG_TABLE_ENTRY_FREE
) == 0);
1404 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
1407 // As the table is expandable, these values must only be read after acquiring
1408 // the lock to avoid a teared access during an expansion
1410 Hash
= ExpComputePartialHashForAddress(Va
);
1411 KeAcquireSpinLock(&ExpLargePoolTableLock
, &OldIrql
);
1412 Hash
&= PoolBigPageTableHash
;
1413 TableSize
= PoolBigPageTableSize
;
1416 // We loop from the current hash bucket to the end of the table, and then
1417 // rollover to hash bucket 0 and keep going from there. If we return back
1418 // to the beginning, then we attempt expansion at the bottom of the loop
1420 EntryStart
= Entry
= &PoolBigPageTable
[Hash
];
1421 EntryEnd
= &PoolBigPageTable
[TableSize
];
1425 // Make sure that this is a free entry and attempt to atomically make the
1429 if (((ULONG_PTR
)OldVa
& POOL_BIG_TABLE_ENTRY_FREE
) &&
1430 (InterlockedCompareExchangePointer(&Entry
->Va
, Va
, OldVa
) == OldVa
))
1433 // We now own this entry, write down the size and the pool tag
1436 Entry
->NumberOfPages
= NumberOfPages
;
1439 // Add one more entry to the count, and see if we're getting within
1440 // 25% of the table size, at which point we'll do an expansion now
1441 // to avoid blocking too hard later on.
1443 // Note that we only do this if it's also been the 16th time that we
1444 // keep losing the race or that we are not finding a free entry anymore,
1445 // which implies a massive number of concurrent big pool allocations.
1447 InterlockedIncrementUL(&ExpPoolBigEntriesInUse
);
1448 if ((i
>= 16) && (ExpPoolBigEntriesInUse
> (TableSize
/ 4)))
1450 DPRINT("Should attempt expansion since we now have %lu entries\n",
1451 ExpPoolBigEntriesInUse
);
1455 // We have our entry, return
1457 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1462 // We don't have our entry yet, so keep trying, making the entry list
1463 // circular if we reach the last entry. We'll eventually break out of
1464 // the loop once we've rolled over and returned back to our original
1468 if (++Entry
>= EntryEnd
) Entry
= &PoolBigPageTable
[0];
1469 } while (Entry
!= EntryStart
);
1472 // This means there's no free hash buckets whatsoever, so we would now have
1473 // to attempt expanding the table
1475 DPRINT1("Big pool expansion needed, not implemented!\n");
1476 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1482 ExpFindAndRemoveTagBigPages(IN PVOID Va
,
1483 OUT PULONG_PTR BigPages
,
1484 IN POOL_TYPE PoolType
)
1486 BOOLEAN FirstTry
= TRUE
;
1489 ULONG PoolTag
, Hash
;
1490 PPOOL_TRACKER_BIG_PAGES Entry
;
1491 ASSERT(((ULONG_PTR
)Va
& POOL_BIG_TABLE_ENTRY_FREE
) == 0);
1492 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
1495 // As the table is expandable, these values must only be read after acquiring
1496 // the lock to avoid a teared access during an expansion
1498 Hash
= ExpComputePartialHashForAddress(Va
);
1499 KeAcquireSpinLock(&ExpLargePoolTableLock
, &OldIrql
);
1500 Hash
&= PoolBigPageTableHash
;
1501 TableSize
= PoolBigPageTableSize
;
1504 // Loop while trying to find this big page allocation
1506 while (PoolBigPageTable
[Hash
].Va
!= Va
)
1509 // Increment the size until we go past the end of the table
1511 if (++Hash
>= TableSize
)
1514 // Is this the second time we've tried?
1519 // This means it was never inserted into the pool table and it
1520 // received the special "BIG" tag -- return that and return 0
1521 // so that the code can ask Mm for the page count instead
1523 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1529 // The first time this happens, reset the hash index and try again
1537 // Now capture all the information we need from the entry, since after we
1538 // release the lock, the data can change
1540 Entry
= &PoolBigPageTable
[Hash
];
1541 *BigPages
= Entry
->NumberOfPages
;
1542 PoolTag
= Entry
->Key
;
1545 // Set the free bit, and decrement the number of allocations. Finally, release
1546 // the lock and return the tag that was located
1548 InterlockedIncrement((PLONG
)&Entry
->Va
);
1549 InterlockedDecrementUL(&ExpPoolBigEntriesInUse
);
1550 KeReleaseSpinLock(&ExpLargePoolTableLock
, OldIrql
);
1556 ExQueryPoolUsage(OUT PULONG PagedPoolPages
,
1557 OUT PULONG NonPagedPoolPages
,
1558 OUT PULONG PagedPoolAllocs
,
1559 OUT PULONG PagedPoolFrees
,
1560 OUT PULONG PagedPoolLookasideHits
,
1561 OUT PULONG NonPagedPoolAllocs
,
1562 OUT PULONG NonPagedPoolFrees
,
1563 OUT PULONG NonPagedPoolLookasideHits
)
1566 PPOOL_DESCRIPTOR PoolDesc
;
1569 // Assume all failures
1571 *PagedPoolPages
= 0;
1572 *PagedPoolAllocs
= 0;
1573 *PagedPoolFrees
= 0;
1576 // Tally up the totals for all the apged pool
1578 for (i
= 0; i
< ExpNumberOfPagedPools
+ 1; i
++)
1580 PoolDesc
= ExpPagedPoolDescriptor
[i
];
1581 *PagedPoolPages
+= PoolDesc
->TotalPages
+ PoolDesc
->TotalBigPages
;
1582 *PagedPoolAllocs
+= PoolDesc
->RunningAllocs
;
1583 *PagedPoolFrees
+= PoolDesc
->RunningDeAllocs
;
1587 // The first non-paged pool has a hardcoded well-known descriptor name
1589 PoolDesc
= &NonPagedPoolDescriptor
;
1590 *NonPagedPoolPages
= PoolDesc
->TotalPages
+ PoolDesc
->TotalBigPages
;
1591 *NonPagedPoolAllocs
= PoolDesc
->RunningAllocs
;
1592 *NonPagedPoolFrees
= PoolDesc
->RunningDeAllocs
;
1595 // If the system has more than one non-paged pool, copy the other descriptor
1599 if (ExpNumberOfNonPagedPools
> 1)
1601 for (i
= 0; i
< ExpNumberOfNonPagedPools
; i
++)
1603 PoolDesc
= ExpNonPagedPoolDescriptor
[i
];
1604 *NonPagedPoolPages
+= PoolDesc
->TotalPages
+ PoolDesc
->TotalBigPages
;
1605 *NonPagedPoolAllocs
+= PoolDesc
->RunningAllocs
;
1606 *NonPagedPoolFrees
+= PoolDesc
->RunningDeAllocs
;
1612 // FIXME: Not yet supported
1614 *NonPagedPoolLookasideHits
+= 0;
1615 *PagedPoolLookasideHits
+= 0;
1620 ExReturnPoolQuota(IN PVOID P
)
1627 if ((ExpPoolFlags
& POOL_FLAG_SPECIAL_POOL
) &&
1628 (MmIsSpecialPoolAddress(P
)))
1635 ASSERT((ULONG_PTR
)Entry
% POOL_BLOCK_SIZE
== 0);
1637 PoolType
= Entry
->PoolType
- 1;
1638 BlockSize
= Entry
->BlockSize
;
1640 if (PoolType
& QUOTA_POOL_MASK
)
1642 Process
= ((PVOID
*)POOL_NEXT_BLOCK(Entry
))[-1];
1643 ASSERT(Process
!= NULL
);
1646 if (Process
->Pcb
.Header
.Type
!= ProcessObject
)
1648 DPRINT1("Object %p is not a process. Type %u, pool type 0x%x, block size %u\n",
1649 Process
, Process
->Pcb
.Header
.Type
, Entry
->PoolType
, BlockSize
);
1650 KeBugCheckEx(BAD_POOL_CALLER
,
1654 (ULONG_PTR
)Process
);
1656 ((PVOID
*)POOL_NEXT_BLOCK(Entry
))[-1] = NULL
;
1657 PsReturnPoolQuota(Process
,
1658 PoolType
& BASE_POOL_TYPE_MASK
,
1659 BlockSize
* POOL_BLOCK_SIZE
);
1660 ObDereferenceObject(Process
);
1665 /* PUBLIC FUNCTIONS ***********************************************************/
1672 ExAllocatePoolWithTag(IN POOL_TYPE PoolType
,
1673 IN SIZE_T NumberOfBytes
,
1676 PPOOL_DESCRIPTOR PoolDesc
;
1677 PLIST_ENTRY ListHead
;
1678 PPOOL_HEADER Entry
, NextEntry
, FragmentEntry
;
1680 USHORT BlockSize
, i
;
1682 PKPRCB Prcb
= KeGetCurrentPrcb();
1683 PGENERAL_LOOKASIDE LookasideList
;
1686 // Some sanity checks
1689 ASSERT(Tag
!= ' GIB');
1690 ASSERT(NumberOfBytes
!= 0);
1691 ExpCheckPoolIrqlLevel(PoolType
, NumberOfBytes
, NULL
);
1694 // Not supported in ReactOS
1696 ASSERT(!(PoolType
& SESSION_POOL_MASK
));
1699 // Check if verifier or special pool is enabled
1701 if (ExpPoolFlags
& (POOL_FLAG_VERIFIER
| POOL_FLAG_SPECIAL_POOL
))
1704 // For verifier, we should call the verification routine
1706 if (ExpPoolFlags
& POOL_FLAG_VERIFIER
)
1708 DPRINT1("Driver Verifier is not yet supported\n");
1712 // For special pool, we check if this is a suitable allocation and do
1713 // the special allocation if needed
1715 if (ExpPoolFlags
& POOL_FLAG_SPECIAL_POOL
)
1718 // Check if this is a special pool allocation
1720 if (MmUseSpecialPool(NumberOfBytes
, Tag
))
1723 // Try to allocate using special pool
1725 Entry
= MmAllocateSpecialPool(NumberOfBytes
, Tag
, PoolType
, 2);
1726 if (Entry
) return Entry
;
1732 // Get the pool type and its corresponding vector for this request
1734 OriginalType
= PoolType
;
1735 PoolType
= PoolType
& BASE_POOL_TYPE_MASK
;
1736 PoolDesc
= PoolVector
[PoolType
];
1737 ASSERT(PoolDesc
!= NULL
);
1740 // Check if this is a big page allocation
1742 if (NumberOfBytes
> POOL_MAX_ALLOC
)
1745 // Allocate pages for it
1747 Entry
= MiAllocatePoolPages(OriginalType
, NumberOfBytes
);
1752 // Out of memory, display current consumption
1754 MiDumpPoolConsumers(FALSE
, 0);
1758 // Must succeed pool is deprecated, but still supported. These allocation
1759 // failures must cause an immediate bugcheck
1761 if (OriginalType
& MUST_SUCCEED_POOL_MASK
)
1763 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
1765 NonPagedPoolDescriptor
.TotalPages
,
1766 NonPagedPoolDescriptor
.TotalBigPages
,
1771 // Internal debugging
1776 // This flag requests printing failures, and can also further specify
1777 // breaking on failures
1779 if (ExpPoolFlags
& POOL_FLAG_DBGPRINT_ON_FAILURE
)
1781 DPRINT1("EX: ExAllocatePool (%lu, 0x%x) returning NULL\n",
1784 if (ExpPoolFlags
& POOL_FLAG_CRASH_ON_FAILURE
) DbgBreakPoint();
1788 // Finally, this flag requests an exception, which we are more than
1791 if (OriginalType
& POOL_RAISE_IF_ALLOCATION_FAILURE
)
1793 ExRaiseStatus(STATUS_INSUFFICIENT_RESOURCES
);
1800 // Increment required counters
1802 InterlockedExchangeAdd((PLONG
)&PoolDesc
->TotalBigPages
,
1803 (LONG
)BYTES_TO_PAGES(NumberOfBytes
));
1804 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, NumberOfBytes
);
1805 InterlockedIncrement((PLONG
)&PoolDesc
->RunningAllocs
);
1808 // Add a tag for the big page allocation and switch to the generic "BIG"
1809 // tag if we failed to do so, then insert a tracker for this alloation.
1811 if (!ExpAddTagForBigPages(Entry
,
1813 (ULONG
)BYTES_TO_PAGES(NumberOfBytes
),
1818 ExpInsertPoolTracker(Tag
, ROUND_TO_PAGES(NumberOfBytes
), OriginalType
);
1823 // Should never request 0 bytes from the pool, but since so many drivers do
1824 // it, we'll just assume they want 1 byte, based on NT's similar behavior
1826 if (!NumberOfBytes
) NumberOfBytes
= 1;
1829 // A pool allocation is defined by its data, a linked list to connect it to
1830 // the free list (if necessary), and a pool header to store accounting info.
1831 // Calculate this size, then convert it into a block size (units of pool
1834 // Note that i cannot overflow (past POOL_LISTS_PER_PAGE) because any such
1835 // request would've been treated as a POOL_MAX_ALLOC earlier and resulted in
1836 // the direct allocation of pages.
1838 i
= (USHORT
)((NumberOfBytes
+ sizeof(POOL_HEADER
) + (POOL_BLOCK_SIZE
- 1))
1840 ASSERT(i
< POOL_LISTS_PER_PAGE
);
1843 // Handle lookaside list optimization for both paged and nonpaged pool
1845 if (i
<= NUMBER_POOL_LOOKASIDE_LISTS
)
1848 // Try popping it from the per-CPU lookaside list
1850 LookasideList
= (PoolType
== PagedPool
) ?
1851 Prcb
->PPPagedLookasideList
[i
- 1].P
:
1852 Prcb
->PPNPagedLookasideList
[i
- 1].P
;
1853 LookasideList
->TotalAllocates
++;
1854 Entry
= (PPOOL_HEADER
)InterlockedPopEntrySList(&LookasideList
->ListHead
);
1858 // We failed, try popping it from the global list
1860 LookasideList
= (PoolType
== PagedPool
) ?
1861 Prcb
->PPPagedLookasideList
[i
- 1].L
:
1862 Prcb
->PPNPagedLookasideList
[i
- 1].L
;
1863 LookasideList
->TotalAllocates
++;
1864 Entry
= (PPOOL_HEADER
)InterlockedPopEntrySList(&LookasideList
->ListHead
);
1868 // If we were able to pop it, update the accounting and return the block
1872 LookasideList
->AllocateHits
++;
1875 // Get the real entry, write down its pool type, and track it
1878 Entry
->PoolType
= OriginalType
+ 1;
1879 ExpInsertPoolTracker(Tag
,
1880 Entry
->BlockSize
* POOL_BLOCK_SIZE
,
1884 // Return the pool allocation
1886 Entry
->PoolTag
= Tag
;
1887 (POOL_FREE_BLOCK(Entry
))->Flink
= NULL
;
1888 (POOL_FREE_BLOCK(Entry
))->Blink
= NULL
;
1889 return POOL_FREE_BLOCK(Entry
);
1894 // Loop in the free lists looking for a block if this size. Start with the
1895 // list optimized for this kind of size lookup
1897 ListHead
= &PoolDesc
->ListHeads
[i
];
1901 // Are there any free entries available on this list?
1903 if (!ExpIsPoolListEmpty(ListHead
))
1906 // Acquire the pool lock now
1908 OldIrql
= ExLockPool(PoolDesc
);
1911 // And make sure the list still has entries
1913 if (ExpIsPoolListEmpty(ListHead
))
1916 // Someone raced us (and won) before we had a chance to acquire
1921 ExUnlockPool(PoolDesc
, OldIrql
);
1926 // Remove a free entry from the list
1927 // Note that due to the way we insert free blocks into multiple lists
1928 // there is a guarantee that any block on this list will either be
1929 // of the correct size, or perhaps larger.
1931 ExpCheckPoolLinks(ListHead
);
1932 Entry
= POOL_ENTRY(ExpRemovePoolHeadList(ListHead
));
1933 ExpCheckPoolLinks(ListHead
);
1934 ExpCheckPoolBlocks(Entry
);
1935 ASSERT(Entry
->BlockSize
>= i
);
1936 ASSERT(Entry
->PoolType
== 0);
1939 // Check if this block is larger that what we need. The block could
1940 // not possibly be smaller, due to the reason explained above (and
1941 // we would've asserted on a checked build if this was the case).
1943 if (Entry
->BlockSize
!= i
)
1946 // Is there an entry before this one?
1948 if (Entry
->PreviousSize
== 0)
1951 // There isn't anyone before us, so take the next block and
1952 // turn it into a fragment that contains the leftover data
1953 // that we don't need to satisfy the caller's request
1955 FragmentEntry
= POOL_BLOCK(Entry
, i
);
1956 FragmentEntry
->BlockSize
= Entry
->BlockSize
- i
;
1959 // And make it point back to us
1961 FragmentEntry
->PreviousSize
= i
;
1964 // Now get the block that follows the new fragment and check
1965 // if it's still on the same page as us (and not at the end)
1967 NextEntry
= POOL_NEXT_BLOCK(FragmentEntry
);
1968 if (PAGE_ALIGN(NextEntry
) != NextEntry
)
1971 // Adjust this next block to point to our newly created
1974 NextEntry
->PreviousSize
= FragmentEntry
->BlockSize
;
1980 // There is a free entry before us, which we know is smaller
1981 // so we'll make this entry the fragment instead
1983 FragmentEntry
= Entry
;
1986 // And then we'll remove from it the actual size required.
1987 // Now the entry is a leftover free fragment
1989 Entry
->BlockSize
-= i
;
1992 // Now let's go to the next entry after the fragment (which
1993 // used to point to our original free entry) and make it
1994 // reference the new fragment entry instead.
1996 // This is the entry that will actually end up holding the
1999 Entry
= POOL_NEXT_BLOCK(Entry
);
2000 Entry
->PreviousSize
= FragmentEntry
->BlockSize
;
2003 // And now let's go to the entry after that one and check if
2004 // it's still on the same page, and not at the end
2006 NextEntry
= POOL_BLOCK(Entry
, i
);
2007 if (PAGE_ALIGN(NextEntry
) != NextEntry
)
2010 // Make it reference the allocation entry
2012 NextEntry
->PreviousSize
= i
;
2017 // Now our (allocation) entry is the right size
2019 Entry
->BlockSize
= i
;
2022 // And the next entry is now the free fragment which contains
2023 // the remaining difference between how big the original entry
2024 // was, and the actual size the caller needs/requested.
2026 FragmentEntry
->PoolType
= 0;
2027 BlockSize
= FragmentEntry
->BlockSize
;
2030 // Now check if enough free bytes remained for us to have a
2031 // "full" entry, which contains enough bytes for a linked list
2032 // and thus can be used for allocations (up to 8 bytes...)
2034 ExpCheckPoolLinks(&PoolDesc
->ListHeads
[BlockSize
- 1]);
2038 // Insert the free entry into the free list for this size
2040 ExpInsertPoolTailList(&PoolDesc
->ListHeads
[BlockSize
- 1],
2041 POOL_FREE_BLOCK(FragmentEntry
));
2042 ExpCheckPoolLinks(POOL_FREE_BLOCK(FragmentEntry
));
2047 // We have found an entry for this allocation, so set the pool type
2048 // and release the lock since we're done
2050 Entry
->PoolType
= OriginalType
+ 1;
2051 ExpCheckPoolBlocks(Entry
);
2052 ExUnlockPool(PoolDesc
, OldIrql
);
2055 // Increment required counters
2057 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, Entry
->BlockSize
* POOL_BLOCK_SIZE
);
2058 InterlockedIncrement((PLONG
)&PoolDesc
->RunningAllocs
);
2061 // Track this allocation
2063 ExpInsertPoolTracker(Tag
,
2064 Entry
->BlockSize
* POOL_BLOCK_SIZE
,
2068 // Return the pool allocation
2070 Entry
->PoolTag
= Tag
;
2071 (POOL_FREE_BLOCK(Entry
))->Flink
= NULL
;
2072 (POOL_FREE_BLOCK(Entry
))->Blink
= NULL
;
2073 return POOL_FREE_BLOCK(Entry
);
2075 } while (++ListHead
!= &PoolDesc
->ListHeads
[POOL_LISTS_PER_PAGE
]);
2078 // There were no free entries left, so we have to allocate a new fresh page
2080 Entry
= MiAllocatePoolPages(OriginalType
, PAGE_SIZE
);
2085 // Out of memory, display current consumption
2087 MiDumpPoolConsumers(FALSE
, 0);
2091 // Must succeed pool is deprecated, but still supported. These allocation
2092 // failures must cause an immediate bugcheck
2094 if (OriginalType
& MUST_SUCCEED_POOL_MASK
)
2096 KeBugCheckEx(MUST_SUCCEED_POOL_EMPTY
,
2098 NonPagedPoolDescriptor
.TotalPages
,
2099 NonPagedPoolDescriptor
.TotalBigPages
,
2104 // Internal debugging
2109 // This flag requests printing failures, and can also further specify
2110 // breaking on failures
2112 if (ExpPoolFlags
& POOL_FLAG_DBGPRINT_ON_FAILURE
)
2114 DPRINT1("EX: ExAllocatePool (%lu, 0x%x) returning NULL\n",
2117 if (ExpPoolFlags
& POOL_FLAG_CRASH_ON_FAILURE
) DbgBreakPoint();
2121 // Finally, this flag requests an exception, which we are more than
2124 if (OriginalType
& POOL_RAISE_IF_ALLOCATION_FAILURE
)
2126 ExRaiseStatus(STATUS_INSUFFICIENT_RESOURCES
);
2130 // Return NULL to the caller in all other cases
2136 // Setup the entry data
2139 Entry
->BlockSize
= i
;
2140 Entry
->PoolType
= OriginalType
+ 1;
2143 // This page will have two entries -- one for the allocation (which we just
2144 // created above), and one for the remaining free bytes, which we're about
2145 // to create now. The free bytes are the whole page minus what was allocated
2146 // and then converted into units of block headers.
2148 BlockSize
= (PAGE_SIZE
/ POOL_BLOCK_SIZE
) - i
;
2149 FragmentEntry
= POOL_BLOCK(Entry
, i
);
2150 FragmentEntry
->Ulong1
= 0;
2151 FragmentEntry
->BlockSize
= BlockSize
;
2152 FragmentEntry
->PreviousSize
= i
;
2155 // Increment required counters
2157 InterlockedIncrement((PLONG
)&PoolDesc
->TotalPages
);
2158 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, Entry
->BlockSize
* POOL_BLOCK_SIZE
);
2161 // Now check if enough free bytes remained for us to have a "full" entry,
2162 // which contains enough bytes for a linked list and thus can be used for
2163 // allocations (up to 8 bytes...)
2165 if (FragmentEntry
->BlockSize
!= 1)
2168 // Excellent -- acquire the pool lock
2170 OldIrql
= ExLockPool(PoolDesc
);
2173 // And insert the free entry into the free list for this block size
2175 ExpCheckPoolLinks(&PoolDesc
->ListHeads
[BlockSize
- 1]);
2176 ExpInsertPoolTailList(&PoolDesc
->ListHeads
[BlockSize
- 1],
2177 POOL_FREE_BLOCK(FragmentEntry
));
2178 ExpCheckPoolLinks(POOL_FREE_BLOCK(FragmentEntry
));
2181 // Release the pool lock
2183 ExpCheckPoolBlocks(Entry
);
2184 ExUnlockPool(PoolDesc
, OldIrql
);
2189 // Simply do a sanity check
2191 ExpCheckPoolBlocks(Entry
);
2195 // Increment performance counters and track this allocation
2197 InterlockedIncrement((PLONG
)&PoolDesc
->RunningAllocs
);
2198 ExpInsertPoolTracker(Tag
,
2199 Entry
->BlockSize
* POOL_BLOCK_SIZE
,
2203 // And return the pool allocation
2205 ExpCheckPoolBlocks(Entry
);
2206 Entry
->PoolTag
= Tag
;
2207 return POOL_FREE_BLOCK(Entry
);
2215 ExAllocatePool(POOL_TYPE PoolType
,
2216 SIZE_T NumberOfBytes
)
2218 ULONG Tag
= TAG_NONE
;
2220 PLDR_DATA_TABLE_ENTRY LdrEntry
;
2222 /* Use the first four letters of the driver name, or "None" if unavailable */
2223 LdrEntry
= KeGetCurrentIrql() <= APC_LEVEL
2224 ? MiLookupDataTableEntry(_ReturnAddress())
2230 for (i
= 0; i
< min(4, LdrEntry
->BaseDllName
.Length
/ sizeof(WCHAR
)); i
++)
2231 Tag
= Tag
>> 8 | (LdrEntry
->BaseDllName
.Buffer
[i
] & 0xff) << 24;
2233 Tag
= Tag
>> 8 | ' ' << 24;
2236 return ExAllocatePoolWithTag(PoolType
, NumberOfBytes
, Tag
);
2244 ExFreePoolWithTag(IN PVOID P
,
2247 PPOOL_HEADER Entry
, NextEntry
;
2251 PPOOL_DESCRIPTOR PoolDesc
;
2253 BOOLEAN Combined
= FALSE
;
2254 PFN_NUMBER PageCount
, RealPageCount
;
2255 PKPRCB Prcb
= KeGetCurrentPrcb();
2256 PGENERAL_LOOKASIDE LookasideList
;
2260 // Check if any of the debug flags are enabled
2262 if (ExpPoolFlags
& (POOL_FLAG_CHECK_TIMERS
|
2263 POOL_FLAG_CHECK_WORKERS
|
2264 POOL_FLAG_CHECK_RESOURCES
|
2265 POOL_FLAG_VERIFIER
|
2266 POOL_FLAG_CHECK_DEADLOCK
|
2267 POOL_FLAG_SPECIAL_POOL
))
2270 // Check if special pool is enabled
2272 if (ExpPoolFlags
& POOL_FLAG_SPECIAL_POOL
)
2275 // Check if it was allocated from a special pool
2277 if (MmIsSpecialPoolAddress(P
))
2280 // Was deadlock verification also enabled? We can do some extra
2281 // checks at this point
2283 if (ExpPoolFlags
& POOL_FLAG_CHECK_DEADLOCK
)
2285 DPRINT1("Verifier not yet supported\n");
2289 // It is, so handle it via special pool free routine
2291 MmFreeSpecialPool(P
);
2297 // For non-big page allocations, we'll do a bunch of checks in here
2299 if (PAGE_ALIGN(P
) != P
)
2302 // Get the entry for this pool allocation
2303 // The pointer math here may look wrong or confusing, but it is quite right
2309 // Get the pool type
2311 PoolType
= (Entry
->PoolType
- 1) & BASE_POOL_TYPE_MASK
;
2314 // FIXME: Many other debugging checks go here
2316 ExpCheckPoolIrqlLevel(PoolType
, 0, P
);
2321 // Check if this is a big page allocation
2323 if (PAGE_ALIGN(P
) == P
)
2326 // We need to find the tag for it, so first we need to find out what
2327 // kind of allocation this was (paged or nonpaged), then we can go
2328 // ahead and try finding the tag for it. Remember to get rid of the
2329 // PROTECTED_POOL tag if it's found.
2331 // Note that if at insertion time, we failed to add the tag for a big
2332 // pool allocation, we used a special tag called 'BIG' to identify the
2333 // allocation, and we may get this tag back. In this scenario, we must
2334 // manually get the size of the allocation by actually counting through
2335 // the PFN database.
2337 PoolType
= MmDeterminePoolType(P
);
2338 ExpCheckPoolIrqlLevel(PoolType
, 0, P
);
2339 Tag
= ExpFindAndRemoveTagBigPages(P
, &PageCount
, PoolType
);
2342 DPRINT1("We do not know the size of this allocation. This is not yet supported\n");
2343 ASSERT(Tag
== ' GIB');
2344 PageCount
= 1; // We are going to lie! This might screw up accounting?
2346 else if (Tag
& PROTECTED_POOL
)
2348 Tag
&= ~PROTECTED_POOL
;
2354 if (TagToFree
&& TagToFree
!= Tag
)
2356 DPRINT1("Freeing pool - invalid tag specified: %.4s != %.4s\n", (char*)&TagToFree
, (char*)&Tag
);
2357 KeBugCheckEx(BAD_POOL_CALLER
, 0x0A, (ULONG_PTR
)P
, Tag
, TagToFree
);
2361 // We have our tag and our page count, so we can go ahead and remove this
2364 ExpRemovePoolTracker(Tag
, PageCount
<< PAGE_SHIFT
, PoolType
);
2367 // Check if any of the debug flags are enabled
2369 if (ExpPoolFlags
& (POOL_FLAG_CHECK_TIMERS
|
2370 POOL_FLAG_CHECK_WORKERS
|
2371 POOL_FLAG_CHECK_RESOURCES
|
2372 POOL_FLAG_CHECK_DEADLOCK
))
2375 // Was deadlock verification also enabled? We can do some extra
2376 // checks at this point
2378 if (ExpPoolFlags
& POOL_FLAG_CHECK_DEADLOCK
)
2380 DPRINT1("Verifier not yet supported\n");
2384 // FIXME: Many debugging checks go here
2391 PoolDesc
= PoolVector
[PoolType
];
2392 InterlockedIncrement((PLONG
)&PoolDesc
->RunningDeAllocs
);
2393 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
,
2394 -(LONG_PTR
)(PageCount
<< PAGE_SHIFT
));
2397 // Do the real free now and update the last counter with the big page count
2399 RealPageCount
= MiFreePoolPages(P
);
2400 ASSERT(RealPageCount
== PageCount
);
2401 InterlockedExchangeAdd((PLONG
)&PoolDesc
->TotalBigPages
,
2402 -(LONG
)RealPageCount
);
2407 // Get the entry for this pool allocation
2408 // The pointer math here may look wrong or confusing, but it is quite right
2412 ASSERT((ULONG_PTR
)Entry
% POOL_BLOCK_SIZE
== 0);
2415 // Get the size of the entry, and it's pool type, then load the descriptor
2416 // for this pool type
2418 BlockSize
= Entry
->BlockSize
;
2419 PoolType
= (Entry
->PoolType
- 1) & BASE_POOL_TYPE_MASK
;
2420 PoolDesc
= PoolVector
[PoolType
];
2423 // Make sure that the IRQL makes sense
2425 ExpCheckPoolIrqlLevel(PoolType
, 0, P
);
2428 // Get the pool tag and get rid of the PROTECTED_POOL flag
2430 Tag
= Entry
->PoolTag
;
2431 if (Tag
& PROTECTED_POOL
) Tag
&= ~PROTECTED_POOL
;
2436 if (TagToFree
&& TagToFree
!= Tag
)
2438 DPRINT1("Freeing pool - invalid tag specified: %.4s != %.4s\n", (char*)&TagToFree
, (char*)&Tag
);
2439 KeBugCheckEx(BAD_POOL_CALLER
, 0x0A, (ULONG_PTR
)P
, Tag
, TagToFree
);
2443 // Track the removal of this allocation
2445 ExpRemovePoolTracker(Tag
,
2446 BlockSize
* POOL_BLOCK_SIZE
,
2447 Entry
->PoolType
- 1);
2450 // Release pool quota, if any
2452 if ((Entry
->PoolType
- 1) & QUOTA_POOL_MASK
)
2454 Process
= ((PVOID
*)POOL_NEXT_BLOCK(Entry
))[-1];
2457 if (Process
->Pcb
.Header
.Type
!= ProcessObject
)
2459 DPRINT1("Object %p is not a process. Type %u, pool type 0x%x, block size %u\n",
2460 Process
, Process
->Pcb
.Header
.Type
, Entry
->PoolType
, BlockSize
);
2461 KeBugCheckEx(BAD_POOL_CALLER
,
2465 (ULONG_PTR
)Process
);
2467 PsReturnPoolQuota(Process
, PoolType
, BlockSize
* POOL_BLOCK_SIZE
);
2468 ObDereferenceObject(Process
);
2473 // Is this allocation small enough to have come from a lookaside list?
2475 if (BlockSize
<= NUMBER_POOL_LOOKASIDE_LISTS
)
2478 // Try pushing it into the per-CPU lookaside list
2480 LookasideList
= (PoolType
== PagedPool
) ?
2481 Prcb
->PPPagedLookasideList
[BlockSize
- 1].P
:
2482 Prcb
->PPNPagedLookasideList
[BlockSize
- 1].P
;
2483 LookasideList
->TotalFrees
++;
2484 if (ExQueryDepthSList(&LookasideList
->ListHead
) < LookasideList
->Depth
)
2486 LookasideList
->FreeHits
++;
2487 InterlockedPushEntrySList(&LookasideList
->ListHead
, P
);
2492 // We failed, try to push it into the global lookaside list
2494 LookasideList
= (PoolType
== PagedPool
) ?
2495 Prcb
->PPPagedLookasideList
[BlockSize
- 1].L
:
2496 Prcb
->PPNPagedLookasideList
[BlockSize
- 1].L
;
2497 LookasideList
->TotalFrees
++;
2498 if (ExQueryDepthSList(&LookasideList
->ListHead
) < LookasideList
->Depth
)
2500 LookasideList
->FreeHits
++;
2501 InterlockedPushEntrySList(&LookasideList
->ListHead
, P
);
2507 // Get the pointer to the next entry
2509 NextEntry
= POOL_BLOCK(Entry
, BlockSize
);
2512 // Update performance counters
2514 InterlockedIncrement((PLONG
)&PoolDesc
->RunningDeAllocs
);
2515 InterlockedExchangeAddSizeT(&PoolDesc
->TotalBytes
, -BlockSize
* POOL_BLOCK_SIZE
);
2518 // Acquire the pool lock
2520 OldIrql
= ExLockPool(PoolDesc
);
2523 // Check if the next allocation is at the end of the page
2525 ExpCheckPoolBlocks(Entry
);
2526 if (PAGE_ALIGN(NextEntry
) != NextEntry
)
2529 // We may be able to combine the block if it's free
2531 if (NextEntry
->PoolType
== 0)
2534 // The next block is free, so we'll do a combine
2539 // Make sure there's actual data in the block -- anything smaller
2540 // than this means we only have the header, so there's no linked list
2543 if ((NextEntry
->BlockSize
!= 1))
2546 // The block is at least big enough to have a linked list, so go
2547 // ahead and remove it
2549 ExpCheckPoolLinks(POOL_FREE_BLOCK(NextEntry
));
2550 ExpRemovePoolEntryList(POOL_FREE_BLOCK(NextEntry
));
2551 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Flink
));
2552 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Blink
));
2556 // Our entry is now combined with the next entry
2558 Entry
->BlockSize
= Entry
->BlockSize
+ NextEntry
->BlockSize
;
2563 // Now check if there was a previous entry on the same page as us
2565 if (Entry
->PreviousSize
)
2568 // Great, grab that entry and check if it's free
2570 NextEntry
= POOL_PREV_BLOCK(Entry
);
2571 if (NextEntry
->PoolType
== 0)
2574 // It is, so we can do a combine
2579 // Make sure there's actual data in the block -- anything smaller
2580 // than this means we only have the header so there's no linked list
2583 if ((NextEntry
->BlockSize
!= 1))
2586 // The block is at least big enough to have a linked list, so go
2587 // ahead and remove it
2589 ExpCheckPoolLinks(POOL_FREE_BLOCK(NextEntry
));
2590 ExpRemovePoolEntryList(POOL_FREE_BLOCK(NextEntry
));
2591 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Flink
));
2592 ExpCheckPoolLinks(ExpDecodePoolLink((POOL_FREE_BLOCK(NextEntry
))->Blink
));
2596 // Combine our original block (which might've already been combined
2597 // with the next block), into the previous block
2599 NextEntry
->BlockSize
= NextEntry
->BlockSize
+ Entry
->BlockSize
;
2602 // And now we'll work with the previous block instead
2609 // By now, it may have been possible for our combined blocks to actually
2610 // have made up a full page (if there were only 2-3 allocations on the
2611 // page, they could've all been combined).
2613 if ((PAGE_ALIGN(Entry
) == Entry
) &&
2614 (PAGE_ALIGN(POOL_NEXT_BLOCK(Entry
)) == POOL_NEXT_BLOCK(Entry
)))
2617 // In this case, release the pool lock, update the performance counter,
2618 // and free the page
2620 ExUnlockPool(PoolDesc
, OldIrql
);
2621 InterlockedExchangeAdd((PLONG
)&PoolDesc
->TotalPages
, -1);
2622 MiFreePoolPages(Entry
);
2627 // Otherwise, we now have a free block (or a combination of 2 or 3)
2629 Entry
->PoolType
= 0;
2630 BlockSize
= Entry
->BlockSize
;
2631 ASSERT(BlockSize
!= 1);
2634 // Check if we actually did combine it with anyone
2639 // Get the first combined block (either our original to begin with, or
2640 // the one after the original, depending if we combined with the previous)
2642 NextEntry
= POOL_NEXT_BLOCK(Entry
);
2645 // As long as the next block isn't on a page boundary, have it point
2648 if (PAGE_ALIGN(NextEntry
) != NextEntry
) NextEntry
->PreviousSize
= BlockSize
;
2652 // Insert this new free block, and release the pool lock
2654 ExpInsertPoolHeadList(&PoolDesc
->ListHeads
[BlockSize
- 1], POOL_FREE_BLOCK(Entry
));
2655 ExpCheckPoolLinks(POOL_FREE_BLOCK(Entry
));
2656 ExUnlockPool(PoolDesc
, OldIrql
);
2667 // Just free without checking for the tag
2669 ExFreePoolWithTag(P
, 0);
2677 ExQueryPoolBlockSize(IN PVOID PoolBlock
,
2678 OUT PBOOLEAN QuotaCharged
)
2693 ExAllocatePoolWithQuota(IN POOL_TYPE PoolType
,
2694 IN SIZE_T NumberOfBytes
)
2697 // Allocate the pool
2699 return ExAllocatePoolWithQuotaTag(PoolType
, NumberOfBytes
, TAG_NONE
);
2707 ExAllocatePoolWithTagPriority(IN POOL_TYPE PoolType
,
2708 IN SIZE_T NumberOfBytes
,
2710 IN EX_POOL_PRIORITY Priority
)
2715 // Allocate the pool
2717 Buffer
= ExAllocatePoolWithTag(PoolType
, NumberOfBytes
, Tag
);
2731 ExAllocatePoolWithQuotaTag(IN POOL_TYPE PoolType
,
2732 IN SIZE_T NumberOfBytes
,
2735 BOOLEAN Raise
= TRUE
;
2739 PEPROCESS Process
= PsGetCurrentProcess();
2742 // Check if we should fail instead of raising an exception
2744 if (PoolType
& POOL_QUOTA_FAIL_INSTEAD_OF_RAISE
)
2747 PoolType
&= ~POOL_QUOTA_FAIL_INSTEAD_OF_RAISE
;
2751 // Inject the pool quota mask
2753 PoolType
+= QUOTA_POOL_MASK
;
2756 // Check if we have enough space to add the quota owner process, as long as
2757 // this isn't the system process, which never gets charged quota
2759 ASSERT(NumberOfBytes
!= 0);
2760 if ((NumberOfBytes
<= (PAGE_SIZE
- POOL_BLOCK_SIZE
- sizeof(PVOID
))) &&
2761 (Process
!= PsInitialSystemProcess
))
2764 // Add space for our EPROCESS pointer
2766 NumberOfBytes
+= sizeof(PEPROCESS
);
2771 // We won't be able to store the pointer, so don't use quota for this
2773 PoolType
-= QUOTA_POOL_MASK
;
2777 // Allocate the pool buffer now
2779 Buffer
= ExAllocatePoolWithTag(PoolType
, NumberOfBytes
, Tag
);
2782 // If the buffer is page-aligned, this is a large page allocation and we
2785 if (PAGE_ALIGN(Buffer
) != Buffer
)
2788 // Also if special pool is enabled, and this was allocated from there,
2789 // we won't touch it either
2791 if ((ExpPoolFlags
& POOL_FLAG_SPECIAL_POOL
) &&
2792 (MmIsSpecialPoolAddress(Buffer
)))
2798 // If it wasn't actually allocated with quota charges, ignore it too
2800 if (!(PoolType
& QUOTA_POOL_MASK
)) return Buffer
;
2803 // If this is the system process, we don't charge quota, so ignore
2805 if (Process
== PsInitialSystemProcess
) return Buffer
;
2808 // Actually go and charge quota for the process now
2810 Entry
= POOL_ENTRY(Buffer
);
2811 Status
= PsChargeProcessPoolQuota(Process
,
2812 PoolType
& BASE_POOL_TYPE_MASK
,
2813 Entry
->BlockSize
* POOL_BLOCK_SIZE
);
2814 if (!NT_SUCCESS(Status
))
2817 // Quota failed, back out the allocation, clear the owner, and fail
2819 ((PVOID
*)POOL_NEXT_BLOCK(Entry
))[-1] = NULL
;
2820 ExFreePoolWithTag(Buffer
, Tag
);
2821 if (Raise
) RtlRaiseStatus(Status
);
2826 // Quota worked, write the owner and then reference it before returning
2828 ((PVOID
*)POOL_NEXT_BLOCK(Entry
))[-1] = Process
;
2829 ObReferenceObject(Process
);
2831 else if (!(Buffer
) && (Raise
))
2834 // The allocation failed, raise an error if we are in raise mode
2836 RtlRaiseStatus(STATUS_INSUFFICIENT_RESOURCES
);
2840 // Return the allocated buffer
2845 #if DBG && defined(KDBG)
2852 ULONG_PTR Address
= 0, Flags
= 0;
2861 if (!KdbpGetHexNumber(Argv
[1], &Address
))
2863 KdbpPrint("Invalid parameter: %s\n", Argv
[0]);
2871 if (!KdbpGetHexNumber(Argv
[1], &Flags
))
2873 KdbpPrint("Invalid parameter: %s\n", Argv
[0]);
2878 /* Check if we got an address */
2881 /* Get the base page */
2882 PoolPage
= PAGE_ALIGN(Address
);
2886 KdbpPrint("Heap is unimplemented\n");
2890 /* No paging support! */
2891 if (!MmIsAddressValid(PoolPage
))
2893 KdbpPrint("Address not accessible!\n");
2898 if ((Address
>= (ULONG_PTR
)MmPagedPoolStart
) && (Address
<= (ULONG_PTR
)MmPagedPoolEnd
))
2899 KdbpPrint("Allocation is from PagedPool region\n");
2900 else if ((Address
>= (ULONG_PTR
)MmNonPagedPoolStart
) && (Address
<= (ULONG_PTR
)MmNonPagedPoolEnd
))
2901 KdbpPrint("Allocation is from NonPagedPool region\n");
2904 KdbpPrint("Address 0x%p is not within any pool!\n", (PVOID
)Address
);
2908 /* Loop all entries of that page */
2912 /* Check if the address is within that entry */
2913 ThisOne
= ((Address
>= (ULONG_PTR
)Entry
) &&
2914 (Address
< (ULONG_PTR
)(Entry
+ Entry
->BlockSize
)));
2916 if (!(Flags
& 1) || ThisOne
)
2918 /* Print the line */
2919 KdbpPrint("%c%p size: %4d previous size: %4d %s %.4s\n",
2920 ThisOne
? '*' : ' ', Entry
, Entry
->BlockSize
, Entry
->PreviousSize
,
2921 (Flags
& 0x80000000) ? "" : (Entry
->PoolType
? "(Allocated)" : "(Free) "),
2922 (Flags
& 0x80000000) ? "" : (PCHAR
)&Entry
->PoolTag
);
2927 Data
= (PULONG
)(Entry
+ 1);
2928 KdbpPrint(" %p %08lx %08lx %08lx %08lx\n"
2929 " %p %08lx %08lx %08lx %08lx\n",
2930 &Data
[0], Data
[0], Data
[1], Data
[2], Data
[3],
2931 &Data
[4], Data
[4], Data
[5], Data
[6], Data
[7]);
2934 /* Go to next entry */
2935 Entry
= POOL_BLOCK(Entry
, Entry
->BlockSize
);
2937 while ((Entry
->BlockSize
!= 0) && ((ULONG_PTR
)Entry
< (ULONG_PTR
)PoolPage
+ PAGE_SIZE
));
2955 Len
= strlen(Argv
[1]);
2960 RtlCopyMemory(Tmp
, Argv
[1], Len
* sizeof(CHAR
));
2962 Tag
= *((PULONG
)Tmp
);
2965 MiDumpPoolConsumers(TRUE
, Tag
);
2970 #endif // DBG && KDBG