init.cpp 14 KB

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