process.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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/device_memory.h"
  13. #include "core/file_sys/program_metadata.h"
  14. #include "core/hle/kernel/code_set.h"
  15. #include "core/hle/kernel/errors.h"
  16. #include "core/hle/kernel/kernel.h"
  17. #include "core/hle/kernel/memory/memory_block_manager.h"
  18. #include "core/hle/kernel/memory/page_table.h"
  19. #include "core/hle/kernel/memory/slab_heap.h"
  20. #include "core/hle/kernel/process.h"
  21. #include "core/hle/kernel/resource_limit.h"
  22. #include "core/hle/kernel/scheduler.h"
  23. #include "core/hle/kernel/thread.h"
  24. #include "core/memory.h"
  25. #include "core/settings.h"
  26. namespace Kernel {
  27. namespace {
  28. /**
  29. * Sets up the primary application thread
  30. *
  31. * @param owner_process The parent process for the main thread
  32. * @param kernel The kernel instance to create the main thread under.
  33. * @param priority The priority to give the main thread
  34. */
  35. void SetupMainThread(Process& owner_process, KernelCore& kernel, u32 priority, VAddr stack_top) {
  36. const VAddr entry_point = owner_process.PageTable().GetCodeRegionStart();
  37. auto thread_res = Thread::Create(kernel, "main", entry_point, priority, 0,
  38. owner_process.GetIdealCore(), stack_top, owner_process);
  39. std::shared_ptr<Thread> thread = std::move(thread_res).Unwrap();
  40. // Register 1 must be a handle to the main thread
  41. const Handle thread_handle = owner_process.GetHandleTable().Create(thread).Unwrap();
  42. thread->GetContext32().cpu_registers[0] = 0;
  43. thread->GetContext64().cpu_registers[0] = 0;
  44. thread->GetContext32().cpu_registers[1] = thread_handle;
  45. thread->GetContext64().cpu_registers[1] = thread_handle;
  46. // Threads by default are dormant, wake up the main thread so it runs when the scheduler fires
  47. thread->ResumeFromWait();
  48. }
  49. } // Anonymous namespace
  50. // Represents a page used for thread-local storage.
  51. //
  52. // Each TLS page contains slots that may be used by processes and threads.
  53. // Every process and thread is created with a slot in some arbitrary page
  54. // (whichever page happens to have an available slot).
  55. class TLSPage {
  56. public:
  57. static constexpr std::size_t num_slot_entries =
  58. Core::Memory::PAGE_SIZE / Core::Memory::TLS_ENTRY_SIZE;
  59. explicit TLSPage(VAddr address) : base_address{address} {}
  60. bool HasAvailableSlots() const {
  61. return !is_slot_used.all();
  62. }
  63. VAddr GetBaseAddress() const {
  64. return base_address;
  65. }
  66. std::optional<VAddr> ReserveSlot() {
  67. for (std::size_t i = 0; i < is_slot_used.size(); i++) {
  68. if (is_slot_used[i]) {
  69. continue;
  70. }
  71. is_slot_used[i] = true;
  72. return base_address + (i * Core::Memory::TLS_ENTRY_SIZE);
  73. }
  74. return std::nullopt;
  75. }
  76. void ReleaseSlot(VAddr address) {
  77. // Ensure that all given addresses are consistent with how TLS pages
  78. // are intended to be used when releasing slots.
  79. ASSERT(IsWithinPage(address));
  80. ASSERT((address % Core::Memory::TLS_ENTRY_SIZE) == 0);
  81. const std::size_t index = (address - base_address) / Core::Memory::TLS_ENTRY_SIZE;
  82. is_slot_used[index] = false;
  83. }
  84. private:
  85. bool IsWithinPage(VAddr address) const {
  86. return base_address <= address && address < base_address + Core::Memory::PAGE_SIZE;
  87. }
  88. VAddr base_address;
  89. std::bitset<num_slot_entries> is_slot_used;
  90. };
  91. std::shared_ptr<Process> Process::Create(Core::System& system, std::string name, ProcessType type) {
  92. auto& kernel = system.Kernel();
  93. std::shared_ptr<Process> process = std::make_shared<Process>(system);
  94. process->name = std::move(name);
  95. process->resource_limit = ResourceLimit::Create(kernel);
  96. process->status = ProcessStatus::Created;
  97. process->program_id = 0;
  98. process->process_id = type == ProcessType::KernelInternal ? kernel.CreateNewKernelProcessID()
  99. : kernel.CreateNewUserProcessID();
  100. process->capabilities.InitializeForMetadatalessProcess();
  101. std::mt19937 rng(Settings::values.rng_seed.value_or(0));
  102. std::uniform_int_distribution<u64> distribution;
  103. std::generate(process->random_entropy.begin(), process->random_entropy.end(),
  104. [&] { return distribution(rng); });
  105. kernel.AppendNewProcess(process);
  106. return process;
  107. }
  108. std::shared_ptr<ResourceLimit> Process::GetResourceLimit() const {
  109. return resource_limit;
  110. }
  111. u64 Process::GetTotalPhysicalMemoryAvailable() const {
  112. const u64 capacity{resource_limit->GetCurrentResourceValue(ResourceType::PhysicalMemory) +
  113. page_table->GetTotalHeapSize() + image_size + main_thread_stack_size};
  114. if (capacity < memory_usage_capacity) {
  115. return capacity;
  116. }
  117. return memory_usage_capacity;
  118. }
  119. u64 Process::GetTotalPhysicalMemoryAvailableWithoutSystemResource() const {
  120. return GetTotalPhysicalMemoryAvailable() - GetSystemResourceSize();
  121. }
  122. u64 Process::GetTotalPhysicalMemoryUsed() const {
  123. return image_size + main_thread_stack_size + page_table->GetTotalHeapSize();
  124. }
  125. u64 Process::GetTotalPhysicalMemoryUsedWithoutSystemResource() const {
  126. return GetTotalPhysicalMemoryUsed() - GetSystemResourceUsage();
  127. }
  128. void Process::InsertConditionVariableThread(std::shared_ptr<Thread> thread) {
  129. VAddr cond_var_addr = thread->GetCondVarWaitAddress();
  130. std::list<std::shared_ptr<Thread>>& thread_list = cond_var_threads[cond_var_addr];
  131. auto it = thread_list.begin();
  132. while (it != thread_list.end()) {
  133. const std::shared_ptr<Thread> current_thread = *it;
  134. if (current_thread->GetPriority() > thread->GetPriority()) {
  135. thread_list.insert(it, thread);
  136. return;
  137. }
  138. ++it;
  139. }
  140. thread_list.push_back(thread);
  141. }
  142. void Process::RemoveConditionVariableThread(std::shared_ptr<Thread> thread) {
  143. VAddr cond_var_addr = thread->GetCondVarWaitAddress();
  144. std::list<std::shared_ptr<Thread>>& thread_list = cond_var_threads[cond_var_addr];
  145. auto it = thread_list.begin();
  146. while (it != thread_list.end()) {
  147. const std::shared_ptr<Thread> current_thread = *it;
  148. if (current_thread.get() == thread.get()) {
  149. thread_list.erase(it);
  150. return;
  151. }
  152. ++it;
  153. }
  154. UNREACHABLE();
  155. }
  156. std::vector<std::shared_ptr<Thread>> Process::GetConditionVariableThreads(
  157. const VAddr cond_var_addr) {
  158. std::vector<std::shared_ptr<Thread>> result{};
  159. std::list<std::shared_ptr<Thread>>& thread_list = cond_var_threads[cond_var_addr];
  160. auto it = thread_list.begin();
  161. while (it != thread_list.end()) {
  162. std::shared_ptr<Thread> current_thread = *it;
  163. result.push_back(current_thread);
  164. ++it;
  165. }
  166. return result;
  167. }
  168. void Process::RegisterThread(const Thread* thread) {
  169. thread_list.push_back(thread);
  170. }
  171. void Process::UnregisterThread(const Thread* thread) {
  172. thread_list.remove(thread);
  173. }
  174. ResultCode Process::ClearSignalState() {
  175. if (status == ProcessStatus::Exited) {
  176. LOG_ERROR(Kernel, "called on a terminated process instance.");
  177. return ERR_INVALID_STATE;
  178. }
  179. if (!is_signaled) {
  180. LOG_ERROR(Kernel, "called on a process instance that isn't signaled.");
  181. return ERR_INVALID_STATE;
  182. }
  183. is_signaled = false;
  184. return RESULT_SUCCESS;
  185. }
  186. ResultCode Process::LoadFromMetadata(const FileSys::ProgramMetadata& metadata,
  187. std::size_t code_size) {
  188. program_id = metadata.GetTitleID();
  189. ideal_core = metadata.GetMainThreadCore();
  190. is_64bit_process = metadata.Is64BitProgram();
  191. system_resource_size = metadata.GetSystemResourceSize();
  192. image_size = code_size;
  193. // Initialize proces address space
  194. if (const ResultCode result{
  195. page_table->InitializeForProcess(metadata.GetAddressSpaceType(), false, 0x8000000,
  196. code_size, Memory::MemoryManager::Pool::Application)};
  197. result.IsError()) {
  198. return result;
  199. }
  200. // Map process code region
  201. if (const ResultCode result{page_table->MapProcessCode(
  202. page_table->GetCodeRegionStart(), code_size / Memory::PageSize,
  203. Memory::MemoryState::Code, Memory::MemoryPermission::None)};
  204. result.IsError()) {
  205. return result;
  206. }
  207. // Initialize process capabilities
  208. const auto& caps{metadata.GetKernelCapabilities()};
  209. if (const ResultCode result{
  210. capabilities.InitializeForUserProcess(caps.data(), caps.size(), *page_table)};
  211. result.IsError()) {
  212. return result;
  213. }
  214. // Set memory usage capacity
  215. switch (metadata.GetAddressSpaceType()) {
  216. case FileSys::ProgramAddressSpaceType::Is32Bit:
  217. case FileSys::ProgramAddressSpaceType::Is36Bit:
  218. case FileSys::ProgramAddressSpaceType::Is39Bit:
  219. memory_usage_capacity = page_table->GetHeapRegionEnd() - page_table->GetHeapRegionStart();
  220. break;
  221. case FileSys::ProgramAddressSpaceType::Is32BitNoMap:
  222. memory_usage_capacity = page_table->GetHeapRegionEnd() - page_table->GetHeapRegionStart() +
  223. page_table->GetAliasRegionEnd() - page_table->GetAliasRegionStart();
  224. break;
  225. default:
  226. UNREACHABLE();
  227. }
  228. // Set initial resource limits
  229. resource_limit->SetLimitValue(
  230. ResourceType::PhysicalMemory,
  231. kernel.MemoryManager().GetSize(Memory::MemoryManager::Pool::Application));
  232. resource_limit->SetLimitValue(ResourceType::Threads, 608);
  233. resource_limit->SetLimitValue(ResourceType::Events, 700);
  234. resource_limit->SetLimitValue(ResourceType::TransferMemory, 128);
  235. resource_limit->SetLimitValue(ResourceType::Sessions, 894);
  236. ASSERT(resource_limit->Reserve(ResourceType::PhysicalMemory, code_size));
  237. // Create TLS region
  238. tls_region_address = CreateTLSRegion();
  239. return handle_table.SetSize(capabilities.GetHandleTableSize());
  240. }
  241. void Process::Run(s32 main_thread_priority, u64 stack_size) {
  242. AllocateMainThreadStack(stack_size);
  243. const std::size_t heap_capacity{memory_usage_capacity - main_thread_stack_size - image_size};
  244. ASSERT(!page_table->SetHeapCapacity(heap_capacity).IsError());
  245. ChangeStatus(ProcessStatus::Running);
  246. SetupMainThread(*this, kernel, main_thread_priority, main_thread_stack_top);
  247. resource_limit->Reserve(ResourceType::Threads, 1);
  248. resource_limit->Reserve(ResourceType::PhysicalMemory, main_thread_stack_size);
  249. }
  250. void Process::PrepareForTermination() {
  251. ChangeStatus(ProcessStatus::Exiting);
  252. const auto stop_threads = [this](const std::vector<std::shared_ptr<Thread>>& thread_list) {
  253. for (auto& thread : thread_list) {
  254. if (thread->GetOwnerProcess() != this)
  255. continue;
  256. if (thread.get() == system.CurrentScheduler().GetCurrentThread())
  257. continue;
  258. // TODO(Subv): When are the other running/ready threads terminated?
  259. ASSERT_MSG(thread->GetStatus() == ThreadStatus::WaitSynch,
  260. "Exiting processes with non-waiting threads is currently unimplemented");
  261. thread->Stop();
  262. }
  263. };
  264. stop_threads(system.GlobalScheduler().GetThreadList());
  265. FreeTLSRegion(tls_region_address);
  266. tls_region_address = 0;
  267. ChangeStatus(ProcessStatus::Exited);
  268. }
  269. /**
  270. * Attempts to find a TLS page that contains a free slot for
  271. * use by a thread.
  272. *
  273. * @returns If a page with an available slot is found, then an iterator
  274. * pointing to the page is returned. Otherwise the end iterator
  275. * is returned instead.
  276. */
  277. static auto FindTLSPageWithAvailableSlots(std::vector<TLSPage>& tls_pages) {
  278. return std::find_if(tls_pages.begin(), tls_pages.end(),
  279. [](const auto& page) { return page.HasAvailableSlots(); });
  280. }
  281. VAddr Process::CreateTLSRegion() {
  282. if (auto tls_page_iter{FindTLSPageWithAvailableSlots(tls_pages)};
  283. tls_page_iter != tls_pages.cend()) {
  284. return *tls_page_iter->ReserveSlot();
  285. }
  286. Memory::Page* const tls_page_ptr{kernel.GetUserSlabHeapPages().Allocate()};
  287. ASSERT(tls_page_ptr);
  288. const VAddr start{page_table->GetKernelMapRegionStart()};
  289. const VAddr size{page_table->GetKernelMapRegionEnd() - start};
  290. const PAddr tls_map_addr{system.DeviceMemory().GetPhysicalAddr(tls_page_ptr)};
  291. const VAddr tls_page_addr{
  292. page_table
  293. ->AllocateAndMapMemory(1, Memory::PageSize, true, start, size / Memory::PageSize,
  294. Memory::MemoryState::ThreadLocal,
  295. Memory::MemoryPermission::ReadAndWrite, tls_map_addr)
  296. .ValueOr(0)};
  297. ASSERT(tls_page_addr);
  298. std::memset(tls_page_ptr, 0, Memory::PageSize);
  299. tls_pages.emplace_back(tls_page_addr);
  300. const auto reserve_result{tls_pages.back().ReserveSlot()};
  301. ASSERT(reserve_result.has_value());
  302. return *reserve_result;
  303. }
  304. void Process::FreeTLSRegion(VAddr tls_address) {
  305. const VAddr aligned_address = Common::AlignDown(tls_address, Core::Memory::PAGE_SIZE);
  306. auto iter =
  307. std::find_if(tls_pages.begin(), tls_pages.end(), [aligned_address](const auto& page) {
  308. return page.GetBaseAddress() == aligned_address;
  309. });
  310. // Something has gone very wrong if we're freeing a region
  311. // with no actual page available.
  312. ASSERT(iter != tls_pages.cend());
  313. iter->ReleaseSlot(tls_address);
  314. }
  315. void Process::LoadModule(CodeSet code_set, VAddr base_addr) {
  316. const auto ReprotectSegment = [&](const CodeSet::Segment& segment,
  317. Memory::MemoryPermission permission) {
  318. page_table->SetCodeMemoryPermission(segment.addr + base_addr, segment.size, permission);
  319. };
  320. system.Memory().WriteBlock(*this, base_addr, code_set.memory.data(), code_set.memory.size());
  321. ReprotectSegment(code_set.CodeSegment(), Memory::MemoryPermission::ReadAndExecute);
  322. ReprotectSegment(code_set.RODataSegment(), Memory::MemoryPermission::Read);
  323. ReprotectSegment(code_set.DataSegment(), Memory::MemoryPermission::ReadAndWrite);
  324. }
  325. Process::Process(Core::System& system)
  326. : SynchronizationObject{system.Kernel()}, page_table{std::make_unique<Memory::PageTable>(
  327. system)},
  328. address_arbiter{system}, mutex{system}, system{system} {}
  329. Process::~Process() = default;
  330. void Process::Acquire(Thread* thread) {
  331. ASSERT_MSG(!ShouldWait(thread), "Object unavailable!");
  332. }
  333. bool Process::ShouldWait(const Thread* thread) const {
  334. return !is_signaled;
  335. }
  336. void Process::ChangeStatus(ProcessStatus new_status) {
  337. if (status == new_status) {
  338. return;
  339. }
  340. status = new_status;
  341. is_signaled = true;
  342. Signal();
  343. }
  344. ResultCode Process::AllocateMainThreadStack(std::size_t stack_size) {
  345. ASSERT(stack_size);
  346. // The kernel always ensures that the given stack size is page aligned.
  347. main_thread_stack_size = Common::AlignUp(stack_size, Memory::PageSize);
  348. const VAddr start{page_table->GetStackRegionStart()};
  349. const std::size_t size{page_table->GetStackRegionEnd() - start};
  350. CASCADE_RESULT(main_thread_stack_top,
  351. page_table->AllocateAndMapMemory(
  352. main_thread_stack_size / Memory::PageSize, Memory::PageSize, false, start,
  353. size / Memory::PageSize, Memory::MemoryState::Stack,
  354. Memory::MemoryPermission::ReadAndWrite));
  355. main_thread_stack_top += main_thread_stack_size;
  356. return RESULT_SUCCESS;
  357. }
  358. } // namespace Kernel