Sync with trunk (48237)
[reactos.git] / ntoskrnl / mm / ARM3 / i386 / init.c
1 /*
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
7 */
8
9 /* INCLUDES *******************************************************************/
10
11 #include <ntoskrnl.h>
12 #define NDEBUG
13 #include <debug.h>
14
15 #line 15 "ARMĀ³::INIT:X86"
16 #define MODULE_INVOLVED_IN_ARM3
17 #include "../../ARM3/miarm.h"
18
19 /* GLOBALS ********************************************************************/
20
21 /* Template PTE and PDE for a kernel page */
22 MMPTE ValidKernelPde = {.u.Hard.Valid = 1, .u.Hard.Write = 1, .u.Hard.Dirty = 1, .u.Hard.Accessed = 1};
23 MMPTE ValidKernelPte = {.u.Hard.Valid = 1, .u.Hard.Write = 1, .u.Hard.Dirty = 1, .u.Hard.Accessed = 1};
24
25 /* Template PDE for a demand-zero page */
26 MMPDE DemandZeroPde = {.u.Long = (MM_READWRITE << MM_PTE_SOFTWARE_PROTECTION_BITS)};
27
28 /* Template PTE for prototype page */
29 MMPTE PrototypePte = {.u.Long = (MM_READWRITE << MM_PTE_SOFTWARE_PROTECTION_BITS) | PTE_PROTOTYPE | 0xFFFFF000};
30
31 /* PRIVATE FUNCTIONS **********************************************************/
32
33 VOID
34 NTAPI
35 MiComputeNonPagedPoolVa(IN ULONG FreePages)
36 {
37 IN PFN_NUMBER PoolPages;
38
39 /* Check if this is a machine with less than 256MB of RAM, and no overide */
40 if ((MmNumberOfPhysicalPages <= MI_MIN_PAGES_FOR_NONPAGED_POOL_TUNING) &&
41 !(MmSizeOfNonPagedPoolInBytes))
42 {
43 /* Force the non paged pool to be 2MB so we can reduce RAM usage */
44 MmSizeOfNonPagedPoolInBytes = 2 * _1MB;
45 }
46
47 /* Hyperspace ends here */
48 MmHyperSpaceEnd = (PVOID)((ULONG_PTR)MmSystemCacheWorkingSetList - 1);
49
50 /* Check if the user gave a ridicuously large nonpaged pool RAM size */
51 if ((MmSizeOfNonPagedPoolInBytes >> PAGE_SHIFT) > (FreePages * 7 / 8))
52 {
53 /* More than 7/8ths of RAM was dedicated to nonpaged pool, ignore! */
54 MmSizeOfNonPagedPoolInBytes = 0;
55 }
56
57 /* Check if no registry setting was set, or if the setting was too low */
58 if (MmSizeOfNonPagedPoolInBytes < MmMinimumNonPagedPoolSize)
59 {
60 /* Start with the minimum (256 KB) and add 32 KB for each MB above 4 */
61 MmSizeOfNonPagedPoolInBytes = MmMinimumNonPagedPoolSize;
62 MmSizeOfNonPagedPoolInBytes += (FreePages - 1024) / 256 * MmMinAdditionNonPagedPoolPerMb;
63 }
64
65 /* Check if the registy setting or our dynamic calculation was too high */
66 if (MmSizeOfNonPagedPoolInBytes > MI_MAX_INIT_NONPAGED_POOL_SIZE)
67 {
68 /* Set it to the maximum */
69 MmSizeOfNonPagedPoolInBytes = MI_MAX_INIT_NONPAGED_POOL_SIZE;
70 }
71
72 /* Check if a percentage cap was set through the registry */
73 if (MmMaximumNonPagedPoolPercent) UNIMPLEMENTED;
74
75 /* Page-align the nonpaged pool size */
76 MmSizeOfNonPagedPoolInBytes &= ~(PAGE_SIZE - 1);
77
78 /* Now, check if there was a registry size for the maximum size */
79 if (!MmMaximumNonPagedPoolInBytes)
80 {
81 /* Start with the default (1MB) */
82 MmMaximumNonPagedPoolInBytes = MmDefaultMaximumNonPagedPool;
83
84 /* Add space for PFN database */
85 MmMaximumNonPagedPoolInBytes += (ULONG)
86 PAGE_ALIGN((MmHighestPhysicalPage + 1) * sizeof(MMPFN));
87
88 /* Check if the machine has more than 512MB of free RAM */
89 if (FreePages >= 0x1F000)
90 {
91 /* Add 200KB for each MB above 4 */
92 MmMaximumNonPagedPoolInBytes += (FreePages - 1024) / 256 *
93 (MmMaxAdditionNonPagedPoolPerMb / 2);
94 if (MmMaximumNonPagedPoolInBytes < MI_MAX_NONPAGED_POOL_SIZE)
95 {
96 /* Make it at least 128MB since this machine has a lot of RAM */
97 MmMaximumNonPagedPoolInBytes = MI_MAX_NONPAGED_POOL_SIZE;
98 }
99 }
100 else
101 {
102 /* Add 400KB for each MB above 4 */
103 MmMaximumNonPagedPoolInBytes += (FreePages - 1024) / 256 *
104 MmMaxAdditionNonPagedPoolPerMb;
105 }
106 }
107
108 /* Make sure there's at least 16 pages + the PFN available for expansion */
109 PoolPages = MmSizeOfNonPagedPoolInBytes + (PAGE_SIZE * 16) +
110 ((ULONG)PAGE_ALIGN(MmHighestPhysicalPage + 1) * sizeof(MMPFN));
111 if (MmMaximumNonPagedPoolInBytes < PoolPages)
112 {
113 /* The maximum should be at least high enough to cover all the above */
114 MmMaximumNonPagedPoolInBytes = PoolPages;
115 }
116
117 /* Systems with 2GB of kernel address space get double the size */
118 PoolPages = MI_MAX_NONPAGED_POOL_SIZE * 2;
119
120 /* On the other hand, make sure that PFN + nonpaged pool doesn't get too big */
121 if (MmMaximumNonPagedPoolInBytes > PoolPages)
122 {
123 /* Trim it down to the maximum architectural limit (256MB) */
124 MmMaximumNonPagedPoolInBytes = PoolPages;
125 }
126
127 /* Check if this is a system with > 128MB of non paged pool */
128 if (MmMaximumNonPagedPoolInBytes > MI_MAX_NONPAGED_POOL_SIZE)
129 {
130 /* Check if the initial size is less than the extra 128MB boost */
131 if (MmSizeOfNonPagedPoolInBytes < (MmMaximumNonPagedPoolInBytes -
132 MI_MAX_NONPAGED_POOL_SIZE))
133 {
134 /* FIXME: Should check if the initial pool can be expanded */
135
136 /* Assume no expansion possible, check ift he maximum is too large */
137 if (MmMaximumNonPagedPoolInBytes > (MmSizeOfNonPagedPoolInBytes +
138 MI_MAX_NONPAGED_POOL_SIZE))
139 {
140 /* Set it to the initial value plus the boost */
141 MmMaximumNonPagedPoolInBytes = MmSizeOfNonPagedPoolInBytes +
142 MI_MAX_NONPAGED_POOL_SIZE;
143 }
144 }
145 }
146 }
147
148 NTSTATUS
149 NTAPI
150 MiInitMachineDependent(IN PLOADER_PARAMETER_BLOCK LoaderBlock)
151 {
152 PLIST_ENTRY NextEntry;
153 PMEMORY_ALLOCATION_DESCRIPTOR MdBlock;
154 ULONG FreePages = 0;
155 PFN_NUMBER PageFrameIndex;
156 PMMPTE StartPde, EndPde, PointerPte, LastPte;
157 MMPTE TempPde, TempPte;
158 PVOID NonPagedPoolExpansionVa;
159 ULONG OldCount;
160 KIRQL OldIrql;
161
162 /* Check for kernel stack size that's too big */
163 if (MmLargeStackSize > (KERNEL_LARGE_STACK_SIZE / _1KB))
164 {
165 /* Sanitize to default value */
166 MmLargeStackSize = KERNEL_LARGE_STACK_SIZE;
167 }
168 else
169 {
170 /* Take the registry setting, and convert it into bytes */
171 MmLargeStackSize *= _1KB;
172
173 /* Now align it to a page boundary */
174 MmLargeStackSize = PAGE_ROUND_UP(MmLargeStackSize);
175
176 /* Sanity checks */
177 ASSERT(MmLargeStackSize <= KERNEL_LARGE_STACK_SIZE);
178 ASSERT((MmLargeStackSize & (PAGE_SIZE - 1)) == 0);
179
180 /* Make sure it's not too low */
181 if (MmLargeStackSize < KERNEL_STACK_SIZE) MmLargeStackSize = KERNEL_STACK_SIZE;
182 }
183
184 /* Check for global bit */
185 #if 0
186 if (KeFeatureBits & KF_GLOBAL_PAGE)
187 {
188 /* Set it on the template PTE and PDE */
189 ValidKernelPte.u.Hard.Global = TRUE;
190 ValidKernelPde.u.Hard.Global = TRUE;
191 }
192 #endif
193 /* Now templates are ready */
194 TempPte = ValidKernelPte;
195 TempPde = ValidKernelPde;
196
197 //
198 // Set CR3 for the system process
199 //
200 PointerPte = MiAddressToPde(PTE_BASE);
201 PageFrameIndex = PFN_FROM_PTE(PointerPte) << PAGE_SHIFT;
202 PsGetCurrentProcess()->Pcb.DirectoryTableBase[0] = PageFrameIndex;
203
204 //
205 // Blow away user-mode
206 //
207 StartPde = MiAddressToPde(0);
208 EndPde = MiAddressToPde(KSEG0_BASE);
209 RtlZeroMemory(StartPde, (EndPde - StartPde) * sizeof(MMPTE));
210
211 //
212 // Loop the memory descriptors
213 //
214 NextEntry = LoaderBlock->MemoryDescriptorListHead.Flink;
215 while (NextEntry != &LoaderBlock->MemoryDescriptorListHead)
216 {
217 //
218 // Get the memory block
219 //
220 MdBlock = CONTAINING_RECORD(NextEntry,
221 MEMORY_ALLOCATION_DESCRIPTOR,
222 ListEntry);
223
224 //
225 // Skip invisible memory
226 //
227 if ((MdBlock->MemoryType != LoaderFirmwarePermanent) &&
228 (MdBlock->MemoryType != LoaderSpecialMemory) &&
229 (MdBlock->MemoryType != LoaderHALCachedMemory) &&
230 (MdBlock->MemoryType != LoaderBBTMemory))
231 {
232 //
233 // Check if BURNMEM was used
234 //
235 if (MdBlock->MemoryType != LoaderBad)
236 {
237 //
238 // Count this in the total of pages
239 //
240 MmNumberOfPhysicalPages += MdBlock->PageCount;
241 }
242
243 //
244 // Check if this is the new lowest page
245 //
246 if (MdBlock->BasePage < MmLowestPhysicalPage)
247 {
248 //
249 // Update the lowest page
250 //
251 MmLowestPhysicalPage = MdBlock->BasePage;
252 }
253
254 //
255 // Check if this is the new highest page
256 //
257 PageFrameIndex = MdBlock->BasePage + MdBlock->PageCount;
258 if (PageFrameIndex > MmHighestPhysicalPage)
259 {
260 //
261 // Update the highest page
262 //
263 MmHighestPhysicalPage = PageFrameIndex - 1;
264 }
265
266 //
267 // Check if this is free memory
268 //
269 if ((MdBlock->MemoryType == LoaderFree) ||
270 (MdBlock->MemoryType == LoaderLoadedProgram) ||
271 (MdBlock->MemoryType == LoaderFirmwareTemporary) ||
272 (MdBlock->MemoryType == LoaderOsloaderStack))
273 {
274 //
275 // Check if this is the largest memory descriptor
276 //
277 if (MdBlock->PageCount > FreePages)
278 {
279 //
280 // For now, it is
281 //
282 MxFreeDescriptor = MdBlock;
283 }
284
285 //
286 // More free pages
287 //
288 FreePages += MdBlock->PageCount;
289 }
290 }
291
292 //
293 // Keep going
294 //
295 NextEntry = MdBlock->ListEntry.Flink;
296 }
297
298 //
299 // Save original values of the free descriptor, since it'll be
300 // altered by early allocations
301 //
302 MxOldFreeDescriptor = *MxFreeDescriptor;
303
304 /* Compute non paged pool limits and size */
305 MiComputeNonPagedPoolVa(FreePages);
306
307 /* Compute color information (L2 cache-separated paging lists) */
308 MiComputeColorInformation();
309
310 //
311 // Calculate the number of bytes for the PFN database, double it for ARM3,
312 // then add the color tables and convert to pages
313 //
314 MxPfnAllocation = (MmHighestPhysicalPage + 1) * sizeof(MMPFN);
315 //MxPfnAllocation <<= 1;
316 MxPfnAllocation += (MmSecondaryColors * sizeof(MMCOLOR_TABLES) * 2);
317 MxPfnAllocation >>= PAGE_SHIFT;
318
319 //
320 // We have to add one to the count here, because in the process of
321 // shifting down to the page size, we actually ended up getting the
322 // lower aligned size (so say, 0x5FFFF bytes is now 0x5F pages).
323 // Later on, we'll shift this number back into bytes, which would cause
324 // us to end up with only 0x5F000 bytes -- when we actually want to have
325 // 0x60000 bytes.
326 //
327 MxPfnAllocation++;
328
329 //
330 // Now calculate the nonpaged pool expansion VA region
331 //
332 MmNonPagedPoolStart = (PVOID)((ULONG_PTR)MmNonPagedPoolEnd -
333 MmMaximumNonPagedPoolInBytes +
334 MmSizeOfNonPagedPoolInBytes);
335 MmNonPagedPoolStart = (PVOID)PAGE_ALIGN(MmNonPagedPoolStart);
336 NonPagedPoolExpansionVa = MmNonPagedPoolStart;
337 DPRINT("NP Pool has been tuned to: %d bytes and %d bytes\n",
338 MmSizeOfNonPagedPoolInBytes, MmMaximumNonPagedPoolInBytes);
339
340 //
341 // Now calculate the nonpaged system VA region, which includes the
342 // nonpaged pool expansion (above) and the system PTEs. Note that it is
343 // then aligned to a PDE boundary (4MB).
344 //
345 MmNonPagedSystemStart = (PVOID)((ULONG_PTR)MmNonPagedPoolStart -
346 (MmNumberOfSystemPtes + 1) * PAGE_SIZE);
347 MmNonPagedSystemStart = (PVOID)((ULONG_PTR)MmNonPagedSystemStart &
348 ~(PDE_MAPPED_VA - 1));
349
350 //
351 // Don't let it go below the minimum
352 //
353 if (MmNonPagedSystemStart < (PVOID)0xEB000000)
354 {
355 //
356 // This is a hard-coded limit in the Windows NT address space
357 //
358 MmNonPagedSystemStart = (PVOID)0xEB000000;
359
360 //
361 // Reduce the amount of system PTEs to reach this point
362 //
363 MmNumberOfSystemPtes = ((ULONG_PTR)MmNonPagedPoolStart -
364 (ULONG_PTR)MmNonPagedSystemStart) >>
365 PAGE_SHIFT;
366 MmNumberOfSystemPtes--;
367 ASSERT(MmNumberOfSystemPtes > 1000);
368 }
369
370 //
371 // Check if we are in a situation where the size of the paged pool
372 // is so large that it overflows into nonpaged pool
373 //
374 if (MmSizeOfPagedPoolInBytes >
375 ((ULONG_PTR)MmNonPagedSystemStart - (ULONG_PTR)MmPagedPoolStart))
376 {
377 //
378 // We need some recalculations here
379 //
380 DPRINT1("Paged pool is too big!\n");
381 }
382
383 //
384 // Normally, the PFN database should start after the loader images.
385 // This is already the case in ReactOS, but for now we want to co-exist
386 // with the old memory manager, so we'll create a "Shadow PFN Database"
387 // instead, and arbitrarly start it at 0xB0000000.
388 //
389 MmPfnDatabase = (PVOID)0xB0000000;
390 ASSERT(((ULONG_PTR)MmPfnDatabase & (PDE_MAPPED_VA - 1)) == 0);
391
392 //
393 // Non paged pool comes after the PFN database
394 //
395 MmNonPagedPoolStart = (PVOID)((ULONG_PTR)MmPfnDatabase +
396 (MxPfnAllocation << PAGE_SHIFT));
397
398 //
399 // Now we actually need to get these many physical pages. Nonpaged pool
400 // is actually also physically contiguous (but not the expansion)
401 //
402 PageFrameIndex = MxGetNextPage(MxPfnAllocation +
403 (MmSizeOfNonPagedPoolInBytes >> PAGE_SHIFT));
404 ASSERT(PageFrameIndex != 0);
405 DPRINT("PFN DB PA PFN begins at: %lx\n", PageFrameIndex);
406 DPRINT("NP PA PFN begins at: %lx\n", PageFrameIndex + MxPfnAllocation);
407
408 /* Convert nonpaged pool size from bytes to pages */
409 MmMaximumNonPagedPoolInPages = MmMaximumNonPagedPoolInBytes >> PAGE_SHIFT;
410
411 //
412 // Now we need some pages to create the page tables for the NP system VA
413 // which includes system PTEs and expansion NP
414 //
415 StartPde = MiAddressToPde(MmNonPagedSystemStart);
416 EndPde = MiAddressToPde((PVOID)((ULONG_PTR)MmNonPagedPoolEnd - 1));
417 while (StartPde <= EndPde)
418 {
419 //
420 // Get a page
421 //
422 TempPde.u.Hard.PageFrameNumber = MxGetNextPage(1);
423 MI_WRITE_VALID_PTE(StartPde, TempPde);
424
425 //
426 // Zero out the page table
427 //
428 PointerPte = MiPteToAddress(StartPde);
429 RtlZeroMemory(PointerPte, PAGE_SIZE);
430
431 //
432 // Next
433 //
434 StartPde++;
435 }
436
437 //
438 // Now we need pages for the page tables which will map initial NP
439 //
440 StartPde = MiAddressToPde(MmPfnDatabase);
441 EndPde = MiAddressToPde((PVOID)((ULONG_PTR)MmNonPagedPoolStart +
442 MmSizeOfNonPagedPoolInBytes - 1));
443 while (StartPde <= EndPde)
444 {
445 //
446 // Get a page
447 //
448 TempPde.u.Hard.PageFrameNumber = MxGetNextPage(1);
449 MI_WRITE_VALID_PTE(StartPde, TempPde);
450
451 //
452 // Zero out the page table
453 //
454 PointerPte = MiPteToAddress(StartPde);
455 RtlZeroMemory(PointerPte, PAGE_SIZE);
456
457 //
458 // Next
459 //
460 StartPde++;
461 }
462
463 //
464 // Now remember where the expansion starts
465 //
466 MmNonPagedPoolExpansionStart = NonPagedPoolExpansionVa;
467
468 //
469 // Last step is to actually map the nonpaged pool
470 //
471 PointerPte = MiAddressToPte(MmNonPagedPoolStart);
472 LastPte = MiAddressToPte((PVOID)((ULONG_PTR)MmNonPagedPoolStart +
473 MmSizeOfNonPagedPoolInBytes - 1));
474 while (PointerPte <= LastPte)
475 {
476 //
477 // Use one of our contigous pages
478 //
479 TempPte.u.Hard.PageFrameNumber = PageFrameIndex++;
480 MI_WRITE_VALID_PTE(PointerPte++, TempPte);
481 }
482
483 //
484 // Sanity check: make sure we have properly defined the system PTE space
485 //
486 ASSERT(MiAddressToPte(MmNonPagedSystemStart) <
487 MiAddressToPte(MmNonPagedPoolExpansionStart));
488
489 /* Now go ahead and initialize the nonpaged pool */
490 MiInitializeNonPagedPool();
491 MiInitializeNonPagedPoolThresholds();
492
493 /* Map the PFN database pages */
494 MiMapPfnDatabase(LoaderBlock);
495
496 /* Initialize the color tables */
497 MiInitializeColorTables();
498
499 /* ReactOS Stuff */
500 extern KEVENT ZeroPageThreadEvent;
501 KeInitializeEvent(&ZeroPageThreadEvent, NotificationEvent, TRUE);
502
503 /* Build the PFN Database */
504 MiInitializePfnDatabase(LoaderBlock);
505 MmInitializeBalancer(MmAvailablePages, 0);
506
507 //
508 // Reset the descriptor back so we can create the correct memory blocks
509 //
510 *MxFreeDescriptor = MxOldFreeDescriptor;
511
512 //
513 // Initialize the nonpaged pool
514 //
515 InitializePool(NonPagedPool, 0);
516
517 //
518 // We PDE-aligned the nonpaged system start VA, so haul some extra PTEs!
519 //
520 PointerPte = MiAddressToPte(MmNonPagedSystemStart);
521 OldCount = MmNumberOfSystemPtes;
522 MmNumberOfSystemPtes = MiAddressToPte(MmNonPagedPoolExpansionStart) -
523 PointerPte;
524 MmNumberOfSystemPtes--;
525 DPRINT("Final System PTE count: %d (%d bytes)\n",
526 MmNumberOfSystemPtes, MmNumberOfSystemPtes * PAGE_SIZE);
527
528 //
529 // Create the system PTE space
530 //
531 MiInitializeSystemPtes(PointerPte, MmNumberOfSystemPtes, SystemPteSpace);
532
533 /* Get the PDE For hyperspace */
534 StartPde = MiAddressToPde(HYPER_SPACE);
535
536 /* Lock PFN database */
537 OldIrql = KeAcquireQueuedSpinLock(LockQueuePfnLock);
538
539 /* Allocate a page for hyperspace and create it */
540 PageFrameIndex = MiRemoveAnyPage(0);
541 TempPde.u.Hard.PageFrameNumber = PageFrameIndex;
542 TempPde.u.Hard.Global = FALSE; // Hyperspace is local!
543 MI_WRITE_VALID_PTE(StartPde, TempPde);
544
545 /* Flush the TLB */
546 KeFlushCurrentTb();
547
548 /* Release the lock */
549 KeReleaseQueuedSpinLock(LockQueuePfnLock, OldIrql);
550
551 //
552 // Zero out the page table now
553 //
554 PointerPte = MiAddressToPte(HYPER_SPACE);
555 RtlZeroMemory(PointerPte, PAGE_SIZE);
556
557 //
558 // Setup the mapping PTEs
559 //
560 MmFirstReservedMappingPte = MiAddressToPte(MI_MAPPING_RANGE_START);
561 MmLastReservedMappingPte = MiAddressToPte(MI_MAPPING_RANGE_END);
562 MmFirstReservedMappingPte->u.Hard.PageFrameNumber = MI_HYPERSPACE_PTES;
563
564 //
565 // Reserve system PTEs for zeroing PTEs and clear them
566 //
567 MiFirstReservedZeroingPte = MiReserveSystemPtes(MI_ZERO_PTES,
568 SystemPteSpace);
569 RtlZeroMemory(MiFirstReservedZeroingPte, MI_ZERO_PTES * sizeof(MMPTE));
570
571 //
572 // Set the counter to maximum to boot with
573 //
574 MiFirstReservedZeroingPte->u.Hard.PageFrameNumber = MI_ZERO_PTES - 1;
575
576 return STATUS_SUCCESS;
577 }
578
579 /* EOF */