process.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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() + GetSystemResourceSize() + image_size +
  114. main_thread_stack_size};
  115. if (capacity < memory_usage_capacity) {
  116. return capacity;
  117. }
  118. return memory_usage_capacity;
  119. }
  120. u64 Process::GetTotalPhysicalMemoryAvailableWithoutSystemResource() const {
  121. return GetTotalPhysicalMemoryAvailable() - GetSystemResourceSize();
  122. }
  123. u64 Process::GetTotalPhysicalMemoryUsed() const {
  124. return image_size + main_thread_stack_size + page_table->GetTotalHeapSize() +
  125. GetSystemResourceSize();
  126. }
  127. u64 Process::GetTotalPhysicalMemoryUsedWithoutSystemResource() const {
  128. return GetTotalPhysicalMemoryUsed() - GetSystemResourceUsage();
  129. }
  130. void Process::InsertConditionVariableThread(std::shared_ptr<Thread> thread) {
  131. VAddr cond_var_addr = thread->GetCondVarWaitAddress();
  132. std::list<std::shared_ptr<Thread>>& thread_list = cond_var_threads[cond_var_addr];
  133. auto it = thread_list.begin();
  134. while (it != thread_list.end()) {
  135. const std::shared_ptr<Thread> current_thread = *it;
  136. if (current_thread->GetPriority() > thread->GetPriority()) {
  137. thread_list.insert(it, thread);
  138. return;
  139. }
  140. ++it;
  141. }
  142. thread_list.push_back(thread);
  143. }
  144. void Process::RemoveConditionVariableThread(std::shared_ptr<Thread> thread) {
  145. VAddr cond_var_addr = thread->GetCondVarWaitAddress();
  146. std::list<std::shared_ptr<Thread>>& thread_list = cond_var_threads[cond_var_addr];
  147. auto it = thread_list.begin();
  148. while (it != thread_list.end()) {
  149. const std::shared_ptr<Thread> current_thread = *it;
  150. if (current_thread.get() == thread.get()) {
  151. thread_list.erase(it);
  152. return;
  153. }
  154. ++it;
  155. }
  156. UNREACHABLE();
  157. }
  158. std::vector<std::shared_ptr<Thread>> Process::GetConditionVariableThreads(
  159. const VAddr cond_var_addr) {
  160. std::vector<std::shared_ptr<Thread>> result{};
  161. std::list<std::shared_ptr<Thread>>& thread_list = cond_var_threads[cond_var_addr];
  162. auto it = thread_list.begin();
  163. while (it != thread_list.end()) {
  164. std::shared_ptr<Thread> current_thread = *it;
  165. result.push_back(current_thread);
  166. ++it;
  167. }
  168. return result;
  169. }
  170. void Process::RegisterThread(const Thread* thread) {
  171. thread_list.push_back(thread);
  172. }
  173. void Process::UnregisterThread(const Thread* thread) {
  174. thread_list.remove(thread);
  175. }
  176. ResultCode Process::ClearSignalState() {
  177. if (status == ProcessStatus::Exited) {
  178. LOG_ERROR(Kernel, "called on a terminated process instance.");
  179. return ERR_INVALID_STATE;
  180. }
  181. if (!is_signaled) {
  182. LOG_ERROR(Kernel, "called on a process instance that isn't signaled.");
  183. return ERR_INVALID_STATE;
  184. }
  185. is_signaled = false;
  186. return RESULT_SUCCESS;
  187. }
  188. ResultCode Process::LoadFromMetadata(const FileSys::ProgramMetadata& metadata,
  189. std::size_t code_size) {
  190. program_id = metadata.GetTitleID();
  191. ideal_core = metadata.GetMainThreadCore();
  192. is_64bit_process = metadata.Is64BitProgram();
  193. system_resource_size = metadata.GetSystemResourceSize();
  194. image_size = code_size;
  195. // Initialize proces address space
  196. if (const ResultCode result{
  197. page_table->InitializeForProcess(metadata.GetAddressSpaceType(), false, 0x8000000,
  198. code_size, Memory::MemoryManager::Pool::Application)};
  199. result.IsError()) {
  200. return result;
  201. }
  202. // Map process code region
  203. if (const ResultCode result{page_table->MapProcessCode(
  204. page_table->GetCodeRegionStart(), code_size / Memory::PageSize,
  205. Memory::MemoryState::Code, Memory::MemoryPermission::None)};
  206. result.IsError()) {
  207. return result;
  208. }
  209. // Initialize process capabilities
  210. const auto& caps{metadata.GetKernelCapabilities()};
  211. if (const ResultCode result{
  212. capabilities.InitializeForUserProcess(caps.data(), caps.size(), *page_table)};
  213. result.IsError()) {
  214. return result;
  215. }
  216. // Set memory usage capacity
  217. switch (metadata.GetAddressSpaceType()) {
  218. case FileSys::ProgramAddressSpaceType::Is32Bit:
  219. case FileSys::ProgramAddressSpaceType::Is36Bit:
  220. case FileSys::ProgramAddressSpaceType::Is39Bit:
  221. memory_usage_capacity = page_table->GetHeapRegionEnd() - page_table->GetHeapRegionStart();
  222. break;
  223. case FileSys::ProgramAddressSpaceType::Is32BitNoMap:
  224. memory_usage_capacity = page_table->GetHeapRegionEnd() - page_table->GetHeapRegionStart() +
  225. page_table->GetAliasRegionEnd() - page_table->GetAliasRegionStart();
  226. break;
  227. default:
  228. UNREACHABLE();
  229. }
  230. // Set initial resource limits
  231. resource_limit->SetLimitValue(
  232. ResourceType::PhysicalMemory,
  233. kernel.MemoryManager().GetSize(Memory::MemoryManager::Pool::Application));
  234. resource_limit->SetLimitValue(ResourceType::Threads, 608);
  235. resource_limit->SetLimitValue(ResourceType::Events, 700);
  236. resource_limit->SetLimitValue(ResourceType::TransferMemory, 128);
  237. resource_limit->SetLimitValue(ResourceType::Sessions, 894);
  238. ASSERT(resource_limit->Reserve(ResourceType::PhysicalMemory, code_size));
  239. // Create TLS region
  240. tls_region_address = CreateTLSRegion();
  241. return handle_table.SetSize(capabilities.GetHandleTableSize());
  242. }
  243. void Process::Run(s32 main_thread_priority, u64 stack_size) {
  244. AllocateMainThreadStack(stack_size);
  245. const std::size_t heap_capacity{memory_usage_capacity - main_thread_stack_size - image_size};
  246. ASSERT(!page_table->SetHeapCapacity(heap_capacity).IsError());
  247. ChangeStatus(ProcessStatus::Running);
  248. SetupMainThread(*this, kernel, main_thread_priority, main_thread_stack_top);
  249. resource_limit->Reserve(ResourceType::Threads, 1);
  250. resource_limit->Reserve(ResourceType::PhysicalMemory, main_thread_stack_size);
  251. }
  252. void Process::PrepareForTermination() {
  253. ChangeStatus(ProcessStatus::Exiting);
  254. const auto stop_threads = [this](const std::vector<std::shared_ptr<Thread>>& thread_list) {
  255. for (auto& thread : thread_list) {
  256. if (thread->GetOwnerProcess() != this)
  257. continue;
  258. if (thread.get() == system.CurrentScheduler().GetCurrentThread())
  259. continue;
  260. // TODO(Subv): When are the other running/ready threads terminated?
  261. ASSERT_MSG(thread->GetStatus() == ThreadStatus::WaitSynch,
  262. "Exiting processes with non-waiting threads is currently unimplemented");
  263. thread->Stop();
  264. }
  265. };
  266. stop_threads(system.GlobalScheduler().GetThreadList());
  267. FreeTLSRegion(tls_region_address);
  268. tls_region_address = 0;
  269. ChangeStatus(ProcessStatus::Exited);
  270. }
  271. /**
  272. * Attempts to find a TLS page that contains a free slot for
  273. * use by a thread.
  274. *
  275. * @returns If a page with an available slot is found, then an iterator
  276. * pointing to the page is returned. Otherwise the end iterator
  277. * is returned instead.
  278. */
  279. static auto FindTLSPageWithAvailableSlots(std::vector<TLSPage>& tls_pages) {
  280. return std::find_if(tls_pages.begin(), tls_pages.end(),
  281. [](const auto& page) { return page.HasAvailableSlots(); });
  282. }
  283. VAddr Process::CreateTLSRegion() {
  284. if (auto tls_page_iter{FindTLSPageWithAvailableSlots(tls_pages)};
  285. tls_page_iter != tls_pages.cend()) {
  286. return *tls_page_iter->ReserveSlot();
  287. }
  288. Memory::Page* const tls_page_ptr{kernel.GetUserSlabHeapPages().Allocate()};
  289. ASSERT(tls_page_ptr);
  290. const VAddr start{page_table->GetKernelMapRegionStart()};
  291. const VAddr size{page_table->GetKernelMapRegionEnd() - start};
  292. const PAddr tls_map_addr{system.DeviceMemory().GetPhysicalAddr(tls_page_ptr)};
  293. const VAddr tls_page_addr{
  294. page_table
  295. ->AllocateAndMapMemory(1, Memory::PageSize, true, start, size / Memory::PageSize,
  296. Memory::MemoryState::ThreadLocal,
  297. Memory::MemoryPermission::ReadAndWrite, tls_map_addr)
  298. .ValueOr(0)};
  299. ASSERT(tls_page_addr);
  300. std::memset(tls_page_ptr, 0, Memory::PageSize);
  301. tls_pages.emplace_back(tls_page_addr);
  302. const auto reserve_result{tls_pages.back().ReserveSlot()};
  303. ASSERT(reserve_result.has_value());
  304. return *reserve_result;
  305. }
  306. void Process::FreeTLSRegion(VAddr tls_address) {
  307. const VAddr aligned_address = Common::AlignDown(tls_address, Core::Memory::PAGE_SIZE);
  308. auto iter =
  309. std::find_if(tls_pages.begin(), tls_pages.end(), [aligned_address](const auto& page) {
  310. return page.GetBaseAddress() == aligned_address;
  311. });
  312. // Something has gone very wrong if we're freeing a region
  313. // with no actual page available.
  314. ASSERT(iter != tls_pages.cend());
  315. iter->ReleaseSlot(tls_address);
  316. }
  317. void Process::LoadModule(CodeSet code_set, VAddr base_addr) {
  318. const auto ReprotectSegment = [&](const CodeSet::Segment& segment,
  319. Memory::MemoryPermission permission) {
  320. page_table->SetCodeMemoryPermission(segment.addr + base_addr, segment.size, permission);
  321. };
  322. system.Memory().WriteBlock(*this, base_addr, code_set.memory.data(), code_set.memory.size());
  323. ReprotectSegment(code_set.CodeSegment(), Memory::MemoryPermission::ReadAndExecute);
  324. ReprotectSegment(code_set.RODataSegment(), Memory::MemoryPermission::Read);
  325. ReprotectSegment(code_set.DataSegment(), Memory::MemoryPermission::ReadAndWrite);
  326. }
  327. Process::Process(Core::System& system)
  328. : SynchronizationObject{system.Kernel()}, page_table{std::make_unique<Memory::PageTable>(
  329. system)},
  330. address_arbiter{system}, mutex{system}, system{system} {}
  331. Process::~Process() = default;
  332. void Process::Acquire(Thread* thread) {
  333. ASSERT_MSG(!ShouldWait(thread), "Object unavailable!");
  334. }
  335. bool Process::ShouldWait(const Thread* thread) const {
  336. return !is_signaled;
  337. }
  338. void Process::ChangeStatus(ProcessStatus new_status) {
  339. if (status == new_status) {
  340. return;
  341. }
  342. status = new_status;
  343. is_signaled = true;
  344. Signal();
  345. }
  346. ResultCode Process::AllocateMainThreadStack(std::size_t stack_size) {
  347. ASSERT(stack_size);
  348. // The kernel always ensures that the given stack size is page aligned.
  349. main_thread_stack_size = Common::AlignUp(stack_size, Memory::PageSize);
  350. const VAddr start{page_table->GetStackRegionStart()};
  351. const std::size_t size{page_table->GetStackRegionEnd() - start};
  352. CASCADE_RESULT(main_thread_stack_top,
  353. page_table->AllocateAndMapMemory(
  354. main_thread_stack_size / Memory::PageSize, Memory::PageSize, false, start,
  355. size / Memory::PageSize, Memory::MemoryState::Stack,
  356. Memory::MemoryPermission::ReadAndWrite));
  357. main_thread_stack_top += main_thread_stack_size;
  358. return RESULT_SUCCESS;
  359. }
  360. } // namespace Kernel