kernel.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. SharedPtr<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.get());
  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->SetCondVarWaitAddress(0);
  58. thread->SetWaitHandle(0);
  59. if (thread->GetStatus() == ThreadStatus::WaitCondVar) {
  60. thread->GetOwnerProcess()->RemoveConditionVariableThread(thread);
  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. system.CoreTiming().RegisterEvent("ThreadWakeupCallback", ThreadWakeupCallback);
  118. }
  119. void InitializePreemption() {
  120. preemption_event = system.CoreTiming().RegisterEvent(
  121. "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. std::atomic<u32> next_object_id{0};
  130. std::atomic<u64> next_kernel_process_id{Process::InitialKIPIDMin};
  131. std::atomic<u64> next_user_process_id{Process::ProcessIDMin};
  132. std::atomic<u64> next_thread_id{1};
  133. // Lists all processes that exist in the current session.
  134. std::vector<SharedPtr<Process>> process_list;
  135. Process* current_process = nullptr;
  136. Kernel::GlobalScheduler global_scheduler;
  137. SharedPtr<ResourceLimit> system_resource_limit;
  138. Core::Timing::EventType* thread_wakeup_event_type = nullptr;
  139. Core::Timing::EventType* preemption_event = nullptr;
  140. // TODO(yuriks): This can be removed if Thread objects are explicitly pooled in the future,
  141. // allowing us to simply use a pool index or similar.
  142. Kernel::HandleTable thread_wakeup_callback_handle_table;
  143. /// Map of named ports managed by the kernel, which can be retrieved using
  144. /// the ConnectToPort SVC.
  145. NamedPortTable named_ports;
  146. // System context
  147. Core::System& system;
  148. };
  149. KernelCore::KernelCore(Core::System& system) : impl{std::make_unique<Impl>(system)} {}
  150. KernelCore::~KernelCore() {
  151. Shutdown();
  152. }
  153. void KernelCore::Initialize() {
  154. impl->Initialize(*this);
  155. }
  156. void KernelCore::Shutdown() {
  157. impl->Shutdown();
  158. }
  159. SharedPtr<ResourceLimit> KernelCore::GetSystemResourceLimit() const {
  160. return impl->system_resource_limit;
  161. }
  162. SharedPtr<Thread> KernelCore::RetrieveThreadFromWakeupCallbackHandleTable(Handle handle) const {
  163. return impl->thread_wakeup_callback_handle_table.Get<Thread>(handle);
  164. }
  165. void KernelCore::AppendNewProcess(SharedPtr<Process> process) {
  166. impl->process_list.push_back(std::move(process));
  167. }
  168. void KernelCore::MakeCurrentProcess(Process* process) {
  169. impl->current_process = process;
  170. if (process == nullptr) {
  171. return;
  172. }
  173. Memory::SetCurrentPageTable(*process);
  174. }
  175. Process* KernelCore::CurrentProcess() {
  176. return impl->current_process;
  177. }
  178. const Process* KernelCore::CurrentProcess() const {
  179. return impl->current_process;
  180. }
  181. const std::vector<SharedPtr<Process>>& KernelCore::GetProcessList() const {
  182. return impl->process_list;
  183. }
  184. Kernel::GlobalScheduler& KernelCore::GlobalScheduler() {
  185. return impl->global_scheduler;
  186. }
  187. const Kernel::GlobalScheduler& KernelCore::GlobalScheduler() const {
  188. return impl->global_scheduler;
  189. }
  190. void KernelCore::AddNamedPort(std::string name, SharedPtr<ClientPort> port) {
  191. impl->named_ports.emplace(std::move(name), std::move(port));
  192. }
  193. KernelCore::NamedPortTable::iterator KernelCore::FindNamedPort(const std::string& name) {
  194. return impl->named_ports.find(name);
  195. }
  196. KernelCore::NamedPortTable::const_iterator KernelCore::FindNamedPort(
  197. const std::string& name) const {
  198. return impl->named_ports.find(name);
  199. }
  200. bool KernelCore::IsValidNamedPort(NamedPortTable::const_iterator port) const {
  201. return port != impl->named_ports.cend();
  202. }
  203. u32 KernelCore::CreateNewObjectID() {
  204. return impl->next_object_id++;
  205. }
  206. u64 KernelCore::CreateNewThreadID() {
  207. return impl->next_thread_id++;
  208. }
  209. u64 KernelCore::CreateNewKernelProcessID() {
  210. return impl->next_kernel_process_id++;
  211. }
  212. u64 KernelCore::CreateNewUserProcessID() {
  213. return impl->next_user_process_id++;
  214. }
  215. Core::Timing::EventType* KernelCore::ThreadWakeupCallbackEventType() const {
  216. return impl->thread_wakeup_event_type;
  217. }
  218. Kernel::HandleTable& KernelCore::ThreadWakeupCallbackHandleTable() {
  219. return impl->thread_wakeup_callback_handle_table;
  220. }
  221. const Kernel::HandleTable& KernelCore::ThreadWakeupCallbackHandleTable() const {
  222. return impl->thread_wakeup_callback_handle_table;
  223. }
  224. } // namespace Kernel