2 * PROJECT: ReactOS Kernel
3 * LICENSE: BSD - See COPYING.ARM in the top level directory
4 * FILE: ntoskrnl/mm/ARM3/procsup.c
5 * PURPOSE: ARM Memory Manager Process Related Management
6 * PROGRAMMERS: ReactOS Portable Systems Group
9 /* INCLUDES *******************************************************************/
15 #define MODULE_INVOLVED_IN_ARM3
16 #include "../ARM3/miarm.h"
18 /* GLOBALS ********************************************************************/
20 ULONG MmProcessColorSeed
= 0x12345678;
21 PMMWSL MmWorkingSetList
;
23 /* PRIVATE FUNCTIONS **********************************************************/
27 MiRosTakeOverPebTebRanges(IN PEPROCESS Process
)
30 PMEMORY_AREA MemoryArea
;
31 PHYSICAL_ADDRESS BoundaryAddressMultiple
;
32 PVOID AllocatedBase
= (PVOID
)USER_SHARED_DATA
;
33 BoundaryAddressMultiple
.QuadPart
= 0;
35 Status
= MmCreateMemoryArea(&Process
->Vm
,
36 MEMORY_AREA_OWNED_BY_ARM3
,
38 ((ULONG_PTR
)MM_HIGHEST_USER_ADDRESS
- 1) -
39 (ULONG_PTR
)USER_SHARED_DATA
,
44 BoundaryAddressMultiple
);
45 ASSERT(NT_SUCCESS(Status
));
50 MiCreatePebOrTeb(IN PEPROCESS Process
,
54 PETHREAD Thread
= PsGetCurrentThread();
58 ULONG_PTR StartAddress
, EndAddress
;
59 LARGE_INTEGER CurrentTime
;
60 TABLE_SEARCH_RESULT Result
= TableFoundNode
;
61 PMMADDRESS_NODE Parent
;
64 Vad
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(MMVAD_LONG
), 'ldaV');
65 if (!Vad
) return STATUS_NO_MEMORY
;
67 /* Setup the primary flags with the size, and make it commited, private, RW */
69 Vad
->u
.VadFlags
.CommitCharge
= BYTES_TO_PAGES(Size
);
70 Vad
->u
.VadFlags
.MemCommit
= TRUE
;
71 Vad
->u
.VadFlags
.PrivateMemory
= TRUE
;
72 Vad
->u
.VadFlags
.Protection
= MM_READWRITE
;
73 Vad
->u
.VadFlags
.NoChange
= TRUE
;
75 /* Setup the secondary flags to make it a secured, writable, long VAD */
76 Vad
->u2
.LongFlags2
= 0;
77 Vad
->u2
.VadFlags2
.OneSecured
= TRUE
;
78 Vad
->u2
.VadFlags2
.LongVad
= TRUE
;
79 Vad
->u2
.VadFlags2
.ReadOnly
= FALSE
;
81 /* Lock the process address space */
82 KeAcquireGuardedMutex(&Process
->AddressCreationLock
);
84 /* Check if this is a PEB creation */
85 if (Size
== sizeof(PEB
))
87 /* Start at the highest valid address */
88 StartAddress
= (ULONG_PTR
)MM_HIGHEST_VAD_ADDRESS
+ 1;
90 /* Select the random coefficient */
91 KeQueryTickCount(&CurrentTime
);
92 CurrentTime
.LowPart
&= ((64 * _1KB
) >> PAGE_SHIFT
) - 1;
93 if (CurrentTime
.LowPart
<= 1) CurrentTime
.LowPart
= 2;
94 RandomCoeff
= CurrentTime
.LowPart
<< PAGE_SHIFT
;
96 /* Select the highest valid address minus the random coefficient */
97 StartAddress
-= RandomCoeff
;
98 EndAddress
= StartAddress
+ ROUND_TO_PAGES(Size
) - 1;
100 /* Try to find something below the random upper margin */
101 Result
= MiFindEmptyAddressRangeDownTree(ROUND_TO_PAGES(Size
),
109 /* Check for success. TableFoundNode means nothing free. */
110 if (Result
== TableFoundNode
)
112 /* For TEBs, or if a PEB location couldn't be found, scan the VAD root */
113 Result
= MiFindEmptyAddressRangeDownTree(ROUND_TO_PAGES(Size
),
114 (ULONG_PTR
)MM_HIGHEST_VAD_ADDRESS
+ 1,
119 /* Bail out, if still nothing free was found */
120 if (Result
== TableFoundNode
) return STATUS_NO_MEMORY
;
123 /* Validate that it came from the VAD ranges */
124 ASSERT(*Base
>= (ULONG_PTR
)MI_LOWEST_VAD_ADDRESS
);
126 /* Build the rest of the VAD now */
127 Vad
->StartingVpn
= (*Base
) >> PAGE_SHIFT
;
128 Vad
->EndingVpn
= ((*Base
) + Size
- 1) >> PAGE_SHIFT
;
129 Vad
->u3
.Secured
.StartVpn
= *Base
;
130 Vad
->u3
.Secured
.EndVpn
= (Vad
->EndingVpn
<< PAGE_SHIFT
) | (PAGE_SIZE
- 1);
131 Vad
->u1
.Parent
= NULL
;
133 /* FIXME: Should setup VAD bitmap */
134 Status
= STATUS_SUCCESS
;
136 /* Pretend as if we own the working set */
137 MiLockProcessWorkingSet(Process
, Thread
);
140 ASSERT(Vad
->EndingVpn
>= Vad
->StartingVpn
);
141 Process
->VadRoot
.NodeHint
= Vad
;
142 Vad
->ControlArea
= NULL
; // For Memory-Area hack
143 Vad
->FirstPrototypePte
= NULL
;
144 DPRINT("VAD: %p\n", Vad
);
145 DPRINT("Allocated PEB/TEB at: 0x%p for %16s\n", *Base
, Process
->ImageFileName
);
146 MiInsertNode(&Process
->VadRoot
, (PVOID
)Vad
, Parent
, Result
);
148 /* Release the working set */
149 MiUnlockProcessWorkingSet(Process
, Thread
);
151 /* Release the address space lock */
152 KeReleaseGuardedMutex(&Process
->AddressCreationLock
);
154 /* Return the status */
160 MmDeleteTeb(IN PEPROCESS Process
,
164 PETHREAD Thread
= PsGetCurrentThread();
166 PMM_AVL_TABLE VadTree
= &Process
->VadRoot
;
167 DPRINT("Deleting TEB: %p in %16s\n", Teb
, Process
->ImageFileName
);
169 /* TEB is one page */
170 TebEnd
= (ULONG_PTR
)Teb
+ ROUND_TO_PAGES(sizeof(TEB
)) - 1;
172 /* Attach to the process */
173 KeAttachProcess(&Process
->Pcb
);
175 /* Lock the process address space */
176 KeAcquireGuardedMutex(&Process
->AddressCreationLock
);
178 /* Find the VAD, make sure it's a TEB VAD */
179 Vad
= MiLocateAddress(Teb
);
180 DPRINT("Removing node for VAD: %lx %lx\n", Vad
->StartingVpn
, Vad
->EndingVpn
);
182 if (Vad
->StartingVpn
!= ((ULONG_PTR
)Teb
>> PAGE_SHIFT
))
184 /* Bug in the AVL code? */
185 DPRINT1("Corrupted VAD!\n");
189 /* Sanity checks for a valid TEB VAD */
190 ASSERT((Vad
->StartingVpn
== ((ULONG_PTR
)Teb
>> PAGE_SHIFT
) &&
191 (Vad
->EndingVpn
== (TebEnd
>> PAGE_SHIFT
))));
192 ASSERT(Vad
->u
.VadFlags
.NoChange
== TRUE
);
193 ASSERT(Vad
->u2
.VadFlags2
.OneSecured
== TRUE
);
194 ASSERT(Vad
->u2
.VadFlags2
.MultipleSecured
== FALSE
);
196 /* Lock the working set */
197 MiLockProcessWorkingSet(Process
, Thread
);
199 /* Remove this VAD from the tree */
200 ASSERT(VadTree
->NumberGenericTableElements
>= 1);
201 MiRemoveNode((PMMADDRESS_NODE
)Vad
, VadTree
);
203 /* Release the working set */
204 MiUnlockProcessWorkingSet(Process
, Thread
);
210 /* Release the address space lock */
211 KeReleaseGuardedMutex(&Process
->AddressCreationLock
);
219 MmDeleteKernelStack(IN PVOID StackBase
,
223 PFN_NUMBER StackPages
, PageFrameNumber
;//, PageTableFrameNumber;
224 PMMPFN Pfn1
;//, Pfn2;
229 // This should be the guard page, so decrement by one
231 PointerPte
= MiAddressToPte(StackBase
);
235 // Calculate pages used
237 StackPages
= BYTES_TO_PAGES(GuiStack
?
238 KERNEL_LARGE_STACK_SIZE
: KERNEL_STACK_SIZE
);
240 /* Acquire the PFN lock */
241 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
246 for (i
= 0; i
< StackPages
; i
++)
249 // Check if this is a valid PTE
251 if (PointerPte
->u
.Hard
.Valid
== 1)
253 /* Get the PTE's page */
254 PageFrameNumber
= PFN_FROM_PTE(PointerPte
);
255 Pfn1
= MiGetPfnEntry(PageFrameNumber
);
256 #if 0 // ARM3 might not own the page table, so don't take this risk. Leak it instead!
257 /* Now get the page of the page table mapping it */
258 PageTableFrameNumber
= Pfn1
->u4
.PteFrame
;
259 Pfn2
= MiGetPfnEntry(PageTableFrameNumber
);
261 /* Remove a shared reference, since the page is going away */
262 MiDecrementShareCount(Pfn2
, PageTableFrameNumber
);
264 /* Set the special pending delete marker */
265 MI_SET_PFN_DELETED(Pfn1
);
267 /* And now delete the actual stack page */
268 MiDecrementShareCount(Pfn1
, PageFrameNumber
);
278 // We should be at the guard page now
280 ASSERT(PointerPte
->u
.Hard
.Valid
== 0);
282 /* Release the PFN lock */
283 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
288 MiReleaseSystemPtes(PointerPte
, StackPages
+ 1, SystemPteSpace
);
293 MmCreateKernelStack(IN BOOLEAN GuiStack
,
296 PFN_NUMBER StackPtes
, StackPages
;
297 PMMPTE PointerPte
, StackPte
;
299 MMPTE TempPte
, InvalidPte
;
301 PFN_NUMBER PageFrameIndex
;
305 // Calculate pages needed
310 // We'll allocate 64KB stack, but only commit 12K
312 StackPtes
= BYTES_TO_PAGES(KERNEL_LARGE_STACK_SIZE
);
313 StackPages
= BYTES_TO_PAGES(KERNEL_LARGE_STACK_COMMIT
);
319 // We'll allocate 12K and that's it
321 StackPtes
= BYTES_TO_PAGES(KERNEL_STACK_SIZE
);
322 StackPages
= StackPtes
;
326 // Reserve stack pages, plus a guard page
328 StackPte
= MiReserveSystemPtes(StackPtes
+ 1, SystemPteSpace
);
329 if (!StackPte
) return NULL
;
332 // Get the stack address
334 BaseAddress
= MiPteToAddress(StackPte
+ StackPtes
+ 1);
337 // Select the right PTE address where we actually start committing pages
339 PointerPte
= StackPte
;
340 if (GuiStack
) PointerPte
+= BYTES_TO_PAGES(KERNEL_LARGE_STACK_SIZE
-
341 KERNEL_LARGE_STACK_COMMIT
);
344 /* Setup the temporary invalid PTE */
345 MI_MAKE_SOFTWARE_PTE(&InvalidPte
, MM_NOACCESS
);
347 /* Setup the template stack PTE */
348 MI_MAKE_HARDWARE_PTE_KERNEL(&TempPte
, PointerPte
+ 1, MM_READWRITE
, 0);
351 // Acquire the PFN DB lock
353 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
356 // Loop each stack page
358 for (i
= 0; i
< StackPages
; i
++)
365 /* Get a page and write the current invalid PTE */
366 MI_SET_USAGE(MI_USAGE_KERNEL_STACK
);
367 MI_SET_PROCESS2(PsGetCurrentProcess()->ImageFileName
);
368 PageFrameIndex
= MiRemoveAnyPage(MI_GET_NEXT_COLOR());
369 MI_WRITE_INVALID_PTE(PointerPte
, InvalidPte
);
371 /* Initialize the PFN entry for this page */
372 MiInitializePfn(PageFrameIndex
, PointerPte
, 1);
374 /* Write the valid PTE */
375 TempPte
.u
.Hard
.PageFrameNumber
= PageFrameIndex
;
376 MI_WRITE_VALID_PTE(PointerPte
, TempPte
);
380 // Release the PFN lock
382 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
385 // Return the stack address
392 MmGrowKernelStackEx(IN PVOID StackPointer
,
395 PKTHREAD Thread
= KeGetCurrentThread();
396 PMMPTE LimitPte
, NewLimitPte
, LastPte
;
398 MMPTE TempPte
, InvalidPte
;
399 PFN_NUMBER PageFrameIndex
;
402 // Make sure the stack did not overflow
404 ASSERT(((ULONG_PTR
)Thread
->StackBase
- (ULONG_PTR
)Thread
->StackLimit
) <=
405 (KERNEL_LARGE_STACK_SIZE
+ PAGE_SIZE
));
408 // Get the current stack limit
410 LimitPte
= MiAddressToPte(Thread
->StackLimit
);
411 ASSERT(LimitPte
->u
.Hard
.Valid
== 1);
414 // Get the new one and make sure this isn't a retarded request
416 NewLimitPte
= MiAddressToPte((PVOID
)((ULONG_PTR
)StackPointer
- GrowSize
));
417 if (NewLimitPte
== LimitPte
) return STATUS_SUCCESS
;
420 // Now make sure you're not going past the reserved space
422 LastPte
= MiAddressToPte((PVOID
)((ULONG_PTR
)Thread
->StackBase
-
423 KERNEL_LARGE_STACK_SIZE
));
424 if (NewLimitPte
< LastPte
)
429 DPRINT1("Thread wants too much stack\n");
430 return STATUS_STACK_OVERFLOW
;
434 // Calculate the number of new pages
438 /* Setup the temporary invalid PTE */
439 MI_MAKE_SOFTWARE_PTE(&InvalidPte
, MM_NOACCESS
);
442 // Acquire the PFN DB lock
444 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
447 // Loop each stack page
449 while (LimitPte
>= NewLimitPte
)
451 /* Get a page and write the current invalid PTE */
452 MI_SET_USAGE(MI_USAGE_KERNEL_STACK_EXPANSION
);
453 MI_SET_PROCESS2(PsGetCurrentProcess()->ImageFileName
);
454 PageFrameIndex
= MiRemoveAnyPage(MI_GET_NEXT_COLOR());
455 MI_WRITE_INVALID_PTE(LimitPte
, InvalidPte
);
457 /* Initialize the PFN entry for this page */
458 MiInitializePfn(PageFrameIndex
, LimitPte
, 1);
460 /* Setup the template stack PTE */
461 MI_MAKE_HARDWARE_PTE_KERNEL(&TempPte
, LimitPte
, MM_READWRITE
, PageFrameIndex
);
463 /* Write the valid PTE */
464 MI_WRITE_VALID_PTE(LimitPte
--, TempPte
);
468 // Release the PFN lock
470 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
475 Thread
->StackLimit
= (ULONG_PTR
)MiPteToAddress(NewLimitPte
);
476 return STATUS_SUCCESS
;
481 MmGrowKernelStack(IN PVOID StackPointer
)
484 // Call the extended version
486 return MmGrowKernelStackEx(StackPointer
, KERNEL_LARGE_STACK_COMMIT
);
491 MmSetMemoryPriorityProcess(IN PEPROCESS Process
,
492 IN UCHAR MemoryPriority
)
497 // Check if we have less then 16MB of Physical Memory
499 if ((MmSystemSize
== MmSmallSystem
) &&
500 (MmNumberOfPhysicalPages
< ((15 * 1024 * 1024) / PAGE_SIZE
)))
503 // Always use background priority
505 MemoryPriority
= MEMORY_PRIORITY_BACKGROUND
;
509 // Save the old priority and update it
511 OldPriority
= (UCHAR
)Process
->Vm
.Flags
.MemoryPriority
;
512 Process
->Vm
.Flags
.MemoryPriority
= MemoryPriority
;
515 // Return the old priority
522 MmGetSessionLocaleId(VOID
)
528 // Get the current process
530 Process
= PsGetCurrentProcess();
533 // Check if it's the Session Leader
535 if (Process
->Vm
.Flags
.SessionLeader
)
538 // Make sure it has a valid Session
540 if (Process
->Session
)
546 return ((PMM_SESSION_SPACE
)Process
->Session
)->LocaleId
;
552 // Not a session leader, return the default
554 return PsDefaultThreadLocaleId
;
559 MmCreatePeb(IN PEPROCESS Process
,
560 IN PINITIAL_PEB InitialPeb
,
564 LARGE_INTEGER SectionOffset
;
566 PVOID TableBase
= NULL
;
567 PIMAGE_NT_HEADERS NtHeaders
;
568 PIMAGE_LOAD_CONFIG_DIRECTORY ImageConfigData
;
570 USHORT Characteristics
;
571 KAFFINITY ProcessAffinityMask
= 0;
572 SectionOffset
.QuadPart
= (ULONGLONG
)0;
578 KeAttachProcess(&Process
->Pcb
);
583 Status
= MmMapViewOfSection(ExpNlsSectionPointer
,
593 DPRINT("NLS Tables at: %p\n", TableBase
);
594 if (!NT_SUCCESS(Status
))
596 /* Cleanup and exit */
604 Status
= MiCreatePebOrTeb(Process
, sizeof(PEB
), (PULONG_PTR
)&Peb
);
605 DPRINT("PEB at: %p\n", Peb
);
606 if (!NT_SUCCESS(Status
))
608 /* Cleanup and exit */
614 // Use SEH in case we can't load the PEB
619 // Initialize the PEB
621 RtlZeroMemory(Peb
, sizeof(PEB
));
626 Peb
->ImageBaseAddress
= Process
->SectionBaseAddress
;
627 Peb
->InheritedAddressSpace
= InitialPeb
->InheritedAddressSpace
;
628 Peb
->Mutant
= InitialPeb
->Mutant
;
629 Peb
->ImageUsesLargePages
= InitialPeb
->ImageUsesLargePages
;
634 Peb
->AnsiCodePageData
= (PCHAR
)TableBase
+ ExpAnsiCodePageDataOffset
;
635 Peb
->OemCodePageData
= (PCHAR
)TableBase
+ ExpOemCodePageDataOffset
;
636 Peb
->UnicodeCaseTableData
= (PCHAR
)TableBase
+ ExpUnicodeCaseTableDataOffset
;
639 // Default Version Data (could get changed below)
641 Peb
->OSMajorVersion
= NtMajorVersion
;
642 Peb
->OSMinorVersion
= NtMinorVersion
;
643 Peb
->OSBuildNumber
= (USHORT
)(NtBuildNumber
& 0x3FFF);
644 Peb
->OSPlatformId
= 2; /* VER_PLATFORM_WIN32_NT */
645 Peb
->OSCSDVersion
= (USHORT
)CmNtCSDVersion
;
648 // Heap and Debug Data
650 Peb
->NumberOfProcessors
= KeNumberProcessors
;
651 Peb
->BeingDebugged
= (BOOLEAN
)(Process
->DebugPort
!= NULL
);
652 Peb
->NtGlobalFlag
= NtGlobalFlag
;
653 /*Peb->HeapSegmentReserve = MmHeapSegmentReserve;
654 Peb->HeapSegmentCommit = MmHeapSegmentCommit;
655 Peb->HeapDeCommitTotalFreeThreshold = MmHeapDeCommitTotalFreeThreshold;
656 Peb->HeapDeCommitFreeBlockThreshold = MmHeapDeCommitFreeBlockThreshold;
657 Peb->CriticalSectionTimeout = MmCriticalSectionTimeout;
658 Peb->MinimumStackCommit = MmMinimumStackCommitInBytes;
660 Peb
->MaximumNumberOfHeaps
= (PAGE_SIZE
- sizeof(PEB
)) / sizeof(PVOID
);
661 Peb
->ProcessHeaps
= (PVOID
*)(Peb
+ 1);
666 if (Process
->Session
) Peb
->SessionId
= 0; // MmGetSessionId(Process);
668 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
674 _SEH2_YIELD(return _SEH2_GetExceptionCode());
679 // Use SEH in case we can't load the image
686 NtHeaders
= RtlImageNtHeader(Peb
->ImageBaseAddress
);
687 Characteristics
= NtHeaders
->FileHeader
.Characteristics
;
689 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
695 _SEH2_YIELD(return STATUS_INVALID_IMAGE_PROTECT
);
705 // Use SEH in case we can't load the headers
710 // Get the Image Config Data too
712 ImageConfigData
= RtlImageDirectoryEntryToData(Peb
->ImageBaseAddress
,
714 IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
,
721 ProbeForRead(ImageConfigData
,
722 sizeof(IMAGE_LOAD_CONFIG_DIRECTORY
),
727 // Write subsystem data
729 Peb
->ImageSubsystem
= NtHeaders
->OptionalHeader
.Subsystem
;
730 Peb
->ImageSubsystemMajorVersion
= NtHeaders
->OptionalHeader
.MajorSubsystemVersion
;
731 Peb
->ImageSubsystemMinorVersion
= NtHeaders
->OptionalHeader
.MinorSubsystemVersion
;
734 // Check for version data
736 if (NtHeaders
->OptionalHeader
.Win32VersionValue
)
739 // Extract values and write them
741 Peb
->OSMajorVersion
= NtHeaders
->OptionalHeader
.Win32VersionValue
& 0xFF;
742 Peb
->OSMinorVersion
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 8) & 0xFF;
743 Peb
->OSBuildNumber
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 16) & 0x3FFF;
744 Peb
->OSPlatformId
= (NtHeaders
->OptionalHeader
.Win32VersionValue
>> 30) ^ 2;
746 /* Process CSD version override */
747 if ((ImageConfigData
) && (ImageConfigData
->CSDVersion
))
749 /* Take the value from the image configuration directory */
750 Peb
->OSCSDVersion
= ImageConfigData
->CSDVersion
;
754 /* Process optional process affinity mask override */
755 if ((ImageConfigData
) && (ImageConfigData
->ProcessAffinityMask
))
757 /* Take the value from the image configuration directory */
758 ProcessAffinityMask
= ImageConfigData
->ProcessAffinityMask
;
762 // Check if this is a UP image
763 if (Characteristics
& IMAGE_FILE_UP_SYSTEM_ONLY
)
766 // Force it to use CPU 0
768 /* FIXME: this should use the MmRotatingUniprocessorNumber */
769 Peb
->ImageProcessAffinityMask
= 0;
774 // Whatever was configured
776 Peb
->ImageProcessAffinityMask
= ProcessAffinityMask
;
779 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
785 _SEH2_YIELD(return STATUS_INVALID_IMAGE_PROTECT
);
791 // Detach from the Process
795 return STATUS_SUCCESS
;
800 MmCreateTeb(IN PEPROCESS Process
,
801 IN PCLIENT_ID ClientId
,
802 IN PINITIAL_TEB InitialTeb
,
806 NTSTATUS Status
= STATUS_SUCCESS
;
812 KeAttachProcess(&Process
->Pcb
);
817 Status
= MiCreatePebOrTeb(Process
, sizeof(TEB
), (PULONG_PTR
)&Teb
);
818 ASSERT(NT_SUCCESS(Status
));
821 // Use SEH in case we can't load the TEB
826 // Initialize the PEB
828 RtlZeroMemory(Teb
, sizeof(TEB
));
833 Teb
->NtTib
.ExceptionList
= EXCEPTION_CHAIN_END
;
834 Teb
->NtTib
.Self
= (PNT_TIB
)Teb
;
837 // Identify this as an OS/2 V3.0 ("Cruiser") TIB
839 Teb
->NtTib
.Version
= 30 << 8;
844 Teb
->ClientId
= *ClientId
;
845 Teb
->RealClientId
= *ClientId
;
846 Teb
->ProcessEnvironmentBlock
= Process
->Peb
;
847 Teb
->CurrentLocale
= PsDefaultThreadLocaleId
;
850 // Check if we have a grandparent TEB
852 if ((InitialTeb
->PreviousStackBase
== NULL
) &&
853 (InitialTeb
->PreviousStackLimit
== NULL
))
856 // Use initial TEB values
858 Teb
->NtTib
.StackBase
= InitialTeb
->StackBase
;
859 Teb
->NtTib
.StackLimit
= InitialTeb
->StackLimit
;
860 Teb
->DeallocationStack
= InitialTeb
->AllocatedStackBase
;
865 // Use grandparent TEB values
867 Teb
->NtTib
.StackBase
= InitialTeb
->PreviousStackBase
;
868 Teb
->NtTib
.StackLimit
= InitialTeb
->PreviousStackLimit
;
872 // Initialize the static unicode string
874 Teb
->StaticUnicodeString
.MaximumLength
= sizeof(Teb
->StaticUnicodeBuffer
);
875 Teb
->StaticUnicodeString
.Buffer
= Teb
->StaticUnicodeBuffer
;
877 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
882 Status
= _SEH2_GetExceptionCode();
896 MiInitializeWorkingSetList(IN PEPROCESS CurrentProcess
)
900 /* Setup some bogus list data */
901 MmWorkingSetList
->LastEntry
= CurrentProcess
->Vm
.MinimumWorkingSetSize
;
902 MmWorkingSetList
->HashTable
= NULL
;
903 MmWorkingSetList
->HashTableSize
= 0;
904 MmWorkingSetList
->NumberOfImageWaiters
= 0;
905 MmWorkingSetList
->Wsle
= (PVOID
)0xDEADBABE;
906 MmWorkingSetList
->VadBitMapHint
= 1;
907 MmWorkingSetList
->HashTableStart
= (PVOID
)0xBADAB00B;
908 MmWorkingSetList
->HighestPermittedHashAddress
= (PVOID
)0xCAFEBABE;
909 MmWorkingSetList
->FirstFree
= 1;
910 MmWorkingSetList
->FirstDynamic
= 2;
911 MmWorkingSetList
->NextSlot
= 3;
912 MmWorkingSetList
->LastInitializedWsle
= 4;
914 /* The rule is that the owner process is always in the FLINK of the PDE's PFN entry */
915 Pfn1
= MiGetPfnEntry(MiAddressToPte(PDE_BASE
)->u
.Hard
.PageFrameNumber
);
916 ASSERT(Pfn1
->u4
.PteFrame
== MiGetPfnEntryIndex(Pfn1
));
917 Pfn1
->u1
.Event
= (PKEVENT
)CurrentProcess
;
922 MmInitializeProcessAddressSpace(IN PEPROCESS Process
,
923 IN PEPROCESS ProcessClone OPTIONAL
,
924 IN PVOID Section OPTIONAL
,
926 IN POBJECT_NAME_INFORMATION
*AuditName OPTIONAL
)
928 NTSTATUS Status
= STATUS_SUCCESS
;
931 PROS_SECTION_OBJECT SectionObject
= Section
;
935 PFN_NUMBER PageFrameNumber
;
936 UNICODE_STRING FileName
;
942 /* We should have a PDE */
943 ASSERT(Process
->Pcb
.DirectoryTableBase
[0] != 0);
944 ASSERT(Process
->PdeUpdateNeeded
== FALSE
);
946 /* Attach to the process */
947 KeAttachProcess(&Process
->Pcb
);
949 /* The address space should now been in phase 1 or 0 */
950 ASSERT(Process
->AddressSpaceInitialized
<= 1);
951 Process
->AddressSpaceInitialized
= 2;
953 /* Initialize the Addresss Space lock */
954 KeInitializeGuardedMutex(&Process
->AddressCreationLock
);
955 Process
->Vm
.WorkingSetExpansionLinks
.Flink
= NULL
;
957 /* Initialize AVL tree */
958 ASSERT(Process
->VadRoot
.NumberGenericTableElements
== 0);
959 Process
->VadRoot
.BalancedRoot
.u1
.Parent
= &Process
->VadRoot
.BalancedRoot
;
961 /* Lock PFN database */
962 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
964 /* Setup the PFN for the PDE base of this process */
965 PointerPte
= MiAddressToPte(PDE_BASE
);
966 PageFrameNumber
= PFN_FROM_PTE(PointerPte
);
967 MiInitializePfn(PageFrameNumber
, PointerPte
, TRUE
);
969 /* Do the same for hyperspace */
970 PointerPde
= MiAddressToPde(HYPER_SPACE
);
971 PageFrameNumber
= PFN_FROM_PTE(PointerPde
);
972 MiInitializePfn(PageFrameNumber
, (PMMPTE
)PointerPde
, TRUE
);
974 /* Setup the PFN for the PTE for the working set */
975 PointerPte
= MiAddressToPte(MI_WORKING_SET_LIST
);
976 MI_MAKE_HARDWARE_PTE(&TempPte
, PointerPte
, MM_READWRITE
, 0);
977 ASSERT(PointerPte
->u
.Long
!= 0);
978 PageFrameNumber
= PFN_FROM_PTE(PointerPte
);
979 MI_WRITE_INVALID_PTE(PointerPte
, DemandZeroPte
);
980 MiInitializePfn(PageFrameNumber
, PointerPte
, TRUE
);
981 TempPte
.u
.Hard
.PageFrameNumber
= PageFrameNumber
;
982 MI_WRITE_VALID_PTE(PointerPte
, TempPte
);
984 /* Now initialize the working set list */
985 MiInitializeWorkingSetList(Process
);
988 ASSERT(Process
->PhysicalVadRoot
== NULL
);
990 /* Release PFN lock */
991 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
993 /* Lock the VAD, ARM3-owned ranges away */
994 MiRosTakeOverPebTebRanges(Process
);
996 /* Check if there's a Section Object */
999 /* Determine the image file name and save it to EPROCESS */
1000 FileName
= SectionObject
->FileObject
->FileName
;
1001 Source
= (PWCHAR
)((PCHAR
)FileName
.Buffer
+ FileName
.Length
);
1002 if (FileName
.Buffer
)
1004 /* Loop the file name*/
1005 while (Source
> FileName
.Buffer
)
1007 /* Make sure this isn't a backslash */
1008 if (*--Source
== OBJ_NAME_PATH_SEPARATOR
)
1010 /* If so, stop it here */
1016 /* Otherwise, keep going */
1022 /* Copy the to the process and truncate it to 15 characters if necessary */
1023 Destination
= Process
->ImageFileName
;
1024 Length
= min(Length
, sizeof(Process
->ImageFileName
) - 1);
1025 while (Length
--) *Destination
++ = (UCHAR
)*Source
++;
1026 *Destination
= ANSI_NULL
;
1028 /* Check if caller wants an audit name */
1031 /* Setup the audit name */
1032 Status
= SeInitializeProcessAuditName(SectionObject
->FileObject
,
1035 if (!NT_SUCCESS(Status
))
1043 /* Map the section */
1044 Status
= MmMapViewOfSection(Section
,
1055 /* Save the pointer */
1056 Process
->SectionBaseAddress
= ImageBase
;
1059 /* Be nice and detach */
1062 /* Return status to caller */
1069 MmInitializeHandBuiltProcess(IN PEPROCESS Process
,
1070 IN PULONG_PTR DirectoryTableBase
)
1072 /* Share the directory base with the idle process */
1073 DirectoryTableBase
[0] = PsGetCurrentProcess()->Pcb
.DirectoryTableBase
[0];
1074 DirectoryTableBase
[1] = PsGetCurrentProcess()->Pcb
.DirectoryTableBase
[1];
1076 /* Initialize the Addresss Space */
1077 KeInitializeGuardedMutex(&Process
->AddressCreationLock
);
1078 KeInitializeSpinLock(&Process
->HyperSpaceLock
);
1079 Process
->Vm
.WorkingSetExpansionLinks
.Flink
= NULL
;
1080 ASSERT(Process
->VadRoot
.NumberGenericTableElements
== 0);
1081 Process
->VadRoot
.BalancedRoot
.u1
.Parent
= &Process
->VadRoot
.BalancedRoot
;
1084 Process
->HasAddressSpace
= TRUE
;//??
1085 return STATUS_SUCCESS
;
1091 MmInitializeHandBuiltProcess2(IN PEPROCESS Process
)
1093 /* Lock the VAD, ARM3-owned ranges away */
1094 MiRosTakeOverPebTebRanges(Process
);
1095 return STATUS_SUCCESS
;
1099 /* FIXME: Evaluate ways to make this portable yet arch-specific */
1102 MmCreateProcessAddressSpace(IN ULONG MinWs
,
1103 IN PEPROCESS Process
,
1104 OUT PULONG_PTR DirectoryTableBase
)
1107 PFN_NUMBER PdeIndex
, HyperIndex
, WsListIndex
;
1109 MMPTE TempPte
, PdePte
;
1111 PMMPTE SystemTable
, HyperTable
;
1115 /* Choose a process color */
1116 Process
->NextPageColor
= RtlRandom(&MmProcessColorSeed
);
1118 /* Setup the hyperspace lock */
1119 KeInitializeSpinLock(&Process
->HyperSpaceLock
);
1121 /* Lock PFN database */
1122 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
1124 /* Get a zero page for the PDE, if possible */
1125 Color
= MI_GET_NEXT_PROCESS_COLOR(Process
);
1126 MI_SET_USAGE(MI_USAGE_PAGE_DIRECTORY
);
1127 PdeIndex
= MiRemoveZeroPageSafe(Color
);
1130 /* No zero pages, grab a free one */
1131 PdeIndex
= MiRemoveAnyPage(Color
);
1133 /* Zero it outside the PFN lock */
1134 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
1135 MiZeroPhysicalPage(PdeIndex
);
1136 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
1139 /* Get a zero page for hyperspace, if possible */
1140 MI_SET_USAGE(MI_USAGE_PAGE_DIRECTORY
);
1141 Color
= MI_GET_NEXT_PROCESS_COLOR(Process
);
1142 HyperIndex
= MiRemoveZeroPageSafe(Color
);
1145 /* No zero pages, grab a free one */
1146 HyperIndex
= MiRemoveAnyPage(Color
);
1148 /* Zero it outside the PFN lock */
1149 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
1150 MiZeroPhysicalPage(HyperIndex
);
1151 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
1154 /* Get a zero page for the woring set list, if possible */
1155 MI_SET_USAGE(MI_USAGE_PAGE_TABLE
);
1156 Color
= MI_GET_NEXT_PROCESS_COLOR(Process
);
1157 WsListIndex
= MiRemoveZeroPageSafe(Color
);
1160 /* No zero pages, grab a free one */
1161 WsListIndex
= MiRemoveAnyPage(Color
);
1163 /* Zero it outside the PFN lock */
1164 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
1165 MiZeroPhysicalPage(WsListIndex
);
1169 /* Release the PFN lock */
1170 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
1173 /* Switch to phase 1 initialization */
1174 ASSERT(Process
->AddressSpaceInitialized
== 0);
1175 Process
->AddressSpaceInitialized
= 1;
1177 /* Set the base directory pointers */
1178 Process
->WorkingSetPage
= WsListIndex
;
1179 DirectoryTableBase
[0] = PdeIndex
<< PAGE_SHIFT
;
1180 DirectoryTableBase
[1] = HyperIndex
<< PAGE_SHIFT
;
1182 /* Make sure we don't already have a page directory setup */
1183 ASSERT(Process
->Pcb
.DirectoryTableBase
[0] == 0);
1185 /* Get a PTE to map hyperspace */
1186 PointerPte
= MiReserveSystemPtes(1, SystemPteSpace
);
1187 ASSERT(PointerPte
!= NULL
);
1190 MI_MAKE_HARDWARE_PTE_KERNEL(&PdePte
,
1195 /* Set it dirty and map it */
1196 MI_MAKE_DIRTY_PAGE(&PdePte
);
1197 MI_WRITE_VALID_PTE(PointerPte
, PdePte
);
1199 /* Now get hyperspace's page table */
1200 HyperTable
= MiPteToAddress(PointerPte
);
1202 /* Now write the PTE/PDE entry for the working set list index itself */
1203 TempPte
= ValidKernelPte
;
1204 TempPte
.u
.Hard
.PageFrameNumber
= WsListIndex
;
1205 PdeOffset
= MiAddressToPteOffset(MmWorkingSetList
);
1206 HyperTable
[PdeOffset
] = TempPte
;
1208 /* Let go of the system PTE */
1209 MiReleaseSystemPtes(PointerPte
, 1, SystemPteSpace
);
1211 /* Save the PTE address of the page directory itself */
1212 Pfn1
= MiGetPfnEntry(PdeIndex
);
1213 Pfn1
->PteAddress
= (PMMPTE
)PDE_BASE
;
1215 /* Insert us into the Mm process list */
1216 InsertTailList(&MmProcessList
, &Process
->MmProcessLinks
);
1218 /* Get a PTE to map the page directory */
1219 PointerPte
= MiReserveSystemPtes(1, SystemPteSpace
);
1220 ASSERT(PointerPte
!= NULL
);
1223 MI_MAKE_HARDWARE_PTE_KERNEL(&PdePte
,
1228 /* Set it dirty and map it */
1229 MI_MAKE_DIRTY_PAGE(&PdePte
);
1230 MI_WRITE_VALID_PTE(PointerPte
, PdePte
);
1232 /* Now get the page directory (which we'll double map, so call it a page table */
1233 SystemTable
= MiPteToAddress(PointerPte
);
1235 /* Copy all the kernel mappings */
1236 PdeOffset
= MiGetPdeOffset(MmSystemRangeStart
);
1237 RtlCopyMemory(&SystemTable
[PdeOffset
],
1238 MiAddressToPde(MmSystemRangeStart
),
1239 PAGE_SIZE
- PdeOffset
* sizeof(MMPTE
));
1241 /* Now write the PTE/PDE entry for hyperspace itself */
1242 TempPte
= ValidKernelPte
;
1243 TempPte
.u
.Hard
.PageFrameNumber
= HyperIndex
;
1244 PdeOffset
= MiGetPdeOffset(HYPER_SPACE
);
1245 SystemTable
[PdeOffset
] = TempPte
;
1249 ASSERT(MiGetPdeOffset(MmHyperSpaceEnd
) >= PdeOffset
);
1251 /* Now do the x86 trick of making the PDE a page table itself */
1252 PdeOffset
= MiGetPdeOffset(PTE_BASE
);
1253 TempPte
.u
.Hard
.PageFrameNumber
= PdeIndex
;
1254 SystemTable
[PdeOffset
] = TempPte
;
1256 /* Let go of the system PTE */
1257 MiReleaseSystemPtes(PointerPte
, 1, SystemPteSpace
);
1264 MmCleanProcessAddressSpace(IN PEPROCESS Process
)
1267 PMM_AVL_TABLE VadTree
;
1268 PETHREAD Thread
= PsGetCurrentThread();
1270 /* Only support this */
1271 ASSERT(Process
->AddressSpaceInitialized
== 2);
1273 /* Lock the process address space from changes */
1274 MmLockAddressSpace(&Process
->Vm
);
1276 /* VM is deleted now */
1277 Process
->VmDeleted
= TRUE
;
1279 /* Enumerate the VADs */
1280 VadTree
= &Process
->VadRoot
;
1281 while (VadTree
->NumberGenericTableElements
)
1283 /* Grab the current VAD */
1284 Vad
= (PMMVAD
)VadTree
->BalancedRoot
.RightChild
;
1286 /* Lock the working set */
1287 MiLockProcessWorkingSet(Process
, Thread
);
1289 /* Remove this VAD from the tree */
1290 ASSERT(VadTree
->NumberGenericTableElements
>= 1);
1291 MiRemoveNode((PMMADDRESS_NODE
)Vad
, VadTree
);
1293 /* Only regular VADs supported for now */
1294 ASSERT(Vad
->u
.VadFlags
.VadType
== VadNone
);
1296 /* Check if this is a section VAD */
1297 if (!(Vad
->u
.VadFlags
.PrivateMemory
) && (Vad
->ControlArea
))
1299 /* Remove the view */
1300 MiRemoveMappedView(Process
, Vad
);
1304 /* Delete the addresses */
1305 MiDeleteVirtualAddresses(Vad
->StartingVpn
<< PAGE_SHIFT
,
1306 (Vad
->EndingVpn
<< PAGE_SHIFT
) | (PAGE_SIZE
- 1),
1309 /* Release the working set */
1310 MiUnlockProcessWorkingSet(Process
, Thread
);
1313 /* Skip ARM3 fake VADs, they'll be freed by MmDeleteProcessAddresSpace */
1314 if (Vad
->u
.VadFlags
.Spare
== 1)
1316 /* Set a flag so MmDeleteMemoryArea knows to free, but not to remove */
1317 Vad
->u
.VadFlags
.Spare
= 2;
1321 /* Free the VAD memory */
1325 /* Release the address space */
1326 MmUnlockAddressSpace(&Process
->Vm
);
1329 /* SYSTEM CALLS ***************************************************************/
1333 NtAllocateUserPhysicalPages(IN HANDLE ProcessHandle
,
1334 IN OUT PULONG_PTR NumberOfPages
,
1335 IN OUT PULONG_PTR UserPfnArray
)
1338 return STATUS_NOT_IMPLEMENTED
;
1343 NtMapUserPhysicalPages(IN PVOID VirtualAddresses
,
1344 IN ULONG_PTR NumberOfPages
,
1345 IN OUT PULONG_PTR UserPfnArray
)
1348 return STATUS_NOT_IMPLEMENTED
;
1353 NtMapUserPhysicalPagesScatter(IN PVOID
*VirtualAddresses
,
1354 IN ULONG_PTR NumberOfPages
,
1355 IN OUT PULONG_PTR UserPfnArray
)
1358 return STATUS_NOT_IMPLEMENTED
;
1363 NtFreeUserPhysicalPages(IN HANDLE ProcessHandle
,
1364 IN OUT PULONG_PTR NumberOfPages
,
1365 IN OUT PULONG_PTR UserPfnArray
)
1368 return STATUS_NOT_IMPLEMENTED
;