[NTOS]: Add an extra layer of protection for freed nonpaged pool: write a 4-byte...
[reactos.git] / reactos / ntoskrnl / mm / ARM3 / pool.c
1 /*
2 * PROJECT: ReactOS Kernel
3 * LICENSE: BSD - See COPYING.ARM in the top level directory
4 * FILE: ntoskrnl/mm/ARM3/pool.c
5 * PURPOSE: ARM Memory Manager Pool Allocator
6 * PROGRAMMERS: ReactOS Portable Systems Group
7 */
8
9 /* INCLUDES *******************************************************************/
10
11 #include <ntoskrnl.h>
12 #define NDEBUG
13 #include <debug.h>
14
15 #line 15 "ARMĀ³::POOL"
16 #define MODULE_INVOLVED_IN_ARM3
17 #include "../ARM3/miarm.h"
18
19 /* GLOBALS ********************************************************************/
20
21 LIST_ENTRY MmNonPagedPoolFreeListHead[MI_MAX_FREE_PAGE_LISTS];
22 PFN_NUMBER MmNumberOfFreeNonPagedPool, MiExpansionPoolPagesInitialCharge;
23 PVOID MmNonPagedPoolEnd0;
24 PFN_NUMBER MiStartOfInitialPoolFrame, MiEndOfInitialPoolFrame;
25 KGUARDED_MUTEX MmPagedPoolMutex;
26 MM_PAGED_POOL_INFO MmPagedPoolInfo;
27 SIZE_T MmAllocatedNonPagedPool;
28 ULONG MmSpecialPoolTag;
29 ULONG MmConsumedPoolPercentage;
30 BOOLEAN MmProtectFreedNonPagedPool;
31
32 /* PRIVATE FUNCTIONS **********************************************************/
33
34 VOID
35 NTAPI
36 MiProtectFreeNonPagedPool(IN PVOID VirtualAddress,
37 IN ULONG PageCount)
38 {
39 PMMPTE PointerPte, LastPte;
40 MMPTE TempPte;
41
42 /* If pool is physical, can't protect PTEs */
43 if (MI_IS_PHYSICAL_ADDRESS(VirtualAddress)) return;
44
45 /* Get PTE pointers and loop */
46 PointerPte = MiAddressToPte(VirtualAddress);
47 LastPte = PointerPte + PageCount;
48 do
49 {
50 /* Capture the PTE for safety */
51 TempPte = *PointerPte;
52
53 /* Mark it as an invalid PTE, set proto bit to recognize it as pool */
54 TempPte.u.Hard.Valid = 0;
55 TempPte.u.Soft.Prototype = 1;
56 MI_WRITE_INVALID_PTE(PointerPte, TempPte);
57 } while (++PointerPte < LastPte);
58
59 /* Flush the TLB */
60 KeFlushEntireTb(TRUE, TRUE);
61 }
62
63 BOOLEAN
64 NTAPI
65 MiUnProtectFreeNonPagedPool(IN PVOID VirtualAddress,
66 IN ULONG PageCount)
67 {
68 PMMPTE PointerPte;
69 MMPTE TempPte;
70 PFN_NUMBER UnprotectedPages = 0;
71
72 /* If pool is physical, can't protect PTEs */
73 if (MI_IS_PHYSICAL_ADDRESS(VirtualAddress)) return FALSE;
74
75 /* Get, and capture the PTE */
76 PointerPte = MiAddressToPte(VirtualAddress);
77 TempPte = *PointerPte;
78
79 /* Loop protected PTEs */
80 while ((TempPte.u.Hard.Valid == 0) && (TempPte.u.Soft.Prototype == 1))
81 {
82 /* Unprotect the PTE */
83 TempPte.u.Hard.Valid = 1;
84 TempPte.u.Soft.Prototype = 0;
85 MI_WRITE_VALID_PTE(PointerPte, TempPte);
86
87 /* One more page */
88 if (++UnprotectedPages == PageCount) break;
89
90 /* Capture next PTE */
91 TempPte = *(++PointerPte);
92 }
93
94 /* Return if any pages were unprotected */
95 return UnprotectedPages ? TRUE : FALSE;
96 }
97
98 VOID
99 FORCEINLINE
100 MiProtectedPoolUnProtectLinks(IN PLIST_ENTRY Links,
101 OUT PVOID* PoolFlink,
102 OUT PVOID* PoolBlink)
103 {
104 BOOLEAN Safe;
105 PVOID PoolVa;
106
107 /* Initialize variables */
108 *PoolFlink = *PoolBlink = NULL;
109
110 /* Check if the list has entries */
111 if (IsListEmpty(Links) == FALSE)
112 {
113 /* We are going to need to forward link to do an insert */
114 PoolVa = Links->Flink;
115
116 /* So make it safe to access */
117 Safe = MiUnProtectFreeNonPagedPool(PoolVa, 1);
118 if (Safe) PoolFlink = PoolVa;
119 }
120
121 /* Are we going to need a backward link too? */
122 if (Links != Links->Blink)
123 {
124 /* Get the head's backward link for the insert */
125 PoolVa = Links->Blink;
126
127 /* Make it safe to access */
128 Safe = MiUnProtectFreeNonPagedPool(PoolVa, 1);
129 if (Safe) PoolBlink = PoolVa;
130 }
131 }
132
133 VOID
134 FORCEINLINE
135 MiProtectedPoolProtectLinks(IN PVOID PoolFlink,
136 IN PVOID PoolBlink)
137 {
138 /* Reprotect the pages, if they got unprotected earlier */
139 if (PoolFlink) MiProtectFreeNonPagedPool(PoolFlink, 1);
140 if (PoolBlink) MiProtectFreeNonPagedPool(PoolBlink, 1);
141 }
142
143 VOID
144 NTAPI
145 MiProtectedPoolInsertList(IN PLIST_ENTRY ListHead,
146 IN PLIST_ENTRY Entry,
147 IN BOOLEAN Critical)
148 {
149 PVOID PoolFlink, PoolBlink;
150
151 /* Make the list accessible */
152 MiProtectedPoolUnProtectLinks(ListHead, &PoolFlink, &PoolBlink);
153
154 /* Now insert in the right position */
155 Critical ? InsertHeadList(ListHead, Entry) : InsertTailList(ListHead, Entry);
156
157 /* And reprotect the pages containing the free links */
158 MiProtectedPoolProtectLinks(PoolFlink, PoolBlink);
159 }
160
161 VOID
162 NTAPI
163 MiProtectedPoolRemoveEntryList(IN PLIST_ENTRY Entry)
164 {
165 PVOID PoolFlink, PoolBlink;
166
167 /* Make the list accessible */
168 MiProtectedPoolUnProtectLinks(Entry, &PoolFlink, &PoolBlink);
169
170 /* Now remove */
171 RemoveEntryList(Entry);
172
173 /* And reprotect the pages containing the free links */
174 if (PoolFlink) MiProtectFreeNonPagedPool(PoolFlink, 1);
175 if (PoolBlink) MiProtectFreeNonPagedPool(PoolBlink, 1);
176 }
177
178 VOID
179 NTAPI
180 MiInitializeNonPagedPoolThresholds(VOID)
181 {
182 PFN_NUMBER Size = MmMaximumNonPagedPoolInPages;
183
184 /* Default low threshold of 8MB or one third of nonpaged pool */
185 MiLowNonPagedPoolThreshold = (8 * _1MB) >> PAGE_SHIFT;
186 MiLowNonPagedPoolThreshold = min(MiLowNonPagedPoolThreshold, Size / 3);
187
188 /* Default high threshold of 20MB or 50% */
189 MiHighNonPagedPoolThreshold = (20 * _1MB) >> PAGE_SHIFT;
190 MiHighNonPagedPoolThreshold = min(MiHighNonPagedPoolThreshold, Size / 2);
191 ASSERT(MiLowNonPagedPoolThreshold < MiHighNonPagedPoolThreshold);
192 }
193
194 VOID
195 NTAPI
196 MiInitializePoolEvents(VOID)
197 {
198 KIRQL OldIrql;
199 PFN_NUMBER FreePoolInPages;
200
201 /* Lock paged pool */
202 KeAcquireGuardedMutex(&MmPagedPoolMutex);
203
204 /* Total size of the paged pool minus the allocated size, is free */
205 FreePoolInPages = MmSizeOfPagedPoolInPages - MmPagedPoolInfo.AllocatedPagedPool;
206
207 /* Check the initial state high state */
208 if (FreePoolInPages >= MiHighPagedPoolThreshold)
209 {
210 /* We have plenty of pool */
211 KeSetEvent(MiHighPagedPoolEvent, 0, FALSE);
212 }
213 else
214 {
215 /* We don't */
216 KeClearEvent(MiHighPagedPoolEvent);
217 }
218
219 /* Check the initial low state */
220 if (FreePoolInPages <= MiLowPagedPoolThreshold)
221 {
222 /* We're very low in free pool memory */
223 KeSetEvent(MiLowPagedPoolEvent, 0, FALSE);
224 }
225 else
226 {
227 /* We're not */
228 KeClearEvent(MiLowPagedPoolEvent);
229 }
230
231 /* Release the paged pool lock */
232 KeReleaseGuardedMutex(&MmPagedPoolMutex);
233
234 /* Now it's time for the nonpaged pool lock */
235 OldIrql = KeAcquireQueuedSpinLock(LockQueueMmNonPagedPoolLock);
236
237 /* Free pages are the maximum minus what's been allocated */
238 FreePoolInPages = MmMaximumNonPagedPoolInPages - MmAllocatedNonPagedPool;
239
240 /* Check if we have plenty */
241 if (FreePoolInPages >= MiHighNonPagedPoolThreshold)
242 {
243 /* We do, set the event */
244 KeSetEvent(MiHighNonPagedPoolEvent, 0, FALSE);
245 }
246 else
247 {
248 /* We don't, clear the event */
249 KeClearEvent(MiHighNonPagedPoolEvent);
250 }
251
252 /* Check if we have very little */
253 if (FreePoolInPages <= MiLowNonPagedPoolThreshold)
254 {
255 /* We do, set the event */
256 KeSetEvent(MiLowNonPagedPoolEvent, 0, FALSE);
257 }
258 else
259 {
260 /* We don't, clear it */
261 KeClearEvent(MiLowNonPagedPoolEvent);
262 }
263
264 /* We're done, release the nonpaged pool lock */
265 KeReleaseQueuedSpinLock(LockQueueMmNonPagedPoolLock, OldIrql);
266 }
267
268 VOID
269 NTAPI
270 MiInitializeNonPagedPool(VOID)
271 {
272 ULONG i;
273 PFN_NUMBER PoolPages;
274 PMMFREE_POOL_ENTRY FreeEntry, FirstEntry;
275 PMMPTE PointerPte;
276 PAGED_CODE();
277
278 //
279 // We keep 4 lists of free pages (4 lists help avoid contention)
280 //
281 for (i = 0; i < MI_MAX_FREE_PAGE_LISTS; i++)
282 {
283 //
284 // Initialize each of them
285 //
286 InitializeListHead(&MmNonPagedPoolFreeListHead[i]);
287 }
288
289 //
290 // Calculate how many pages the initial nonpaged pool has
291 //
292 PoolPages = BYTES_TO_PAGES(MmSizeOfNonPagedPoolInBytes);
293 MmNumberOfFreeNonPagedPool = PoolPages;
294
295 //
296 // Initialize the first free entry
297 //
298 FreeEntry = MmNonPagedPoolStart;
299 FirstEntry = FreeEntry;
300 FreeEntry->Size = PoolPages;
301 FreeEntry->Signature = MM_FREE_POOL_SIGNATURE;
302 FreeEntry->Owner = FirstEntry;
303
304 //
305 // Insert it into the last list
306 //
307 InsertHeadList(&MmNonPagedPoolFreeListHead[MI_MAX_FREE_PAGE_LISTS - 1],
308 &FreeEntry->List);
309
310 //
311 // Now create free entries for every single other page
312 //
313 while (PoolPages-- > 1)
314 {
315 //
316 // Link them all back to the original entry
317 //
318 FreeEntry = (PMMFREE_POOL_ENTRY)((ULONG_PTR)FreeEntry + PAGE_SIZE);
319 FreeEntry->Owner = FirstEntry;
320 FreeEntry->Signature = MM_FREE_POOL_SIGNATURE;
321 }
322
323 //
324 // Validate and remember first allocated pool page
325 //
326 PointerPte = MiAddressToPte(MmNonPagedPoolStart);
327 ASSERT(PointerPte->u.Hard.Valid == 1);
328 MiStartOfInitialPoolFrame = PFN_FROM_PTE(PointerPte);
329
330 //
331 // Keep track of where initial nonpaged pool ends
332 //
333 MmNonPagedPoolEnd0 = (PVOID)((ULONG_PTR)MmNonPagedPoolStart +
334 MmSizeOfNonPagedPoolInBytes);
335
336 //
337 // Validate and remember last allocated pool page
338 //
339 PointerPte = MiAddressToPte((PVOID)((ULONG_PTR)MmNonPagedPoolEnd0 - 1));
340 ASSERT(PointerPte->u.Hard.Valid == 1);
341 MiEndOfInitialPoolFrame = PFN_FROM_PTE(PointerPte);
342
343 //
344 // Validate the first nonpaged pool expansion page (which is a guard page)
345 //
346 PointerPte = MiAddressToPte(MmNonPagedPoolExpansionStart);
347 ASSERT(PointerPte->u.Hard.Valid == 0);
348
349 //
350 // Calculate the size of the expansion region alone
351 //
352 MiExpansionPoolPagesInitialCharge =
353 BYTES_TO_PAGES(MmMaximumNonPagedPoolInBytes - MmSizeOfNonPagedPoolInBytes);
354
355 //
356 // Remove 2 pages, since there's a guard page on top and on the bottom
357 //
358 MiExpansionPoolPagesInitialCharge -= 2;
359
360 //
361 // Now initialize the nonpaged pool expansion PTE space. Remember there's a
362 // guard page on top so make sure to skip it. The bottom guard page will be
363 // guaranteed by the fact our size is off by one.
364 //
365 MiInitializeSystemPtes(PointerPte + 1,
366 MiExpansionPoolPagesInitialCharge,
367 NonPagedPoolExpansion);
368 }
369
370 PVOID
371 NTAPI
372 MiAllocatePoolPages(IN POOL_TYPE PoolType,
373 IN SIZE_T SizeInBytes)
374 {
375 PFN_NUMBER SizeInPages, PageFrameNumber;
376 ULONG i;
377 KIRQL OldIrql;
378 PLIST_ENTRY NextEntry, NextHead, LastHead;
379 PMMPTE PointerPte, StartPte;
380 MMPTE TempPte;
381 PMMPFN Pfn1;
382 PVOID BaseVa, BaseVaStart;
383 PMMFREE_POOL_ENTRY FreeEntry;
384 PKSPIN_LOCK_QUEUE LockQueue;
385
386 //
387 // Figure out how big the allocation is in pages
388 //
389 SizeInPages = BYTES_TO_PAGES(SizeInBytes);
390
391 //
392 // Handle paged pool
393 //
394 if ((PoolType & BASE_POOL_TYPE_MASK) == PagedPool)
395 {
396 //
397 // Lock the paged pool mutex
398 //
399 KeAcquireGuardedMutex(&MmPagedPoolMutex);
400
401 //
402 // Find some empty allocation space
403 //
404 i = RtlFindClearBitsAndSet(MmPagedPoolInfo.PagedPoolAllocationMap,
405 SizeInPages,
406 MmPagedPoolInfo.PagedPoolHint);
407 if (i == 0xFFFFFFFF)
408 {
409 //
410 // Get the page bit count
411 //
412 i = ((SizeInPages - 1) / 1024) + 1;
413 DPRINT1("Paged pool expansion: %d %x\n", i, SizeInPages);
414
415 //
416 // Check if there is enougn paged pool expansion space left
417 //
418 if (MmPagedPoolInfo.NextPdeForPagedPoolExpansion >
419 MiAddressToPte(MmPagedPoolInfo.LastPteForPagedPool))
420 {
421 //
422 // Out of memory!
423 //
424 DPRINT1("OUT OF PAGED POOL!!!\n");
425 KeReleaseGuardedMutex(&MmPagedPoolMutex);
426 return NULL;
427 }
428
429 //
430 // Check if we'll have to expand past the last PTE we have available
431 //
432 if (((i - 1) + MmPagedPoolInfo.NextPdeForPagedPoolExpansion) >
433 MiAddressToPte(MmPagedPoolInfo.LastPteForPagedPool))
434 {
435 //
436 // We can only support this much then
437 //
438 SizeInPages = MiAddressToPte(MmPagedPoolInfo.LastPteForPagedPool) -
439 MmPagedPoolInfo.NextPdeForPagedPoolExpansion +
440 1;
441 ASSERT(SizeInPages < i);
442 i = SizeInPages;
443 }
444 else
445 {
446 //
447 // Otherwise, there is plenty of space left for this expansion
448 //
449 SizeInPages = i;
450 }
451
452 //
453 // Get the template PTE we'll use to expand
454 //
455 TempPte = ValidKernelPte;
456
457 //
458 // Get the first PTE in expansion space
459 //
460 PointerPte = MmPagedPoolInfo.NextPdeForPagedPoolExpansion;
461 BaseVa = MiPteToAddress(PointerPte);
462 BaseVaStart = BaseVa;
463
464 //
465 // Lock the PFN database and loop pages
466 //
467 OldIrql = KeAcquireQueuedSpinLock(LockQueuePfnLock);
468 do
469 {
470 //
471 // It should not already be valid
472 //
473 ASSERT(PointerPte->u.Hard.Valid == 0);
474
475 /* Request a page */
476 PageFrameNumber = MiRemoveAnyPage(0);
477 TempPte.u.Hard.PageFrameNumber = PageFrameNumber;
478
479 #if (_MI_PAGING_LEVELS >= 3)
480 /* On PAE/x64 systems, there's no double-buffering */
481 ASSERT(FALSE);
482 #else
483 //
484 // Save it into our double-buffered system page directory
485 //
486 /* This seems to be making the assumption that one PDE is one page long */
487 C_ASSERT(PAGE_SIZE == (PD_COUNT * (sizeof(MMPTE) * PDE_COUNT)));
488 MmSystemPagePtes[(ULONG_PTR)PointerPte & (PAGE_SIZE - 1) /
489 sizeof(MMPTE)] = TempPte;
490
491 /* Initialize the PFN */
492 MiInitializePfnForOtherProcess(PageFrameNumber,
493 PointerPte,
494 MmSystemPageDirectory[(PointerPte - (PMMPTE)PDE_BASE) / PDE_COUNT]);
495
496 /* Write the actual PTE now */
497 MI_WRITE_VALID_PTE(PointerPte++, TempPte);
498 #endif
499 //
500 // Move on to the next expansion address
501 //
502 BaseVa = (PVOID)((ULONG_PTR)BaseVa + PAGE_SIZE);
503 } while (--i > 0);
504
505 //
506 // Release the PFN database lock
507 //
508 KeReleaseQueuedSpinLock(LockQueuePfnLock, OldIrql);
509
510 //
511 // These pages are now available, clear their availablity bits
512 //
513 RtlClearBits(MmPagedPoolInfo.PagedPoolAllocationMap,
514 (MmPagedPoolInfo.NextPdeForPagedPoolExpansion -
515 MiAddressToPte(MmPagedPoolInfo.FirstPteForPagedPool)) *
516 1024,
517 SizeInPages * 1024);
518
519 //
520 // Update the next expansion location
521 //
522 MmPagedPoolInfo.NextPdeForPagedPoolExpansion += SizeInPages;
523
524 //
525 // Zero out the newly available memory
526 //
527 RtlZeroMemory(BaseVaStart, SizeInPages * PAGE_SIZE);
528
529 //
530 // Now try consuming the pages again
531 //
532 SizeInPages = BYTES_TO_PAGES(SizeInBytes);
533 i = RtlFindClearBitsAndSet(MmPagedPoolInfo.PagedPoolAllocationMap,
534 SizeInPages,
535 0);
536 if (i == 0xFFFFFFFF)
537 {
538 //
539 // Out of memory!
540 //
541 DPRINT1("OUT OF PAGED POOL!!!\n");
542 KeReleaseGuardedMutex(&MmPagedPoolMutex);
543 return NULL;
544 }
545 }
546
547 //
548 // Update the pool hint if the request was just one page
549 //
550 if (SizeInPages == 1) MmPagedPoolInfo.PagedPoolHint = i + 1;
551
552 //
553 // Update the end bitmap so we know the bounds of this allocation when
554 // the time comes to free it
555 //
556 RtlSetBit(MmPagedPoolInfo.EndOfPagedPoolBitmap, i + SizeInPages - 1);
557
558 //
559 // Now we can release the lock (it mainly protects the bitmap)
560 //
561 KeReleaseGuardedMutex(&MmPagedPoolMutex);
562
563 //
564 // Now figure out where this allocation starts
565 //
566 BaseVa = (PVOID)((ULONG_PTR)MmPagedPoolStart + (i << PAGE_SHIFT));
567
568 //
569 // Flush the TLB
570 //
571 KeFlushEntireTb(TRUE, TRUE);
572
573 /* Setup a demand-zero writable PTE */
574 MI_MAKE_SOFTWARE_PTE(&TempPte, MM_READWRITE);
575
576 //
577 // Find the first and last PTE, then loop them all
578 //
579 PointerPte = MiAddressToPte(BaseVa);
580 StartPte = PointerPte + SizeInPages;
581 do
582 {
583 //
584 // Write the demand zero PTE and keep going
585 //
586 ASSERT(PointerPte->u.Hard.Valid == 0);
587 *PointerPte++ = TempPte;
588 } while (PointerPte < StartPte);
589
590 //
591 // Return the allocation address to the caller
592 //
593 return BaseVa;
594 }
595
596 //
597 // Allocations of less than 4 pages go into their individual buckets
598 //
599 i = SizeInPages - 1;
600 if (i >= MI_MAX_FREE_PAGE_LISTS) i = MI_MAX_FREE_PAGE_LISTS - 1;
601
602 //
603 // Loop through all the free page lists based on the page index
604 //
605 NextHead = &MmNonPagedPoolFreeListHead[i];
606 LastHead = &MmNonPagedPoolFreeListHead[MI_MAX_FREE_PAGE_LISTS];
607
608 //
609 // Acquire the nonpaged pool lock
610 //
611 OldIrql = KeAcquireQueuedSpinLock(LockQueueMmNonPagedPoolLock);
612 do
613 {
614 //
615 // Now loop through all the free page entries in this given list
616 //
617 NextEntry = NextHead->Flink;
618 while (NextEntry != NextHead)
619 {
620 /* Is freed non paged pool enabled */
621 if (MmProtectFreedNonPagedPool)
622 {
623 /* We need to be able to touch this page, unprotect it */
624 MiUnProtectFreeNonPagedPool(NextEntry, 0);
625 }
626
627 //
628 // Grab the entry and see if it can handle our allocation
629 //
630 FreeEntry = CONTAINING_RECORD(NextEntry, MMFREE_POOL_ENTRY, List);
631 ASSERT(FreeEntry->Signature == MM_FREE_POOL_SIGNATURE);
632 if (FreeEntry->Size >= SizeInPages)
633 {
634 //
635 // It does, so consume the pages from here
636 //
637 FreeEntry->Size -= SizeInPages;
638
639 //
640 // The allocation will begin in this free page area
641 //
642 BaseVa = (PVOID)((ULONG_PTR)FreeEntry +
643 (FreeEntry->Size << PAGE_SHIFT));
644
645 /* Remove the item from the list, depending if pool is protected */
646 MmProtectFreedNonPagedPool ?
647 MiProtectedPoolRemoveEntryList(&FreeEntry->List) :
648 RemoveEntryList(&FreeEntry->List);
649
650 //
651 // However, check if its' still got space left
652 //
653 if (FreeEntry->Size != 0)
654 {
655 /* Check which list to insert this entry into */
656 i = FreeEntry->Size - 1;
657 if (i >= MI_MAX_FREE_PAGE_LISTS) i = MI_MAX_FREE_PAGE_LISTS - 1;
658
659 /* Insert the entry into the free list head, check for prot. pool */
660 MmProtectFreedNonPagedPool ?
661 MiProtectedPoolInsertList(&MmNonPagedPoolFreeListHead[i], &FreeEntry->List, TRUE) :
662 InsertTailList(&MmNonPagedPoolFreeListHead[i], &FreeEntry->List);
663
664 /* Is freed non paged pool protected? */
665 if (MmProtectFreedNonPagedPool)
666 {
667 /* Protect the freed pool! */
668 MiProtectFreeNonPagedPool(FreeEntry, FreeEntry->Size);
669 }
670 }
671
672 //
673 // Grab the PTE for this allocation
674 //
675 PointerPte = MiAddressToPte(BaseVa);
676 ASSERT(PointerPte->u.Hard.Valid == 1);
677
678 //
679 // Grab the PFN NextEntry and index
680 //
681 Pfn1 = MiGetPfnEntry(PFN_FROM_PTE(PointerPte));
682
683 //
684 // Now mark it as the beginning of an allocation
685 //
686 ASSERT(Pfn1->u3.e1.StartOfAllocation == 0);
687 Pfn1->u3.e1.StartOfAllocation = 1;
688
689 //
690 // Check if the allocation is larger than one page
691 //
692 if (SizeInPages != 1)
693 {
694 //
695 // Navigate to the last PFN entry and PTE
696 //
697 PointerPte += SizeInPages - 1;
698 ASSERT(PointerPte->u.Hard.Valid == 1);
699 Pfn1 = MiGetPfnEntry(PointerPte->u.Hard.PageFrameNumber);
700 }
701
702 //
703 // Mark this PFN as the last (might be the same as the first)
704 //
705 ASSERT(Pfn1->u3.e1.EndOfAllocation == 0);
706 Pfn1->u3.e1.EndOfAllocation = 1;
707
708 //
709 // Release the nonpaged pool lock, and return the allocation
710 //
711 KeReleaseQueuedSpinLock(LockQueueMmNonPagedPoolLock, OldIrql);
712 return BaseVa;
713 }
714
715 //
716 // Try the next free page entry
717 //
718 NextEntry = FreeEntry->List.Flink;
719
720 /* Is freed non paged pool protected? */
721 if (MmProtectFreedNonPagedPool)
722 {
723 /* Protect the freed pool! */
724 MiProtectFreeNonPagedPool(FreeEntry, FreeEntry->Size);
725 }
726 }
727 } while (++NextHead < LastHead);
728
729 //
730 // If we got here, we're out of space.
731 // Start by releasing the lock
732 //
733 KeReleaseQueuedSpinLock(LockQueueMmNonPagedPoolLock, OldIrql);
734
735 //
736 // Allocate some system PTEs
737 //
738 StartPte = MiReserveSystemPtes(SizeInPages, NonPagedPoolExpansion);
739 PointerPte = StartPte;
740 if (StartPte == NULL)
741 {
742 //
743 // Ran out of memory
744 //
745 DPRINT1("Out of NP Expansion Pool\n");
746 return NULL;
747 }
748
749 //
750 // Acquire the pool lock now
751 //
752 OldIrql = KeAcquireQueuedSpinLock(LockQueueMmNonPagedPoolLock);
753
754 //
755 // Lock the PFN database too
756 //
757 LockQueue = &KeGetCurrentPrcb()->LockQueue[LockQueuePfnLock];
758 KeAcquireQueuedSpinLockAtDpcLevel(LockQueue);
759
760 //
761 // Loop the pages
762 //
763 TempPte = ValidKernelPte;
764 do
765 {
766 /* Allocate a page */
767 PageFrameNumber = MiRemoveAnyPage(0);
768
769 /* Get the PFN entry for it and fill it out */
770 Pfn1 = MiGetPfnEntry(PageFrameNumber);
771 Pfn1->u3.e2.ReferenceCount = 1;
772 Pfn1->u2.ShareCount = 1;
773 Pfn1->PteAddress = PointerPte;
774 Pfn1->u3.e1.PageLocation = ActiveAndValid;
775 Pfn1->u4.VerifierAllocation = 0;
776
777 /* Write the PTE for it */
778 TempPte.u.Hard.PageFrameNumber = PageFrameNumber;
779 MI_WRITE_VALID_PTE(PointerPte++, TempPte);
780 } while (--SizeInPages > 0);
781
782 //
783 // This is the last page
784 //
785 Pfn1->u3.e1.EndOfAllocation = 1;
786
787 //
788 // Get the first page and mark it as such
789 //
790 Pfn1 = MiGetPfnEntry(StartPte->u.Hard.PageFrameNumber);
791 Pfn1->u3.e1.StartOfAllocation = 1;
792
793 //
794 // Release the PFN and nonpaged pool lock
795 //
796 KeReleaseQueuedSpinLockFromDpcLevel(LockQueue);
797 KeReleaseQueuedSpinLock(LockQueueMmNonPagedPoolLock, OldIrql);
798
799 //
800 // Return the address
801 //
802 return MiPteToAddress(StartPte);
803 }
804
805 ULONG
806 NTAPI
807 MiFreePoolPages(IN PVOID StartingVa)
808 {
809 PMMPTE PointerPte, StartPte;
810 PMMPFN Pfn1, StartPfn;
811 PFN_NUMBER FreePages, NumberOfPages;
812 KIRQL OldIrql;
813 PMMFREE_POOL_ENTRY FreeEntry, NextEntry, LastEntry;
814 ULONG i, End;
815
816 //
817 // Handle paged pool
818 //
819 if ((StartingVa >= MmPagedPoolStart) && (StartingVa <= MmPagedPoolEnd))
820 {
821 //
822 // Calculate the offset from the beginning of paged pool, and convert it
823 // into pages
824 //
825 i = ((ULONG_PTR)StartingVa - (ULONG_PTR)MmPagedPoolStart) >> PAGE_SHIFT;
826 End = i;
827
828 //
829 // Now use the end bitmap to scan until we find a set bit, meaning that
830 // this allocation finishes here
831 //
832 while (!RtlTestBit(MmPagedPoolInfo.EndOfPagedPoolBitmap, End)) End++;
833
834 //
835 // Now calculate the total number of pages this allocation spans
836 //
837 NumberOfPages = End - i + 1;
838
839 /* Delete the actual pages */
840 PointerPte = MmPagedPoolInfo.FirstPteForPagedPool + i;
841 FreePages = MiDeleteSystemPageableVm(PointerPte, NumberOfPages, 0, NULL);
842 ASSERT(FreePages == NumberOfPages);
843
844 //
845 // Acquire the paged pool lock
846 //
847 KeAcquireGuardedMutex(&MmPagedPoolMutex);
848
849 //
850 // Clear the allocation and free bits
851 //
852 RtlClearBit(MmPagedPoolInfo.EndOfPagedPoolBitmap, i);
853 RtlClearBits(MmPagedPoolInfo.PagedPoolAllocationMap, i, NumberOfPages);
854
855 //
856 // Update the hint if we need to
857 //
858 if (i < MmPagedPoolInfo.PagedPoolHint) MmPagedPoolInfo.PagedPoolHint = i;
859
860 //
861 // Release the lock protecting the bitmaps
862 //
863 KeReleaseGuardedMutex(&MmPagedPoolMutex);
864
865 //
866 // And finally return the number of pages freed
867 //
868 return NumberOfPages;
869 }
870
871 //
872 // Get the first PTE and its corresponding PFN entry
873 //
874 StartPte = PointerPte = MiAddressToPte(StartingVa);
875 StartPfn = Pfn1 = MiGetPfnEntry(PointerPte->u.Hard.PageFrameNumber);
876
877 //
878 // Loop until we find the last PTE
879 //
880 while (Pfn1->u3.e1.EndOfAllocation == 0)
881 {
882 //
883 // Keep going
884 //
885 PointerPte++;
886 Pfn1 = MiGetPfnEntry(PointerPte->u.Hard.PageFrameNumber);
887 }
888
889 //
890 // Now we know how many pages we have
891 //
892 NumberOfPages = PointerPte - StartPte + 1;
893
894 //
895 // Acquire the nonpaged pool lock
896 //
897 OldIrql = KeAcquireQueuedSpinLock(LockQueueMmNonPagedPoolLock);
898
899 //
900 // Mark the first and last PTEs as not part of an allocation anymore
901 //
902 StartPfn->u3.e1.StartOfAllocation = 0;
903 Pfn1->u3.e1.EndOfAllocation = 0;
904
905 //
906 // Assume we will free as many pages as the allocation was
907 //
908 FreePages = NumberOfPages;
909
910 //
911 // Peek one page past the end of the allocation
912 //
913 PointerPte++;
914
915 //
916 // Guard against going past initial nonpaged pool
917 //
918 if (MiGetPfnEntryIndex(Pfn1) == MiEndOfInitialPoolFrame)
919 {
920 //
921 // This page is on the outskirts of initial nonpaged pool, so ignore it
922 //
923 Pfn1 = NULL;
924 }
925 else
926 {
927 /* Sanity check */
928 ASSERT((ULONG_PTR)StartingVa + NumberOfPages <= (ULONG_PTR)MmNonPagedPoolEnd);
929
930 /* Check if protected pool is enabled */
931 if (MmProtectFreedNonPagedPool)
932 {
933 /* The freed block will be merged, it must be made accessible */
934 MiUnProtectFreeNonPagedPool(MiPteToAddress(PointerPte), 0);
935 }
936
937 //
938 // Otherwise, our entire allocation must've fit within the initial non
939 // paged pool, or the expansion nonpaged pool, so get the PFN entry of
940 // the next allocation
941 //
942 if (PointerPte->u.Hard.Valid == 1)
943 {
944 //
945 // It's either expansion or initial: get the PFN entry
946 //
947 Pfn1 = MiGetPfnEntry(PointerPte->u.Hard.PageFrameNumber);
948 }
949 else
950 {
951 //
952 // This means we've reached the guard page that protects the end of
953 // the expansion nonpaged pool
954 //
955 Pfn1 = NULL;
956 }
957
958 }
959
960 //
961 // Check if this allocation actually exists
962 //
963 if ((Pfn1) && (Pfn1->u3.e1.StartOfAllocation == 0))
964 {
965 //
966 // It doesn't, so we should actually locate a free entry descriptor
967 //
968 FreeEntry = (PMMFREE_POOL_ENTRY)((ULONG_PTR)StartingVa +
969 (NumberOfPages << PAGE_SHIFT));
970 ASSERT(FreeEntry->Signature == MM_FREE_POOL_SIGNATURE);
971 ASSERT(FreeEntry->Owner == FreeEntry);
972
973 /* Consume this entry's pages */
974 FreePages += FreeEntry->Size;
975
976 /* Remove the item from the list, depending if pool is protected */
977 MmProtectFreedNonPagedPool ?
978 MiProtectedPoolRemoveEntryList(&FreeEntry->List) :
979 RemoveEntryList(&FreeEntry->List);
980 }
981
982 //
983 // Now get the official free entry we'll create for the caller's allocation
984 //
985 FreeEntry = StartingVa;
986
987 //
988 // Check if the our allocation is the very first page
989 //
990 if (MiGetPfnEntryIndex(StartPfn) == MiStartOfInitialPoolFrame)
991 {
992 //
993 // Then we can't do anything or we'll risk underflowing
994 //
995 Pfn1 = NULL;
996 }
997 else
998 {
999 //
1000 // Otherwise, get the PTE for the page right before our allocation
1001 //
1002 PointerPte -= NumberOfPages + 1;
1003
1004 /* Check if protected pool is enabled */
1005 if (MmProtectFreedNonPagedPool)
1006 {
1007 /* The freed block will be merged, it must be made accessible */
1008 MiUnProtectFreeNonPagedPool(MiPteToAddress(PointerPte), 0);
1009 }
1010
1011 /* Check if this is valid pool, or a guard page */
1012 if (PointerPte->u.Hard.Valid == 1)
1013 {
1014 //
1015 // It's either expansion or initial nonpaged pool, get the PFN entry
1016 //
1017 Pfn1 = MiGetPfnEntry(PointerPte->u.Hard.PageFrameNumber);
1018 }
1019 else
1020 {
1021 //
1022 // We must've reached the guard page, so don't risk touching it
1023 //
1024 Pfn1 = NULL;
1025 }
1026 }
1027
1028 //
1029 // Check if there is a valid PFN entry for the page before the allocation
1030 // and then check if this page was actually the end of an allocation.
1031 // If it wasn't, then we know for sure it's a free page
1032 //
1033 if ((Pfn1) && (Pfn1->u3.e1.EndOfAllocation == 0))
1034 {
1035 //
1036 // Get the free entry descriptor for that given page range
1037 //
1038 FreeEntry = (PMMFREE_POOL_ENTRY)((ULONG_PTR)StartingVa - PAGE_SIZE);
1039 ASSERT(FreeEntry->Signature == MM_FREE_POOL_SIGNATURE);
1040 FreeEntry = FreeEntry->Owner;
1041
1042 /* Check if protected pool is enabled */
1043 if (MmProtectFreedNonPagedPool)
1044 {
1045 /* The freed block will be merged, it must be made accessible */
1046 MiUnProtectFreeNonPagedPool(FreeEntry, 0);
1047 }
1048
1049 //
1050 // Check if the entry is small enough to be indexed on a free list
1051 // If it is, we'll want to re-insert it, since we're about to
1052 // collapse our pages on top of it, which will change its count
1053 //
1054 if (FreeEntry->Size < (MI_MAX_FREE_PAGE_LISTS - 1))
1055 {
1056 /* Remove the item from the list, depending if pool is protected */
1057 MmProtectFreedNonPagedPool ?
1058 MiProtectedPoolRemoveEntryList(&FreeEntry->List) :
1059 RemoveEntryList(&FreeEntry->List);
1060
1061 //
1062 // Update its size
1063 //
1064 FreeEntry->Size += FreePages;
1065
1066 //
1067 // And now find the new appropriate list to place it in
1068 //
1069 i = (ULONG)(FreeEntry->Size - 1);
1070 if (i >= MI_MAX_FREE_PAGE_LISTS) i = MI_MAX_FREE_PAGE_LISTS - 1;
1071
1072 /* Insert the entry into the free list head, check for prot. pool */
1073 MmProtectFreedNonPagedPool ?
1074 MiProtectedPoolInsertList(&MmNonPagedPoolFreeListHead[i], &FreeEntry->List, TRUE) :
1075 InsertTailList(&MmNonPagedPoolFreeListHead[i], &FreeEntry->List);
1076 }
1077 else
1078 {
1079 //
1080 // Otherwise, just combine our free pages into this entry
1081 //
1082 FreeEntry->Size += FreePages;
1083 }
1084 }
1085
1086 //
1087 // Check if we were unable to do any compaction, and we'll stick with this
1088 //
1089 if (FreeEntry == StartingVa)
1090 {
1091 //
1092 // Well, now we are a free entry. At worse we just have our newly freed
1093 // pages, at best we have our pages plus whatever entry came after us
1094 //
1095 FreeEntry->Size = FreePages;
1096
1097 //
1098 // Find the appropriate list we should be on
1099 //
1100 i = FreeEntry->Size - 1;
1101 if (i >= MI_MAX_FREE_PAGE_LISTS) i = MI_MAX_FREE_PAGE_LISTS - 1;
1102
1103 /* Insert the entry into the free list head, check for prot. pool */
1104 MmProtectFreedNonPagedPool ?
1105 MiProtectedPoolInsertList(&MmNonPagedPoolFreeListHead[i], &FreeEntry->List, TRUE) :
1106 InsertTailList(&MmNonPagedPoolFreeListHead[i], &FreeEntry->List);
1107 }
1108
1109 //
1110 // Just a sanity check
1111 //
1112 ASSERT(FreePages != 0);
1113
1114 //
1115 // Get all the pages between our allocation and its end. These will all now
1116 // become free page chunks.
1117 //
1118 NextEntry = StartingVa;
1119 LastEntry = (PMMFREE_POOL_ENTRY)((ULONG_PTR)NextEntry + (FreePages << PAGE_SHIFT));
1120 do
1121 {
1122 //
1123 // Link back to the parent free entry, and keep going
1124 //
1125 NextEntry->Owner = FreeEntry;
1126 NextEntry->Signature = MM_FREE_POOL_SIGNATURE;
1127 NextEntry = (PMMFREE_POOL_ENTRY)((ULONG_PTR)NextEntry + PAGE_SIZE);
1128 } while (NextEntry != LastEntry);
1129
1130 /* Is freed non paged pool protected? */
1131 if (MmProtectFreedNonPagedPool)
1132 {
1133 /* Protect the freed pool! */
1134 MiProtectFreeNonPagedPool(FreeEntry, FreeEntry->Size);
1135 }
1136
1137 //
1138 // We're done, release the lock and let the caller know how much we freed
1139 //
1140 KeReleaseQueuedSpinLock(LockQueueMmNonPagedPoolLock, OldIrql);
1141 return NumberOfPages;
1142 }
1143
1144
1145 BOOLEAN
1146 NTAPI
1147 MiRaisePoolQuota(IN POOL_TYPE PoolType,
1148 IN ULONG CurrentMaxQuota,
1149 OUT PULONG NewMaxQuota)
1150 {
1151 //
1152 // Not implemented
1153 //
1154 UNIMPLEMENTED;
1155 *NewMaxQuota = CurrentMaxQuota + 65536;
1156 return TRUE;
1157 }
1158
1159 /* PUBLIC FUNCTIONS ***********************************************************/
1160
1161 /*
1162 * @unimplemented
1163 */
1164 PVOID
1165 NTAPI
1166 MmAllocateMappingAddress(IN SIZE_T NumberOfBytes,
1167 IN ULONG PoolTag)
1168 {
1169 UNIMPLEMENTED;
1170 return NULL;
1171 }
1172
1173 /*
1174 * @unimplemented
1175 */
1176 VOID
1177 NTAPI
1178 MmFreeMappingAddress(IN PVOID BaseAddress,
1179 IN ULONG PoolTag)
1180 {
1181 UNIMPLEMENTED;
1182 }
1183
1184 /* EOF */