k_process.cpp 20 KB

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