2 * PROJECT: ReactOS Kernel
3 * LICENSE: BSD - See COPYING.ARM in the top level directory
4 * FILE: ntoskrnl/mm/ARM3/i386/init.c
5 * PURPOSE: ARM Memory Manager Initialization for x86
6 * PROGRAMMERS: ReactOS Portable Systems Group
9 /* INCLUDES *******************************************************************/
16 #define MODULE_INVOLVED_IN_ARM3
17 #include "../../ARM3/miarm.h"
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 ULONG MmSizeOfNonPagedPoolInBytes
;
27 ULONG MmMaximumNonPagedPoolInBytes
;
30 // These numbers describe the discrete equation components of the nonpaged
31 // pool sizing algorithm.
33 // They are described on http://support.microsoft.com/default.aspx/kb/126402/ja
34 // along with the algorithm that uses them, which is implemented later below.
36 ULONG MmMinimumNonPagedPoolSize
= 256 * 1024;
37 ULONG MmMinAdditionNonPagedPoolPerMb
= 32 * 1024;
38 ULONG MmDefaultMaximumNonPagedPool
= 1024 * 1024;
39 ULONG MmMaxAdditionNonPagedPoolPerMb
= 400 * 1024;
42 // The memory layout (and especially variable names) of the NT kernel mode
43 // components can be a bit hard to twig, especially when it comes to the non
46 // There are really two components to the non-paged pool:
48 // - The initial nonpaged pool, sized dynamically up to a maximum.
49 // - The expansion nonpaged pool, sized dynamically up to a maximum.
51 // The initial nonpaged pool is physically continuous for performance, and
52 // immediately follows the PFN database, typically sharing the same PDE. It is
53 // a very small resource (32MB on a 1GB system), and capped at 128MB.
55 // Right now we call this the "ARM³ Nonpaged Pool" and it begins somewhere after
56 // the PFN database (which starts at 0xB0000000).
58 // The expansion nonpaged pool, on the other hand, can grow much bigger (400MB
59 // for a 1GB system). On ARM³ however, it is currently capped at 128MB.
61 // The address where the initial nonpaged pool starts is aptly named
62 // MmNonPagedPoolStart, and it describes a range of MmSizeOfNonPagedPoolInBytes
65 // Expansion nonpaged pool starts at an address described by the variable called
66 // MmNonPagedPoolExpansionStart, and it goes on for MmMaximumNonPagedPoolInBytes
67 // minus MmSizeOfNonPagedPoolInBytes bytes, always reaching MmNonPagedPoolEnd
68 // (because of the way it's calculated) at 0xFFBE0000.
70 // Initial nonpaged pool is allocated and mapped early-on during boot, but what
71 // about the expansion nonpaged pool? It is instead composed of special pages
72 // which belong to what are called System PTEs. These PTEs are the matter of a
73 // later discussion, but they are also considered part of the "nonpaged" OS, due
74 // to the fact that they are never paged out -- once an address is described by
75 // a System PTE, it is always valid, until the System PTE is torn down.
77 // System PTEs are actually composed of two "spaces", the system space proper,
78 // and the nonpaged pool expansion space. The latter, as we've already seen,
79 // begins at MmNonPagedPoolExpansionStart. Based on the number of System PTEs
80 // that the system will support, the remaining address space below this address
81 // is used to hold the system space PTEs. This address, in turn, is held in the
82 // variable named MmNonPagedSystemStart, which itself is never allowed to go
83 // below 0xEB000000 (thus creating an upper bound on the number of System PTEs).
85 // This means that 330MB are reserved for total nonpaged system VA, on top of
86 // whatever the initial nonpaged pool allocation is.
88 // The following URLs, valid as of April 23rd, 2008, support this evidence:
90 // http://www.cs.miami.edu/~burt/journal/NT/memory.html
91 // http://www.ditii.com/2007/09/28/windows-memory-management-x86-virtual-address-space/
93 PVOID MmNonPagedSystemStart
;
94 PVOID MmNonPagedPoolStart
;
95 PVOID MmNonPagedPoolExpansionStart
;
96 PVOID MmNonPagedPoolEnd
= MI_NONPAGED_POOL_END
;
99 // This is where paged pool starts by default
101 PVOID MmPagedPoolStart
= MI_PAGED_POOL_START
;
102 PVOID MmPagedPoolEnd
;
105 // And this is its default size
107 ULONG MmSizeOfPagedPoolInBytes
= MI_MIN_INIT_PAGED_POOLSIZE
;
108 PFN_NUMBER MmSizeOfPagedPoolInPages
= MI_MIN_INIT_PAGED_POOLSIZE
/ PAGE_SIZE
;
111 // Session space starts at 0xBFFFFFFF and grows downwards
112 // By default, it includes an 8MB image area where we map win32k and video card
113 // drivers, followed by a 4MB area containing the session's working set. This is
114 // then followed by a 20MB mapped view area and finally by the session's paged
115 // pool, by default 16MB.
117 // On a normal system, this results in session space occupying the region from
118 // 0xBD000000 to 0xC0000000
120 // See miarm.h for the defines that determine the sizing of this region. On an
121 // NT system, some of these can be configured through the registry, but we don't
124 PVOID MiSessionSpaceEnd
; // 0xC0000000
125 PVOID MiSessionImageEnd
; // 0xC0000000
126 PVOID MiSessionImageStart
; // 0xBF800000
127 PVOID MiSessionViewStart
; // 0xBE000000
128 PVOID MiSessionPoolEnd
; // 0xBE000000
129 PVOID MiSessionPoolStart
; // 0xBD000000
130 PVOID MmSessionBase
; // 0xBD000000
132 ULONG MmSessionViewSize
;
133 ULONG MmSessionPoolSize
;
134 ULONG MmSessionImageSize
;
137 // The system view space, on the other hand, is where sections that are memory
138 // mapped into "system space" end up.
140 // By default, it is a 16MB region.
142 PVOID MiSystemViewStart
;
143 ULONG MmSystemViewSize
;
146 // A copy of the system page directory (the page directory associated with the
147 // System process) is kept (double-mapped) by the manager in order to lazily
148 // map paged pool PDEs into external processes when they fault on a paged pool
151 PFN_NUMBER MmSystemPageDirectory
;
152 PMMPTE MmSystemPagePtes
;
155 // Windows NT seems to choose between 7000, 11000 and 50000
156 // On systems with more than 32MB, this number is then doubled, and further
157 // aligned up to a PDE boundary (4MB).
159 ULONG MmNumberOfSystemPtes
;
162 // This is how many pages the PFN database will take up
163 // In Windows, this includes the Quark Color Table, but not in ARM³
165 ULONG MxPfnAllocation
;
168 // Unlike the old ReactOS Memory Manager, ARM³ (and Windows) does not keep track
169 // of pages that are not actually valid physical memory, such as ACPI reserved
170 // regions, BIOS address ranges, or holes in physical memory address space which
171 // could indicate device-mapped I/O memory.
173 // In fact, the lack of a PFN entry for a page usually indicates that this is
174 // I/O space instead.
176 // A bitmap, called the PFN bitmap, keeps track of all page frames by assigning
177 // a bit to each. If the bit is set, then the page is valid physical RAM.
179 RTL_BITMAP MiPfnBitMap
;
182 // This structure describes the different pieces of RAM-backed address space
184 PPHYSICAL_MEMORY_DESCRIPTOR MmPhysicalMemoryBlock
;
187 // Before we have a PFN database, memory comes straight from our physical memory
188 // blocks, which is nice because it's guaranteed contiguous and also because once
189 // we take a page from here, the system doesn't see it anymore.
190 // However, once the fun is over, those pages must be re-integrated back into
191 // PFN society life, and that requires us keeping a copy of the original layout
192 // so that we can parse it later.
194 PMEMORY_ALLOCATION_DESCRIPTOR MxFreeDescriptor
;
195 MEMORY_ALLOCATION_DESCRIPTOR MxOldFreeDescriptor
;
198 // This is where we keep track of the most basic physical layout markers
200 ULONG MmNumberOfPhysicalPages
, MmHighestPhysicalPage
, MmLowestPhysicalPage
= -1;
203 // The total number of pages mapped by the boot loader, which include the kernel
204 // HAL, boot drivers, registry, NLS files and other loader data structures is
205 // kept track of here. This depends on "LoaderPagesSpanned" being correct when
206 // coming from the loader.
208 // This number is later aligned up to a PDE boundary.
210 ULONG MmBootImageSize
;
213 // These three variables keep track of the core separation of address space that
214 // exists between kernel mode and user mode.
216 ULONG MmUserProbeAddress
;
217 PVOID MmHighestUserAddress
;
218 PVOID MmSystemRangeStart
;
222 PVOID MmSystemCacheStart
;
223 PVOID MmSystemCacheEnd
;
224 MMSUPPORT MmSystemCacheWs
;
226 /* PRIVATE FUNCTIONS **********************************************************/
229 // In Bavaria, this is probably a hate crime
233 MiSyncARM3WithROS(IN PVOID AddressStart
,
237 // Puerile piece of junk-grade carbonized horseshit puss sold to the lowest bidder
239 ULONG Pde
= ADDR_TO_PDE_OFFSET(AddressStart
);
240 while (Pde
<= ADDR_TO_PDE_OFFSET(AddressEnd
))
243 // This both odious and heinous
245 extern ULONG MmGlobalKernelPageDirectory
[1024];
246 MmGlobalKernelPageDirectory
[Pde
] = ((PULONG
)PDE_BASE
)[Pde
];
253 MxGetNextPage(IN PFN_NUMBER PageCount
)
258 // Make sure we have enough pages
260 if (PageCount
> MxFreeDescriptor
->PageCount
)
265 KeBugCheckEx(INSTALL_MORE_MEMORY
,
266 MmNumberOfPhysicalPages
,
267 MxFreeDescriptor
->PageCount
,
268 MxOldFreeDescriptor
.PageCount
,
273 // Use our lowest usable free pages
275 Pfn
= MxFreeDescriptor
->BasePage
;
276 MxFreeDescriptor
->BasePage
+= PageCount
;
277 MxFreeDescriptor
->PageCount
-= PageCount
;
281 PPHYSICAL_MEMORY_DESCRIPTOR
283 MmInitializeMemoryLimits(IN PLOADER_PARAMETER_BLOCK LoaderBlock
,
284 IN PBOOLEAN IncludeType
)
286 PLIST_ENTRY NextEntry
;
287 ULONG Run
= 0, InitialRuns
= 0;
288 PFN_NUMBER NextPage
= -1, PageCount
= 0;
289 PPHYSICAL_MEMORY_DESCRIPTOR Buffer
, NewBuffer
;
290 PMEMORY_ALLOCATION_DESCRIPTOR MdBlock
;
293 // Scan the memory descriptors
295 NextEntry
= LoaderBlock
->MemoryDescriptorListHead
.Flink
;
296 while (NextEntry
!= &LoaderBlock
->MemoryDescriptorListHead
)
299 // For each one, increase the memory allocation estimate
302 NextEntry
= NextEntry
->Flink
;
306 // Allocate the maximum we'll ever need
308 Buffer
= ExAllocatePoolWithTag(NonPagedPool
,
309 sizeof(PHYSICAL_MEMORY_DESCRIPTOR
) +
310 sizeof(PHYSICAL_MEMORY_RUN
) *
313 if (!Buffer
) return NULL
;
316 // For now that's how many runs we have
318 Buffer
->NumberOfRuns
= InitialRuns
;
321 // Now loop through the descriptors again
323 NextEntry
= LoaderBlock
->MemoryDescriptorListHead
.Flink
;
324 while (NextEntry
!= &LoaderBlock
->MemoryDescriptorListHead
)
327 // Grab each one, and check if it's one we should include
329 MdBlock
= CONTAINING_RECORD(NextEntry
,
330 MEMORY_ALLOCATION_DESCRIPTOR
,
332 if ((MdBlock
->MemoryType
< LoaderMaximum
) &&
333 (IncludeType
[MdBlock
->MemoryType
]))
336 // Add this to our running total
338 PageCount
+= MdBlock
->PageCount
;
341 // Check if the next page is described by the next descriptor
343 if (MdBlock
->BasePage
== NextPage
)
346 // Combine it into the same physical run
348 ASSERT(MdBlock
->PageCount
!= 0);
349 Buffer
->Run
[Run
- 1].PageCount
+= MdBlock
->PageCount
;
350 NextPage
+= MdBlock
->PageCount
;
355 // Otherwise just duplicate the descriptor's contents
357 Buffer
->Run
[Run
].BasePage
= MdBlock
->BasePage
;
358 Buffer
->Run
[Run
].PageCount
= MdBlock
->PageCount
;
359 NextPage
= Buffer
->Run
[Run
].BasePage
+ Buffer
->Run
[Run
].PageCount
;
362 // And in this case, increase the number of runs
369 // Try the next descriptor
371 NextEntry
= MdBlock
->ListEntry
.Flink
;
375 // We should not have been able to go past our initial estimate
377 ASSERT(Run
<= Buffer
->NumberOfRuns
);
380 // Our guess was probably exaggerated...
382 if (InitialRuns
> Run
)
385 // Allocate a more accurately sized buffer
387 NewBuffer
= ExAllocatePoolWithTag(NonPagedPool
,
388 sizeof(PHYSICAL_MEMORY_DESCRIPTOR
) +
389 sizeof(PHYSICAL_MEMORY_RUN
) *
395 // Copy the old buffer into the new, then free it
397 RtlCopyMemory(NewBuffer
->Run
,
399 sizeof(PHYSICAL_MEMORY_RUN
) * Run
);
403 // Now use the new buffer
410 // Write the final numbers, and return it
412 Buffer
->NumberOfRuns
= Run
;
413 Buffer
->NumberOfPages
= PageCount
;
419 MiBuildPagedPool(VOID
)
421 PMMPTE PointerPte
, PointerPde
;
422 MMPTE TempPte
= HyperTemplatePte
;
423 PFN_NUMBER PageFrameIndex
;
425 ULONG Size
, BitMapSize
;
428 // Get the page frame number for the system page directory
430 PointerPte
= MiAddressToPte(PDE_BASE
);
431 MmSystemPageDirectory
= PFN_FROM_PTE(PointerPte
);
434 // Allocate a system PTE which will hold a copy of the page directory
436 PointerPte
= MiReserveSystemPtes(1, SystemPteSpace
);
438 MmSystemPagePtes
= MiPteToAddress(PointerPte
);
441 // Make this system PTE point to the system page directory.
442 // It is now essentially double-mapped. This will be used later for lazy
443 // evaluation of PDEs accross process switches, similarly to how the Global
444 // page directory array in the old ReactOS Mm is used (but in a less hacky
447 TempPte
= HyperTemplatePte
;
448 TempPte
.u
.Hard
.PageFrameNumber
= MmSystemPageDirectory
;
449 ASSERT(PointerPte
->u
.Hard
.Valid
== 0);
450 ASSERT(TempPte
.u
.Hard
.Valid
== 1);
451 *PointerPte
= TempPte
;
454 // Let's get back to paged pool work: size it up.
455 // By default, it should be twice as big as nonpaged pool.
457 MmSizeOfPagedPoolInBytes
= 2 * MmMaximumNonPagedPoolInBytes
;
458 if (MmSizeOfPagedPoolInBytes
> ((ULONG_PTR
)MmNonPagedSystemStart
-
459 (ULONG_PTR
)MmPagedPoolStart
))
462 // On the other hand, we have limited VA space, so make sure that the VA
463 // for paged pool doesn't overflow into nonpaged pool VA. Otherwise, set
464 // whatever maximum is possible.
466 MmSizeOfPagedPoolInBytes
= (ULONG_PTR
)MmNonPagedSystemStart
-
467 (ULONG_PTR
)MmPagedPoolStart
;
471 // Get the size in pages and make sure paged pool is at least 32MB.
473 Size
= MmSizeOfPagedPoolInBytes
;
474 if (Size
< MI_MIN_INIT_PAGED_POOLSIZE
) Size
= MI_MIN_INIT_PAGED_POOLSIZE
;
475 Size
= BYTES_TO_PAGES(Size
);
478 // Now check how many PTEs will be required for these many pages.
480 Size
= (Size
+ (1024 - 1)) / 1024;
483 // Recompute the page-aligned size of the paged pool, in bytes and pages.
485 MmSizeOfPagedPoolInBytes
= Size
* PAGE_SIZE
* 1024;
486 MmSizeOfPagedPoolInPages
= MmSizeOfPagedPoolInBytes
>> PAGE_SHIFT
;
489 // Let's be really sure this doesn't overflow into nonpaged system VA
491 ASSERT((MmSizeOfPagedPoolInBytes
+ (ULONG_PTR
)MmPagedPoolStart
) <=
492 (ULONG_PTR
)MmNonPagedSystemStart
);
495 // This is where paged pool ends
497 MmPagedPoolEnd
= (PVOID
)(((ULONG_PTR
)MmPagedPoolStart
+
498 MmSizeOfPagedPoolInBytes
) - 1);
501 // So now get the PDE for paged pool and zero it out
503 PointerPde
= MiAddressToPde(MmPagedPoolStart
);
504 RtlZeroMemory(PointerPde
,
505 (1 + MiAddressToPde(MmPagedPoolEnd
) - PointerPde
) * sizeof(MMPTE
));
508 // Next, get the first and last PTE
510 PointerPte
= MiAddressToPte(MmPagedPoolStart
);
511 MmPagedPoolInfo
.FirstPteForPagedPool
= PointerPte
;
512 MmPagedPoolInfo
.LastPteForPagedPool
= MiAddressToPte(MmPagedPoolEnd
);
515 // Lock the PFN database
517 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
520 // Allocate a page and map the first paged pool PDE
522 PageFrameIndex
= MmAllocPage(MC_NPPOOL
, 0);
523 TempPte
.u
.Hard
.PageFrameNumber
= PageFrameIndex
;
524 ASSERT(PointerPde
->u
.Hard
.Valid
== 0);
525 ASSERT(TempPte
.u
.Hard
.Valid
== 1);
526 *PointerPde
= TempPte
;
529 // Release the PFN database lock
531 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
534 // We only have one PDE mapped for now... at fault time, additional PDEs
535 // will be allocated to handle paged pool growth. This is where they'll have
538 MmPagedPoolInfo
.NextPdeForPagedPoolExpansion
= PointerPde
+ 1;
541 // We keep track of each page via a bit, so check how big the bitmap will
542 // have to be (make sure to align our page count such that it fits nicely
543 // into a 4-byte aligned bitmap.
545 // We'll also allocate the bitmap header itself part of the same buffer.
548 ASSERT(Size
== MmSizeOfPagedPoolInPages
);
550 Size
= sizeof(RTL_BITMAP
) + (((Size
+ 31) / 32) * sizeof(ULONG
));
553 // Allocate the allocation bitmap, which tells us which regions have not yet
554 // been mapped into memory
556 MmPagedPoolInfo
.PagedPoolAllocationMap
= ExAllocatePoolWithTag(NonPagedPool
,
559 ASSERT(MmPagedPoolInfo
.PagedPoolAllocationMap
);
562 // Initialize it such that at first, only the first page's worth of PTEs is
563 // marked as allocated (incidentially, the first PDE we allocated earlier).
565 RtlInitializeBitMap(MmPagedPoolInfo
.PagedPoolAllocationMap
,
566 (PULONG
)(MmPagedPoolInfo
.PagedPoolAllocationMap
+ 1),
568 RtlSetAllBits(MmPagedPoolInfo
.PagedPoolAllocationMap
);
569 RtlClearBits(MmPagedPoolInfo
.PagedPoolAllocationMap
, 0, 1024);
572 // We have a second bitmap, which keeps track of where allocations end.
573 // Given the allocation bitmap and a base address, we can therefore figure
574 // out which page is the last page of that allocation, and thus how big the
575 // entire allocation is.
577 MmPagedPoolInfo
.EndOfPagedPoolBitmap
= ExAllocatePoolWithTag(NonPagedPool
,
580 ASSERT(MmPagedPoolInfo
.EndOfPagedPoolBitmap
);
581 RtlInitializeBitMap(MmPagedPoolInfo
.EndOfPagedPoolBitmap
,
582 (PULONG
)(MmPagedPoolInfo
.EndOfPagedPoolBitmap
+ 1),
586 // Since no allocations have been made yet, there are no bits set as the end
588 RtlClearAllBits(MmPagedPoolInfo
.EndOfPagedPoolBitmap
);
591 // Initialize paged pool.
593 InitializePool(PagedPool
, 0);
596 // Initialize the paged pool mutex
598 KeInitializeGuardedMutex(&MmPagedPoolMutex
);
603 MmArmInitSystem(IN ULONG Phase
,
604 IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
606 PLIST_ENTRY NextEntry
;
607 PMEMORY_ALLOCATION_DESCRIPTOR MdBlock
;
609 PFN_NUMBER PageFrameIndex
;
610 PMMPTE StartPde
, EndPde
, PointerPte
, LastPte
;
611 MMPTE TempPde
= HyperTemplatePte
, TempPte
= HyperTemplatePte
;
612 PVOID NonPagedPoolExpansionVa
;
614 BOOLEAN IncludeType
[LoaderMaximum
];
617 PPHYSICAL_MEMORY_RUN Run
;
618 PFN_NUMBER FreePage
, FreePageCount
, PagesLeft
, BasePage
, PageCount
;
623 // Define the basic user vs. kernel address space separation
625 MmSystemRangeStart
= (PVOID
)KSEG0_BASE
;
626 MmUserProbeAddress
= (ULONG_PTR
)MmSystemRangeStart
- 0x10000;
627 MmHighestUserAddress
= (PVOID
)(MmUserProbeAddress
- 1);
630 // Get the size of the boot loader's image allocations and then round
631 // that region up to a PDE size, so that any PDEs we might create for
632 // whatever follows are separate from the PDEs that boot loader might've
633 // already created (and later, we can blow all that away if we want to).
635 MmBootImageSize
= KeLoaderBlock
->Extension
->LoaderPagesSpanned
;
636 MmBootImageSize
*= PAGE_SIZE
;
637 MmBootImageSize
= (MmBootImageSize
+ (4 * 1024 * 1024) - 1) & ~((4 * 1024 * 1024) - 1);
638 ASSERT((MmBootImageSize
% (4 * 1024 * 1024)) == 0);
641 // Set the size of session view, pool, and image
643 MmSessionSize
= MI_SESSION_SIZE
;
644 MmSessionViewSize
= MI_SESSION_VIEW_SIZE
;
645 MmSessionPoolSize
= MI_SESSION_POOL_SIZE
;
646 MmSessionImageSize
= MI_SESSION_IMAGE_SIZE
;
649 // Set the size of system view
651 MmSystemViewSize
= MI_SYSTEM_VIEW_SIZE
;
654 // This is where it all ends
656 MiSessionImageEnd
= (PVOID
)PTE_BASE
;
659 // This is where we will load Win32k.sys and the video driver
661 MiSessionImageStart
= (PVOID
)((ULONG_PTR
)MiSessionImageEnd
-
665 // So the view starts right below the session working set (itself below
668 MiSessionViewStart
= (PVOID
)((ULONG_PTR
)MiSessionImageEnd
-
670 MI_SESSION_WORKING_SET_SIZE
-
674 // Session pool follows
676 MiSessionPoolEnd
= MiSessionViewStart
;
677 MiSessionPoolStart
= (PVOID
)((ULONG_PTR
)MiSessionPoolEnd
-
681 // And it all begins here
683 MmSessionBase
= MiSessionPoolStart
;
686 // Sanity check that our math is correct
688 ASSERT((ULONG_PTR
)MmSessionBase
+ MmSessionSize
== PTE_BASE
);
691 // Session space ends wherever image session space ends
693 MiSessionSpaceEnd
= MiSessionImageEnd
;
696 // System view space ends at session space, so now that we know where
697 // this is, we can compute the base address of system view space itself.
699 MiSystemViewStart
= (PVOID
)((ULONG_PTR
)MmSessionBase
-
703 // Set CR3 for the system process
705 PointerPte
= MiAddressToPde(PTE_BASE
);
706 PageFrameIndex
= PFN_FROM_PTE(PointerPte
) << PAGE_SHIFT
;
707 PsGetCurrentProcess()->Pcb
.DirectoryTableBase
[0] = PageFrameIndex
;
710 // Blow away user-mode
712 StartPde
= MiAddressToPde(0);
713 EndPde
= MiAddressToPde(KSEG0_BASE
);
714 RtlZeroMemory(StartPde
, (EndPde
- StartPde
) * sizeof(MMPTE
));
717 // Loop the memory descriptors
719 NextEntry
= LoaderBlock
->MemoryDescriptorListHead
.Flink
;
720 while (NextEntry
!= &LoaderBlock
->MemoryDescriptorListHead
)
723 // Get the memory block
725 MdBlock
= CONTAINING_RECORD(NextEntry
,
726 MEMORY_ALLOCATION_DESCRIPTOR
,
730 // Skip invisible memory
732 if ((MdBlock
->MemoryType
!= LoaderFirmwarePermanent
) &&
733 (MdBlock
->MemoryType
!= LoaderSpecialMemory
) &&
734 (MdBlock
->MemoryType
!= LoaderHALCachedMemory
) &&
735 (MdBlock
->MemoryType
!= LoaderBBTMemory
))
738 // Check if BURNMEM was used
740 if (MdBlock
->MemoryType
!= LoaderBad
)
743 // Count this in the total of pages
745 MmNumberOfPhysicalPages
+= MdBlock
->PageCount
;
749 // Check if this is the new lowest page
751 if (MdBlock
->BasePage
< MmLowestPhysicalPage
)
754 // Update the lowest page
756 MmLowestPhysicalPage
= MdBlock
->BasePage
;
760 // Check if this is the new highest page
762 PageFrameIndex
= MdBlock
->BasePage
+ MdBlock
->PageCount
;
763 if (PageFrameIndex
> MmHighestPhysicalPage
)
766 // Update the highest page
768 MmHighestPhysicalPage
= PageFrameIndex
- 1;
772 // Check if this is free memory
774 if ((MdBlock
->MemoryType
== LoaderFree
) ||
775 (MdBlock
->MemoryType
== LoaderLoadedProgram
) ||
776 (MdBlock
->MemoryType
== LoaderFirmwareTemporary
) ||
777 (MdBlock
->MemoryType
== LoaderOsloaderStack
))
780 // Check if this is the largest memory descriptor
782 if (MdBlock
->PageCount
> FreePages
)
787 FreePages
= MdBlock
->PageCount
;
788 MxFreeDescriptor
= MdBlock
;
796 NextEntry
= MdBlock
->ListEntry
.Flink
;
800 // Save original values of the free descriptor, since it'll be
801 // altered by early allocations
803 MxOldFreeDescriptor
= *MxFreeDescriptor
;
806 // Check if this is a machine with less than 19MB of RAM
808 if (MmNumberOfPhysicalPages
< MI_MIN_PAGES_FOR_SYSPTE_TUNING
)
811 // Use the very minimum of system PTEs
813 MmNumberOfSystemPtes
= 7000;
818 // Use the default, but check if we have more than 32MB of RAM
820 MmNumberOfSystemPtes
= 11000;
821 if (MmNumberOfPhysicalPages
> MI_MIN_PAGES_FOR_SYSPTE_BOOST
)
824 // Double the amount of system PTEs
826 MmNumberOfSystemPtes
<<= 1;
830 DPRINT("System PTE count has been tuned to %d (%d bytes)\n",
831 MmNumberOfSystemPtes
, MmNumberOfSystemPtes
* PAGE_SIZE
);
834 // Check if this is a machine with less than 256MB of RAM, and no overide
836 if ((MmNumberOfPhysicalPages
<= MI_MIN_PAGES_FOR_NONPAGED_POOL_TUNING
) &&
837 !(MmSizeOfNonPagedPoolInBytes
))
840 // Force the non paged pool to be 2MB so we can reduce RAM usage
842 MmSizeOfNonPagedPoolInBytes
= 2 * 1024 * 1024;
846 // Check if the user gave a ridicuously large nonpaged pool RAM size
848 if ((MmSizeOfNonPagedPoolInBytes
>> PAGE_SHIFT
) >
849 (MmNumberOfPhysicalPages
* 7 / 8))
852 // More than 7/8ths of RAM was dedicated to nonpaged pool, ignore!
854 MmSizeOfNonPagedPoolInBytes
= 0;
858 // Check if no registry setting was set, or if the setting was too low
860 if (MmSizeOfNonPagedPoolInBytes
< MmMinimumNonPagedPoolSize
)
863 // Start with the minimum (256 KB) and add 32 KB for each MB above 4
865 MmSizeOfNonPagedPoolInBytes
= MmMinimumNonPagedPoolSize
;
866 MmSizeOfNonPagedPoolInBytes
+= (MmNumberOfPhysicalPages
- 1024) /
867 256 * MmMinAdditionNonPagedPoolPerMb
;
871 // Check if the registy setting or our dynamic calculation was too high
873 if (MmSizeOfNonPagedPoolInBytes
> MI_MAX_INIT_NONPAGED_POOL_SIZE
)
876 // Set it to the maximum
878 MmSizeOfNonPagedPoolInBytes
= MI_MAX_INIT_NONPAGED_POOL_SIZE
;
882 // Check if a percentage cap was set through the registry
884 if (MmMaximumNonPagedPoolPercent
)
887 // Don't feel like supporting this right now
893 // Page-align the nonpaged pool size
895 MmSizeOfNonPagedPoolInBytes
&= ~(PAGE_SIZE
- 1);
898 // Now, check if there was a registry size for the maximum size
900 if (!MmMaximumNonPagedPoolInBytes
)
903 // Start with the default (1MB) and add 400 KB for each MB above 4
905 MmMaximumNonPagedPoolInBytes
= MmDefaultMaximumNonPagedPool
;
906 MmMaximumNonPagedPoolInBytes
+= (MmNumberOfPhysicalPages
- 1024) /
907 256 * MmMaxAdditionNonPagedPoolPerMb
;
911 // Don't let the maximum go too high
913 if (MmMaximumNonPagedPoolInBytes
> MI_MAX_NONPAGED_POOL_SIZE
)
916 // Set it to the upper limit
918 MmMaximumNonPagedPoolInBytes
= MI_MAX_NONPAGED_POOL_SIZE
;
922 // Calculate the number of bytes, and then convert to pages
924 MxPfnAllocation
= (MmHighestPhysicalPage
+ 1) * sizeof(MMPFN
);
925 MxPfnAllocation
>>= PAGE_SHIFT
;
928 // We have to add one to the count here, because in the process of
929 // shifting down to the page size, we actually ended up getting the
930 // lower aligned size (so say, 0x5FFFF bytes is now 0x5F pages).
931 // Later on, we'll shift this number back into bytes, which would cause
932 // us to end up with only 0x5F000 bytes -- when we actually want to have
938 // Now calculate the nonpaged pool expansion VA region
940 MmNonPagedPoolStart
= (PVOID
)((ULONG_PTR
)MmNonPagedPoolEnd
-
941 MmMaximumNonPagedPoolInBytes
+
942 MmSizeOfNonPagedPoolInBytes
);
943 MmNonPagedPoolStart
= (PVOID
)PAGE_ALIGN(MmNonPagedPoolStart
);
944 NonPagedPoolExpansionVa
= MmNonPagedPoolStart
;
945 DPRINT("NP Pool has been tuned to: %d bytes and %d bytes\n",
946 MmSizeOfNonPagedPoolInBytes
, MmMaximumNonPagedPoolInBytes
);
949 // Now calculate the nonpaged system VA region, which includes the
950 // nonpaged pool expansion (above) and the system PTEs. Note that it is
951 // then aligned to a PDE boundary (4MB).
953 MmNonPagedSystemStart
= (PVOID
)((ULONG_PTR
)MmNonPagedPoolStart
-
954 (MmNumberOfSystemPtes
+ 1) * PAGE_SIZE
);
955 MmNonPagedSystemStart
= (PVOID
)((ULONG_PTR
)MmNonPagedSystemStart
&
956 ~((4 * 1024 * 1024) - 1));
959 // Don't let it go below the minimum
961 if (MmNonPagedSystemStart
< (PVOID
)0xEB000000)
964 // This is a hard-coded limit in the Windows NT address space
966 MmNonPagedSystemStart
= (PVOID
)0xEB000000;
969 // Reduce the amount of system PTEs to reach this point
971 MmNumberOfSystemPtes
= ((ULONG_PTR
)MmNonPagedPoolStart
-
972 (ULONG_PTR
)MmNonPagedSystemStart
) >>
974 MmNumberOfSystemPtes
--;
975 ASSERT(MmNumberOfSystemPtes
> 1000);
979 // Normally, the PFN database should start after the loader images.
980 // This is already the case in ReactOS, but for now we want to co-exist
981 // with the old memory manager, so we'll create a "Shadow PFN Database"
982 // instead, and arbitrarly start it at 0xB0000000.
984 MmPfnDatabase
= (PVOID
)0xB0000000;
985 ASSERT(((ULONG_PTR
)MmPfnDatabase
& ((4 * 1024 * 1024) - 1)) == 0);
988 // Non paged pool comes after the PFN database
990 MmNonPagedPoolStart
= (PVOID
)((ULONG_PTR
)MmPfnDatabase
+
991 (MxPfnAllocation
<< PAGE_SHIFT
));
994 // Now we actually need to get these many physical pages. Nonpaged pool
995 // is actually also physically contiguous (but not the expansion)
997 PageFrameIndex
= MxGetNextPage(MxPfnAllocation
+
998 (MmSizeOfNonPagedPoolInBytes
>> PAGE_SHIFT
));
999 ASSERT(PageFrameIndex
!= 0);
1000 DPRINT("PFN DB PA PFN begins at: %lx\n", PageFrameIndex
);
1001 DPRINT("NP PA PFN begins at: %lx\n", PageFrameIndex
+ MxPfnAllocation
);
1004 // Now we need some pages to create the page tables for the NP system VA
1005 // which includes system PTEs and expansion NP
1007 StartPde
= MiAddressToPde(MmNonPagedSystemStart
);
1008 EndPde
= MiAddressToPde((PVOID
)((ULONG_PTR
)MmNonPagedPoolEnd
- 1));
1009 while (StartPde
<= EndPde
)
1014 ASSERT(StartPde
->u
.Hard
.Valid
== 0);
1019 TempPde
.u
.Hard
.PageFrameNumber
= MxGetNextPage(1);
1020 ASSERT(TempPde
.u
.Hard
.Valid
== 1);
1021 *StartPde
= TempPde
;
1024 // Zero out the page table
1026 PointerPte
= MiPteToAddress(StartPde
);
1027 RtlZeroMemory(PointerPte
, PAGE_SIZE
);
1036 // Now we need pages for the page tables which will map initial NP
1038 StartPde
= MiAddressToPde(MmPfnDatabase
);
1039 EndPde
= MiAddressToPde((PVOID
)((ULONG_PTR
)MmNonPagedPoolStart
+
1040 MmSizeOfNonPagedPoolInBytes
- 1));
1041 while (StartPde
<= EndPde
)
1046 ASSERT(StartPde
->u
.Hard
.Valid
== 0);
1051 TempPde
.u
.Hard
.PageFrameNumber
= MxGetNextPage(1);
1052 ASSERT(TempPde
.u
.Hard
.Valid
== 1);
1053 *StartPde
= TempPde
;
1056 // Zero out the page table
1058 PointerPte
= MiPteToAddress(StartPde
);
1059 RtlZeroMemory(PointerPte
, PAGE_SIZE
);
1068 // Now remember where the expansion starts
1070 MmNonPagedPoolExpansionStart
= NonPagedPoolExpansionVa
;
1073 // Last step is to actually map the nonpaged pool
1075 PointerPte
= MiAddressToPte(MmNonPagedPoolStart
);
1076 LastPte
= MiAddressToPte((PVOID
)((ULONG_PTR
)MmNonPagedPoolStart
+
1077 MmSizeOfNonPagedPoolInBytes
- 1));
1078 while (PointerPte
<= LastPte
)
1081 // Use one of our contigous pages
1083 TempPte
.u
.Hard
.PageFrameNumber
= PageFrameIndex
++;
1084 ASSERT(PointerPte
->u
.Hard
.Valid
== 0);
1085 ASSERT(TempPte
.u
.Hard
.Valid
== 1);
1086 *PointerPte
++ = TempPte
;
1090 // Sanity check: make sure we have properly defined the system PTE space
1092 ASSERT(MiAddressToPte(MmNonPagedSystemStart
) <
1093 MiAddressToPte(MmNonPagedPoolExpansionStart
));
1096 // Now go ahead and initialize the ARM³ nonpaged pool
1098 MiInitializeArmPool();
1101 // Get current page data, since we won't be using MxGetNextPage as it
1102 // would corrupt our state
1104 FreePage
= MxFreeDescriptor
->BasePage
;
1105 FreePageCount
= MxFreeDescriptor
->PageCount
;
1109 // Loop the memory descriptors
1111 NextEntry
= KeLoaderBlock
->MemoryDescriptorListHead
.Flink
;
1112 while (NextEntry
!= &KeLoaderBlock
->MemoryDescriptorListHead
)
1115 // Get the descriptor
1117 MdBlock
= CONTAINING_RECORD(NextEntry
,
1118 MEMORY_ALLOCATION_DESCRIPTOR
,
1120 if ((MdBlock
->MemoryType
== LoaderFirmwarePermanent
) ||
1121 (MdBlock
->MemoryType
== LoaderBBTMemory
) ||
1122 (MdBlock
->MemoryType
== LoaderSpecialMemory
))
1125 // These pages are not part of the PFN database
1127 NextEntry
= MdBlock
->ListEntry
.Flink
;
1132 // Next, check if this is our special free descriptor we've found
1134 if (MdBlock
== MxFreeDescriptor
)
1137 // Use the real numbers instead
1139 BasePage
= MxOldFreeDescriptor
.BasePage
;
1140 PageCount
= MxOldFreeDescriptor
.PageCount
;
1145 // Use the descriptor's numbers
1147 BasePage
= MdBlock
->BasePage
;
1148 PageCount
= MdBlock
->PageCount
;
1152 // Get the PTEs for this range
1154 PointerPte
= MiAddressToPte(&MmPfnDatabase
[BasePage
]);
1155 LastPte
= MiAddressToPte(((ULONG_PTR
)&MmPfnDatabase
[BasePage
+ PageCount
]) - 1);
1156 DPRINT("MD Type: %lx Base: %lx Count: %lx\n", MdBlock
->MemoryType
, BasePage
, PageCount
);
1161 while (PointerPte
<= LastPte
)
1164 // We'll only touch PTEs that aren't already valid
1166 if (PointerPte
->u
.Hard
.Valid
== 0)
1169 // Use the next free page
1171 TempPte
.u
.Hard
.PageFrameNumber
= FreePage
;
1172 ASSERT(FreePageCount
!= 0);
1175 // Consume free pages
1184 KeBugCheckEx(INSTALL_MORE_MEMORY
,
1185 MmNumberOfPhysicalPages
,
1187 MxOldFreeDescriptor
.PageCount
,
1192 // Write out this PTE
1195 ASSERT(PointerPte
->u
.Hard
.Valid
== 0);
1196 ASSERT(TempPte
.u
.Hard
.Valid
== 1);
1197 *PointerPte
= TempPte
;
1202 RtlZeroMemory(MiPteToAddress(PointerPte
), PAGE_SIZE
);
1212 // Do the next address range
1214 NextEntry
= MdBlock
->ListEntry
.Flink
;
1218 // Now update the free descriptors to consume the pages we used up during
1219 // the PFN allocation loop
1221 MxFreeDescriptor
->BasePage
= FreePage
;
1222 MxFreeDescriptor
->PageCount
= FreePageCount
;
1224 else if (Phase
== 1) // IN BETWEEN, THE PFN DATABASE IS NOW CREATED
1227 // Reset the descriptor back so we can create the correct memory blocks
1229 *MxFreeDescriptor
= MxOldFreeDescriptor
;
1232 // Initialize the nonpaged pool
1234 InitializePool(NonPagedPool
, 0);
1237 // We PDE-aligned the nonpaged system start VA, so haul some extra PTEs!
1239 PointerPte
= MiAddressToPte(MmNonPagedSystemStart
);
1240 OldCount
= MmNumberOfSystemPtes
;
1241 MmNumberOfSystemPtes
= MiAddressToPte(MmNonPagedPoolExpansionStart
) -
1243 MmNumberOfSystemPtes
--;
1244 DPRINT("Final System PTE count: %d (%d bytes)\n",
1245 MmNumberOfSystemPtes
, MmNumberOfSystemPtes
* PAGE_SIZE
);
1248 // Create the system PTE space
1250 MiInitializeSystemPtes(PointerPte
, MmNumberOfSystemPtes
, SystemPteSpace
);
1253 // Get the PDE For hyperspace
1255 StartPde
= MiAddressToPde(HYPER_SPACE
);
1258 // Allocate a page for it and create it
1260 PageFrameIndex
= MmAllocPage(MC_SYSTEM
, 0);
1261 TempPde
.u
.Hard
.PageFrameNumber
= PageFrameIndex
;
1262 TempPde
.u
.Hard
.Global
= FALSE
; // Hyperspace is local!
1263 ASSERT(StartPde
->u
.Hard
.Valid
== 0);
1264 ASSERT(TempPde
.u
.Hard
.Valid
== 1);
1265 *StartPde
= TempPde
;
1268 // Zero out the page table now
1270 PointerPte
= MiAddressToPte(HYPER_SPACE
);
1271 RtlZeroMemory(PointerPte
, PAGE_SIZE
);
1274 // Setup the mapping PTEs
1276 MmFirstReservedMappingPte
= MiAddressToPte(MI_MAPPING_RANGE_START
);
1277 MmLastReservedMappingPte
= MiAddressToPte(MI_MAPPING_RANGE_END
);
1278 MmFirstReservedMappingPte
->u
.Hard
.PageFrameNumber
= MI_HYPERSPACE_PTES
;
1281 // Reserve system PTEs for zeroing PTEs and clear them
1283 MiFirstReservedZeroingPte
= MiReserveSystemPtes(MI_ZERO_PTES
,
1285 RtlZeroMemory(MiFirstReservedZeroingPte
, MI_ZERO_PTES
* sizeof(MMPTE
));
1288 // Set the counter to maximum to boot with
1290 MiFirstReservedZeroingPte
->u
.Hard
.PageFrameNumber
= MI_ZERO_PTES
- 1;
1293 // Sync us up with ReactOS Mm
1295 MiSyncARM3WithROS(MmNonPagedSystemStart
, (PVOID
)((ULONG_PTR
)MmNonPagedPoolEnd
- 1));
1296 MiSyncARM3WithROS(MmPfnDatabase
, (PVOID
)((ULONG_PTR
)MmNonPagedPoolStart
+ MmSizeOfNonPagedPoolInBytes
- 1));
1297 MiSyncARM3WithROS((PVOID
)HYPER_SPACE
, (PVOID
)(HYPER_SPACE
+ PAGE_SIZE
- 1));
1300 // Instantiate memory that we don't consider RAM/usable
1301 // We use the same exclusions that Windows does, in order to try to be
1302 // compatible with WinLDR-style booting
1304 for (i
= 0; i
< LoaderMaximum
; i
++) IncludeType
[i
] = TRUE
;
1305 IncludeType
[LoaderBad
] = FALSE
;
1306 IncludeType
[LoaderFirmwarePermanent
] = FALSE
;
1307 IncludeType
[LoaderSpecialMemory
] = FALSE
;
1308 IncludeType
[LoaderBBTMemory
] = FALSE
;
1311 // Build the physical memory block
1313 MmPhysicalMemoryBlock
= MmInitializeMemoryLimits(LoaderBlock
,
1317 // Allocate enough buffer for the PFN bitmap
1318 // Align it up to a 32-bit boundary
1320 Bitmap
= ExAllocatePoolWithTag(NonPagedPool
,
1321 (((MmHighestPhysicalPage
+ 1) + 31) / 32) * 4,
1328 KeBugCheckEx(INSTALL_MORE_MEMORY
,
1329 MmNumberOfPhysicalPages
,
1330 MmLowestPhysicalPage
,
1331 MmHighestPhysicalPage
,
1336 // Initialize it and clear all the bits to begin with
1338 RtlInitializeBitMap(&MiPfnBitMap
,
1340 MmHighestPhysicalPage
+ 1);
1341 RtlClearAllBits(&MiPfnBitMap
);
1344 // Loop physical memory runs
1346 for (i
= 0; i
< MmPhysicalMemoryBlock
->NumberOfRuns
; i
++)
1351 Run
= &MmPhysicalMemoryBlock
->Run
[i
];
1352 DPRINT("PHYSICAL RAM [0x%08p to 0x%08p]\n",
1353 Run
->BasePage
<< PAGE_SHIFT
,
1354 (Run
->BasePage
+ Run
->PageCount
) << PAGE_SHIFT
);
1357 // Make sure it has pages inside it
1362 // Set the bits in the PFN bitmap
1364 RtlSetBits(&MiPfnBitMap
, Run
->BasePage
, Run
->PageCount
);
1369 // Size up paged pool and build the shadow system page directory
1375 // Always return success for now
1377 return STATUS_SUCCESS
;