2 * PROJECT: ReactOS Kernel
3 * LICENSE: BSD - See COPYING.ARM in the top level directory
4 * FILE: ntoskrnl/mm/ARM3/mminit.c
5 * PURPOSE: ARM Memory Manager Initialization
6 * PROGRAMMERS: ReactOS Portable Systems Group
9 /* INCLUDES *******************************************************************/
15 #define MODULE_INVOLVED_IN_ARM3
17 #undef MmSystemRangeStart
19 /* GLOBALS ********************************************************************/
22 // These are all registry-configurable, but by default, the memory manager will
23 // figure out the most appropriate values.
25 ULONG MmMaximumNonPagedPoolPercent
;
26 SIZE_T MmSizeOfNonPagedPoolInBytes
;
27 SIZE_T MmMaximumNonPagedPoolInBytes
;
29 /* Some of the same values, in pages */
30 PFN_NUMBER MmMaximumNonPagedPoolInPages
;
33 // These numbers describe the discrete equation components of the nonpaged
34 // pool sizing algorithm.
36 // They are described on http://support.microsoft.com/default.aspx/kb/126402/ja
37 // along with the algorithm that uses them, which is implemented later below.
39 SIZE_T MmMinimumNonPagedPoolSize
= 256 * 1024;
40 ULONG MmMinAdditionNonPagedPoolPerMb
= 32 * 1024;
41 SIZE_T MmDefaultMaximumNonPagedPool
= 1024 * 1024;
42 ULONG MmMaxAdditionNonPagedPoolPerMb
= 400 * 1024;
45 // The memory layout (and especially variable names) of the NT kernel mode
46 // components can be a bit hard to twig, especially when it comes to the non
49 // There are really two components to the non-paged pool:
51 // - The initial nonpaged pool, sized dynamically up to a maximum.
52 // - The expansion nonpaged pool, sized dynamically up to a maximum.
54 // The initial nonpaged pool is physically continuous for performance, and
55 // immediately follows the PFN database, typically sharing the same PDE. It is
56 // a very small resource (32MB on a 1GB system), and capped at 128MB.
58 // Right now we call this the "ARM³ Nonpaged Pool" and it begins somewhere after
59 // the PFN database (which starts at 0xB0000000).
61 // The expansion nonpaged pool, on the other hand, can grow much bigger (400MB
62 // for a 1GB system). On ARM³ however, it is currently capped at 128MB.
64 // The address where the initial nonpaged pool starts is aptly named
65 // MmNonPagedPoolStart, and it describes a range of MmSizeOfNonPagedPoolInBytes
68 // Expansion nonpaged pool starts at an address described by the variable called
69 // MmNonPagedPoolExpansionStart, and it goes on for MmMaximumNonPagedPoolInBytes
70 // minus MmSizeOfNonPagedPoolInBytes bytes, always reaching MmNonPagedPoolEnd
71 // (because of the way it's calculated) at 0xFFBE0000.
73 // Initial nonpaged pool is allocated and mapped early-on during boot, but what
74 // about the expansion nonpaged pool? It is instead composed of special pages
75 // which belong to what are called System PTEs. These PTEs are the matter of a
76 // later discussion, but they are also considered part of the "nonpaged" OS, due
77 // to the fact that they are never paged out -- once an address is described by
78 // a System PTE, it is always valid, until the System PTE is torn down.
80 // System PTEs are actually composed of two "spaces", the system space proper,
81 // and the nonpaged pool expansion space. The latter, as we've already seen,
82 // begins at MmNonPagedPoolExpansionStart. Based on the number of System PTEs
83 // that the system will support, the remaining address space below this address
84 // is used to hold the system space PTEs. This address, in turn, is held in the
85 // variable named MmNonPagedSystemStart, which itself is never allowed to go
86 // below 0xEB000000 (thus creating an upper bound on the number of System PTEs).
88 // This means that 330MB are reserved for total nonpaged system VA, on top of
89 // whatever the initial nonpaged pool allocation is.
91 // The following URLs, valid as of April 23rd, 2008, support this evidence:
93 // http://www.cs.miami.edu/~burt/journal/NT/memory.html
94 // http://www.ditii.com/2007/09/28/windows-memory-management-x86-virtual-address-space/
96 PVOID MmNonPagedSystemStart
;
97 SIZE_T MiNonPagedSystemSize
;
98 PVOID MmNonPagedPoolStart
;
99 PVOID MmNonPagedPoolExpansionStart
;
100 PVOID MmNonPagedPoolEnd
= MI_NONPAGED_POOL_END
;
103 // This is where paged pool starts by default
105 PVOID MmPagedPoolStart
= MI_PAGED_POOL_START
;
106 PVOID MmPagedPoolEnd
;
109 // And this is its default size
111 SIZE_T MmSizeOfPagedPoolInBytes
= MI_MIN_INIT_PAGED_POOLSIZE
;
112 PFN_NUMBER MmSizeOfPagedPoolInPages
= MI_MIN_INIT_PAGED_POOLSIZE
/ PAGE_SIZE
;
115 // Session space starts at 0xBFFFFFFF and grows downwards
116 // By default, it includes an 8MB image area where we map win32k and video card
117 // drivers, followed by a 4MB area containing the session's working set. This is
118 // then followed by a 20MB mapped view area and finally by the session's paged
119 // pool, by default 16MB.
121 // On a normal system, this results in session space occupying the region from
122 // 0xBD000000 to 0xC0000000
124 // See miarm.h for the defines that determine the sizing of this region. On an
125 // NT system, some of these can be configured through the registry, but we don't
128 PVOID MiSessionSpaceEnd
; // 0xC0000000
129 PVOID MiSessionImageEnd
; // 0xC0000000
130 PVOID MiSessionImageStart
; // 0xBF800000
131 PVOID MiSessionSpaceWs
;
132 PVOID MiSessionViewStart
; // 0xBE000000
133 PVOID MiSessionPoolEnd
; // 0xBE000000
134 PVOID MiSessionPoolStart
; // 0xBD000000
135 PVOID MmSessionBase
; // 0xBD000000
136 SIZE_T MmSessionSize
;
137 SIZE_T MmSessionViewSize
;
138 SIZE_T MmSessionPoolSize
;
139 SIZE_T MmSessionImageSize
;
142 * These are the PTE addresses of the boundaries carved out above
144 PMMPTE MiSessionImagePteStart
;
145 PMMPTE MiSessionImagePteEnd
;
146 PMMPTE MiSessionBasePte
;
147 PMMPTE MiSessionLastPte
;
150 // The system view space, on the other hand, is where sections that are memory
151 // mapped into "system space" end up.
153 // By default, it is a 16MB region, but we hack it to be 32MB for ReactOS
155 PVOID MiSystemViewStart
;
156 SIZE_T MmSystemViewSize
;
158 #if (_MI_PAGING_LEVELS == 2)
160 // A copy of the system page directory (the page directory associated with the
161 // System process) is kept (double-mapped) by the manager in order to lazily
162 // map paged pool PDEs into external processes when they fault on a paged pool
165 PFN_NUMBER MmSystemPageDirectory
[PD_COUNT
];
166 PMMPDE MmSystemPagePtes
;
170 // The system cache starts right after hyperspace. The first few pages are for
171 // keeping track of the system working set list.
173 // This should be 0xC0C00000 -- the cache itself starts at 0xC1000000
175 PMMWSL MmSystemCacheWorkingSetList
= (PVOID
)MI_SYSTEM_CACHE_WS_START
;
178 // Windows NT seems to choose between 7000, 11000 and 50000
179 // On systems with more than 32MB, this number is then doubled, and further
180 // aligned up to a PDE boundary (4MB).
182 PFN_COUNT MmNumberOfSystemPtes
;
185 // This is how many pages the PFN database will take up
186 // In Windows, this includes the Quark Color Table, but not in ARM³
188 PFN_NUMBER MxPfnAllocation
;
191 // Unlike the old ReactOS Memory Manager, ARM³ (and Windows) does not keep track
192 // of pages that are not actually valid physical memory, such as ACPI reserved
193 // regions, BIOS address ranges, or holes in physical memory address space which
194 // could indicate device-mapped I/O memory.
196 // In fact, the lack of a PFN entry for a page usually indicates that this is
197 // I/O space instead.
199 // A bitmap, called the PFN bitmap, keeps track of all page frames by assigning
200 // a bit to each. If the bit is set, then the page is valid physical RAM.
202 RTL_BITMAP MiPfnBitMap
;
205 // This structure describes the different pieces of RAM-backed address space
207 PPHYSICAL_MEMORY_DESCRIPTOR MmPhysicalMemoryBlock
;
210 // This is where we keep track of the most basic physical layout markers
212 PFN_NUMBER MmHighestPhysicalPage
, MmLowestPhysicalPage
= -1;
213 PFN_COUNT MmNumberOfPhysicalPages
;
216 // The total number of pages mapped by the boot loader, which include the kernel
217 // HAL, boot drivers, registry, NLS files and other loader data structures is
218 // kept track of here. This depends on "LoaderPagesSpanned" being correct when
219 // coming from the loader.
221 // This number is later aligned up to a PDE boundary.
223 SIZE_T MmBootImageSize
;
226 // These three variables keep track of the core separation of address space that
227 // exists between kernel mode and user mode.
229 ULONG_PTR MmUserProbeAddress
;
230 PVOID MmHighestUserAddress
;
231 PVOID MmSystemRangeStart
;
233 /* And these store the respective highest PTE/PDE address */
234 PMMPTE MiHighestUserPte
;
235 PMMPDE MiHighestUserPde
;
236 #if (_MI_PAGING_LEVELS >= 3)
237 PMMPTE MiHighestUserPpe
;
238 #if (_MI_PAGING_LEVELS >= 4)
239 PMMPTE MiHighestUserPxe
;
243 /* These variables define the system cache address space */
244 PVOID MmSystemCacheStart
;
245 PVOID MmSystemCacheEnd
;
246 MMSUPPORT MmSystemCacheWs
;
249 // This is where hyperspace ends (followed by the system cache working set)
251 PVOID MmHyperSpaceEnd
;
254 // Page coloring algorithm data
256 ULONG MmSecondaryColors
;
257 ULONG MmSecondaryColorMask
;
260 // Actual (registry-configurable) size of a GUI thread's stack
262 ULONG MmLargeStackSize
= KERNEL_LARGE_STACK_SIZE
;
265 // Before we have a PFN database, memory comes straight from our physical memory
266 // blocks, which is nice because it's guaranteed contiguous and also because once
267 // we take a page from here, the system doesn't see it anymore.
268 // However, once the fun is over, those pages must be re-integrated back into
269 // PFN society life, and that requires us keeping a copy of the original layout
270 // so that we can parse it later.
272 PMEMORY_ALLOCATION_DESCRIPTOR MxFreeDescriptor
;
273 MEMORY_ALLOCATION_DESCRIPTOR MxOldFreeDescriptor
;
276 * For each page's worth bytes of L2 cache in a given set/way line, the zero and
277 * free lists are organized in what is called a "color".
279 * This array points to the two lists, so it can be thought of as a multi-dimensional
280 * array of MmFreePagesByColor[2][MmSecondaryColors]. Since the number is dynamic,
281 * we describe the array in pointer form instead.
283 * On a final note, the color tables themselves are right after the PFN database.
285 C_ASSERT(FreePageList
== 1);
286 PMMCOLOR_TABLES MmFreePagesByColor
[FreePageList
+ 1];
288 /* An event used in Phase 0 before the rest of the system is ready to go */
291 /* All the events used for memory threshold notifications */
292 PKEVENT MiLowMemoryEvent
;
293 PKEVENT MiHighMemoryEvent
;
294 PKEVENT MiLowPagedPoolEvent
;
295 PKEVENT MiHighPagedPoolEvent
;
296 PKEVENT MiLowNonPagedPoolEvent
;
297 PKEVENT MiHighNonPagedPoolEvent
;
299 /* The actual thresholds themselves, in page numbers */
300 PFN_NUMBER MmLowMemoryThreshold
;
301 PFN_NUMBER MmHighMemoryThreshold
;
302 PFN_NUMBER MiLowPagedPoolThreshold
;
303 PFN_NUMBER MiHighPagedPoolThreshold
;
304 PFN_NUMBER MiLowNonPagedPoolThreshold
;
305 PFN_NUMBER MiHighNonPagedPoolThreshold
;
308 * This number determines how many free pages must exist, at minimum, until we
309 * start trimming working sets and flushing modified pages to obtain more free
312 * This number changes if the system detects that this is a server product
314 PFN_NUMBER MmMinimumFreePages
= 26;
317 * This number indicates how many pages we consider to be a low limit of having
318 * "plenty" of free memory.
320 * It is doubled on systems that have more than 63MB of memory
322 PFN_NUMBER MmPlentyFreePages
= 400;
324 /* These values store the type of system this is (small, med, large) and if server */
326 MM_SYSTEMSIZE MmSystemSize
;
329 * These values store the cache working set minimums and maximums, in pages
331 * The minimum value is boosted on systems with more than 24MB of RAM, and cut
332 * down to only 32 pages on embedded (<24MB RAM) systems.
334 * An extra boost of 2MB is given on systems with more than 33MB of RAM.
336 PFN_NUMBER MmSystemCacheWsMinimum
= 288;
337 PFN_NUMBER MmSystemCacheWsMaximum
= 350;
339 /* FIXME: Move to cache/working set code later */
340 BOOLEAN MmLargeSystemCache
;
343 * This value determines in how many fragments/chunks the subsection prototype
344 * PTEs should be allocated when mapping a section object. It is configurable in
345 * the registry through the MapAllocationFragment parameter.
347 * The default is 64KB on systems with more than 1GB of RAM, 32KB on systems with
348 * more than 256MB of RAM, and 16KB on systems with less than 256MB of RAM.
350 * The maximum it can be set to is 2MB, and the minimum is 4KB.
352 SIZE_T MmAllocationFragment
;
355 * These two values track how much virtual memory can be committed, and when
356 * expansion should happen.
358 // FIXME: They should be moved elsewhere since it's not an "init" setting?
359 SIZE_T MmTotalCommitLimit
;
360 SIZE_T MmTotalCommitLimitMaximum
;
363 * These values tune certain user parameters. They have default values set here,
364 * as well as in the code, and can be overwritten by registry settings.
366 SIZE_T MmHeapSegmentReserve
= 1 * _1MB
;
367 SIZE_T MmHeapSegmentCommit
= 2 * PAGE_SIZE
;
368 SIZE_T MmHeapDeCommitTotalFreeThreshold
= 64 * _1KB
;
369 SIZE_T MmHeapDeCommitFreeBlockThreshold
= PAGE_SIZE
;
370 SIZE_T MmMinimumStackCommitInBytes
= 0;
372 /* Internal setting used for debugging memory descriptors */
373 BOOLEAN MiDbgEnableMdDump
=
380 /* Number of memory descriptors in the loader block */
381 ULONG MiNumberDescriptors
= 0;
383 /* Number of free pages in the loader block */
384 PFN_NUMBER MiNumberOfFreePages
= 0;
386 /* Timeout value for critical sections (2.5 minutes) */
387 ULONG MmCritsectTimeoutSeconds
= 150; // NT value: 720 * 60 * 60; (30 days)
388 LARGE_INTEGER MmCriticalSectionTimeout
;
390 /* PRIVATE FUNCTIONS **********************************************************/
394 MiScanMemoryDescriptors(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
396 PLIST_ENTRY ListEntry
;
397 PMEMORY_ALLOCATION_DESCRIPTOR Descriptor
;
398 PFN_NUMBER PageFrameIndex
, FreePages
= 0;
400 /* Loop the memory descriptors */
401 for (ListEntry
= LoaderBlock
->MemoryDescriptorListHead
.Flink
;
402 ListEntry
!= &LoaderBlock
->MemoryDescriptorListHead
;
403 ListEntry
= ListEntry
->Flink
)
405 /* Get the descriptor */
406 Descriptor
= CONTAINING_RECORD(ListEntry
,
407 MEMORY_ALLOCATION_DESCRIPTOR
,
409 DPRINT("MD Type: %lx Base: %lx Count: %lx\n",
410 Descriptor
->MemoryType
, Descriptor
->BasePage
, Descriptor
->PageCount
);
412 /* Count this descriptor */
413 MiNumberDescriptors
++;
415 /* Check if this is invisible memory */
416 if ((Descriptor
->MemoryType
== LoaderFirmwarePermanent
) ||
417 (Descriptor
->MemoryType
== LoaderSpecialMemory
) ||
418 (Descriptor
->MemoryType
== LoaderHALCachedMemory
) ||
419 (Descriptor
->MemoryType
== LoaderBBTMemory
))
421 /* Skip this descriptor */
425 /* Check if this is bad memory */
426 if (Descriptor
->MemoryType
!= LoaderBad
)
428 /* Count this in the total of pages */
429 MmNumberOfPhysicalPages
+= (PFN_COUNT
)Descriptor
->PageCount
;
432 /* Check if this is the new lowest page */
433 if (Descriptor
->BasePage
< MmLowestPhysicalPage
)
435 /* Update the lowest page */
436 MmLowestPhysicalPage
= Descriptor
->BasePage
;
439 /* Check if this is the new highest page */
440 PageFrameIndex
= Descriptor
->BasePage
+ Descriptor
->PageCount
;
441 if (PageFrameIndex
> MmHighestPhysicalPage
)
443 /* Update the highest page */
444 MmHighestPhysicalPage
= PageFrameIndex
- 1;
447 /* Check if this is free memory */
448 if ((Descriptor
->MemoryType
== LoaderFree
) ||
449 (Descriptor
->MemoryType
== LoaderLoadedProgram
) ||
450 (Descriptor
->MemoryType
== LoaderFirmwareTemporary
) ||
451 (Descriptor
->MemoryType
== LoaderOsloaderStack
))
453 /* Count it too free pages */
454 MiNumberOfFreePages
+= Descriptor
->PageCount
;
456 /* Check if this is the largest memory descriptor */
457 if (Descriptor
->PageCount
> FreePages
)
460 MxFreeDescriptor
= Descriptor
;
461 FreePages
= Descriptor
->PageCount
;
466 /* Save original values of the free descriptor, since it'll be
467 * altered by early allocations */
468 MxOldFreeDescriptor
= *MxFreeDescriptor
;
474 MxGetNextPage(IN PFN_NUMBER PageCount
)
478 /* Make sure we have enough pages */
479 if (PageCount
> MxFreeDescriptor
->PageCount
)
481 /* Crash the system */
482 KeBugCheckEx(INSTALL_MORE_MEMORY
,
483 MmNumberOfPhysicalPages
,
484 MxFreeDescriptor
->PageCount
,
485 MxOldFreeDescriptor
.PageCount
,
489 /* Use our lowest usable free pages */
490 Pfn
= MxFreeDescriptor
->BasePage
;
491 MxFreeDescriptor
->BasePage
+= PageCount
;
492 MxFreeDescriptor
->PageCount
-= PageCount
;
499 MiComputeColorInformation(VOID
)
501 ULONG L2Associativity
;
503 /* Check if no setting was provided already */
504 if (!MmSecondaryColors
)
506 /* Get L2 cache information */
507 L2Associativity
= KeGetPcr()->SecondLevelCacheAssociativity
;
509 /* The number of colors is the number of cache bytes by set/way */
510 MmSecondaryColors
= KeGetPcr()->SecondLevelCacheSize
;
511 if (L2Associativity
) MmSecondaryColors
/= L2Associativity
;
514 /* Now convert cache bytes into pages */
515 MmSecondaryColors
>>= PAGE_SHIFT
;
516 if (!MmSecondaryColors
)
518 /* If there was no cache data from the KPCR, use the default colors */
519 MmSecondaryColors
= MI_SECONDARY_COLORS
;
523 /* Otherwise, make sure there aren't too many colors */
524 if (MmSecondaryColors
> MI_MAX_SECONDARY_COLORS
)
526 /* Set the maximum */
527 MmSecondaryColors
= MI_MAX_SECONDARY_COLORS
;
530 /* Make sure there aren't too little colors */
531 if (MmSecondaryColors
< MI_MIN_SECONDARY_COLORS
)
533 /* Set the default */
534 MmSecondaryColors
= MI_SECONDARY_COLORS
;
537 /* Finally make sure the colors are a power of two */
538 if (MmSecondaryColors
& (MmSecondaryColors
- 1))
540 /* Set the default */
541 MmSecondaryColors
= MI_SECONDARY_COLORS
;
545 /* Compute the mask and store it */
546 MmSecondaryColorMask
= MmSecondaryColors
- 1;
547 KeGetCurrentPrcb()->SecondaryColorMask
= MmSecondaryColorMask
;
553 MiInitializeColorTables(VOID
)
556 PMMPTE PointerPte
, LastPte
;
557 MMPTE TempPte
= ValidKernelPte
;
559 /* The color table starts after the ARM3 PFN database */
560 MmFreePagesByColor
[0] = (PMMCOLOR_TABLES
)&MmPfnDatabase
[MmHighestPhysicalPage
+ 1];
562 /* Loop the PTEs. We have two color tables for each secondary color */
563 PointerPte
= MiAddressToPte(&MmFreePagesByColor
[0][0]);
564 LastPte
= MiAddressToPte((ULONG_PTR
)MmFreePagesByColor
[0] +
565 (2 * MmSecondaryColors
* sizeof(MMCOLOR_TABLES
))
567 while (PointerPte
<= LastPte
)
569 /* Check for valid PTE */
570 if (PointerPte
->u
.Hard
.Valid
== 0)
572 /* Get a page and map it */
573 TempPte
.u
.Hard
.PageFrameNumber
= MxGetNextPage(1);
574 MI_WRITE_VALID_PTE(PointerPte
, TempPte
);
576 /* Zero out the page */
577 RtlZeroMemory(MiPteToAddress(PointerPte
), PAGE_SIZE
);
584 /* Now set the address of the next list, right after this one */
585 MmFreePagesByColor
[1] = &MmFreePagesByColor
[0][MmSecondaryColors
];
587 /* Now loop the lists to set them up */
588 for (i
= 0; i
< MmSecondaryColors
; i
++)
590 /* Set both free and zero lists for each color */
591 MmFreePagesByColor
[ZeroedPageList
][i
].Flink
= LIST_HEAD
;
592 MmFreePagesByColor
[ZeroedPageList
][i
].Blink
= (PVOID
)LIST_HEAD
;
593 MmFreePagesByColor
[ZeroedPageList
][i
].Count
= 0;
594 MmFreePagesByColor
[FreePageList
][i
].Flink
= LIST_HEAD
;
595 MmFreePagesByColor
[FreePageList
][i
].Blink
= (PVOID
)LIST_HEAD
;
596 MmFreePagesByColor
[FreePageList
][i
].Count
= 0;
604 MiIsRegularMemory(IN PLOADER_PARAMETER_BLOCK LoaderBlock
,
607 PLIST_ENTRY NextEntry
;
608 PMEMORY_ALLOCATION_DESCRIPTOR MdBlock
;
610 /* Loop the memory descriptors */
611 NextEntry
= LoaderBlock
->MemoryDescriptorListHead
.Flink
;
612 while (NextEntry
!= &LoaderBlock
->MemoryDescriptorListHead
)
614 /* Get the memory descriptor */
615 MdBlock
= CONTAINING_RECORD(NextEntry
,
616 MEMORY_ALLOCATION_DESCRIPTOR
,
619 /* Check if this PFN could be part of the block */
620 if (Pfn
>= (MdBlock
->BasePage
))
622 /* Check if it really is part of the block */
623 if (Pfn
< (MdBlock
->BasePage
+ MdBlock
->PageCount
))
625 /* Check if the block is actually memory we don't map */
626 if ((MdBlock
->MemoryType
== LoaderFirmwarePermanent
) ||
627 (MdBlock
->MemoryType
== LoaderBBTMemory
) ||
628 (MdBlock
->MemoryType
== LoaderSpecialMemory
))
630 /* We don't need PFN database entries for this memory */
634 /* This is memory we want to map */
640 /* Blocks are ordered, so if it's not here, it doesn't exist */
644 /* Get to the next descriptor */
645 NextEntry
= MdBlock
->ListEntry
.Flink
;
648 /* Check if this PFN is actually from our free memory descriptor */
649 if ((Pfn
>= MxOldFreeDescriptor
.BasePage
) &&
650 (Pfn
< MxOldFreeDescriptor
.BasePage
+ MxOldFreeDescriptor
.PageCount
))
652 /* We use these pages for initial mappings, so we do want to count them */
656 /* Otherwise this isn't memory that we describe or care about */
663 MiMapPfnDatabase(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
665 PFN_NUMBER FreePage
, FreePageCount
, PagesLeft
, BasePage
, PageCount
;
666 PLIST_ENTRY NextEntry
;
667 PMEMORY_ALLOCATION_DESCRIPTOR MdBlock
;
668 PMMPTE PointerPte
, LastPte
;
669 MMPTE TempPte
= ValidKernelPte
;
671 /* Get current page data, since we won't be using MxGetNextPage as it would corrupt our state */
672 FreePage
= MxFreeDescriptor
->BasePage
;
673 FreePageCount
= MxFreeDescriptor
->PageCount
;
676 /* Loop the memory descriptors */
677 NextEntry
= LoaderBlock
->MemoryDescriptorListHead
.Flink
;
678 while (NextEntry
!= &LoaderBlock
->MemoryDescriptorListHead
)
680 /* Get the descriptor */
681 MdBlock
= CONTAINING_RECORD(NextEntry
,
682 MEMORY_ALLOCATION_DESCRIPTOR
,
684 if ((MdBlock
->MemoryType
== LoaderFirmwarePermanent
) ||
685 (MdBlock
->MemoryType
== LoaderBBTMemory
) ||
686 (MdBlock
->MemoryType
== LoaderSpecialMemory
))
688 /* These pages are not part of the PFN database */
689 NextEntry
= MdBlock
->ListEntry
.Flink
;
693 /* Next, check if this is our special free descriptor we've found */
694 if (MdBlock
== MxFreeDescriptor
)
696 /* Use the real numbers instead */
697 BasePage
= MxOldFreeDescriptor
.BasePage
;
698 PageCount
= MxOldFreeDescriptor
.PageCount
;
702 /* Use the descriptor's numbers */
703 BasePage
= MdBlock
->BasePage
;
704 PageCount
= MdBlock
->PageCount
;
707 /* Get the PTEs for this range */
708 PointerPte
= MiAddressToPte(&MmPfnDatabase
[BasePage
]);
709 LastPte
= MiAddressToPte(((ULONG_PTR
)&MmPfnDatabase
[BasePage
+ PageCount
]) - 1);
710 DPRINT("MD Type: %lx Base: %lx Count: %lx\n", MdBlock
->MemoryType
, BasePage
, PageCount
);
713 while (PointerPte
<= LastPte
)
715 /* We'll only touch PTEs that aren't already valid */
716 if (PointerPte
->u
.Hard
.Valid
== 0)
718 /* Use the next free page */
719 TempPte
.u
.Hard
.PageFrameNumber
= FreePage
;
720 ASSERT(FreePageCount
!= 0);
722 /* Consume free pages */
728 KeBugCheckEx(INSTALL_MORE_MEMORY
,
729 MmNumberOfPhysicalPages
,
731 MxOldFreeDescriptor
.PageCount
,
735 /* Write out this PTE */
737 MI_WRITE_VALID_PTE(PointerPte
, TempPte
);
740 RtlZeroMemory(MiPteToAddress(PointerPte
), PAGE_SIZE
);
747 /* Do the next address range */
748 NextEntry
= MdBlock
->ListEntry
.Flink
;
751 /* Now update the free descriptors to consume the pages we used up during the PFN allocation loop */
752 MxFreeDescriptor
->BasePage
= FreePage
;
753 MxFreeDescriptor
->PageCount
= FreePageCount
;
759 MiBuildPfnDatabaseFromPages(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
764 PFN_NUMBER PageFrameIndex
, StartupPdIndex
, PtePageIndex
;
766 ULONG_PTR BaseAddress
= 0;
768 /* PFN of the startup page directory */
769 StartupPdIndex
= PFN_FROM_PTE(MiAddressToPde(PDE_BASE
));
771 /* Start with the first PDE and scan them all */
772 PointerPde
= MiAddressToPde(NULL
);
773 Count
= PD_COUNT
* PDE_COUNT
;
774 for (i
= 0; i
< Count
; i
++)
776 /* Check for valid PDE */
777 if (PointerPde
->u
.Hard
.Valid
== 1)
779 /* Get the PFN from it */
780 PageFrameIndex
= PFN_FROM_PTE(PointerPde
);
782 /* Do we want a PFN entry for this page? */
783 if (MiIsRegularMemory(LoaderBlock
, PageFrameIndex
))
785 /* Yes we do, set it up */
786 Pfn1
= MiGetPfnEntry(PageFrameIndex
);
787 Pfn1
->u4
.PteFrame
= StartupPdIndex
;
788 Pfn1
->PteAddress
= (PMMPTE
)PointerPde
;
789 Pfn1
->u2
.ShareCount
++;
790 Pfn1
->u3
.e2
.ReferenceCount
= 1;
791 Pfn1
->u3
.e1
.PageLocation
= ActiveAndValid
;
792 Pfn1
->u3
.e1
.CacheAttribute
= MiNonCached
;
794 Pfn1
->PfnUsage
= MI_USAGE_INIT_MEMORY
;
795 memcpy(Pfn1
->ProcessName
, "Initial PDE", 16);
804 /* Now get the PTE and scan the pages */
805 PointerPte
= MiAddressToPte(BaseAddress
);
806 for (j
= 0; j
< PTE_COUNT
; j
++)
808 /* Check for a valid PTE */
809 if (PointerPte
->u
.Hard
.Valid
== 1)
811 /* Increase the shared count of the PFN entry for the PDE */
812 ASSERT(Pfn1
!= NULL
);
813 Pfn1
->u2
.ShareCount
++;
815 /* Now check if the PTE is valid memory too */
816 PtePageIndex
= PFN_FROM_PTE(PointerPte
);
817 if (MiIsRegularMemory(LoaderBlock
, PtePageIndex
))
820 * Only add pages above the end of system code or pages
821 * that are part of nonpaged pool
823 if ((BaseAddress
>= 0xA0000000) ||
824 ((BaseAddress
>= (ULONG_PTR
)MmNonPagedPoolStart
) &&
825 (BaseAddress
< (ULONG_PTR
)MmNonPagedPoolStart
+
826 MmSizeOfNonPagedPoolInBytes
)))
828 /* Get the PFN entry and make sure it too is valid */
829 Pfn2
= MiGetPfnEntry(PtePageIndex
);
830 if ((MmIsAddressValid(Pfn2
)) &&
831 (MmIsAddressValid(Pfn2
+ 1)))
833 /* Setup the PFN entry */
834 Pfn2
->u4
.PteFrame
= PageFrameIndex
;
835 Pfn2
->PteAddress
= PointerPte
;
836 Pfn2
->u2
.ShareCount
++;
837 Pfn2
->u3
.e2
.ReferenceCount
= 1;
838 Pfn2
->u3
.e1
.PageLocation
= ActiveAndValid
;
839 Pfn2
->u3
.e1
.CacheAttribute
= MiNonCached
;
841 Pfn2
->PfnUsage
= MI_USAGE_INIT_MEMORY
;
842 memcpy(Pfn1
->ProcessName
, "Initial PTE", 16);
851 BaseAddress
+= PAGE_SIZE
;
856 /* Next PDE mapped address */
857 BaseAddress
+= PDE_MAPPED_VA
;
868 MiBuildPfnDatabaseZeroPage(VOID
)
873 /* Grab the lowest page and check if it has no real references */
874 Pfn1
= MiGetPfnEntry(MmLowestPhysicalPage
);
875 if (!(MmLowestPhysicalPage
) && !(Pfn1
->u3
.e2
.ReferenceCount
))
877 /* Make it a bogus page to catch errors */
878 PointerPde
= MiAddressToPde(0xFFFFFFFF);
879 Pfn1
->u4
.PteFrame
= PFN_FROM_PTE(PointerPde
);
880 Pfn1
->PteAddress
= (PMMPTE
)PointerPde
;
881 Pfn1
->u2
.ShareCount
++;
882 Pfn1
->u3
.e2
.ReferenceCount
= 0xFFF0;
883 Pfn1
->u3
.e1
.PageLocation
= ActiveAndValid
;
884 Pfn1
->u3
.e1
.CacheAttribute
= MiNonCached
;
891 MiBuildPfnDatabaseFromLoaderBlock(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
893 PLIST_ENTRY NextEntry
;
894 PFN_NUMBER PageCount
= 0;
895 PMEMORY_ALLOCATION_DESCRIPTOR MdBlock
;
896 PFN_NUMBER PageFrameIndex
;
902 /* Now loop through the descriptors */
903 NextEntry
= LoaderBlock
->MemoryDescriptorListHead
.Flink
;
904 while (NextEntry
!= &LoaderBlock
->MemoryDescriptorListHead
)
906 /* Get the current descriptor */
907 MdBlock
= CONTAINING_RECORD(NextEntry
,
908 MEMORY_ALLOCATION_DESCRIPTOR
,
912 PageCount
= MdBlock
->PageCount
;
913 PageFrameIndex
= MdBlock
->BasePage
;
915 /* Don't allow memory above what the PFN database is mapping */
916 if (PageFrameIndex
> MmHighestPhysicalPage
)
918 /* Since they are ordered, everything past here will be larger */
922 /* On the other hand, the end page might be higher up... */
923 if ((PageFrameIndex
+ PageCount
) > (MmHighestPhysicalPage
+ 1))
925 /* In which case we'll trim the descriptor to go as high as we can */
926 PageCount
= MmHighestPhysicalPage
+ 1 - PageFrameIndex
;
927 MdBlock
->PageCount
= PageCount
;
929 /* But if there's nothing left to trim, we got too high, so quit */
930 if (!PageCount
) break;
933 /* Now check the descriptor type */
934 switch (MdBlock
->MemoryType
)
936 /* Check for bad RAM */
939 DPRINT1("You either have specified /BURNMEMORY or damaged RAM modules.\n");
942 /* Check for free RAM */
944 case LoaderLoadedProgram
:
945 case LoaderFirmwareTemporary
:
946 case LoaderOsloaderStack
:
948 /* Get the last page of this descriptor. Note we loop backwards */
949 PageFrameIndex
+= PageCount
- 1;
950 Pfn1
= MiGetPfnEntry(PageFrameIndex
);
952 /* Lock the PFN Database */
953 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
956 /* If the page really has no references, mark it as free */
957 if (!Pfn1
->u3
.e2
.ReferenceCount
)
959 /* Add it to the free list */
960 Pfn1
->u3
.e1
.CacheAttribute
= MiNonCached
;
961 MiInsertPageInFreeList(PageFrameIndex
);
964 /* Go to the next page */
969 /* Release PFN database */
970 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
972 /* Done with this block */
975 /* Check for pages that are invisible to us */
976 case LoaderFirmwarePermanent
:
977 case LoaderSpecialMemory
:
978 case LoaderBBTMemory
:
985 /* Map these pages with the KSEG0 mapping that adds 0x80000000 */
986 PointerPte
= MiAddressToPte(KSEG0_BASE
+ (PageFrameIndex
<< PAGE_SHIFT
));
987 Pfn1
= MiGetPfnEntry(PageFrameIndex
);
990 /* Check if the page is really unused */
991 PointerPde
= MiAddressToPde(KSEG0_BASE
+ (PageFrameIndex
<< PAGE_SHIFT
));
992 if (!Pfn1
->u3
.e2
.ReferenceCount
)
994 /* Mark it as being in-use */
995 Pfn1
->u4
.PteFrame
= PFN_FROM_PTE(PointerPde
);
996 Pfn1
->PteAddress
= PointerPte
;
997 Pfn1
->u2
.ShareCount
++;
998 Pfn1
->u3
.e2
.ReferenceCount
= 1;
999 Pfn1
->u3
.e1
.PageLocation
= ActiveAndValid
;
1000 Pfn1
->u3
.e1
.CacheAttribute
= MiNonCached
;
1002 Pfn1
->PfnUsage
= MI_USAGE_BOOT_DRIVER
;
1005 /* Check for RAM disk page */
1006 if (MdBlock
->MemoryType
== LoaderXIPRom
)
1008 /* Make it a pseudo-I/O ROM mapping */
1010 Pfn1
->u2
.ShareCount
= 0;
1011 Pfn1
->u3
.e2
.ReferenceCount
= 0;
1012 Pfn1
->u3
.e1
.PageLocation
= 0;
1013 Pfn1
->u3
.e1
.Rom
= 1;
1014 Pfn1
->u4
.InPageError
= 0;
1015 Pfn1
->u3
.e1
.PrototypePte
= 1;
1019 /* Advance page structures */
1027 /* Next descriptor entry */
1028 NextEntry
= MdBlock
->ListEntry
.Flink
;
1035 MiBuildPfnDatabaseSelf(VOID
)
1037 PMMPTE PointerPte
, LastPte
;
1040 /* Loop the PFN database page */
1041 PointerPte
= MiAddressToPte(MiGetPfnEntry(MmLowestPhysicalPage
));
1042 LastPte
= MiAddressToPte(MiGetPfnEntry(MmHighestPhysicalPage
));
1043 while (PointerPte
<= LastPte
)
1045 /* Make sure the page is valid */
1046 if (PointerPte
->u
.Hard
.Valid
== 1)
1048 /* Get the PFN entry and just mark it referenced */
1049 Pfn1
= MiGetPfnEntry(PointerPte
->u
.Hard
.PageFrameNumber
);
1050 Pfn1
->u2
.ShareCount
= 1;
1051 Pfn1
->u3
.e2
.ReferenceCount
= 1;
1053 Pfn1
->PfnUsage
= MI_USAGE_PFN_DATABASE
;
1065 MiInitializePfnDatabase(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
1067 /* Scan memory and start setting up PFN entries */
1068 MiBuildPfnDatabaseFromPages(LoaderBlock
);
1070 /* Add the zero page */
1071 MiBuildPfnDatabaseZeroPage();
1073 /* Scan the loader block and build the rest of the PFN database */
1074 MiBuildPfnDatabaseFromLoaderBlock(LoaderBlock
);
1076 /* Finally add the pages for the PFN database itself */
1077 MiBuildPfnDatabaseSelf();
1079 #endif /* !_M_AMD64 */
1084 MmFreeLoaderBlock(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
1087 PMEMORY_ALLOCATION_DESCRIPTOR MdBlock
;
1089 PFN_NUMBER BasePage
, LoaderPages
;
1092 PPHYSICAL_MEMORY_RUN Buffer
, Entry
;
1094 /* Loop the descriptors in order to count them */
1096 NextMd
= LoaderBlock
->MemoryDescriptorListHead
.Flink
;
1097 while (NextMd
!= &LoaderBlock
->MemoryDescriptorListHead
)
1099 MdBlock
= CONTAINING_RECORD(NextMd
,
1100 MEMORY_ALLOCATION_DESCRIPTOR
,
1103 NextMd
= MdBlock
->ListEntry
.Flink
;
1106 /* Allocate a structure to hold the physical runs */
1107 Buffer
= ExAllocatePoolWithTag(NonPagedPool
,
1108 i
* sizeof(PHYSICAL_MEMORY_RUN
),
1110 ASSERT(Buffer
!= NULL
);
1113 /* Loop the descriptors again */
1114 NextMd
= LoaderBlock
->MemoryDescriptorListHead
.Flink
;
1115 while (NextMd
!= &LoaderBlock
->MemoryDescriptorListHead
)
1117 /* Check what kind this was */
1118 MdBlock
= CONTAINING_RECORD(NextMd
,
1119 MEMORY_ALLOCATION_DESCRIPTOR
,
1121 switch (MdBlock
->MemoryType
)
1123 /* Registry, NLS, and heap data */
1124 case LoaderRegistryData
:
1125 case LoaderOsloaderHeap
:
1127 /* Are all a candidate for deletion */
1128 Entry
->BasePage
= MdBlock
->BasePage
;
1129 Entry
->PageCount
= MdBlock
->PageCount
;
1132 /* We keep the rest */
1137 /* Move to the next descriptor */
1138 NextMd
= MdBlock
->ListEntry
.Flink
;
1141 /* Acquire the PFN lock */
1142 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
1146 while (--Entry
>= Buffer
)
1148 /* See how many pages are in this run */
1149 i
= Entry
->PageCount
;
1150 BasePage
= Entry
->BasePage
;
1152 /* Loop each page */
1153 Pfn1
= MiGetPfnEntry(BasePage
);
1156 /* Check if it has references or is in any kind of list */
1157 if (!(Pfn1
->u3
.e2
.ReferenceCount
) && (!Pfn1
->u1
.Flink
))
1159 /* Set the new PTE address and put this page into the free list */
1160 Pfn1
->PteAddress
= (PMMPTE
)(BasePage
<< PAGE_SHIFT
);
1161 MiInsertPageInFreeList(BasePage
);
1166 /* It has a reference, so simply drop it */
1167 ASSERT(MI_IS_PHYSICAL_ADDRESS(MiPteToAddress(Pfn1
->PteAddress
)) == FALSE
);
1169 /* Drop a dereference on this page, which should delete it */
1170 Pfn1
->PteAddress
->u
.Long
= 0;
1171 MI_SET_PFN_DELETED(Pfn1
);
1172 MiDecrementShareCount(Pfn1
, BasePage
);
1176 /* Move to the next page */
1182 /* Release the PFN lock and flush the TLB */
1183 DPRINT("Loader pages freed: %lx\n", LoaderPages
);
1184 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
1187 /* Free our run structure */
1188 ExFreePoolWithTag(Buffer
, 'lMmM');
1194 MiAdjustWorkingSetManagerParameters(IN BOOLEAN Client
)
1196 /* This function needs to do more work, for now, we tune page minimums */
1198 /* Check for a system with around 64MB RAM or more */
1199 if (MmNumberOfPhysicalPages
>= (63 * _1MB
) / PAGE_SIZE
)
1201 /* Double the minimum amount of pages we consider for a "plenty free" scenario */
1202 MmPlentyFreePages
*= 2;
1209 MiNotifyMemoryEvents(VOID
)
1211 /* Are we in a low-memory situation? */
1212 if (MmAvailablePages
< MmLowMemoryThreshold
)
1214 /* Clear high, set low */
1215 if (KeReadStateEvent(MiHighMemoryEvent
)) KeClearEvent(MiHighMemoryEvent
);
1216 if (!KeReadStateEvent(MiLowMemoryEvent
)) KeSetEvent(MiLowMemoryEvent
, 0, FALSE
);
1218 else if (MmAvailablePages
< MmHighMemoryThreshold
)
1220 /* We are in between, clear both */
1221 if (KeReadStateEvent(MiHighMemoryEvent
)) KeClearEvent(MiHighMemoryEvent
);
1222 if (KeReadStateEvent(MiLowMemoryEvent
)) KeClearEvent(MiLowMemoryEvent
);
1226 /* Clear low, set high */
1227 if (KeReadStateEvent(MiLowMemoryEvent
)) KeClearEvent(MiLowMemoryEvent
);
1228 if (!KeReadStateEvent(MiHighMemoryEvent
)) KeSetEvent(MiHighMemoryEvent
, 0, FALSE
);
1235 MiCreateMemoryEvent(IN PUNICODE_STRING Name
,
1242 OBJECT_ATTRIBUTES ObjectAttributes
;
1243 SECURITY_DESCRIPTOR SecurityDescriptor
;
1246 Status
= RtlCreateSecurityDescriptor(&SecurityDescriptor
,
1247 SECURITY_DESCRIPTOR_REVISION
);
1248 if (!NT_SUCCESS(Status
)) return Status
;
1250 /* One ACL with 3 ACEs, containing each one SID */
1251 DaclLength
= sizeof(ACL
) +
1252 3 * sizeof(ACCESS_ALLOWED_ACE
) +
1253 RtlLengthSid(SeLocalSystemSid
) +
1254 RtlLengthSid(SeAliasAdminsSid
) +
1255 RtlLengthSid(SeWorldSid
);
1257 /* Allocate space for the DACL */
1258 Dacl
= ExAllocatePoolWithTag(PagedPool
, DaclLength
, 'lcaD');
1259 if (!Dacl
) return STATUS_INSUFFICIENT_RESOURCES
;
1261 /* Setup the ACL inside it */
1262 Status
= RtlCreateAcl(Dacl
, DaclLength
, ACL_REVISION
);
1263 if (!NT_SUCCESS(Status
)) goto CleanUp
;
1265 /* Add query rights for everyone */
1266 Status
= RtlAddAccessAllowedAce(Dacl
,
1268 SYNCHRONIZE
| EVENT_QUERY_STATE
| READ_CONTROL
,
1270 if (!NT_SUCCESS(Status
)) goto CleanUp
;
1272 /* Full rights for the admin */
1273 Status
= RtlAddAccessAllowedAce(Dacl
,
1277 if (!NT_SUCCESS(Status
)) goto CleanUp
;
1279 /* As well as full rights for the system */
1280 Status
= RtlAddAccessAllowedAce(Dacl
,
1284 if (!NT_SUCCESS(Status
)) goto CleanUp
;
1286 /* Set this DACL inside the SD */
1287 Status
= RtlSetDaclSecurityDescriptor(&SecurityDescriptor
,
1291 if (!NT_SUCCESS(Status
)) goto CleanUp
;
1293 /* Setup the event attributes, making sure it's a permanent one */
1294 InitializeObjectAttributes(&ObjectAttributes
,
1296 OBJ_KERNEL_HANDLE
| OBJ_PERMANENT
,
1298 &SecurityDescriptor
);
1300 /* Create the event */
1301 Status
= ZwCreateEvent(&EventHandle
,
1308 ExFreePoolWithTag(Dacl
, 'lcaD');
1310 /* Check if this is the success path */
1311 if (NT_SUCCESS(Status
))
1313 /* Add a reference to the object, then close the handle we had */
1314 Status
= ObReferenceObjectByHandle(EventHandle
,
1320 ZwClose (EventHandle
);
1330 MiInitializeMemoryEvents(VOID
)
1332 UNICODE_STRING LowString
= RTL_CONSTANT_STRING(L
"\\KernelObjects\\LowMemoryCondition");
1333 UNICODE_STRING HighString
= RTL_CONSTANT_STRING(L
"\\KernelObjects\\HighMemoryCondition");
1334 UNICODE_STRING LowPagedPoolString
= RTL_CONSTANT_STRING(L
"\\KernelObjects\\LowPagedPoolCondition");
1335 UNICODE_STRING HighPagedPoolString
= RTL_CONSTANT_STRING(L
"\\KernelObjects\\HighPagedPoolCondition");
1336 UNICODE_STRING LowNonPagedPoolString
= RTL_CONSTANT_STRING(L
"\\KernelObjects\\LowNonPagedPoolCondition");
1337 UNICODE_STRING HighNonPagedPoolString
= RTL_CONSTANT_STRING(L
"\\KernelObjects\\HighNonPagedPoolCondition");
1340 /* Check if we have a registry setting */
1341 if (MmLowMemoryThreshold
)
1343 /* Convert it to pages */
1344 MmLowMemoryThreshold
*= (_1MB
/ PAGE_SIZE
);
1348 /* The low memory threshold is hit when we don't consider that we have "plenty" of free pages anymore */
1349 MmLowMemoryThreshold
= MmPlentyFreePages
;
1351 /* More than one GB of memory? */
1352 if (MmNumberOfPhysicalPages
> 0x40000)
1354 /* Start at 32MB, and add another 16MB for each GB */
1355 MmLowMemoryThreshold
= (32 * _1MB
) / PAGE_SIZE
;
1356 MmLowMemoryThreshold
+= ((MmNumberOfPhysicalPages
- 0x40000) >> 7);
1358 else if (MmNumberOfPhysicalPages
> 0x8000)
1360 /* For systems with > 128MB RAM, add another 4MB for each 128MB */
1361 MmLowMemoryThreshold
+= ((MmNumberOfPhysicalPages
- 0x8000) >> 5);
1364 /* Don't let the minimum threshold go past 64MB */
1365 MmLowMemoryThreshold
= min(MmLowMemoryThreshold
, (64 * _1MB
) / PAGE_SIZE
);
1368 /* Check if we have a registry setting */
1369 if (MmHighMemoryThreshold
)
1371 /* Convert it into pages */
1372 MmHighMemoryThreshold
*= (_1MB
/ PAGE_SIZE
);
1376 /* Otherwise, the default is three times the low memory threshold */
1377 MmHighMemoryThreshold
= 3 * MmLowMemoryThreshold
;
1378 ASSERT(MmHighMemoryThreshold
> MmLowMemoryThreshold
);
1381 /* Make sure high threshold is actually higher than the low */
1382 MmHighMemoryThreshold
= max(MmHighMemoryThreshold
, MmLowMemoryThreshold
);
1384 /* Create the memory events for all the thresholds */
1385 Status
= MiCreateMemoryEvent(&LowString
, &MiLowMemoryEvent
);
1386 if (!NT_SUCCESS(Status
)) return FALSE
;
1387 Status
= MiCreateMemoryEvent(&HighString
, &MiHighMemoryEvent
);
1388 if (!NT_SUCCESS(Status
)) return FALSE
;
1389 Status
= MiCreateMemoryEvent(&LowPagedPoolString
, &MiLowPagedPoolEvent
);
1390 if (!NT_SUCCESS(Status
)) return FALSE
;
1391 Status
= MiCreateMemoryEvent(&HighPagedPoolString
, &MiHighPagedPoolEvent
);
1392 if (!NT_SUCCESS(Status
)) return FALSE
;
1393 Status
= MiCreateMemoryEvent(&LowNonPagedPoolString
, &MiLowNonPagedPoolEvent
);
1394 if (!NT_SUCCESS(Status
)) return FALSE
;
1395 Status
= MiCreateMemoryEvent(&HighNonPagedPoolString
, &MiHighNonPagedPoolEvent
);
1396 if (!NT_SUCCESS(Status
)) return FALSE
;
1398 /* Now setup the pool events */
1399 MiInitializePoolEvents();
1401 /* Set the initial event state */
1402 MiNotifyMemoryEvents();
1409 MiAddHalIoMappings(VOID
)
1412 PMMPDE PointerPde
, LastPde
;
1415 PFN_NUMBER PageFrameIndex
;
1417 /* HAL Heap address -- should be on a PDE boundary */
1418 BaseAddress
= (PVOID
)MM_HAL_VA_START
;
1419 ASSERT(MiAddressToPteOffset(BaseAddress
) == 0);
1421 /* Check how many PDEs the heap has */
1422 PointerPde
= MiAddressToPde(BaseAddress
);
1423 LastPde
= MiAddressToPde((PVOID
)MM_HAL_VA_END
);
1425 while (PointerPde
<= LastPde
)
1427 /* Does the HAL own this mapping? */
1428 if ((PointerPde
->u
.Hard
.Valid
== 1) &&
1429 (MI_IS_PAGE_LARGE(PointerPde
) == FALSE
))
1431 /* Get the PTE for it and scan each page */
1432 PointerPte
= MiAddressToPte(BaseAddress
);
1433 for (j
= 0 ; j
< PTE_COUNT
; j
++)
1435 /* Does the HAL own this page? */
1436 if (PointerPte
->u
.Hard
.Valid
== 1)
1438 /* Is the HAL using it for device or I/O mapped memory? */
1439 PageFrameIndex
= PFN_FROM_PTE(PointerPte
);
1440 if (!MiGetPfnEntry(PageFrameIndex
))
1442 /* FIXME: For PAT, we need to track I/O cache attributes for coherency */
1443 DPRINT1("HAL I/O Mapping at %p is unsafe\n", BaseAddress
);
1447 /* Move to the next page */
1448 BaseAddress
= (PVOID
)((ULONG_PTR
)BaseAddress
+ PAGE_SIZE
);
1454 /* Move to the next address */
1455 BaseAddress
= (PVOID
)((ULONG_PTR
)BaseAddress
+ PDE_MAPPED_VA
);
1458 /* Move to the next PDE */
1465 MmDumpArmPfnDatabase(IN BOOLEAN StatusOnly
)
1469 PCHAR Consumer
= "Unknown";
1471 ULONG ActivePages
= 0, FreePages
= 0, OtherPages
= 0;
1473 ULONG UsageBucket
[MI_USAGE_FREE_PAGE
+ 1] = {0};
1474 PCHAR MI_USAGE_TEXT
[MI_USAGE_FREE_PAGE
+ 1] =
1502 // Loop the PFN database
1504 KeRaiseIrql(HIGH_LEVEL
, &OldIrql
);
1505 for (i
= 0; i
<= MmHighestPhysicalPage
; i
++)
1507 Pfn1
= MiGetPfnEntry(i
);
1508 if (!Pfn1
) continue;
1510 ASSERT(Pfn1
->PfnUsage
<= MI_USAGE_FREE_PAGE
);
1513 // Get the page location
1515 switch (Pfn1
->u3
.e1
.PageLocation
)
1517 case ActiveAndValid
:
1519 Consumer
= "Active and Valid";
1523 case ZeroedPageList
:
1525 Consumer
= "Zero Page List";
1531 Consumer
= "Free Page List";
1537 Consumer
= "Other (ASSERT!)";
1543 /* Add into bucket */
1544 UsageBucket
[Pfn1
->PfnUsage
]++;
1548 // Pretty-print the page
1551 DbgPrint("0x%08p:\t%20s\t(%04d.%04d)\t[%16s - %16s])\n",
1554 Pfn1
->u3
.e2
.ReferenceCount
,
1555 Pfn1
->u2
.ShareCount
== LIST_HEAD
? 0xFFFF : Pfn1
->u2
.ShareCount
,
1557 MI_USAGE_TEXT
[Pfn1
->PfnUsage
],
1565 DbgPrint("Active: %5d pages\t[%6d KB]\n", ActivePages
, (ActivePages
<< PAGE_SHIFT
) / 1024);
1566 DbgPrint("Free: %5d pages\t[%6d KB]\n", FreePages
, (FreePages
<< PAGE_SHIFT
) / 1024);
1567 DbgPrint("-----------------------------------------\n");
1569 OtherPages
= UsageBucket
[MI_USAGE_BOOT_DRIVER
];
1570 DbgPrint("Boot Images: %5d pages\t[%6d KB]\n", OtherPages
, (OtherPages
<< PAGE_SHIFT
) / 1024);
1571 OtherPages
= UsageBucket
[MI_USAGE_DRIVER_PAGE
];
1572 DbgPrint("System Drivers: %5d pages\t[%6d KB]\n", OtherPages
, (OtherPages
<< PAGE_SHIFT
) / 1024);
1573 OtherPages
= UsageBucket
[MI_USAGE_PFN_DATABASE
];
1574 DbgPrint("PFN Database: %5d pages\t[%6d KB]\n", OtherPages
, (OtherPages
<< PAGE_SHIFT
) / 1024);
1575 OtherPages
= UsageBucket
[MI_USAGE_PAGE_TABLE
] + UsageBucket
[MI_USAGE_LEGACY_PAGE_DIRECTORY
];
1576 DbgPrint("Page Tables: %5d pages\t[%6d KB]\n", OtherPages
, (OtherPages
<< PAGE_SHIFT
) / 1024);
1577 OtherPages
= UsageBucket
[MI_USAGE_NONPAGED_POOL
] + UsageBucket
[MI_USAGE_NONPAGED_POOL_EXPANSION
];
1578 DbgPrint("NonPaged Pool: %5d pages\t[%6d KB]\n", OtherPages
, (OtherPages
<< PAGE_SHIFT
) / 1024);
1579 OtherPages
= UsageBucket
[MI_USAGE_PAGED_POOL
];
1580 DbgPrint("Paged Pool: %5d pages\t[%6d KB]\n", OtherPages
, (OtherPages
<< PAGE_SHIFT
) / 1024);
1581 OtherPages
= UsageBucket
[MI_USAGE_KERNEL_STACK
] + UsageBucket
[MI_USAGE_KERNEL_STACK_EXPANSION
];
1582 DbgPrint("Kernel Stack: %5d pages\t[%6d KB]\n", OtherPages
, (OtherPages
<< PAGE_SHIFT
) / 1024);
1583 OtherPages
= UsageBucket
[MI_USAGE_INIT_MEMORY
];
1584 DbgPrint("Init Memory: %5d pages\t[%6d KB]\n", OtherPages
, (OtherPages
<< PAGE_SHIFT
) / 1024);
1585 OtherPages
= UsageBucket
[MI_USAGE_SECTION
];
1586 DbgPrint("Sections: %5d pages\t[%6d KB]\n", OtherPages
, (OtherPages
<< PAGE_SHIFT
) / 1024);
1587 OtherPages
= UsageBucket
[MI_USAGE_CACHE
];
1588 DbgPrint("Cache: %5d pages\t[%6d KB]\n", OtherPages
, (OtherPages
<< PAGE_SHIFT
) / 1024);
1590 KeLowerIrql(OldIrql
);
1593 PPHYSICAL_MEMORY_DESCRIPTOR
1596 MmInitializeMemoryLimits(IN PLOADER_PARAMETER_BLOCK LoaderBlock
,
1597 IN PBOOLEAN IncludeType
)
1599 PLIST_ENTRY NextEntry
;
1600 ULONG Run
= 0, InitialRuns
;
1601 PFN_NUMBER NextPage
= -1, PageCount
= 0;
1602 PPHYSICAL_MEMORY_DESCRIPTOR Buffer
, NewBuffer
;
1603 PMEMORY_ALLOCATION_DESCRIPTOR MdBlock
;
1606 // Start with the maximum we might need
1608 InitialRuns
= MiNumberDescriptors
;
1611 // Allocate the maximum we'll ever need
1613 Buffer
= ExAllocatePoolWithTag(NonPagedPool
,
1614 sizeof(PHYSICAL_MEMORY_DESCRIPTOR
) +
1615 sizeof(PHYSICAL_MEMORY_RUN
) *
1618 if (!Buffer
) return NULL
;
1621 // For now that's how many runs we have
1623 Buffer
->NumberOfRuns
= InitialRuns
;
1626 // Now loop through the descriptors again
1628 NextEntry
= LoaderBlock
->MemoryDescriptorListHead
.Flink
;
1629 while (NextEntry
!= &LoaderBlock
->MemoryDescriptorListHead
)
1632 // Grab each one, and check if it's one we should include
1634 MdBlock
= CONTAINING_RECORD(NextEntry
,
1635 MEMORY_ALLOCATION_DESCRIPTOR
,
1637 if ((MdBlock
->MemoryType
< LoaderMaximum
) &&
1638 (IncludeType
[MdBlock
->MemoryType
]))
1641 // Add this to our running total
1643 PageCount
+= MdBlock
->PageCount
;
1646 // Check if the next page is described by the next descriptor
1648 if (MdBlock
->BasePage
== NextPage
)
1651 // Combine it into the same physical run
1653 ASSERT(MdBlock
->PageCount
!= 0);
1654 Buffer
->Run
[Run
- 1].PageCount
+= MdBlock
->PageCount
;
1655 NextPage
+= MdBlock
->PageCount
;
1660 // Otherwise just duplicate the descriptor's contents
1662 Buffer
->Run
[Run
].BasePage
= MdBlock
->BasePage
;
1663 Buffer
->Run
[Run
].PageCount
= MdBlock
->PageCount
;
1664 NextPage
= Buffer
->Run
[Run
].BasePage
+ Buffer
->Run
[Run
].PageCount
;
1667 // And in this case, increase the number of runs
1674 // Try the next descriptor
1676 NextEntry
= MdBlock
->ListEntry
.Flink
;
1680 // We should not have been able to go past our initial estimate
1682 ASSERT(Run
<= Buffer
->NumberOfRuns
);
1685 // Our guess was probably exaggerated...
1687 if (InitialRuns
> Run
)
1690 // Allocate a more accurately sized buffer
1692 NewBuffer
= ExAllocatePoolWithTag(NonPagedPool
,
1693 sizeof(PHYSICAL_MEMORY_DESCRIPTOR
) +
1694 sizeof(PHYSICAL_MEMORY_RUN
) *
1700 // Copy the old buffer into the new, then free it
1702 RtlCopyMemory(NewBuffer
->Run
,
1704 sizeof(PHYSICAL_MEMORY_RUN
) * Run
);
1705 ExFreePoolWithTag(Buffer
, 'lMmM');
1708 // Now use the new buffer
1715 // Write the final numbers, and return it
1717 Buffer
->NumberOfRuns
= Run
;
1718 Buffer
->NumberOfPages
= PageCount
;
1725 MiBuildPagedPool(VOID
)
1729 MMPDE TempPde
= ValidKernelPde
;
1730 PFN_NUMBER PageFrameIndex
;
1734 #if (_MI_PAGING_LEVELS >= 3)
1735 MMPPE TempPpe
= ValidKernelPpe
;
1737 #elif (_MI_PAGING_LEVELS == 2)
1738 MMPTE TempPte
= ValidKernelPte
;
1741 // Get the page frame number for the system page directory
1743 PointerPte
= MiAddressToPte(PDE_BASE
);
1744 ASSERT(PD_COUNT
== 1);
1745 MmSystemPageDirectory
[0] = PFN_FROM_PTE(PointerPte
);
1748 // Allocate a system PTE which will hold a copy of the page directory
1750 PointerPte
= MiReserveSystemPtes(1, SystemPteSpace
);
1752 MmSystemPagePtes
= MiPteToAddress(PointerPte
);
1755 // Make this system PTE point to the system page directory.
1756 // It is now essentially double-mapped. This will be used later for lazy
1757 // evaluation of PDEs accross process switches, similarly to how the Global
1758 // page directory array in the old ReactOS Mm is used (but in a less hacky
1761 TempPte
= ValidKernelPte
;
1762 ASSERT(PD_COUNT
== 1);
1763 TempPte
.u
.Hard
.PageFrameNumber
= MmSystemPageDirectory
[0];
1764 MI_WRITE_VALID_PTE(PointerPte
, TempPte
);
1767 // Let's get back to paged pool work: size it up.
1768 // By default, it should be twice as big as nonpaged pool.
1770 MmSizeOfPagedPoolInBytes
= 2 * MmMaximumNonPagedPoolInBytes
;
1771 if (MmSizeOfPagedPoolInBytes
> ((ULONG_PTR
)MmNonPagedSystemStart
-
1772 (ULONG_PTR
)MmPagedPoolStart
))
1775 // On the other hand, we have limited VA space, so make sure that the VA
1776 // for paged pool doesn't overflow into nonpaged pool VA. Otherwise, set
1777 // whatever maximum is possible.
1779 MmSizeOfPagedPoolInBytes
= (ULONG_PTR
)MmNonPagedSystemStart
-
1780 (ULONG_PTR
)MmPagedPoolStart
;
1784 // Get the size in pages and make sure paged pool is at least 32MB.
1786 Size
= MmSizeOfPagedPoolInBytes
;
1787 if (Size
< MI_MIN_INIT_PAGED_POOLSIZE
) Size
= MI_MIN_INIT_PAGED_POOLSIZE
;
1788 Size
= BYTES_TO_PAGES(Size
);
1791 // Now check how many PTEs will be required for these many pages.
1793 Size
= (Size
+ (1024 - 1)) / 1024;
1796 // Recompute the page-aligned size of the paged pool, in bytes and pages.
1798 MmSizeOfPagedPoolInBytes
= Size
* PAGE_SIZE
* 1024;
1799 MmSizeOfPagedPoolInPages
= MmSizeOfPagedPoolInBytes
>> PAGE_SHIFT
;
1802 // Let's be really sure this doesn't overflow into nonpaged system VA
1804 ASSERT((MmSizeOfPagedPoolInBytes
+ (ULONG_PTR
)MmPagedPoolStart
) <=
1805 (ULONG_PTR
)MmNonPagedSystemStart
);
1808 // This is where paged pool ends
1810 MmPagedPoolEnd
= (PVOID
)(((ULONG_PTR
)MmPagedPoolStart
+
1811 MmSizeOfPagedPoolInBytes
) - 1);
1814 // Lock the PFN database
1816 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
1818 #if (_MI_PAGING_LEVELS >= 3)
1819 /* On these systems, there's no double-mapping, so instead, the PPEs
1820 * are setup to span the entire paged pool area, so there's no need for the
1822 for (PointerPpe
= MiAddressToPpe(MmPagedPoolStart
);
1823 PointerPpe
<= MiAddressToPpe(MmPagedPoolEnd
);
1826 /* Check if the PPE is already valid */
1827 if (!PointerPpe
->u
.Hard
.Valid
)
1829 /* It is not, so map a fresh zeroed page */
1830 TempPpe
.u
.Hard
.PageFrameNumber
= MiRemoveZeroPage(0);
1831 MI_WRITE_VALID_PPE(PointerPpe
, TempPpe
);
1837 // So now get the PDE for paged pool and zero it out
1839 PointerPde
= MiAddressToPde(MmPagedPoolStart
);
1840 RtlZeroMemory(PointerPde
,
1841 (1 + MiAddressToPde(MmPagedPoolEnd
) - PointerPde
) * sizeof(MMPDE
));
1844 // Next, get the first and last PTE
1846 PointerPte
= MiAddressToPte(MmPagedPoolStart
);
1847 MmPagedPoolInfo
.FirstPteForPagedPool
= PointerPte
;
1848 MmPagedPoolInfo
.LastPteForPagedPool
= MiAddressToPte(MmPagedPoolEnd
);
1850 /* Allocate a page and map the first paged pool PDE */
1851 MI_SET_USAGE(MI_USAGE_PAGED_POOL
);
1852 MI_SET_PROCESS2("Kernel");
1853 PageFrameIndex
= MiRemoveZeroPage(0);
1854 TempPde
.u
.Hard
.PageFrameNumber
= PageFrameIndex
;
1855 MI_WRITE_VALID_PDE(PointerPde
, TempPde
);
1856 #if (_MI_PAGING_LEVELS >= 3)
1857 /* Use the PPE of MmPagedPoolStart that was setup above */
1858 // Bla = PFN_FROM_PTE(PpeAddress(MmPagedPool...));
1860 /* Initialize the PFN entry for it */
1861 MiInitializePfnForOtherProcess(PageFrameIndex
,
1863 PFN_FROM_PTE(MiAddressToPpe(MmPagedPoolStart
)));
1865 /* Do it this way */
1866 // Bla = MmSystemPageDirectory[(PointerPde - (PMMPTE)PDE_BASE) / PDE_COUNT]
1868 /* Initialize the PFN entry for it */
1869 MiInitializePfnForOtherProcess(PageFrameIndex
,
1871 MmSystemPageDirectory
[(PointerPde
- (PMMPDE
)PDE_BASE
) / PDE_COUNT
]);
1875 // Release the PFN database lock
1877 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
1880 // We only have one PDE mapped for now... at fault time, additional PDEs
1881 // will be allocated to handle paged pool growth. This is where they'll have
1884 MmPagedPoolInfo
.NextPdeForPagedPoolExpansion
= PointerPde
+ 1;
1887 // We keep track of each page via a bit, so check how big the bitmap will
1888 // have to be (make sure to align our page count such that it fits nicely
1889 // into a 4-byte aligned bitmap.
1891 // We'll also allocate the bitmap header itself part of the same buffer.
1894 ASSERT(Size
== MmSizeOfPagedPoolInPages
);
1895 BitMapSize
= (ULONG
)Size
;
1896 Size
= sizeof(RTL_BITMAP
) + (((Size
+ 31) / 32) * sizeof(ULONG
));
1899 // Allocate the allocation bitmap, which tells us which regions have not yet
1900 // been mapped into memory
1902 MmPagedPoolInfo
.PagedPoolAllocationMap
= ExAllocatePoolWithTag(NonPagedPool
,
1905 ASSERT(MmPagedPoolInfo
.PagedPoolAllocationMap
);
1908 // Initialize it such that at first, only the first page's worth of PTEs is
1909 // marked as allocated (incidentially, the first PDE we allocated earlier).
1911 RtlInitializeBitMap(MmPagedPoolInfo
.PagedPoolAllocationMap
,
1912 (PULONG
)(MmPagedPoolInfo
.PagedPoolAllocationMap
+ 1),
1914 RtlSetAllBits(MmPagedPoolInfo
.PagedPoolAllocationMap
);
1915 RtlClearBits(MmPagedPoolInfo
.PagedPoolAllocationMap
, 0, 1024);
1918 // We have a second bitmap, which keeps track of where allocations end.
1919 // Given the allocation bitmap and a base address, we can therefore figure
1920 // out which page is the last page of that allocation, and thus how big the
1921 // entire allocation is.
1923 MmPagedPoolInfo
.EndOfPagedPoolBitmap
= ExAllocatePoolWithTag(NonPagedPool
,
1926 ASSERT(MmPagedPoolInfo
.EndOfPagedPoolBitmap
);
1927 RtlInitializeBitMap(MmPagedPoolInfo
.EndOfPagedPoolBitmap
,
1928 (PULONG
)(MmPagedPoolInfo
.EndOfPagedPoolBitmap
+ 1),
1932 // Since no allocations have been made yet, there are no bits set as the end
1934 RtlClearAllBits(MmPagedPoolInfo
.EndOfPagedPoolBitmap
);
1937 // Initialize paged pool.
1939 InitializePool(PagedPool
, 0);
1941 /* Initialize special pool */
1942 MiInitializeSpecialPool();
1944 /* Default low threshold of 30MB or one fifth of paged pool */
1945 MiLowPagedPoolThreshold
= (30 * _1MB
) >> PAGE_SHIFT
;
1946 MiLowPagedPoolThreshold
= min(MiLowPagedPoolThreshold
, Size
/ 5);
1948 /* Default high threshold of 60MB or 25% */
1949 MiHighPagedPoolThreshold
= (60 * _1MB
) >> PAGE_SHIFT
;
1950 MiHighPagedPoolThreshold
= min(MiHighPagedPoolThreshold
, (Size
* 2) / 5);
1951 ASSERT(MiLowPagedPoolThreshold
< MiHighPagedPoolThreshold
);
1953 /* Setup the global session space */
1954 MiInitializeSystemSpaceMap(NULL
);
1960 MiDbgDumpMemoryDescriptors(VOID
)
1962 PLIST_ENTRY NextEntry
;
1963 PMEMORY_ALLOCATION_DESCRIPTOR Md
;
1964 PFN_NUMBER TotalPages
= 0;
1973 "FirmwareTemporary ",
1974 "FirmwarePermanent ",
1981 "ConsoleOutDriver ",
1983 "StartupKernelStack",
1984 "StartupPanicStack ",
1996 DPRINT1("Base\t\tLength\t\tType\n");
1997 for (NextEntry
= KeLoaderBlock
->MemoryDescriptorListHead
.Flink
;
1998 NextEntry
!= &KeLoaderBlock
->MemoryDescriptorListHead
;
1999 NextEntry
= NextEntry
->Flink
)
2001 Md
= CONTAINING_RECORD(NextEntry
, MEMORY_ALLOCATION_DESCRIPTOR
, ListEntry
);
2002 DPRINT1("%08lX\t%08lX\t%s\n", Md
->BasePage
, Md
->PageCount
, MemType
[Md
->MemoryType
]);
2003 TotalPages
+= Md
->PageCount
;
2006 DPRINT1("Total: %08lX (%lu MB)\n", (ULONG
)TotalPages
, (ULONG
)(TotalPages
* PAGE_SIZE
) / 1024 / 1024);
2012 MmArmInitSystem(IN ULONG Phase
,
2013 IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
2016 BOOLEAN IncludeType
[LoaderMaximum
];
2018 PPHYSICAL_MEMORY_RUN Run
;
2019 PFN_NUMBER PageCount
;
2022 PMMPTE PointerPte
, TestPte
;
2026 /* Dump memory descriptors */
2027 if (MiDbgEnableMdDump
) MiDbgDumpMemoryDescriptors();
2030 // Instantiate memory that we don't consider RAM/usable
2031 // We use the same exclusions that Windows does, in order to try to be
2032 // compatible with WinLDR-style booting
2034 for (i
= 0; i
< LoaderMaximum
; i
++) IncludeType
[i
] = TRUE
;
2035 IncludeType
[LoaderBad
] = FALSE
;
2036 IncludeType
[LoaderFirmwarePermanent
] = FALSE
;
2037 IncludeType
[LoaderSpecialMemory
] = FALSE
;
2038 IncludeType
[LoaderBBTMemory
] = FALSE
;
2041 /* Count physical pages on the system */
2042 MiScanMemoryDescriptors(LoaderBlock
);
2044 /* Initialize the phase 0 temporary event */
2045 KeInitializeEvent(&MiTempEvent
, NotificationEvent
, FALSE
);
2047 /* Set all the events to use the temporary event for now */
2048 MiLowMemoryEvent
= &MiTempEvent
;
2049 MiHighMemoryEvent
= &MiTempEvent
;
2050 MiLowPagedPoolEvent
= &MiTempEvent
;
2051 MiHighPagedPoolEvent
= &MiTempEvent
;
2052 MiLowNonPagedPoolEvent
= &MiTempEvent
;
2053 MiHighNonPagedPoolEvent
= &MiTempEvent
;
2056 // Define the basic user vs. kernel address space separation
2058 MmSystemRangeStart
= (PVOID
)MI_DEFAULT_SYSTEM_RANGE_START
;
2059 MmUserProbeAddress
= (ULONG_PTR
)MI_USER_PROBE_ADDRESS
;
2060 MmHighestUserAddress
= (PVOID
)MI_HIGHEST_USER_ADDRESS
;
2062 /* Highest PTE and PDE based on the addresses above */
2063 MiHighestUserPte
= MiAddressToPte(MmHighestUserAddress
);
2064 MiHighestUserPde
= MiAddressToPde(MmHighestUserAddress
);
2065 #if (_MI_PAGING_LEVELS >= 3)
2066 MiHighestUserPpe
= MiAddressToPpe(MmHighestUserAddress
);
2067 #if (_MI_PAGING_LEVELS >= 4)
2068 MiHighestUserPxe
= MiAddressToPxe(MmHighestUserAddress
);
2072 // Get the size of the boot loader's image allocations and then round
2073 // that region up to a PDE size, so that any PDEs we might create for
2074 // whatever follows are separate from the PDEs that boot loader might've
2075 // already created (and later, we can blow all that away if we want to).
2077 MmBootImageSize
= KeLoaderBlock
->Extension
->LoaderPagesSpanned
;
2078 MmBootImageSize
*= PAGE_SIZE
;
2079 MmBootImageSize
= (MmBootImageSize
+ PDE_MAPPED_VA
- 1) & ~(PDE_MAPPED_VA
- 1);
2080 ASSERT((MmBootImageSize
% PDE_MAPPED_VA
) == 0);
2082 /* Initialize session space address layout */
2083 MiInitializeSessionSpaceLayout();
2085 /* Set the based section highest address */
2086 MmHighSectionBase
= (PVOID
)((ULONG_PTR
)MmHighestUserAddress
- 0x800000);
2089 /* The subection PTE format depends on things being 8-byte aligned */
2090 ASSERT((sizeof(CONTROL_AREA
) % 8) == 0);
2091 ASSERT((sizeof(SUBSECTION
) % 8) == 0);
2093 /* Prototype PTEs are assumed to be in paged pool, so check if the math works */
2094 PointerPte
= (PMMPTE
)MmPagedPoolStart
;
2095 MI_MAKE_PROTOTYPE_PTE(&TempPte
, PointerPte
);
2096 TestPte
= MiProtoPteToPte(&TempPte
);
2097 ASSERT(PointerPte
== TestPte
);
2099 /* Try the last nonpaged pool address */
2100 PointerPte
= (PMMPTE
)MI_NONPAGED_POOL_END
;
2101 MI_MAKE_PROTOTYPE_PTE(&TempPte
, PointerPte
);
2102 TestPte
= MiProtoPteToPte(&TempPte
);
2103 ASSERT(PointerPte
== TestPte
);
2105 /* Try a bunch of random addresses near the end of the address space */
2106 PointerPte
= (PMMPTE
)0xFFFC8000;
2107 for (j
= 0; j
< 20; j
+= 1)
2109 MI_MAKE_PROTOTYPE_PTE(&TempPte
, PointerPte
);
2110 TestPte
= MiProtoPteToPte(&TempPte
);
2111 ASSERT(PointerPte
== TestPte
);
2115 /* Subsection PTEs are always in nonpaged pool, pick a random address to try */
2116 PointerPte
= (PMMPTE
)0xFFAACBB8;
2117 MI_MAKE_SUBSECTION_PTE(&TempPte
, PointerPte
);
2118 TestPte
= MiSubsectionPteToSubsection(&TempPte
);
2119 ASSERT(PointerPte
== TestPte
);
2122 /* Loop all 8 standby lists */
2123 for (i
= 0; i
< 8; i
++)
2125 /* Initialize them */
2126 MmStandbyPageListByPriority
[i
].Total
= 0;
2127 MmStandbyPageListByPriority
[i
].ListName
= StandbyPageList
;
2128 MmStandbyPageListByPriority
[i
].Flink
= MM_EMPTY_LIST
;
2129 MmStandbyPageListByPriority
[i
].Blink
= MM_EMPTY_LIST
;
2132 /* Initialize the user mode image list */
2133 InitializeListHead(&MmLoadedUserImageList
);
2135 /* Initialize critical section timeout value (relative time is negative) */
2136 MmCriticalSectionTimeout
.QuadPart
= MmCritsectTimeoutSeconds
* (-10000000LL);
2138 /* Initialize the paged pool mutex and the section commit mutex */
2139 KeInitializeGuardedMutex(&MmPagedPoolMutex
);
2140 KeInitializeGuardedMutex(&MmSectionCommitMutex
);
2141 KeInitializeGuardedMutex(&MmSectionBasedMutex
);
2143 /* Initialize the Loader Lock */
2144 KeInitializeMutant(&MmSystemLoadLock
, FALSE
);
2146 /* Set the zero page event */
2147 KeInitializeEvent(&MmZeroingPageEvent
, SynchronizationEvent
, FALSE
);
2148 MmZeroingPageThreadActive
= FALSE
;
2150 /* Initialize the dead stack S-LIST */
2151 InitializeSListHead(&MmDeadStackSListHead
);
2154 // Check if this is a machine with less than 19MB of RAM
2156 PageCount
= MmNumberOfPhysicalPages
;
2157 if (PageCount
< MI_MIN_PAGES_FOR_SYSPTE_TUNING
)
2160 // Use the very minimum of system PTEs
2162 MmNumberOfSystemPtes
= 7000;
2169 MmNumberOfSystemPtes
= 11000;
2170 if (PageCount
> MI_MIN_PAGES_FOR_SYSPTE_BOOST
)
2173 // Double the amount of system PTEs
2175 MmNumberOfSystemPtes
<<= 1;
2177 if (PageCount
> MI_MIN_PAGES_FOR_SYSPTE_BOOST_BOOST
)
2180 // Double the amount of system PTEs
2182 MmNumberOfSystemPtes
<<= 1;
2186 DPRINT("System PTE count has been tuned to %lu (%lu bytes)\n",
2187 MmNumberOfSystemPtes
, MmNumberOfSystemPtes
* PAGE_SIZE
);
2189 /* Check if no values are set for the heap limits */
2190 if (MmHeapSegmentReserve
== 0)
2192 MmHeapSegmentReserve
= 2 * _1MB
;
2195 if (MmHeapSegmentCommit
== 0)
2197 MmHeapSegmentCommit
= 2 * PAGE_SIZE
;
2200 if (MmHeapDeCommitTotalFreeThreshold
== 0)
2202 MmHeapDeCommitTotalFreeThreshold
= 64 * _1KB
;
2205 if (MmHeapDeCommitFreeBlockThreshold
== 0)
2207 MmHeapDeCommitFreeBlockThreshold
= PAGE_SIZE
;
2210 /* Initialize the working set lock */
2211 ExInitializePushLock(&MmSystemCacheWs
.WorkingSetMutex
);
2213 /* Set commit limit */
2214 MmTotalCommitLimit
= 2 * _1GB
;
2215 MmTotalCommitLimitMaximum
= MmTotalCommitLimit
;
2217 /* Has the allocation fragment been setup? */
2218 if (!MmAllocationFragment
)
2220 /* Use the default value */
2221 MmAllocationFragment
= MI_ALLOCATION_FRAGMENT
;
2222 if (PageCount
< ((256 * _1MB
) / PAGE_SIZE
))
2224 /* On memory systems with less than 256MB, divide by 4 */
2225 MmAllocationFragment
= MI_ALLOCATION_FRAGMENT
/ 4;
2227 else if (PageCount
< (_1GB
/ PAGE_SIZE
))
2229 /* On systems with less than 1GB, divide by 2 */
2230 MmAllocationFragment
= MI_ALLOCATION_FRAGMENT
/ 2;
2235 /* Convert from 1KB fragments to pages */
2236 MmAllocationFragment
*= _1KB
;
2237 MmAllocationFragment
= ROUND_TO_PAGES(MmAllocationFragment
);
2239 /* Don't let it past the maximum */
2240 MmAllocationFragment
= min(MmAllocationFragment
,
2241 MI_MAX_ALLOCATION_FRAGMENT
);
2243 /* Don't let it too small either */
2244 MmAllocationFragment
= max(MmAllocationFragment
,
2245 MI_MIN_ALLOCATION_FRAGMENT
);
2248 /* Check for kernel stack size that's too big */
2249 if (MmLargeStackSize
> (KERNEL_LARGE_STACK_SIZE
/ _1KB
))
2251 /* Sanitize to default value */
2252 MmLargeStackSize
= KERNEL_LARGE_STACK_SIZE
;
2256 /* Take the registry setting, and convert it into bytes */
2257 MmLargeStackSize
*= _1KB
;
2259 /* Now align it to a page boundary */
2260 MmLargeStackSize
= PAGE_ROUND_UP(MmLargeStackSize
);
2263 ASSERT(MmLargeStackSize
<= KERNEL_LARGE_STACK_SIZE
);
2264 ASSERT((MmLargeStackSize
& (PAGE_SIZE
- 1)) == 0);
2266 /* Make sure it's not too low */
2267 if (MmLargeStackSize
< KERNEL_STACK_SIZE
) MmLargeStackSize
= KERNEL_STACK_SIZE
;
2270 /* Compute color information (L2 cache-separated paging lists) */
2271 MiComputeColorInformation();
2273 // Calculate the number of bytes for the PFN database
2274 // then add the color tables and convert to pages
2275 MxPfnAllocation
= (MmHighestPhysicalPage
+ 1) * sizeof(MMPFN
);
2276 MxPfnAllocation
+= (MmSecondaryColors
* sizeof(MMCOLOR_TABLES
) * 2);
2277 MxPfnAllocation
>>= PAGE_SHIFT
;
2279 // We have to add one to the count here, because in the process of
2280 // shifting down to the page size, we actually ended up getting the
2281 // lower aligned size (so say, 0x5FFFF bytes is now 0x5F pages).
2282 // Later on, we'll shift this number back into bytes, which would cause
2283 // us to end up with only 0x5F000 bytes -- when we actually want to have
2287 /* Initialize the platform-specific parts */
2288 MiInitMachineDependent(LoaderBlock
);
2291 // Build the physical memory block
2293 MmPhysicalMemoryBlock
= MmInitializeMemoryLimits(LoaderBlock
,
2297 // Allocate enough buffer for the PFN bitmap
2298 // Align it up to a 32-bit boundary
2300 Bitmap
= ExAllocatePoolWithTag(NonPagedPool
,
2301 (((MmHighestPhysicalPage
+ 1) + 31) / 32) * 4,
2308 KeBugCheckEx(INSTALL_MORE_MEMORY
,
2309 MmNumberOfPhysicalPages
,
2310 MmLowestPhysicalPage
,
2311 MmHighestPhysicalPage
,
2316 // Initialize it and clear all the bits to begin with
2318 RtlInitializeBitMap(&MiPfnBitMap
,
2320 (ULONG
)MmHighestPhysicalPage
+ 1);
2321 RtlClearAllBits(&MiPfnBitMap
);
2324 // Loop physical memory runs
2326 for (i
= 0; i
< MmPhysicalMemoryBlock
->NumberOfRuns
; i
++)
2331 Run
= &MmPhysicalMemoryBlock
->Run
[i
];
2332 DPRINT("PHYSICAL RAM [0x%08p to 0x%08p]\n",
2333 Run
->BasePage
<< PAGE_SHIFT
,
2334 (Run
->BasePage
+ Run
->PageCount
) << PAGE_SHIFT
);
2337 // Make sure it has pages inside it
2342 // Set the bits in the PFN bitmap
2344 RtlSetBits(&MiPfnBitMap
, (ULONG
)Run
->BasePage
, (ULONG
)Run
->PageCount
);
2348 /* Look for large page cache entries that need caching */
2349 MiSyncCachedRanges();
2351 /* Loop for HAL Heap I/O device mappings that need coherency tracking */
2352 MiAddHalIoMappings();
2354 /* Set the initial resident page count */
2355 MmResidentAvailablePages
= MmAvailablePages
- 32;
2357 /* Initialize large page structures on PAE/x64, and MmProcessList on x86 */
2358 MiInitializeLargePageSupport();
2360 /* Check if the registry says any drivers should be loaded with large pages */
2361 MiInitializeDriverLargePageList();
2363 /* Relocate the boot drivers into system PTE space and fixup their PFNs */
2364 MiReloadBootLoadedDrivers(LoaderBlock
);
2366 /* FIXME: Call out into Driver Verifier for initialization */
2368 /* Check how many pages the system has */
2369 if (MmNumberOfPhysicalPages
<= ((13 * _1MB
) / PAGE_SIZE
))
2371 /* Set small system */
2372 MmSystemSize
= MmSmallSystem
;
2373 MmMaximumDeadKernelStacks
= 0;
2375 else if (MmNumberOfPhysicalPages
<= ((19 * _1MB
) / PAGE_SIZE
))
2377 /* Set small system and add 100 pages for the cache */
2378 MmSystemSize
= MmSmallSystem
;
2379 MmSystemCacheWsMinimum
+= 100;
2380 MmMaximumDeadKernelStacks
= 2;
2384 /* Set medium system and add 400 pages for the cache */
2385 MmSystemSize
= MmMediumSystem
;
2386 MmSystemCacheWsMinimum
+= 400;
2387 MmMaximumDeadKernelStacks
= 5;
2390 /* Check for less than 24MB */
2391 if (MmNumberOfPhysicalPages
< ((24 * _1MB
) / PAGE_SIZE
))
2393 /* No more than 32 pages */
2394 MmSystemCacheWsMinimum
= 32;
2397 /* Check for more than 32MB */
2398 if (MmNumberOfPhysicalPages
>= ((32 * _1MB
) / PAGE_SIZE
))
2400 /* Check for product type being "Wi" for WinNT */
2401 if (MmProductType
== '\0i\0W')
2403 /* Then this is a large system */
2404 MmSystemSize
= MmLargeSystem
;
2408 /* For servers, we need 64MB to consider this as being large */
2409 if (MmNumberOfPhysicalPages
>= ((64 * _1MB
) / PAGE_SIZE
))
2411 /* Set it as large */
2412 MmSystemSize
= MmLargeSystem
;
2417 /* Check for more than 33 MB */
2418 if (MmNumberOfPhysicalPages
> ((33 * _1MB
) / PAGE_SIZE
))
2420 /* Add another 500 pages to the cache */
2421 MmSystemCacheWsMinimum
+= 500;
2424 /* Now setup the shared user data fields */
2425 ASSERT(SharedUserData
->NumberOfPhysicalPages
== 0);
2426 SharedUserData
->NumberOfPhysicalPages
= MmNumberOfPhysicalPages
;
2427 SharedUserData
->LargePageMinimum
= 0;
2429 /* Check for workstation (Wi for WinNT) */
2430 if (MmProductType
== '\0i\0W')
2432 /* Set Windows NT Workstation product type */
2433 SharedUserData
->NtProductType
= NtProductWinNt
;
2438 /* Check for LanMan server (La for LanmanNT) */
2439 if (MmProductType
== '\0a\0L')
2441 /* This is a domain controller */
2442 SharedUserData
->NtProductType
= NtProductLanManNt
;
2446 /* Otherwise it must be a normal server (Se for ServerNT) */
2447 SharedUserData
->NtProductType
= NtProductServer
;
2450 /* Set the product type, and make the system more aggressive with low memory */
2452 MmMinimumFreePages
= 81;
2455 /* Update working set tuning parameters */
2456 MiAdjustWorkingSetManagerParameters(!MmProductType
);
2458 /* Finetune the page count by removing working set and NP expansion */
2459 MmResidentAvailablePages
-= MiExpansionPoolPagesInitialCharge
;
2460 MmResidentAvailablePages
-= MmSystemCacheWsMinimum
;
2461 MmResidentAvailableAtInit
= MmResidentAvailablePages
;
2462 if (MmResidentAvailablePages
<= 0)
2464 /* This should not happen */
2465 DPRINT1("System cache working set too big\n");
2469 /* Initialize the system cache */
2470 //MiInitializeSystemCache(MmSystemCacheWsMinimum, MmAvailablePages);
2472 /* Update the commit limit */
2473 MmTotalCommitLimit
= MmAvailablePages
;
2474 if (MmTotalCommitLimit
> 1024) MmTotalCommitLimit
-= 1024;
2475 MmTotalCommitLimitMaximum
= MmTotalCommitLimit
;
2477 /* Size up paged pool and build the shadow system page directory */
2480 /* Debugger physical memory support is now ready to be used */
2481 MmDebugPte
= MiAddressToPte(MiDebugMapping
);
2483 /* Initialize the loaded module list */
2484 MiInitializeLoadedModuleList(LoaderBlock
);
2488 // Always return success for now