kernel.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <atomic>
  5. #include <memory>
  6. #include <mutex>
  7. #include <utility>
  8. #include "common/assert.h"
  9. #include "common/logging/log.h"
  10. #include "core/core.h"
  11. #include "core/core_timing.h"
  12. #include "core/core_timing_util.h"
  13. #include "core/hle/kernel/address_arbiter.h"
  14. #include "core/hle/kernel/client_port.h"
  15. #include "core/hle/kernel/errors.h"
  16. #include "core/hle/kernel/handle_table.h"
  17. #include "core/hle/kernel/kernel.h"
  18. #include "core/hle/kernel/process.h"
  19. #include "core/hle/kernel/resource_limit.h"
  20. #include "core/hle/kernel/scheduler.h"
  21. #include "core/hle/kernel/thread.h"
  22. #include "core/hle/lock.h"
  23. #include "core/hle/result.h"
  24. #include "core/memory.h"
  25. namespace Kernel {
  26. /**
  27. * Callback that will wake up the thread it was scheduled for
  28. * @param thread_handle The handle of the thread that's been awoken
  29. * @param cycles_late The number of CPU cycles that have passed since the desired wakeup time
  30. */
  31. static void ThreadWakeupCallback(u64 thread_handle, [[maybe_unused]] s64 cycles_late) {
  32. const auto proper_handle = static_cast<Handle>(thread_handle);
  33. const auto& system = Core::System::GetInstance();
  34. // Lock the global kernel mutex when we enter the kernel HLE.
  35. std::lock_guard lock{HLE::g_hle_lock};
  36. std::shared_ptr<Thread> thread =
  37. system.Kernel().RetrieveThreadFromWakeupCallbackHandleTable(proper_handle);
  38. if (thread == nullptr) {
  39. LOG_CRITICAL(Kernel, "Callback fired for invalid thread {:08X}", proper_handle);
  40. return;
  41. }
  42. bool resume = true;
  43. if (thread->GetStatus() == ThreadStatus::WaitSynch ||
  44. thread->GetStatus() == ThreadStatus::WaitHLEEvent) {
  45. // Remove the thread from each of its waiting objects' waitlists
  46. for (const auto& object : thread->GetWaitObjects()) {
  47. object->RemoveWaitingThread(thread);
  48. }
  49. thread->ClearWaitObjects();
  50. // Invoke the wakeup callback before clearing the wait objects
  51. if (thread->HasWakeupCallback()) {
  52. resume = thread->InvokeWakeupCallback(ThreadWakeupReason::Timeout, thread, nullptr, 0);
  53. }
  54. } else if (thread->GetStatus() == ThreadStatus::WaitMutex ||
  55. thread->GetStatus() == ThreadStatus::WaitCondVar) {
  56. thread->SetMutexWaitAddress(0);
  57. thread->SetWaitHandle(0);
  58. if (thread->GetStatus() == ThreadStatus::WaitCondVar) {
  59. thread->GetOwnerProcess()->RemoveConditionVariableThread(thread);
  60. thread->SetCondVarWaitAddress(0);
  61. }
  62. auto* const lock_owner = thread->GetLockOwner();
  63. // Threads waking up by timeout from WaitProcessWideKey do not perform priority inheritance
  64. // and don't have a lock owner unless SignalProcessWideKey was called first and the thread
  65. // wasn't awakened due to the mutex already being acquired.
  66. if (lock_owner != nullptr) {
  67. lock_owner->RemoveMutexWaiter(thread);
  68. }
  69. }
  70. if (thread->GetArbiterWaitAddress() != 0) {
  71. ASSERT(thread->GetStatus() == ThreadStatus::WaitArb);
  72. thread->SetArbiterWaitAddress(0);
  73. }
  74. if (resume) {
  75. if (thread->GetStatus() == ThreadStatus::WaitCondVar ||
  76. thread->GetStatus() == ThreadStatus::WaitArb) {
  77. thread->SetWaitSynchronizationResult(RESULT_TIMEOUT);
  78. }
  79. thread->ResumeFromWait();
  80. }
  81. }
  82. struct KernelCore::Impl {
  83. explicit Impl(Core::System& system) : system{system}, global_scheduler{system} {}
  84. void Initialize(KernelCore& kernel) {
  85. Shutdown();
  86. InitializeSystemResourceLimit(kernel);
  87. InitializeThreads();
  88. InitializePreemption();
  89. }
  90. void Shutdown() {
  91. next_object_id = 0;
  92. next_kernel_process_id = Process::InitialKIPIDMin;
  93. next_user_process_id = Process::ProcessIDMin;
  94. next_thread_id = 1;
  95. process_list.clear();
  96. current_process = nullptr;
  97. system_resource_limit = nullptr;
  98. thread_wakeup_callback_handle_table.Clear();
  99. thread_wakeup_event_type = nullptr;
  100. preemption_event = nullptr;
  101. global_scheduler.Shutdown();
  102. named_ports.clear();
  103. }
  104. // Creates the default system resource limit
  105. void InitializeSystemResourceLimit(KernelCore& kernel) {
  106. system_resource_limit = ResourceLimit::Create(kernel);
  107. // If setting the default system values fails, then something seriously wrong has occurred.
  108. ASSERT(system_resource_limit->SetLimitValue(ResourceType::PhysicalMemory, 0x200000000)
  109. .IsSuccess());
  110. ASSERT(system_resource_limit->SetLimitValue(ResourceType::Threads, 800).IsSuccess());
  111. ASSERT(system_resource_limit->SetLimitValue(ResourceType::Events, 700).IsSuccess());
  112. ASSERT(system_resource_limit->SetLimitValue(ResourceType::TransferMemory, 200).IsSuccess());
  113. ASSERT(system_resource_limit->SetLimitValue(ResourceType::Sessions, 900).IsSuccess());
  114. }
  115. void InitializeThreads() {
  116. thread_wakeup_event_type =
  117. Core::Timing::CreateEvent("ThreadWakeupCallback", ThreadWakeupCallback);
  118. }
  119. void InitializePreemption() {
  120. preemption_event =
  121. Core::Timing::CreateEvent("PreemptionCallback", [this](u64 userdata, s64 cycles_late) {
  122. global_scheduler.PreemptThreads();
  123. s64 time_interval = Core::Timing::msToCycles(std::chrono::milliseconds(10));
  124. system.CoreTiming().ScheduleEvent(time_interval, preemption_event);
  125. });
  126. s64 time_interval = Core::Timing::msToCycles(std::chrono::milliseconds(10));
  127. system.CoreTiming().ScheduleEvent(time_interval, preemption_event);
  128. }
  129. void MakeCurrentProcess(Process* process) {
  130. current_process = process;
  131. if (process == nullptr) {
  132. return;
  133. }
  134. system.Memory().SetCurrentPageTable(*process);
  135. }
  136. std::atomic<u32> next_object_id{0};
  137. std::atomic<u64> next_kernel_process_id{Process::InitialKIPIDMin};
  138. std::atomic<u64> next_user_process_id{Process::ProcessIDMin};
  139. std::atomic<u64> next_thread_id{1};
  140. // Lists all processes that exist in the current session.
  141. std::vector<std::shared_ptr<Process>> process_list;
  142. Process* current_process = nullptr;
  143. Kernel::GlobalScheduler global_scheduler;
  144. std::shared_ptr<ResourceLimit> system_resource_limit;
  145. std::shared_ptr<Core::Timing::EventType> thread_wakeup_event_type;
  146. std::shared_ptr<Core::Timing::EventType> preemption_event;
  147. // TODO(yuriks): This can be removed if Thread objects are explicitly pooled in the future,
  148. // allowing us to simply use a pool index or similar.
  149. Kernel::HandleTable thread_wakeup_callback_handle_table;
  150. /// Map of named ports managed by the kernel, which can be retrieved using
  151. /// the ConnectToPort SVC.
  152. NamedPortTable named_ports;
  153. // System context
  154. Core::System& system;
  155. };
  156. KernelCore::KernelCore(Core::System& system) : impl{std::make_unique<Impl>(system)} {}
  157. KernelCore::~KernelCore() {
  158. Shutdown();
  159. }
  160. void KernelCore::Initialize() {
  161. impl->Initialize(*this);
  162. }
  163. void KernelCore::Shutdown() {
  164. impl->Shutdown();
  165. }
  166. std::shared_ptr<ResourceLimit> KernelCore::GetSystemResourceLimit() const {
  167. return impl->system_resource_limit;
  168. }
  169. std::shared_ptr<Thread> KernelCore::RetrieveThreadFromWakeupCallbackHandleTable(
  170. Handle handle) const {
  171. return impl->thread_wakeup_callback_handle_table.Get<Thread>(handle);
  172. }
  173. void KernelCore::AppendNewProcess(std::shared_ptr<Process> process) {
  174. impl->process_list.push_back(std::move(process));
  175. }
  176. void KernelCore::MakeCurrentProcess(Process* process) {
  177. impl->MakeCurrentProcess(process);
  178. }
  179. Process* KernelCore::CurrentProcess() {
  180. return impl->current_process;
  181. }
  182. const Process* KernelCore::CurrentProcess() const {
  183. return impl->current_process;
  184. }
  185. const std::vector<std::shared_ptr<Process>>& KernelCore::GetProcessList() const {
  186. return impl->process_list;
  187. }
  188. Kernel::GlobalScheduler& KernelCore::GlobalScheduler() {
  189. return impl->global_scheduler;
  190. }
  191. const Kernel::GlobalScheduler& KernelCore::GlobalScheduler() const {
  192. return impl->global_scheduler;
  193. }
  194. void KernelCore::AddNamedPort(std::string name, std::shared_ptr<ClientPort> port) {
  195. impl->named_ports.emplace(std::move(name), std::move(port));
  196. }
  197. KernelCore::NamedPortTable::iterator KernelCore::FindNamedPort(const std::string& name) {
  198. return impl->named_ports.find(name);
  199. }
  200. KernelCore::NamedPortTable::const_iterator KernelCore::FindNamedPort(
  201. const std::string& name) const {
  202. return impl->named_ports.find(name);
  203. }
  204. bool KernelCore::IsValidNamedPort(NamedPortTable::const_iterator port) const {
  205. return port != impl->named_ports.cend();
  206. }
  207. u32 KernelCore::CreateNewObjectID() {
  208. return impl->next_object_id++;
  209. }
  210. u64 KernelCore::CreateNewThreadID() {
  211. return impl->next_thread_id++;
  212. }
  213. u64 KernelCore::CreateNewKernelProcessID() {
  214. return impl->next_kernel_process_id++;
  215. }
  216. u64 KernelCore::CreateNewUserProcessID() {
  217. return impl->next_user_process_id++;
  218. }
  219. const std::shared_ptr<Core::Timing::EventType>& KernelCore::ThreadWakeupCallbackEventType() const {
  220. return impl->thread_wakeup_event_type;
  221. }
  222. Kernel::HandleTable& KernelCore::ThreadWakeupCallbackHandleTable() {
  223. return impl->thread_wakeup_callback_handle_table;
  224. }
  225. const Kernel::HandleTable& KernelCore::ThreadWakeupCallbackHandleTable() const {
  226. return impl->thread_wakeup_callback_handle_table;
  227. }
  228. } // namespace Kernel