PowerStateSwitchTask.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /*
  2. * Copyright (c) 2023, kleines Filmröllchen <filmroellchen@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Platform.h>
  7. #if ARCH(X86_64)
  8. # include <Kernel/Arch/x86_64/I8042Reboot.h>
  9. # include <Kernel/Arch/x86_64/Shutdown.h>
  10. #elif ARCH(AARCH64)
  11. # include <Kernel/Arch/aarch64/RPi/Watchdog.h>
  12. #endif
  13. #include <AK/StringView.h>
  14. #include <Kernel/Arch/PowerState.h>
  15. #include <Kernel/FileSystem/FileSystem.h>
  16. #include <Kernel/FileSystem/VirtualFileSystem.h>
  17. #include <Kernel/Firmware/ACPI/Parser.h>
  18. #include <Kernel/Library/Panic.h>
  19. #include <Kernel/Sections.h>
  20. #include <Kernel/TTY/ConsoleManagement.h>
  21. #include <Kernel/Tasks/FinalizerTask.h>
  22. #include <Kernel/Tasks/PowerStateSwitchTask.h>
  23. #include <Kernel/Tasks/Process.h>
  24. #include <Kernel/Tasks/Scheduler.h>
  25. namespace Kernel {
  26. Thread* g_power_state_switch_task;
  27. bool g_in_system_shutdown { false };
  28. void PowerStateSwitchTask::power_state_switch_task(void* raw_entry_data)
  29. {
  30. Thread::current()->set_priority(THREAD_PRIORITY_HIGH);
  31. auto entry_data = bit_cast<PowerStateCommand>(raw_entry_data);
  32. switch (entry_data) {
  33. case PowerStateCommand::Shutdown:
  34. MUST(PowerStateSwitchTask::perform_shutdown(DoReboot::No));
  35. break;
  36. case PowerStateCommand::Reboot:
  37. MUST(PowerStateSwitchTask::perform_shutdown(DoReboot::Yes));
  38. break;
  39. default:
  40. PANIC("Unknown power state command: {}", to_underlying(entry_data));
  41. }
  42. // Although common, the system may not halt through this task.
  43. // Clear the power state switch task so that it can be spawned again.
  44. g_power_state_switch_task = nullptr;
  45. }
  46. void PowerStateSwitchTask::spawn(PowerStateCommand command)
  47. {
  48. VERIFY(g_power_state_switch_task == nullptr);
  49. auto [_, power_state_switch_task_thread] = MUST(Process::create_kernel_process(
  50. "Power State Switch Task"sv, power_state_switch_task, bit_cast<void*>(command)));
  51. g_power_state_switch_task = move(power_state_switch_task_thread);
  52. }
  53. ErrorOr<void> PowerStateSwitchTask::perform_shutdown(PowerStateSwitchTask::DoReboot do_reboot)
  54. {
  55. // We assume that by this point userland has tried as much as possible to shut down everything in an orderly fashion.
  56. // Therefore, we force kill remaining processes, including Kernel processes, except the finalizer and ourselves.
  57. dbgln("Killing remaining processes...");
  58. Optional<Process&> finalizer_process;
  59. Process::all_instances().for_each([&](Process& process) {
  60. if (process.pid() == g_finalizer->process().pid())
  61. finalizer_process = process;
  62. });
  63. VERIFY(finalizer_process.has_value());
  64. // Allow init process and finalizer task to be killed.
  65. g_in_system_shutdown = true;
  66. // Make sure to kill all user processes first, otherwise we might get weird hangups.
  67. TRY(kill_all_user_processes());
  68. size_t alive_process_count = 0;
  69. Process::all_instances().for_each([&](Process& process) {
  70. if (!process.is_kernel_process() && !process.is_dead())
  71. alive_process_count++;
  72. });
  73. // Don't panic here (since we may panic in a bit anyways) but report the probable cause of an unclean shutdown.
  74. if (alive_process_count != 0)
  75. dbgln("We're not the last process alive; proper shutdown may fail!");
  76. ConsoleManagement::the().switch_to_debug();
  77. dbgln("Locking all file systems...");
  78. FileSystem::lock_all();
  79. FileSystem::sync();
  80. dbgln("Unmounting all file systems...");
  81. auto unmount_was_successful = true;
  82. while (unmount_was_successful) {
  83. unmount_was_successful = false;
  84. Vector<Mount&, 16> mounts;
  85. TRY(VirtualFileSystem::the().for_each_mount([&](auto const& mount) -> ErrorOr<void> {
  86. TRY(mounts.try_append(const_cast<Mount&>(mount)));
  87. return {};
  88. }));
  89. if (mounts.is_empty())
  90. break;
  91. auto const remaining_mounts = mounts.size();
  92. while (!mounts.is_empty()) {
  93. auto& mount = mounts.take_last();
  94. mount.guest_fs().flush_writes();
  95. auto mount_path = TRY(mount.absolute_path());
  96. auto& mount_inode = mount.guest();
  97. auto const result = VirtualFileSystem::the().unmount(mount_inode, mount_path->view());
  98. if (result.is_error()) {
  99. dbgln("Error during unmount of {}: {}", mount_path, result.error());
  100. // FIXME: For unknown reasons the root FS stays busy even after everything else has shut down and was unmounted.
  101. // Until we find the underlying issue, allow an unclean shutdown here.
  102. if (remaining_mounts <= 1)
  103. dbgln("BUG! One mount remaining; the root file system may not be unmountable at all. Shutting down anyways.");
  104. } else {
  105. unmount_was_successful = true;
  106. }
  107. }
  108. }
  109. // NOTE: We don't really need to kill kernel processes, because in contrast
  110. // to user processes, kernel processes will simply not make syscalls
  111. // or do some other unexpected behavior.
  112. // Therefore, we just lock the scheduler big lock to ensure nothing happens
  113. // beyond this point forward.
  114. SpinlockLocker lock(g_scheduler_lock);
  115. if (do_reboot == DoReboot::Yes) {
  116. dbgln("Attempting system reboot...");
  117. dbgln("attempting reboot via ACPI");
  118. if (ACPI::is_enabled())
  119. ACPI::Parser::the()->try_acpi_reboot();
  120. arch_specific_reboot();
  121. dmesgln("Reboot can't be completed. It's safe to turn off the computer!");
  122. Processor::halt();
  123. VERIFY_NOT_REACHED();
  124. }
  125. VERIFY(do_reboot == DoReboot::No);
  126. dbgln("Attempting system shutdown...");
  127. arch_specific_poweroff();
  128. dmesgln("Shutdown can't be completed. It's safe to turn off the computer!");
  129. Processor::halt();
  130. VERIFY_NOT_REACHED();
  131. }
  132. ErrorOr<void> PowerStateSwitchTask::kill_all_user_processes()
  133. {
  134. {
  135. SpinlockLocker lock(g_scheduler_lock);
  136. Process::all_instances().for_each([&](Process& process) {
  137. if (!process.is_kernel_process())
  138. process.die();
  139. });
  140. }
  141. // Although we *could* finalize processes ourselves (g_in_system_shutdown allows this),
  142. // we're nice citizens and let the finalizer task perform final duties before we kill it.
  143. Scheduler::notify_finalizer();
  144. int alive_process_count = 1;
  145. MonotonicTime last_status_time = TimeManagement::the().monotonic_time();
  146. while (alive_process_count > 0) {
  147. Scheduler::yield();
  148. alive_process_count = 0;
  149. Process::all_instances().for_each([&](Process& process) {
  150. if (!process.is_kernel_process() && !process.is_dead())
  151. alive_process_count++;
  152. });
  153. if (TimeManagement::the().monotonic_time() - last_status_time > Duration::from_seconds(2)) {
  154. last_status_time = TimeManagement::the().monotonic_time();
  155. dmesgln("Waiting on {} processes to exit...", alive_process_count);
  156. if constexpr (PROCESS_DEBUG) {
  157. Process::all_instances().for_each_const([&](Process const& process) {
  158. if (!process.is_kernel_process() && !process.is_dead()) {
  159. dbgln("Process (user) {:2} dead={} dying={} ({})",
  160. process.pid(), process.is_dead(), process.is_dying(),
  161. process.name().with([](auto& name) { return name.representable_view(); }));
  162. }
  163. });
  164. }
  165. }
  166. }
  167. return {};
  168. }
  169. }