init.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Types.h>
  7. #include <Kernel/ACPI/DynamicParser.h>
  8. #include <Kernel/ACPI/Initialize.h>
  9. #include <Kernel/ACPI/MultiProcessorParser.h>
  10. #include <Kernel/Arch/PC/BIOS.h>
  11. #include <Kernel/Arch/x86/Processor.h>
  12. #include <Kernel/BootInfo.h>
  13. #include <Kernel/Bus/PCI/Access.h>
  14. #include <Kernel/Bus/PCI/Initializer.h>
  15. #include <Kernel/Bus/USB/UHCIController.h>
  16. #include <Kernel/CMOS.h>
  17. #include <Kernel/CommandLine.h>
  18. #include <Kernel/Devices/FullDevice.h>
  19. #include <Kernel/Devices/HID/HIDManagement.h>
  20. #include <Kernel/Devices/KCOVDevice.h>
  21. #include <Kernel/Devices/MemoryDevice.h>
  22. #include <Kernel/Devices/NullDevice.h>
  23. #include <Kernel/Devices/PCISerialDevice.h>
  24. #include <Kernel/Devices/RandomDevice.h>
  25. #include <Kernel/Devices/SB16.h>
  26. #include <Kernel/Devices/SerialDevice.h>
  27. #include <Kernel/Devices/VMWareBackdoor.h>
  28. #include <Kernel/Devices/ZeroDevice.h>
  29. #include <Kernel/FileSystem/Ext2FileSystem.h>
  30. #include <Kernel/FileSystem/SysFS.h>
  31. #include <Kernel/FileSystem/VirtualFileSystem.h>
  32. #include <Kernel/Graphics/GraphicsManagement.h>
  33. #include <Kernel/Heap/SlabAllocator.h>
  34. #include <Kernel/Heap/kmalloc.h>
  35. #include <Kernel/Interrupts/APIC.h>
  36. #include <Kernel/Interrupts/InterruptManagement.h>
  37. #include <Kernel/Interrupts/PIC.h>
  38. #include <Kernel/KSyms.h>
  39. #include <Kernel/Multiboot.h>
  40. #include <Kernel/Net/NetworkTask.h>
  41. #include <Kernel/Net/NetworkingManagement.h>
  42. #include <Kernel/Panic.h>
  43. #include <Kernel/Prekernel/Prekernel.h>
  44. #include <Kernel/Process.h>
  45. #include <Kernel/ProcessExposed.h>
  46. #include <Kernel/RTC.h>
  47. #include <Kernel/Random.h>
  48. #include <Kernel/Scheduler.h>
  49. #include <Kernel/Sections.h>
  50. #include <Kernel/Storage/StorageManagement.h>
  51. #include <Kernel/TTY/ConsoleManagement.h>
  52. #include <Kernel/TTY/PTYMultiplexer.h>
  53. #include <Kernel/TTY/VirtualConsole.h>
  54. #include <Kernel/Tasks/FinalizerTask.h>
  55. #include <Kernel/Tasks/SyncTask.h>
  56. #include <Kernel/Time/TimeManagement.h>
  57. #include <Kernel/VM/MemoryManager.h>
  58. #include <Kernel/VirtIO/VirtIO.h>
  59. #include <Kernel/WorkQueue.h>
  60. #include <Kernel/kstdio.h>
  61. // Defined in the linker script
  62. typedef void (*ctor_func_t)();
  63. extern ctor_func_t start_heap_ctors[];
  64. extern ctor_func_t end_heap_ctors[];
  65. extern ctor_func_t start_ctors[];
  66. extern ctor_func_t end_ctors[];
  67. extern size_t __stack_chk_guard;
  68. size_t __stack_chk_guard;
  69. extern "C" u8 start_of_safemem_text[];
  70. extern "C" u8 end_of_safemem_text[];
  71. extern "C" u8 start_of_safemem_atomic_text[];
  72. extern "C" u8 end_of_safemem_atomic_text[];
  73. extern "C" u8 end_of_kernel_image[];
  74. multiboot_module_entry_t multiboot_copy_boot_modules_array[16];
  75. size_t multiboot_copy_boot_modules_count;
  76. READONLY_AFTER_INIT bool g_in_early_boot;
  77. namespace Kernel {
  78. [[noreturn]] static void init_stage2(void*);
  79. static void setup_serial_debug();
  80. // boot.S expects these functions to exactly have the following signatures.
  81. // We declare them here to ensure their signatures don't accidentally change.
  82. extern "C" void init_finished(u32 cpu) __attribute__((used));
  83. extern "C" [[noreturn]] void init_ap(FlatPtr cpu, Processor* processor_info);
  84. extern "C" [[noreturn]] void init(BootInfo const&);
  85. READONLY_AFTER_INIT VirtualConsole* tty0;
  86. static Processor s_bsp_processor; // global but let's keep it "private"
  87. // SerenityOS Kernel C++ entry point :^)
  88. //
  89. // This is where C++ execution begins, after boot.S transfers control here.
  90. //
  91. // The purpose of init() is to start multi-tasking. It does the bare minimum
  92. // amount of work needed to start the scheduler.
  93. //
  94. // Once multi-tasking is ready, we spawn a new thread that starts in the
  95. // init_stage2() function. Initialization continues there.
  96. extern "C" {
  97. READONLY_AFTER_INIT PhysicalAddress start_of_prekernel_image;
  98. READONLY_AFTER_INIT PhysicalAddress end_of_prekernel_image;
  99. READONLY_AFTER_INIT FlatPtr kernel_base;
  100. READONLY_AFTER_INIT size_t physical_to_virtual_offset;
  101. #if ARCH(X86_64)
  102. READONLY_AFTER_INIT PhysicalAddress boot_pml4t;
  103. #endif
  104. READONLY_AFTER_INIT PhysicalAddress boot_pdpt;
  105. READONLY_AFTER_INIT PhysicalAddress boot_pd0;
  106. READONLY_AFTER_INIT PhysicalAddress boot_pd_kernel;
  107. READONLY_AFTER_INIT PageTableEntry* boot_pd_kernel_pt1023;
  108. READONLY_AFTER_INIT const char* kernel_cmdline;
  109. READONLY_AFTER_INIT u32 multiboot_flags;
  110. READONLY_AFTER_INIT multiboot_memory_map_t* multiboot_memory_map;
  111. READONLY_AFTER_INIT size_t multiboot_memory_map_count;
  112. READONLY_AFTER_INIT multiboot_module_entry_t* multiboot_modules;
  113. READONLY_AFTER_INIT size_t multiboot_modules_count;
  114. READONLY_AFTER_INIT PhysicalAddress multiboot_framebuffer_addr;
  115. READONLY_AFTER_INIT u32 multiboot_framebuffer_pitch;
  116. READONLY_AFTER_INIT u32 multiboot_framebuffer_width;
  117. READONLY_AFTER_INIT u32 multiboot_framebuffer_height;
  118. READONLY_AFTER_INIT u8 multiboot_framebuffer_bpp;
  119. READONLY_AFTER_INIT u8 multiboot_framebuffer_type;
  120. }
  121. extern "C" [[noreturn]] UNMAP_AFTER_INIT void init(BootInfo const& boot_info)
  122. {
  123. g_in_early_boot = true;
  124. start_of_prekernel_image = PhysicalAddress { boot_info.start_of_prekernel_image };
  125. end_of_prekernel_image = PhysicalAddress { boot_info.end_of_prekernel_image };
  126. physical_to_virtual_offset = boot_info.physical_to_virtual_offset;
  127. kernel_base = boot_info.kernel_base;
  128. #if ARCH(X86_64)
  129. gdt64ptr = boot_info.gdt64ptr;
  130. code64_sel = boot_info.code64_sel;
  131. boot_pml4t = PhysicalAddress { boot_info.boot_pml4t };
  132. #endif
  133. boot_pdpt = PhysicalAddress { boot_info.boot_pdpt };
  134. boot_pd0 = PhysicalAddress { boot_info.boot_pd0 };
  135. boot_pd_kernel = PhysicalAddress { boot_info.boot_pd_kernel };
  136. boot_pd_kernel_pt1023 = (PageTableEntry*)boot_info.boot_pd_kernel_pt1023;
  137. kernel_cmdline = (char const*)boot_info.kernel_cmdline;
  138. multiboot_flags = boot_info.multiboot_flags;
  139. multiboot_memory_map = (multiboot_memory_map_t*)boot_info.multiboot_memory_map;
  140. multiboot_memory_map_count = boot_info.multiboot_memory_map_count;
  141. multiboot_modules = (multiboot_module_entry_t*)boot_info.multiboot_modules;
  142. multiboot_modules_count = boot_info.multiboot_modules_count;
  143. multiboot_framebuffer_addr = PhysicalAddress { boot_info.multiboot_framebuffer_addr };
  144. multiboot_framebuffer_pitch = boot_info.multiboot_framebuffer_pitch;
  145. multiboot_framebuffer_width = boot_info.multiboot_framebuffer_width;
  146. multiboot_framebuffer_height = boot_info.multiboot_framebuffer_height;
  147. multiboot_framebuffer_bpp = boot_info.multiboot_framebuffer_bpp;
  148. multiboot_framebuffer_type = boot_info.multiboot_framebuffer_type;
  149. setup_serial_debug();
  150. // We need to copy the command line before kmalloc is initialized,
  151. // as it may overwrite parts of multiboot!
  152. CommandLine::early_initialize(kernel_cmdline);
  153. memcpy(multiboot_copy_boot_modules_array, multiboot_modules, multiboot_modules_count * sizeof(multiboot_module_entry_t));
  154. multiboot_copy_boot_modules_count = multiboot_modules_count;
  155. s_bsp_processor.early_initialize(0);
  156. // Invoke the constructors needed for the kernel heap
  157. for (ctor_func_t* ctor = start_heap_ctors; ctor < end_heap_ctors; ctor++)
  158. (*ctor)();
  159. kmalloc_init();
  160. slab_alloc_init();
  161. load_kernel_symbol_table();
  162. ConsoleDevice::initialize();
  163. s_bsp_processor.initialize(0);
  164. CommandLine::initialize();
  165. MemoryManager::initialize(0);
  166. // Ensure that the safemem sections are not empty. This could happen if the linker accidentally discards the sections.
  167. VERIFY(start_of_safemem_text != end_of_safemem_text);
  168. VERIFY(start_of_safemem_atomic_text != end_of_safemem_atomic_text);
  169. // Invoke all static global constructors in the kernel.
  170. // Note that we want to do this as early as possible.
  171. for (ctor_func_t* ctor = start_ctors; ctor < end_ctors; ctor++)
  172. (*ctor)();
  173. APIC::initialize();
  174. InterruptManagement::initialize();
  175. ACPI::initialize();
  176. // Initialize TimeManagement before using randomness!
  177. TimeManagement::initialize(0);
  178. __stack_chk_guard = get_fast_random<size_t>();
  179. ProcFSComponentRegistry::initialize();
  180. Thread::initialize();
  181. Process::initialize();
  182. Scheduler::initialize();
  183. dmesgln("Starting SerenityOS...");
  184. {
  185. RefPtr<Thread> init_stage2_thread;
  186. Process::create_kernel_process(init_stage2_thread, "init_stage2", init_stage2, nullptr, THREAD_AFFINITY_DEFAULT, Process::RegisterProcess::No);
  187. // We need to make sure we drop the reference for init_stage2_thread
  188. // before calling into Scheduler::start, otherwise we will have a
  189. // dangling Thread that never gets cleaned up
  190. }
  191. Scheduler::start();
  192. VERIFY_NOT_REACHED();
  193. }
  194. //
  195. // This is where C++ execution begins for APs, after boot.S transfers control here.
  196. //
  197. // The purpose of init_ap() is to initialize APs for multi-tasking.
  198. //
  199. extern "C" [[noreturn]] UNMAP_AFTER_INIT void init_ap(FlatPtr cpu, Processor* processor_info)
  200. {
  201. processor_info->early_initialize(cpu);
  202. processor_info->initialize(cpu);
  203. MemoryManager::initialize(cpu);
  204. Scheduler::set_idle_thread(APIC::the().get_idle_thread(cpu));
  205. Scheduler::start();
  206. VERIFY_NOT_REACHED();
  207. }
  208. //
  209. // This method is called once a CPU enters the scheduler and its idle thread
  210. // At this point the initial boot stack can be freed
  211. //
  212. extern "C" UNMAP_AFTER_INIT void init_finished(u32 cpu)
  213. {
  214. if (cpu == 0) {
  215. // TODO: we can reuse the boot stack, maybe for kmalloc()?
  216. } else {
  217. APIC::the().init_finished(cpu);
  218. TimeManagement::initialize(cpu);
  219. }
  220. }
  221. void init_stage2(void*)
  222. {
  223. // This is a little bit of a hack. We can't register our process at the time we're
  224. // creating it, but we need to be registered otherwise finalization won't be happy.
  225. // The colonel process gets away without having to do this because it never exits.
  226. Process::register_new(*Process::current());
  227. WorkQueue::initialize();
  228. if (APIC::initialized() && APIC::the().enabled_processor_count() > 1) {
  229. // We can't start the APs until we have a scheduler up and running.
  230. // We need to be able to process ICI messages, otherwise another
  231. // core may send too many and end up deadlocking once the pool is
  232. // exhausted
  233. APIC::the().boot_aps();
  234. }
  235. // Initialize the PCI Bus as early as possible, for early boot (PCI based) serial logging
  236. SysFSComponentRegistry::initialize();
  237. PCI::initialize();
  238. PCISerialDevice::detect();
  239. VirtualFileSystem::initialize();
  240. NullDevice::initialize();
  241. if (!get_serial_debug())
  242. (void)SerialDevice::must_create(0).leak_ref();
  243. (void)SerialDevice::must_create(1).leak_ref();
  244. (void)SerialDevice::must_create(2).leak_ref();
  245. (void)SerialDevice::must_create(3).leak_ref();
  246. VMWareBackdoor::the(); // don't wait until first mouse packet
  247. HIDManagement::initialize();
  248. GraphicsManagement::the().initialize();
  249. ConsoleManagement::the().initialize();
  250. SyncTask::spawn();
  251. FinalizerTask::spawn();
  252. auto boot_profiling = kernel_command_line().is_boot_profiling_enabled();
  253. USB::UHCIController::detect();
  254. BIOSSysFSDirectory::initialize();
  255. ACPI::ACPISysFSDirectory::initialize();
  256. VirtIO::detect();
  257. NetworkingManagement::the().initialize();
  258. Syscall::initialize();
  259. #ifdef ENABLE_KERNEL_COVERAGE_COLLECTION
  260. (void)KCOVDevice::must_create().leak_ref();
  261. #endif
  262. (void)MemoryDevice::must_create().leak_ref();
  263. (void)ZeroDevice::must_create().leak_ref();
  264. (void)FullDevice::must_create().leak_ref();
  265. (void)RandomDevice::must_create().leak_ref();
  266. PTYMultiplexer::initialize();
  267. SB16::detect();
  268. StorageManagement::initialize(kernel_command_line().root_device(), kernel_command_line().is_force_pio());
  269. if (!VirtualFileSystem::the().mount_root(StorageManagement::the().root_filesystem())) {
  270. PANIC("VirtualFileSystem::mount_root failed");
  271. }
  272. Process::current()->set_root_directory(VirtualFileSystem::the().root_custody());
  273. // Switch out of early boot mode.
  274. g_in_early_boot = false;
  275. // NOTE: Everything marked READONLY_AFTER_INIT becomes non-writable after this point.
  276. MM.protect_readonly_after_init_memory();
  277. // NOTE: Everything marked UNMAP_AFTER_INIT becomes inaccessible after this point.
  278. MM.unmap_text_after_init();
  279. // NOTE: Everything in the .ksyms section becomes inaccessible after this point.
  280. MM.unmap_ksyms_after_init();
  281. int error;
  282. // FIXME: It would be nicer to set the mode from userspace.
  283. // FIXME: It would be smarter to not hardcode that the first tty is the only graphical one
  284. ConsoleManagement::the().first_tty()->set_graphical(GraphicsManagement::the().framebuffer_devices_exist());
  285. RefPtr<Thread> thread;
  286. auto userspace_init = kernel_command_line().userspace_init();
  287. auto init_args = kernel_command_line().userspace_init_args();
  288. Process::create_user_process(thread, userspace_init, (uid_t)0, (gid_t)0, ProcessID(0), error, move(init_args), {}, tty0);
  289. if (error != 0) {
  290. PANIC("init_stage2: Error spawning SystemServer: {}", error);
  291. }
  292. thread->set_priority(THREAD_PRIORITY_HIGH);
  293. if (boot_profiling) {
  294. dbgln("Starting full system boot profiling");
  295. auto result = Process::current()->sys$profiling_enable(-1, ~0ull);
  296. VERIFY(!result.is_error());
  297. }
  298. NetworkTask::spawn();
  299. Process::current()->sys$exit(0);
  300. VERIFY_NOT_REACHED();
  301. }
  302. UNMAP_AFTER_INIT void setup_serial_debug()
  303. {
  304. // serial_debug will output all the dbgln() data to COM1 at
  305. // 8-N-1 57600 baud. this is particularly useful for debugging the boot
  306. // process on live hardware.
  307. if (StringView(kernel_cmdline).contains("serial_debug")) {
  308. set_serial_debug(true);
  309. }
  310. }
  311. // Define some Itanium C++ ABI methods to stop the linker from complaining.
  312. // If we actually call these something has gone horribly wrong
  313. void* __dso_handle __attribute__((visibility("hidden")));
  314. }