kernel.cpp 8.8 KB

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