process.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. // Copyright 2015 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <bitset>
  6. #include <memory>
  7. #include <random>
  8. #include "common/alignment.h"
  9. #include "common/assert.h"
  10. #include "common/logging/log.h"
  11. #include "core/core.h"
  12. #include "core/file_sys/program_metadata.h"
  13. #include "core/hle/kernel/code_set.h"
  14. #include "core/hle/kernel/errors.h"
  15. #include "core/hle/kernel/kernel.h"
  16. #include "core/hle/kernel/process.h"
  17. #include "core/hle/kernel/resource_limit.h"
  18. #include "core/hle/kernel/scheduler.h"
  19. #include "core/hle/kernel/thread.h"
  20. #include "core/hle/kernel/vm_manager.h"
  21. #include "core/memory.h"
  22. #include "core/settings.h"
  23. namespace Kernel {
  24. namespace {
  25. /**
  26. * Sets up the primary application thread
  27. *
  28. * @param owner_process The parent process for the main thread
  29. * @param kernel The kernel instance to create the main thread under.
  30. * @param priority The priority to give the main thread
  31. */
  32. void SetupMainThread(Process& owner_process, KernelCore& kernel, u32 priority) {
  33. const auto& vm_manager = owner_process.VMManager();
  34. const VAddr entry_point = vm_manager.GetCodeRegionBaseAddress();
  35. const VAddr stack_top = vm_manager.GetTLSIORegionEndAddress();
  36. auto thread_res = Thread::Create(kernel, "main", entry_point, priority, 0,
  37. owner_process.GetIdealCore(), stack_top, owner_process);
  38. SharedPtr<Thread> thread = std::move(thread_res).Unwrap();
  39. // Register 1 must be a handle to the main thread
  40. const Handle thread_handle = owner_process.GetHandleTable().Create(thread).Unwrap();
  41. thread->GetContext().cpu_registers[1] = thread_handle;
  42. // Threads by default are dormant, wake up the main thread so it runs when the scheduler fires
  43. thread->ResumeFromWait();
  44. }
  45. } // Anonymous namespace
  46. // Represents a page used for thread-local storage.
  47. //
  48. // Each TLS page contains slots that may be used by processes and threads.
  49. // Every process and thread is created with a slot in some arbitrary page
  50. // (whichever page happens to have an available slot).
  51. class TLSPage {
  52. public:
  53. static constexpr std::size_t num_slot_entries = Memory::PAGE_SIZE / Memory::TLS_ENTRY_SIZE;
  54. explicit TLSPage(VAddr address) : base_address{address} {}
  55. bool HasAvailableSlots() const {
  56. return !is_slot_used.all();
  57. }
  58. VAddr GetBaseAddress() const {
  59. return base_address;
  60. }
  61. std::optional<VAddr> ReserveSlot() {
  62. for (std::size_t i = 0; i < is_slot_used.size(); i++) {
  63. if (is_slot_used[i]) {
  64. continue;
  65. }
  66. is_slot_used[i] = true;
  67. return base_address + (i * Memory::TLS_ENTRY_SIZE);
  68. }
  69. return std::nullopt;
  70. }
  71. void ReleaseSlot(VAddr address) {
  72. // Ensure that all given addresses are consistent with how TLS pages
  73. // are intended to be used when releasing slots.
  74. ASSERT(IsWithinPage(address));
  75. ASSERT((address % Memory::TLS_ENTRY_SIZE) == 0);
  76. const std::size_t index = (address - base_address) / Memory::TLS_ENTRY_SIZE;
  77. is_slot_used[index] = false;
  78. }
  79. private:
  80. bool IsWithinPage(VAddr address) const {
  81. return base_address <= address && address < base_address + Memory::PAGE_SIZE;
  82. }
  83. VAddr base_address;
  84. std::bitset<num_slot_entries> is_slot_used;
  85. };
  86. SharedPtr<Process> Process::Create(Core::System& system, std::string name, ProcessType type) {
  87. auto& kernel = system.Kernel();
  88. SharedPtr<Process> process(new Process(system));
  89. process->name = std::move(name);
  90. process->resource_limit = kernel.GetSystemResourceLimit();
  91. process->status = ProcessStatus::Created;
  92. process->program_id = 0;
  93. process->process_id = type == ProcessType::KernelInternal ? kernel.CreateNewKernelProcessID()
  94. : kernel.CreateNewUserProcessID();
  95. process->capabilities.InitializeForMetadatalessProcess();
  96. std::mt19937 rng(Settings::values.rng_seed.value_or(0));
  97. std::uniform_int_distribution<u64> distribution;
  98. std::generate(process->random_entropy.begin(), process->random_entropy.end(),
  99. [&] { return distribution(rng); });
  100. kernel.AppendNewProcess(process);
  101. return process;
  102. }
  103. SharedPtr<ResourceLimit> Process::GetResourceLimit() const {
  104. return resource_limit;
  105. }
  106. u64 Process::GetTotalPhysicalMemoryAvailable() const {
  107. return vm_manager.GetTotalPhysicalMemoryAvailable();
  108. }
  109. u64 Process::GetTotalPhysicalMemoryAvailableWithoutMmHeap() const {
  110. // TODO: Subtract the personal heap size from this when the
  111. // personal heap is implemented.
  112. return GetTotalPhysicalMemoryAvailable();
  113. }
  114. u64 Process::GetTotalPhysicalMemoryUsed() const {
  115. return vm_manager.GetCurrentHeapSize() + main_thread_stack_size + code_memory_size;
  116. }
  117. u64 Process::GetTotalPhysicalMemoryUsedWithoutMmHeap() const {
  118. // TODO: Subtract the personal heap size from this when the
  119. // personal heap is implemented.
  120. return GetTotalPhysicalMemoryUsed();
  121. }
  122. void Process::RegisterThread(const Thread* thread) {
  123. thread_list.push_back(thread);
  124. }
  125. void Process::UnregisterThread(const Thread* thread) {
  126. thread_list.remove(thread);
  127. }
  128. ResultCode Process::ClearSignalState() {
  129. if (status == ProcessStatus::Exited) {
  130. LOG_ERROR(Kernel, "called on a terminated process instance.");
  131. return ERR_INVALID_STATE;
  132. }
  133. if (!is_signaled) {
  134. LOG_ERROR(Kernel, "called on a process instance that isn't signaled.");
  135. return ERR_INVALID_STATE;
  136. }
  137. is_signaled = false;
  138. return RESULT_SUCCESS;
  139. }
  140. ResultCode Process::LoadFromMetadata(const FileSys::ProgramMetadata& metadata) {
  141. program_id = metadata.GetTitleID();
  142. ideal_core = metadata.GetMainThreadCore();
  143. is_64bit_process = metadata.Is64BitProgram();
  144. vm_manager.Reset(metadata.GetAddressSpaceType());
  145. const auto& caps = metadata.GetKernelCapabilities();
  146. const auto capability_init_result =
  147. capabilities.InitializeForUserProcess(caps.data(), caps.size(), vm_manager);
  148. if (capability_init_result.IsError()) {
  149. return capability_init_result;
  150. }
  151. return handle_table.SetSize(capabilities.GetHandleTableSize());
  152. }
  153. void Process::Run(s32 main_thread_priority, u64 stack_size) {
  154. AllocateMainThreadStack(stack_size);
  155. tls_region_address = CreateTLSRegion();
  156. vm_manager.LogLayout();
  157. ChangeStatus(ProcessStatus::Running);
  158. SetupMainThread(*this, kernel, main_thread_priority);
  159. }
  160. void Process::PrepareForTermination() {
  161. ChangeStatus(ProcessStatus::Exiting);
  162. const auto stop_threads = [this](const std::vector<SharedPtr<Thread>>& thread_list) {
  163. for (auto& thread : thread_list) {
  164. if (thread->GetOwnerProcess() != this)
  165. continue;
  166. if (thread == system.CurrentScheduler().GetCurrentThread())
  167. continue;
  168. // TODO(Subv): When are the other running/ready threads terminated?
  169. ASSERT_MSG(thread->GetStatus() == ThreadStatus::WaitSynch,
  170. "Exiting processes with non-waiting threads is currently unimplemented");
  171. thread->Stop();
  172. }
  173. };
  174. stop_threads(system.Scheduler(0).GetThreadList());
  175. stop_threads(system.Scheduler(1).GetThreadList());
  176. stop_threads(system.Scheduler(2).GetThreadList());
  177. stop_threads(system.Scheduler(3).GetThreadList());
  178. FreeTLSRegion(tls_region_address);
  179. tls_region_address = 0;
  180. ChangeStatus(ProcessStatus::Exited);
  181. }
  182. /**
  183. * Attempts to find a TLS page that contains a free slot for
  184. * use by a thread.
  185. *
  186. * @returns If a page with an available slot is found, then an iterator
  187. * pointing to the page is returned. Otherwise the end iterator
  188. * is returned instead.
  189. */
  190. static auto FindTLSPageWithAvailableSlots(std::vector<TLSPage>& tls_pages) {
  191. return std::find_if(tls_pages.begin(), tls_pages.end(),
  192. [](const auto& page) { return page.HasAvailableSlots(); });
  193. }
  194. VAddr Process::CreateTLSRegion() {
  195. auto tls_page_iter = FindTLSPageWithAvailableSlots(tls_pages);
  196. if (tls_page_iter == tls_pages.cend()) {
  197. const auto region_address =
  198. vm_manager.FindFreeRegion(vm_manager.GetTLSIORegionBaseAddress(),
  199. vm_manager.GetTLSIORegionEndAddress(), Memory::PAGE_SIZE);
  200. ASSERT(region_address.Succeeded());
  201. const auto map_result = vm_manager.MapMemoryBlock(
  202. *region_address, std::make_shared<std::vector<u8>>(Memory::PAGE_SIZE), 0,
  203. Memory::PAGE_SIZE, MemoryState::ThreadLocal);
  204. ASSERT(map_result.Succeeded());
  205. tls_pages.emplace_back(*region_address);
  206. const auto reserve_result = tls_pages.back().ReserveSlot();
  207. ASSERT(reserve_result.has_value());
  208. return *reserve_result;
  209. }
  210. return *tls_page_iter->ReserveSlot();
  211. }
  212. void Process::FreeTLSRegion(VAddr tls_address) {
  213. const VAddr aligned_address = Common::AlignDown(tls_address, Memory::PAGE_SIZE);
  214. auto iter =
  215. std::find_if(tls_pages.begin(), tls_pages.end(), [aligned_address](const auto& page) {
  216. return page.GetBaseAddress() == aligned_address;
  217. });
  218. // Something has gone very wrong if we're freeing a region
  219. // with no actual page available.
  220. ASSERT(iter != tls_pages.cend());
  221. iter->ReleaseSlot(tls_address);
  222. }
  223. void Process::LoadModule(CodeSet module_, VAddr base_addr) {
  224. const auto memory = std::make_shared<std::vector<u8>>(std::move(module_.memory));
  225. const auto MapSegment = [&](const CodeSet::Segment& segment, VMAPermission permissions,
  226. MemoryState memory_state) {
  227. const auto vma = vm_manager
  228. .MapMemoryBlock(segment.addr + base_addr, memory, segment.offset,
  229. segment.size, memory_state)
  230. .Unwrap();
  231. vm_manager.Reprotect(vma, permissions);
  232. };
  233. // Map CodeSet segments
  234. MapSegment(module_.CodeSegment(), VMAPermission::ReadExecute, MemoryState::Code);
  235. MapSegment(module_.RODataSegment(), VMAPermission::Read, MemoryState::CodeData);
  236. MapSegment(module_.DataSegment(), VMAPermission::ReadWrite, MemoryState::CodeData);
  237. code_memory_size += module_.memory.size();
  238. }
  239. Process::Process(Core::System& system)
  240. : WaitObject{system.Kernel()}, vm_manager{system},
  241. address_arbiter{system}, mutex{system}, system{system} {}
  242. Process::~Process() = default;
  243. void Process::Acquire(Thread* thread) {
  244. ASSERT_MSG(!ShouldWait(thread), "Object unavailable!");
  245. }
  246. bool Process::ShouldWait(const Thread* thread) const {
  247. return !is_signaled;
  248. }
  249. void Process::ChangeStatus(ProcessStatus new_status) {
  250. if (status == new_status) {
  251. return;
  252. }
  253. status = new_status;
  254. is_signaled = true;
  255. WakeupAllWaitingThreads();
  256. }
  257. void Process::AllocateMainThreadStack(u64 stack_size) {
  258. // The kernel always ensures that the given stack size is page aligned.
  259. main_thread_stack_size = Common::AlignUp(stack_size, Memory::PAGE_SIZE);
  260. // Allocate and map the main thread stack
  261. const VAddr mapping_address = vm_manager.GetTLSIORegionEndAddress() - main_thread_stack_size;
  262. vm_manager
  263. .MapMemoryBlock(mapping_address, std::make_shared<std::vector<u8>>(main_thread_stack_size),
  264. 0, main_thread_stack_size, MemoryState::Stack)
  265. .Unwrap();
  266. }
  267. } // namespace Kernel