2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS kernel
4 * FILE: ntoskrnl/ex/init.c
5 * PURPOSE: Executive initalization
7 * PROGRAMMERS: Alex Ionescu (alex@relsoft.net) - Added ExpInitializeExecutive
8 * and optimized/cleaned it.
9 * Eric Kohl (ekohl@abo.rhein-zeitung.de)
13 #include <ntos/bootvid.h>
15 #include <internal/debug.h>
17 /* DATA **********************************************************************/
19 extern ULONG MmCoreDumpType
;
20 extern CHAR KiTimerSystemAuditing
;
21 extern PVOID Ki386InitialStackArray
[MAXIMUM_PROCESSORS
];
22 extern ADDRESS_RANGE KeMemoryMap
[64];
23 extern ULONG KeMemoryMapRangeCount
;
24 extern ULONG_PTR FirstKrnlPhysAddr
;
25 extern ULONG_PTR LastKrnlPhysAddr
;
26 extern ULONG_PTR LastKernelAddress
;
27 extern LOADER_MODULE KeLoaderModules
[64];
28 extern PRTL_MESSAGE_RESOURCE_DATA KiBugCodeMessages
;
29 extern LIST_ENTRY KiProfileListHead
;
30 extern LIST_ENTRY KiProfileSourceListHead
;
31 extern KSPIN_LOCK KiProfileLock
;
33 VOID
PspPostInitSystemProcess(VOID
);
35 /* FUNCTIONS ****************************************************************/
40 InitSystemSharedUserPage (PCSZ ParameterLine
)
42 UNICODE_STRING ArcDeviceName
;
43 UNICODE_STRING ArcName
;
44 UNICODE_STRING BootPath
;
45 UNICODE_STRING DriveDeviceName
;
46 UNICODE_STRING DriveName
;
47 WCHAR DriveNameBuffer
[20];
53 OBJECT_ATTRIBUTES ObjectAttributes
;
56 BOOLEAN BootDriveFound
= FALSE
;
60 * The shared user page has been zeroed-out right after creation.
61 * There is NO need to do this again.
63 Ki386SetProcessorFeatures();
65 /* Set the Version Data */
66 SharedUserData
->NtProductType
= NtProductWinNt
;
67 SharedUserData
->ProductTypeIsValid
= TRUE
;
68 SharedUserData
->NtMajorVersion
= 5;
69 SharedUserData
->NtMinorVersion
= 0;
72 * Retrieve the current dos system path
73 * (e.g.: C:\reactos) from the given arc path
74 * (e.g.: multi(0)disk(0)rdisk(0)partititon(1)\reactos)
75 * Format: "<arc_name>\<path> [options...]"
78 /* Create local parameter line copy */
79 ParamBuffer
= ExAllocatePool(PagedPool
, 256);
80 strcpy (ParamBuffer
, (char *)ParameterLine
);
81 DPRINT("%s\n", ParamBuffer
);
84 p
= strchr (ParamBuffer
, ' ');
86 DPRINT("%s\n", ParamBuffer
);
89 p
= strchr (ParamBuffer
, '\\');
92 DPRINT("Boot path: %s\n", p
);
93 RtlCreateUnicodeStringFromAsciiz (&BootPath
, p
);
98 DPRINT("Boot path: %s\n", "\\");
99 RtlCreateUnicodeStringFromAsciiz (&BootPath
, "\\");
101 DPRINT("Arc name: %s\n", ParamBuffer
);
103 /* Only ARC Name left - Build full ARC Name */
104 ArcNameBuffer
= ExAllocatePool (PagedPool
, 256 * sizeof(WCHAR
));
105 swprintf (ArcNameBuffer
, L
"\\ArcName\\%S", ParamBuffer
);
106 RtlInitUnicodeString (&ArcName
, ArcNameBuffer
);
107 DPRINT("Arc name: %wZ\n", &ArcName
);
109 /* Free ParamBuffer */
110 ExFreePool (ParamBuffer
);
112 /* Allocate ARC Device Name string */
113 ArcDeviceName
.Length
= 0;
114 ArcDeviceName
.MaximumLength
= 256 * sizeof(WCHAR
);
115 ArcDeviceName
.Buffer
= ExAllocatePool (PagedPool
, 256 * sizeof(WCHAR
));
117 /* Open the Symbolic Link */
118 InitializeObjectAttributes(&ObjectAttributes
,
123 Status
= NtOpenSymbolicLinkObject(&Handle
,
124 SYMBOLIC_LINK_ALL_ACCESS
,
127 /* Free the String */
128 ExFreePool(ArcName
.Buffer
);
130 /* Check for Success */
131 if (!NT_SUCCESS(Status
)) {
133 /* Free the Strings */
134 RtlFreeUnicodeString(&BootPath
);
135 ExFreePool(ArcDeviceName
.Buffer
);
136 CPRINT("NtOpenSymbolicLinkObject() failed (Status %x)\n", Status
);
141 Status
= NtQuerySymbolicLinkObject(Handle
,
146 /* Check for Success */
147 if (!NT_SUCCESS(Status
)) {
149 /* Free the Strings */
150 RtlFreeUnicodeString(&BootPath
);
151 ExFreePool(ArcDeviceName
.Buffer
);
152 CPRINT("NtQuerySymbolicLinkObject() failed (Status %x)\n", Status
);
155 DPRINT("Length: %lu ArcDeviceName: %wZ\n", Length
, &ArcDeviceName
);
157 /* Allocate Device Name string */
158 DriveDeviceName
.Length
= 0;
159 DriveDeviceName
.MaximumLength
= 256 * sizeof(WCHAR
);
160 DriveDeviceName
.Buffer
= ExAllocatePool (PagedPool
, 256 * sizeof(WCHAR
));
163 for (i
= 0; i
< 26; i
++) {
165 /* Setup the String */
166 swprintf (DriveNameBuffer
, L
"\\??\\%C:", 'A' + i
);
167 RtlInitUnicodeString(&DriveName
,
170 /* Open the Symbolic Link */
171 InitializeObjectAttributes(&ObjectAttributes
,
176 Status
= NtOpenSymbolicLinkObject(&Handle
,
177 SYMBOLIC_LINK_ALL_ACCESS
,
180 /* If it failed, skip to the next drive */
181 if (!NT_SUCCESS(Status
)) {
182 DPRINT("Failed to open link %wZ\n", &DriveName
);
187 Status
= NtQuerySymbolicLinkObject(Handle
,
191 /* If it failed, skip to the next drive */
192 if (!NT_SUCCESS(Status
)) {
193 DPRINT("Failed to query link %wZ\n", &DriveName
);
196 DPRINT("Opened link: %wZ ==> %wZ\n", &DriveName
, &DriveDeviceName
);
198 /* See if we've found the boot drive */
199 if (!RtlCompareUnicodeString (&ArcDeviceName
, &DriveDeviceName
, FALSE
)) {
201 DPRINT("DOS Boot path: %c:%wZ\n", 'A' + i
, &BootPath
);
202 swprintf(SharedUserData
->NtSystemRoot
, L
"%C:%wZ", 'A' + i
, &BootPath
);
203 BootDriveFound
= TRUE
;
206 /* Close this Link */
210 /* Free all the Strings we have in memory */
211 RtlFreeUnicodeString (&BootPath
);
212 ExFreePool(DriveDeviceName
.Buffer
);
213 ExFreePool(ArcDeviceName
.Buffer
);
215 /* Make sure we found the Boot Drive */
216 if (BootDriveFound
== FALSE
) {
218 DbgPrint("No system drive found!\n");
219 KEBUGCHECK (NO_BOOT_DEVICE
);
226 ExecuteRuntimeAsserts(VOID
)
229 * Fail at runtime if someone has changed various structures without
230 * updating the offsets used for the assembler code.
232 ASSERT(FIELD_OFFSET(KTHREAD
, InitialStack
) == KTHREAD_INITIAL_STACK
);
233 ASSERT(FIELD_OFFSET(KTHREAD
, Teb
) == KTHREAD_TEB
);
234 ASSERT(FIELD_OFFSET(KTHREAD
, KernelStack
) == KTHREAD_KERNEL_STACK
);
235 ASSERT(FIELD_OFFSET(KTHREAD
, NpxState
) == KTHREAD_NPX_STATE
);
236 ASSERT(FIELD_OFFSET(KTHREAD
, ServiceTable
) == KTHREAD_SERVICE_TABLE
);
237 ASSERT(FIELD_OFFSET(KTHREAD
, PreviousMode
) == KTHREAD_PREVIOUS_MODE
);
238 ASSERT(FIELD_OFFSET(KTHREAD
, TrapFrame
) == KTHREAD_TRAP_FRAME
);
239 ASSERT(FIELD_OFFSET(KTHREAD
, CallbackStack
) == KTHREAD_CALLBACK_STACK
);
240 ASSERT(FIELD_OFFSET(KTHREAD
, ApcState
.Process
) == KTHREAD_APCSTATE_PROCESS
);
241 ASSERT(FIELD_OFFSET(KPROCESS
, DirectoryTableBase
) == KPROCESS_DIRECTORY_TABLE_BASE
);
242 ASSERT(FIELD_OFFSET(KPROCESS
, IopmOffset
) == KPROCESS_IOPM_OFFSET
);
243 ASSERT(FIELD_OFFSET(KPROCESS
, LdtDescriptor
) == KPROCESS_LDT_DESCRIPTOR0
);
244 ASSERT(FIELD_OFFSET(KTRAP_FRAME
, Reserved9
) == KTRAP_FRAME_RESERVED9
);
245 ASSERT(FIELD_OFFSET(KV86M_TRAP_FRAME
, SavedExceptionStack
) == TF_SAVED_EXCEPTION_STACK
);
246 ASSERT(FIELD_OFFSET(KV86M_TRAP_FRAME
, regs
) == TF_REGS
);
247 ASSERT(FIELD_OFFSET(KV86M_TRAP_FRAME
, orig_ebp
) == TF_ORIG_EBP
);
248 ASSERT(FIELD_OFFSET(KPCR
, Tib
.ExceptionList
) == KPCR_EXCEPTION_LIST
);
249 ASSERT(FIELD_OFFSET(KPCR
, Self
) == KPCR_SELF
);
250 ASSERT(FIELD_OFFSET(KPCR
, PrcbData
) + FIELD_OFFSET(KPRCB
, CurrentThread
) == KPCR_CURRENT_THREAD
);
251 ASSERT(FIELD_OFFSET(KPCR
, PrcbData
) + FIELD_OFFSET(KPRCB
, NpxThread
) == KPCR_NPX_THREAD
);
252 ASSERT(FIELD_OFFSET(KTSS
, Esp0
) == KTSS_ESP0
);
253 ASSERT(FIELD_OFFSET(KTSS
, Eflags
) == KTSS_EFLAGS
);
254 ASSERT(FIELD_OFFSET(KTSS
, IoMapBase
) == KTSS_IOMAPBASE
);
255 ASSERT(sizeof(FX_SAVE_AREA
) == SIZEOF_FX_SAVE_AREA
);
261 ParseAndCacheLoadedModules(PBOOLEAN SetupBoot
)
266 /* Loop the Module List and get the modules we want */
267 for (i
= 1; i
< KeLoaderBlock
.ModsCount
; i
++) {
269 /* Get the Name of this Module */
270 if (!(Name
= strrchr((PCHAR
)KeLoaderModules
[i
].String
, '\\'))) {
273 Name
= (PCHAR
)KeLoaderModules
[i
].String
;
281 /* Now check for any of the modules we will need later */
282 if (!_stricmp(Name
, "ansi.nls")) {
284 CachedModules
[AnsiCodepage
] = &KeLoaderModules
[i
];
286 } else if (!_stricmp(Name
, "oem.nls")) {
288 CachedModules
[OemCodepage
] = &KeLoaderModules
[i
];
290 } else if (!_stricmp(Name
, "casemap.nls")) {
292 CachedModules
[UnicodeCasemap
] = &KeLoaderModules
[i
];
294 } else if (!_stricmp(Name
, "system") || !_stricmp(Name
, "system.hiv")) {
296 CachedModules
[SystemRegistry
] = &KeLoaderModules
[i
];
299 } else if (!_stricmp(Name
, "hardware") || !_stricmp(Name
, "hardware.hiv")) {
301 CachedModules
[HardwareRegistry
] = &KeLoaderModules
[i
];
309 ParseCommandLine(PULONG MaxMem
,
312 PBOOLEAN ForceAcpiDisable
)
316 p1
= (PCHAR
)KeLoaderBlock
.CommandLine
;
317 while(*p1
&& (p2
= strchr(p1
, '/'))) {
320 if (!_strnicmp(p2
, "MAXMEM", 6)) {
323 while (isspace(*p2
)) p2
++;
329 while(isspace(*p2
)) p2
++;
332 while (isdigit(*p2
)) {
333 *MaxMem
= *MaxMem
* 10 + *p2
- '0';
339 } else if (!_strnicmp(p2
, "NOGUIBOOT", 9)) {
344 } else if (!_strnicmp(p2
, "CRASHDUMP", 9)) {
350 if (!_strnicmp(p2
, "FULL", 4)) {
352 MmCoreDumpType
= MM_CORE_DUMP_TYPE_FULL
;
356 MmCoreDumpType
= MM_CORE_DUMP_TYPE_NONE
;
359 } else if (!_strnicmp(p2
, "BOOTLOG", 7)) {
363 } else if (!_strnicmp(p2
, "NOACPI", 6)) {
366 *ForceAcpiDisable
= TRUE
;
376 ExpInitializeExecutive(VOID
)
379 UNICODE_STRING EventName
;
380 HANDLE InitDoneEventHandle
;
381 OBJECT_ATTRIBUTES ObjectAttributes
;
382 BOOLEAN NoGuiBoot
= FALSE
;
383 BOOLEAN BootLog
= FALSE
;
385 BOOLEAN SetupBoot
= TRUE
;
386 BOOLEAN ForceAcpiDisable
= FALSE
;
387 LARGE_INTEGER Timeout
;
388 HANDLE ProcessHandle
;
392 /* Check if the structures match the ASM offset constants */
393 ExecuteRuntimeAsserts();
395 /* Sets up the Text Sections of the Kernel and HAL for debugging */
398 /* Lower the IRQL to Dispatch Level */
399 KeLowerIrql(DISPATCH_LEVEL
);
401 /* Sets up the VDM Data */
404 /* Parse Command Line Settings */
405 ParseCommandLine(&MaxMem
, &NoGuiBoot
, &BootLog
, &ForceAcpiDisable
);
407 /* Initialize Kernel Memory Address Space */
408 MmInit1(FirstKrnlPhysAddr
,
411 (PADDRESS_RANGE
)&KeMemoryMap
,
412 KeMemoryMapRangeCount
,
413 MaxMem
> 8 ? MaxMem
: 4096);
415 /* Parse the Loaded Modules (by FreeLoader) and cache the ones we'll need */
416 ParseAndCacheLoadedModules(&SetupBoot
);
418 /* Initialize the kernel debugger parameters */
419 KdInitSystem(0, (PLOADER_PARAMETER_BLOCK
)&KeLoaderBlock
);
421 /* Initialize the Dispatcher, Clock and Bug Check Mechanisms. */
424 /* Bring back the IRQL to Passive */
425 KeLowerIrql(PASSIVE_LEVEL
);
427 /* Initialize Profiling */
428 InitializeListHead(&KiProfileListHead
);
429 InitializeListHead(&KiProfileSourceListHead
);
430 KeInitializeSpinLock(&KiProfileLock
);
432 /* Load basic Security for other Managers */
433 if (!SeInit1()) KEBUGCHECK(SECURITY_INITIALIZATION_FAILED
);
435 /* Create the Basic Object Manager Types to allow new Object Types */
438 /* Initialize Lookaside Lists */
441 /* Set up Region Maps, Sections and the Paging File */
444 /* Initialize Tokens now that the Object Manager is ready */
445 if (!SeInit2()) KEBUGCHECK(SECURITY1_INITIALIZATION_FAILED
);
447 /* Set 1 CPU for now, we'll increment this later */
448 KeNumberProcessors
= 1;
450 /* Initalize the Process Manager */
451 PiInitProcessManager();
453 /* Break into the Debugger if requested */
454 if (KdPollBreakIn()) DbgBreakPointWithStatus (DBG_STATUS_CONTROL_C
);
456 /* Initialize all processors */
457 while (!HalAllProcessorsStarted()) {
459 PVOID ProcessorStack
;
461 /* Set up the Kernel and Process Manager for this CPU */
462 KePrepareForApplicationProcessorInit(KeNumberProcessors
);
463 KeCreateApplicationProcessorIdleThread(KeNumberProcessors
);
465 /* Allocate a stack for use when booting the processor */
466 ProcessorStack
= Ki386InitialStackArray
[((int)KeNumberProcessors
)] + MM_STACK_SIZE
;
468 /* Tell HAL a new CPU is being started */
469 HalStartNextProcessor(0, (ULONG
)ProcessorStack
- 2*sizeof(FX_SAVE_AREA
));
470 KeNumberProcessors
++;
473 /* Do Phase 1 HAL Initalization */
474 HalInitSystem(1, (PLOADER_PARAMETER_BLOCK
)&KeLoaderBlock
);
476 /* Initialize Basic System Objects and Worker Threads */
479 /* Create the system handle table, assign it to the system process, create
480 the client id table and assign a PID for the system process. This needs
481 to be done before the worker threads are initialized so the system
482 process gets the first PID (4) */
483 PspPostInitSystemProcess();
485 /* initialize the worker threads */
486 ExpInitializeWorkerThreads();
488 /* initialize callbacks */
489 ExpInitializeCallbacks();
491 /* Call KD Providers at Phase 1 */
492 KdInitSystem(1, (PLOADER_PARAMETER_BLOCK
)&KeLoaderBlock
);
494 /* Initialize I/O Objects, Filesystems, Error Logging and Shutdown */
498 PoInit((PLOADER_PARAMETER_BLOCK
)&KeLoaderBlock
, ForceAcpiDisable
);
500 /* Initialize the Registry (Hives are NOT yet loaded!) */
501 CmInitializeRegistry();
503 /* Unmap Low memory, initialize the Page Zeroing and the Balancer Thread */
506 /* Initialize Cache Views */
509 /* Initialize File Locking */
510 FsRtlpInitFileLockingImplementation();
512 /* Report all resources used by hal */
513 HalReportResourceUsage();
515 /* Clear the screen to blue */
516 HalInitSystem(2, (PLOADER_PARAMETER_BLOCK
)&KeLoaderBlock
);
518 /* Display version number and copyright/warranty message */
519 HalDisplayString("Starting ReactOS "KERNEL_VERSION_STR
" (Build "
520 KERNEL_VERSION_BUILD_STR
")\n");
521 HalDisplayString(RES_STR_LEGAL_COPYRIGHT
);
522 HalDisplayString("\n\nReactOS is free software, covered by the GNU General "
523 "Public License, and you\n");
524 HalDisplayString("are welcome to change it and/or distribute copies of it "
526 HalDisplayString("conditions. There is absolutely no warranty for "
529 /* Display number of Processors */
531 "Found %d system processor(s). [%lu MB Memory]\n",
533 (KeLoaderBlock
.MemHigher
+ 1088)/ 1024);
534 HalDisplayString(str
);
536 /* Call KD Providers at Phase 2 */
537 KdInitSystem(2, (PLOADER_PARAMETER_BLOCK
)&KeLoaderBlock
);
539 /* Import and create NLS Data and Sections */
542 /* Import and Load Registry Hives */
543 CmInitHives(SetupBoot
);
545 /* Initialize the time zone information from the registry */
546 ExpInitTimeZoneInfo();
548 /* Enter the kernel debugger before starting up the boot drivers */
551 /* Setup Drivers and Root Device Node */
554 /* Display the boot screen image if not disabled */
555 if (!NoGuiBoot
) InbvEnableBootDriver(TRUE
);
557 /* Create ARC Names, SystemRoot SymLink, Load Drivers and Assign Letters */
560 /* Load the System DLL and its Entrypoints */
561 LdrpInitializeSystemDll();
563 /* Initialize the Default Locale */
564 PiInitDefaultLocale();
566 /* Initialize shared user page. Set dos system path, dos device map, etc. */
567 InitSystemSharedUserPage ((PCHAR
)KeLoaderBlock
.CommandLine
);
569 /* Create 'ReactOSInitDone' event */
570 RtlInitUnicodeString(&EventName
, L
"\\ReactOSInitDone");
571 InitializeObjectAttributes(&ObjectAttributes
,
576 Status
= ZwCreateEvent(&InitDoneEventHandle
,
579 SynchronizationEvent
,
582 /* Check for Success */
583 if (!NT_SUCCESS(Status
)) {
585 DPRINT1("Failed to create 'ReactOSInitDone' event (Status 0x%x)\n", Status
);
586 InitDoneEventHandle
= INVALID_HANDLE_VALUE
;
589 /* Launch initial process */
590 Status
= LdrLoadInitialProcess(&ProcessHandle
,
593 /* Check for success, Bugcheck if we failed */
594 if (!NT_SUCCESS(Status
)) {
596 KEBUGCHECKEX(SESSION4_INITIALIZATION_FAILED
, Status
, 0, 0, 0);
599 /* Wait on the Completion Event */
600 if (InitDoneEventHandle
!= INVALID_HANDLE_VALUE
) {
602 HANDLE Handles
[2]; /* Init event, Initial process */
604 /* Setup the Handles to wait on */
605 Handles
[0] = InitDoneEventHandle
;
606 Handles
[1] = ProcessHandle
;
608 /* Wait for the system to be initialized */
609 Timeout
.QuadPart
= (LONGLONG
)-1200000000; /* 120 second timeout */
610 Status
= ZwWaitForMultipleObjects(2,
615 if (!NT_SUCCESS(Status
)) {
617 DPRINT1("NtWaitForMultipleObjects failed with status 0x%x!\n", Status
);
619 } else if (Status
== STATUS_TIMEOUT
) {
621 DPRINT1("WARNING: System not initialized after 120 seconds.\n");
623 } else if (Status
== STATUS_WAIT_0
+ 1) {
625 /* Crash the system if the initial process was terminated. */
626 KEBUGCHECKEX(SESSION5_INITIALIZATION_FAILED
, Status
, 0, 0, 0);
629 /* Disable the Boot Logo */
630 if (!NoGuiBoot
) InbvEnableBootDriver(FALSE
);
632 /* Signal the Event and close the handle */
633 ZwSetEvent(InitDoneEventHandle
, NULL
);
634 ZwClose(InitDoneEventHandle
);
638 /* On failure to create 'ReactOSInitDone' event, go to text mode ASAP */
639 if (!NoGuiBoot
) InbvEnableBootDriver(FALSE
);
641 /* Crash the system if the initial process terminates within 5 seconds. */
642 Timeout
.QuadPart
= (LONGLONG
)-50000000; /* 5 second timeout */
643 Status
= ZwWaitForSingleObject(ProcessHandle
,
647 /* Check for timeout, crash if the initial process didn't initalize */
648 if (Status
!= STATUS_TIMEOUT
) KEBUGCHECKEX(SESSION5_INITIALIZATION_FAILED
, Status
, 1, 0, 0);
651 /* Enable the Clock, close remaining handles */
652 KiTimerSystemAuditing
= 1;
653 ZwClose(ThreadHandle
);
654 ZwClose(ProcessHandle
);
660 ExpInitLookasideLists();
666 ExpInitializeEventImplementation();
667 ExpInitializeEventPairImplementation();
668 ExpInitializeMutantImplementation();
669 ExpInitializeSemaphoreImplementation();
670 ExpInitializeTimerImplementation();
672 ExpInitializeProfileImplementation();
675 ExpInitializeHandleTables();