process.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 <ctime>
  7. #include <memory>
  8. #include <random>
  9. #include "common/alignment.h"
  10. #include "common/assert.h"
  11. #include "common/logging/log.h"
  12. #include "core/core.h"
  13. #include "core/device_memory.h"
  14. #include "core/file_sys/program_metadata.h"
  15. #include "core/hle/kernel/code_set.h"
  16. #include "core/hle/kernel/k_resource_limit.h"
  17. #include "core/hle/kernel/k_scheduler.h"
  18. #include "core/hle/kernel/k_scoped_resource_reservation.h"
  19. #include "core/hle/kernel/k_thread.h"
  20. #include "core/hle/kernel/kernel.h"
  21. #include "core/hle/kernel/memory/memory_block_manager.h"
  22. #include "core/hle/kernel/memory/page_table.h"
  23. #include "core/hle/kernel/memory/slab_heap.h"
  24. #include "core/hle/kernel/process.h"
  25. #include "core/hle/kernel/svc_results.h"
  26. #include "core/hle/lock.h"
  27. #include "core/memory.h"
  28. #include "core/settings.h"
  29. namespace Kernel {
  30. namespace {
  31. /**
  32. * Sets up the primary application thread
  33. *
  34. * @param system The system instance to create the main thread under.
  35. * @param owner_process The parent process for the main thread
  36. * @param priority The priority to give the main thread
  37. */
  38. void SetupMainThread(Core::System& system, Process& owner_process, u32 priority, VAddr stack_top) {
  39. const VAddr entry_point = owner_process.PageTable().GetCodeRegionStart();
  40. ASSERT(owner_process.GetResourceLimit()->Reserve(LimitableResource::Threads, 1));
  41. auto thread_res = KThread::Create(system, ThreadType::User, "main", entry_point, priority, 0,
  42. owner_process.GetIdealCoreId(), stack_top, &owner_process);
  43. std::shared_ptr<KThread> thread = std::move(thread_res).Unwrap();
  44. // Register 1 must be a handle to the main thread
  45. const Handle thread_handle = owner_process.GetHandleTable().Create(thread).Unwrap();
  46. thread->GetContext32().cpu_registers[0] = 0;
  47. thread->GetContext64().cpu_registers[0] = 0;
  48. thread->GetContext32().cpu_registers[1] = thread_handle;
  49. thread->GetContext64().cpu_registers[1] = thread_handle;
  50. auto& kernel = system.Kernel();
  51. // Threads by default are dormant, wake up the main thread so it runs when the scheduler fires
  52. {
  53. KScopedSchedulerLock lock{kernel};
  54. thread->SetState(ThreadState::Runnable);
  55. }
  56. }
  57. } // Anonymous namespace
  58. // Represents a page used for thread-local storage.
  59. //
  60. // Each TLS page contains slots that may be used by processes and threads.
  61. // Every process and thread is created with a slot in some arbitrary page
  62. // (whichever page happens to have an available slot).
  63. class TLSPage {
  64. public:
  65. static constexpr std::size_t num_slot_entries =
  66. Core::Memory::PAGE_SIZE / Core::Memory::TLS_ENTRY_SIZE;
  67. explicit TLSPage(VAddr address) : base_address{address} {}
  68. bool HasAvailableSlots() const {
  69. return !is_slot_used.all();
  70. }
  71. VAddr GetBaseAddress() const {
  72. return base_address;
  73. }
  74. std::optional<VAddr> ReserveSlot() {
  75. for (std::size_t i = 0; i < is_slot_used.size(); i++) {
  76. if (is_slot_used[i]) {
  77. continue;
  78. }
  79. is_slot_used[i] = true;
  80. return base_address + (i * Core::Memory::TLS_ENTRY_SIZE);
  81. }
  82. return std::nullopt;
  83. }
  84. void ReleaseSlot(VAddr address) {
  85. // Ensure that all given addresses are consistent with how TLS pages
  86. // are intended to be used when releasing slots.
  87. ASSERT(IsWithinPage(address));
  88. ASSERT((address % Core::Memory::TLS_ENTRY_SIZE) == 0);
  89. const std::size_t index = (address - base_address) / Core::Memory::TLS_ENTRY_SIZE;
  90. is_slot_used[index] = false;
  91. }
  92. private:
  93. bool IsWithinPage(VAddr address) const {
  94. return base_address <= address && address < base_address + Core::Memory::PAGE_SIZE;
  95. }
  96. VAddr base_address;
  97. std::bitset<num_slot_entries> is_slot_used;
  98. };
  99. std::shared_ptr<Process> Process::Create(Core::System& system, std::string name, ProcessType type) {
  100. auto& kernel = system.Kernel();
  101. std::shared_ptr<Process> process = std::make_shared<Process>(system);
  102. process->name = std::move(name);
  103. // TODO: This is inaccurate
  104. // The process should hold a reference to the kernel-wide resource limit.
  105. process->resource_limit = std::make_shared<KResourceLimit>(kernel, system);
  106. process->status = ProcessStatus::Created;
  107. process->program_id = 0;
  108. process->process_id = type == ProcessType::KernelInternal ? kernel.CreateNewKernelProcessID()
  109. : kernel.CreateNewUserProcessID();
  110. process->capabilities.InitializeForMetadatalessProcess();
  111. std::mt19937 rng(Settings::values.rng_seed.GetValue().value_or(std::time(nullptr)));
  112. std::uniform_int_distribution<u64> distribution;
  113. std::generate(process->random_entropy.begin(), process->random_entropy.end(),
  114. [&] { return distribution(rng); });
  115. kernel.AppendNewProcess(process);
  116. return process;
  117. }
  118. std::shared_ptr<KResourceLimit> Process::GetResourceLimit() const {
  119. return resource_limit;
  120. }
  121. void Process::IncrementThreadCount() {
  122. ASSERT(num_threads >= 0);
  123. num_created_threads++;
  124. if (const auto count = ++num_threads; count > peak_num_threads) {
  125. peak_num_threads = count;
  126. }
  127. }
  128. void Process::DecrementThreadCount() {
  129. ASSERT(num_threads > 0);
  130. if (const auto count = --num_threads; count == 0) {
  131. UNIMPLEMENTED_MSG("Process termination is not implemented!");
  132. }
  133. }
  134. u64 Process::GetTotalPhysicalMemoryAvailable() const {
  135. // TODO: This is expected to always return the application memory pool size after accurately
  136. // reserving kernel resources. The current workaround uses a process-local resource limit of
  137. // application memory pool size, which is inaccurate.
  138. const u64 capacity{resource_limit->GetFreeValue(LimitableResource::PhysicalMemory) +
  139. page_table->GetTotalHeapSize() + GetSystemResourceSize() + image_size +
  140. main_thread_stack_size};
  141. if (capacity < memory_usage_capacity) {
  142. return capacity;
  143. }
  144. return memory_usage_capacity;
  145. }
  146. u64 Process::GetTotalPhysicalMemoryAvailableWithoutSystemResource() const {
  147. return GetTotalPhysicalMemoryAvailable() - GetSystemResourceSize();
  148. }
  149. u64 Process::GetTotalPhysicalMemoryUsed() const {
  150. return image_size + main_thread_stack_size + page_table->GetTotalHeapSize() +
  151. GetSystemResourceSize();
  152. }
  153. u64 Process::GetTotalPhysicalMemoryUsedWithoutSystemResource() const {
  154. return GetTotalPhysicalMemoryUsed() - GetSystemResourceUsage();
  155. }
  156. bool Process::ReleaseUserException(KThread* thread) {
  157. KScopedSchedulerLock sl{kernel};
  158. if (exception_thread == thread) {
  159. exception_thread = nullptr;
  160. // Remove waiter thread.
  161. s32 num_waiters{};
  162. KThread* next = thread->RemoveWaiterByKey(
  163. std::addressof(num_waiters),
  164. reinterpret_cast<uintptr_t>(std::addressof(exception_thread)));
  165. if (next != nullptr) {
  166. if (next->GetState() == ThreadState::Waiting) {
  167. next->SetState(ThreadState::Runnable);
  168. } else {
  169. KScheduler::SetSchedulerUpdateNeeded(kernel);
  170. }
  171. }
  172. return true;
  173. } else {
  174. return false;
  175. }
  176. }
  177. void Process::PinCurrentThread() {
  178. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  179. // Get the current thread.
  180. const s32 core_id = GetCurrentCoreId(kernel);
  181. KThread* cur_thread = GetCurrentThreadPointer(kernel);
  182. // Pin it.
  183. PinThread(core_id, cur_thread);
  184. cur_thread->Pin();
  185. // An update is needed.
  186. KScheduler::SetSchedulerUpdateNeeded(kernel);
  187. }
  188. void Process::UnpinCurrentThread() {
  189. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  190. // Get the current thread.
  191. const s32 core_id = GetCurrentCoreId(kernel);
  192. KThread* cur_thread = GetCurrentThreadPointer(kernel);
  193. // Unpin it.
  194. cur_thread->Unpin();
  195. UnpinThread(core_id, cur_thread);
  196. // An update is needed.
  197. KScheduler::SetSchedulerUpdateNeeded(kernel);
  198. }
  199. void Process::RegisterThread(const KThread* thread) {
  200. thread_list.push_back(thread);
  201. }
  202. void Process::UnregisterThread(const KThread* thread) {
  203. thread_list.remove(thread);
  204. }
  205. ResultCode Process::Reset() {
  206. // Lock the process and the scheduler.
  207. KScopedLightLock lk(state_lock);
  208. KScopedSchedulerLock sl{kernel};
  209. // Validate that we're in a state that we can reset.
  210. R_UNLESS(status != ProcessStatus::Exited, ResultInvalidState);
  211. R_UNLESS(is_signaled, ResultInvalidState);
  212. // Clear signaled.
  213. is_signaled = false;
  214. return RESULT_SUCCESS;
  215. }
  216. ResultCode Process::LoadFromMetadata(const FileSys::ProgramMetadata& metadata,
  217. std::size_t code_size) {
  218. program_id = metadata.GetTitleID();
  219. ideal_core = metadata.GetMainThreadCore();
  220. is_64bit_process = metadata.Is64BitProgram();
  221. system_resource_size = metadata.GetSystemResourceSize();
  222. image_size = code_size;
  223. // Set initial resource limits
  224. resource_limit->SetLimitValue(
  225. LimitableResource::PhysicalMemory,
  226. kernel.MemoryManager().GetSize(Memory::MemoryManager::Pool::Application));
  227. KScopedResourceReservation memory_reservation(resource_limit, LimitableResource::PhysicalMemory,
  228. code_size + system_resource_size);
  229. if (!memory_reservation.Succeeded()) {
  230. LOG_ERROR(Kernel, "Could not reserve process memory requirements of size {:X} bytes",
  231. code_size + system_resource_size);
  232. return ResultResourceLimitedExceeded;
  233. }
  234. // Initialize proces address space
  235. if (const ResultCode result{
  236. page_table->InitializeForProcess(metadata.GetAddressSpaceType(), false, 0x8000000,
  237. code_size, Memory::MemoryManager::Pool::Application)};
  238. result.IsError()) {
  239. return result;
  240. }
  241. // Map process code region
  242. if (const ResultCode result{page_table->MapProcessCode(
  243. page_table->GetCodeRegionStart(), code_size / Memory::PageSize,
  244. Memory::MemoryState::Code, Memory::MemoryPermission::None)};
  245. result.IsError()) {
  246. return result;
  247. }
  248. // Initialize process capabilities
  249. const auto& caps{metadata.GetKernelCapabilities()};
  250. if (const ResultCode result{
  251. capabilities.InitializeForUserProcess(caps.data(), caps.size(), *page_table)};
  252. result.IsError()) {
  253. return result;
  254. }
  255. // Set memory usage capacity
  256. switch (metadata.GetAddressSpaceType()) {
  257. case FileSys::ProgramAddressSpaceType::Is32Bit:
  258. case FileSys::ProgramAddressSpaceType::Is36Bit:
  259. case FileSys::ProgramAddressSpaceType::Is39Bit:
  260. memory_usage_capacity = page_table->GetHeapRegionEnd() - page_table->GetHeapRegionStart();
  261. break;
  262. case FileSys::ProgramAddressSpaceType::Is32BitNoMap:
  263. memory_usage_capacity = page_table->GetHeapRegionEnd() - page_table->GetHeapRegionStart() +
  264. page_table->GetAliasRegionEnd() - page_table->GetAliasRegionStart();
  265. break;
  266. default:
  267. UNREACHABLE();
  268. }
  269. resource_limit->SetLimitValue(LimitableResource::Threads, 608);
  270. resource_limit->SetLimitValue(LimitableResource::Events, 700);
  271. resource_limit->SetLimitValue(LimitableResource::TransferMemory, 128);
  272. resource_limit->SetLimitValue(LimitableResource::Sessions, 894);
  273. // Create TLS region
  274. tls_region_address = CreateTLSRegion();
  275. memory_reservation.Commit();
  276. return handle_table.SetSize(capabilities.GetHandleTableSize());
  277. }
  278. void Process::Run(s32 main_thread_priority, u64 stack_size) {
  279. AllocateMainThreadStack(stack_size);
  280. resource_limit->Reserve(LimitableResource::Threads, 1);
  281. resource_limit->Reserve(LimitableResource::PhysicalMemory, main_thread_stack_size);
  282. const std::size_t heap_capacity{memory_usage_capacity - main_thread_stack_size - image_size};
  283. ASSERT(!page_table->SetHeapCapacity(heap_capacity).IsError());
  284. ChangeStatus(ProcessStatus::Running);
  285. SetupMainThread(system, *this, main_thread_priority, main_thread_stack_top);
  286. }
  287. void Process::PrepareForTermination() {
  288. ChangeStatus(ProcessStatus::Exiting);
  289. const auto stop_threads = [this](const std::vector<std::shared_ptr<KThread>>& thread_list) {
  290. for (auto& thread : thread_list) {
  291. if (thread->GetOwnerProcess() != this)
  292. continue;
  293. if (thread.get() == kernel.CurrentScheduler()->GetCurrentThread())
  294. continue;
  295. // TODO(Subv): When are the other running/ready threads terminated?
  296. ASSERT_MSG(thread->GetState() == ThreadState::Waiting,
  297. "Exiting processes with non-waiting threads is currently unimplemented");
  298. thread->Exit();
  299. }
  300. };
  301. stop_threads(system.GlobalSchedulerContext().GetThreadList());
  302. FreeTLSRegion(tls_region_address);
  303. tls_region_address = 0;
  304. if (resource_limit) {
  305. resource_limit->Release(LimitableResource::PhysicalMemory,
  306. main_thread_stack_size + image_size);
  307. }
  308. ChangeStatus(ProcessStatus::Exited);
  309. }
  310. /**
  311. * Attempts to find a TLS page that contains a free slot for
  312. * use by a thread.
  313. *
  314. * @returns If a page with an available slot is found, then an iterator
  315. * pointing to the page is returned. Otherwise the end iterator
  316. * is returned instead.
  317. */
  318. static auto FindTLSPageWithAvailableSlots(std::vector<TLSPage>& tls_pages) {
  319. return std::find_if(tls_pages.begin(), tls_pages.end(),
  320. [](const auto& page) { return page.HasAvailableSlots(); });
  321. }
  322. VAddr Process::CreateTLSRegion() {
  323. KScopedSchedulerLock lock(system.Kernel());
  324. if (auto tls_page_iter{FindTLSPageWithAvailableSlots(tls_pages)};
  325. tls_page_iter != tls_pages.cend()) {
  326. return *tls_page_iter->ReserveSlot();
  327. }
  328. Memory::Page* const tls_page_ptr{kernel.GetUserSlabHeapPages().Allocate()};
  329. ASSERT(tls_page_ptr);
  330. const VAddr start{page_table->GetKernelMapRegionStart()};
  331. const VAddr size{page_table->GetKernelMapRegionEnd() - start};
  332. const PAddr tls_map_addr{system.DeviceMemory().GetPhysicalAddr(tls_page_ptr)};
  333. const VAddr tls_page_addr{
  334. page_table
  335. ->AllocateAndMapMemory(1, Memory::PageSize, true, start, size / Memory::PageSize,
  336. Memory::MemoryState::ThreadLocal,
  337. Memory::MemoryPermission::ReadAndWrite, tls_map_addr)
  338. .ValueOr(0)};
  339. ASSERT(tls_page_addr);
  340. std::memset(tls_page_ptr, 0, Memory::PageSize);
  341. tls_pages.emplace_back(tls_page_addr);
  342. const auto reserve_result{tls_pages.back().ReserveSlot()};
  343. ASSERT(reserve_result.has_value());
  344. return *reserve_result;
  345. }
  346. void Process::FreeTLSRegion(VAddr tls_address) {
  347. KScopedSchedulerLock lock(system.Kernel());
  348. const VAddr aligned_address = Common::AlignDown(tls_address, Core::Memory::PAGE_SIZE);
  349. auto iter =
  350. std::find_if(tls_pages.begin(), tls_pages.end(), [aligned_address](const auto& page) {
  351. return page.GetBaseAddress() == aligned_address;
  352. });
  353. // Something has gone very wrong if we're freeing a region
  354. // with no actual page available.
  355. ASSERT(iter != tls_pages.cend());
  356. iter->ReleaseSlot(tls_address);
  357. }
  358. void Process::LoadModule(CodeSet code_set, VAddr base_addr) {
  359. std::lock_guard lock{HLE::g_hle_lock};
  360. const auto ReprotectSegment = [&](const CodeSet::Segment& segment,
  361. Memory::MemoryPermission permission) {
  362. page_table->SetCodeMemoryPermission(segment.addr + base_addr, segment.size, permission);
  363. };
  364. system.Memory().WriteBlock(*this, base_addr, code_set.memory.data(), code_set.memory.size());
  365. ReprotectSegment(code_set.CodeSegment(), Memory::MemoryPermission::ReadAndExecute);
  366. ReprotectSegment(code_set.RODataSegment(), Memory::MemoryPermission::Read);
  367. ReprotectSegment(code_set.DataSegment(), Memory::MemoryPermission::ReadAndWrite);
  368. }
  369. bool Process::IsSignaled() const {
  370. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  371. return is_signaled;
  372. }
  373. Process::Process(Core::System& system)
  374. : KSynchronizationObject{system.Kernel()},
  375. page_table{std::make_unique<Memory::PageTable>(system)}, handle_table{system.Kernel()},
  376. address_arbiter{system}, condition_var{system}, state_lock{system.Kernel()}, system{system} {}
  377. Process::~Process() = default;
  378. void Process::ChangeStatus(ProcessStatus new_status) {
  379. if (status == new_status) {
  380. return;
  381. }
  382. status = new_status;
  383. is_signaled = true;
  384. NotifyAvailable();
  385. }
  386. ResultCode Process::AllocateMainThreadStack(std::size_t stack_size) {
  387. ASSERT(stack_size);
  388. // The kernel always ensures that the given stack size is page aligned.
  389. main_thread_stack_size = Common::AlignUp(stack_size, Memory::PageSize);
  390. const VAddr start{page_table->GetStackRegionStart()};
  391. const std::size_t size{page_table->GetStackRegionEnd() - start};
  392. CASCADE_RESULT(main_thread_stack_top,
  393. page_table->AllocateAndMapMemory(
  394. main_thread_stack_size / Memory::PageSize, Memory::PageSize, false, start,
  395. size / Memory::PageSize, Memory::MemoryState::Stack,
  396. Memory::MemoryPermission::ReadAndWrite));
  397. main_thread_stack_top += main_thread_stack_size;
  398. return RESULT_SUCCESS;
  399. }
  400. } // namespace Kernel