process.cpp 16 KB

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