init.cpp 16 KB

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