k_process.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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_slab_heap.h"
  26. #include "core/hle/kernel/k_thread.h"
  27. #include "core/hle/kernel/kernel.h"
  28. #include "core/hle/kernel/svc_results.h"
  29. #include "core/hle/lock.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. // Pin it.
  189. PinThread(core_id, cur_thread);
  190. cur_thread->Pin();
  191. // An update is needed.
  192. KScheduler::SetSchedulerUpdateNeeded(kernel);
  193. }
  194. void KProcess::UnpinCurrentThread() {
  195. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  196. // Get the current thread.
  197. const s32 core_id = GetCurrentCoreId(kernel);
  198. KThread* cur_thread = GetCurrentThreadPointer(kernel);
  199. // Unpin it.
  200. cur_thread->Unpin();
  201. UnpinThread(core_id, cur_thread);
  202. // An update is needed.
  203. KScheduler::SetSchedulerUpdateNeeded(kernel);
  204. }
  205. ResultCode KProcess::AddSharedMemory(KSharedMemory* shmem, [[maybe_unused]] VAddr address,
  206. [[maybe_unused]] size_t size) {
  207. // Lock ourselves, to prevent concurrent access.
  208. KScopedLightLock lk(state_lock);
  209. // TODO(bunnei): Manage KSharedMemoryInfo list here.
  210. // Open a reference to the shared memory.
  211. shmem->Open();
  212. return ResultSuccess;
  213. }
  214. void KProcess::RemoveSharedMemory(KSharedMemory* shmem, [[maybe_unused]] VAddr address,
  215. [[maybe_unused]] size_t size) {
  216. // Lock ourselves, to prevent concurrent access.
  217. KScopedLightLock lk(state_lock);
  218. // TODO(bunnei): Manage KSharedMemoryInfo list here.
  219. // Close a reference to the shared memory.
  220. shmem->Close();
  221. }
  222. void KProcess::RegisterThread(const KThread* thread) {
  223. thread_list.push_back(thread);
  224. }
  225. void KProcess::UnregisterThread(const KThread* thread) {
  226. thread_list.remove(thread);
  227. }
  228. ResultCode KProcess::Reset() {
  229. // Lock the process and the scheduler.
  230. KScopedLightLock lk(state_lock);
  231. KScopedSchedulerLock sl{kernel};
  232. // Validate that we're in a state that we can reset.
  233. R_UNLESS(status != ProcessStatus::Exited, ResultInvalidState);
  234. R_UNLESS(is_signaled, ResultInvalidState);
  235. // Clear signaled.
  236. is_signaled = false;
  237. return ResultSuccess;
  238. }
  239. ResultCode KProcess::LoadFromMetadata(const FileSys::ProgramMetadata& metadata,
  240. std::size_t code_size) {
  241. program_id = metadata.GetTitleID();
  242. ideal_core = metadata.GetMainThreadCore();
  243. is_64bit_process = metadata.Is64BitProgram();
  244. system_resource_size = metadata.GetSystemResourceSize();
  245. image_size = code_size;
  246. KScopedResourceReservation memory_reservation(resource_limit, LimitableResource::PhysicalMemory,
  247. code_size + system_resource_size);
  248. if (!memory_reservation.Succeeded()) {
  249. LOG_ERROR(Kernel, "Could not reserve process memory requirements of size {:X} bytes",
  250. code_size + system_resource_size);
  251. return ResultLimitReached;
  252. }
  253. // Initialize proces address space
  254. if (const ResultCode result{
  255. page_table->InitializeForProcess(metadata.GetAddressSpaceType(), false, 0x8000000,
  256. code_size, KMemoryManager::Pool::Application)};
  257. result.IsError()) {
  258. return result;
  259. }
  260. // Map process code region
  261. if (const ResultCode result{page_table->MapProcessCode(page_table->GetCodeRegionStart(),
  262. code_size / PageSize, KMemoryState::Code,
  263. KMemoryPermission::None)};
  264. result.IsError()) {
  265. return result;
  266. }
  267. // Initialize process capabilities
  268. const auto& caps{metadata.GetKernelCapabilities()};
  269. if (const ResultCode result{
  270. capabilities.InitializeForUserProcess(caps.data(), caps.size(), *page_table)};
  271. result.IsError()) {
  272. return result;
  273. }
  274. // Set memory usage capacity
  275. switch (metadata.GetAddressSpaceType()) {
  276. case FileSys::ProgramAddressSpaceType::Is32Bit:
  277. case FileSys::ProgramAddressSpaceType::Is36Bit:
  278. case FileSys::ProgramAddressSpaceType::Is39Bit:
  279. memory_usage_capacity = page_table->GetHeapRegionEnd() - page_table->GetHeapRegionStart();
  280. break;
  281. case FileSys::ProgramAddressSpaceType::Is32BitNoMap:
  282. memory_usage_capacity = page_table->GetHeapRegionEnd() - page_table->GetHeapRegionStart() +
  283. page_table->GetAliasRegionEnd() - page_table->GetAliasRegionStart();
  284. break;
  285. default:
  286. UNREACHABLE();
  287. }
  288. // Create TLS region
  289. tls_region_address = CreateTLSRegion();
  290. memory_reservation.Commit();
  291. return handle_table.Initialize(capabilities.GetHandleTableSize());
  292. }
  293. void KProcess::Run(s32 main_thread_priority, u64 stack_size) {
  294. AllocateMainThreadStack(stack_size);
  295. resource_limit->Reserve(LimitableResource::Threads, 1);
  296. resource_limit->Reserve(LimitableResource::PhysicalMemory, main_thread_stack_size);
  297. const std::size_t heap_capacity{memory_usage_capacity - main_thread_stack_size - image_size};
  298. ASSERT(!page_table->SetHeapCapacity(heap_capacity).IsError());
  299. ChangeStatus(ProcessStatus::Running);
  300. SetupMainThread(kernel.System(), *this, main_thread_priority, main_thread_stack_top);
  301. }
  302. void KProcess::PrepareForTermination() {
  303. ChangeStatus(ProcessStatus::Exiting);
  304. const auto stop_threads = [this](const std::vector<KThread*>& in_thread_list) {
  305. for (auto& thread : in_thread_list) {
  306. if (thread->GetOwnerProcess() != this)
  307. continue;
  308. if (thread == kernel.CurrentScheduler()->GetCurrentThread())
  309. continue;
  310. // TODO(Subv): When are the other running/ready threads terminated?
  311. ASSERT_MSG(thread->GetState() == ThreadState::Waiting,
  312. "Exiting processes with non-waiting threads is currently unimplemented");
  313. thread->Exit();
  314. }
  315. };
  316. stop_threads(kernel.System().GlobalSchedulerContext().GetThreadList());
  317. FreeTLSRegion(tls_region_address);
  318. tls_region_address = 0;
  319. if (resource_limit) {
  320. resource_limit->Release(LimitableResource::PhysicalMemory,
  321. main_thread_stack_size + image_size);
  322. }
  323. ChangeStatus(ProcessStatus::Exited);
  324. }
  325. void KProcess::Finalize() {
  326. // Release memory to the resource limit.
  327. if (resource_limit != nullptr) {
  328. resource_limit->Close();
  329. }
  330. // Finalize the handle table and close any open handles.
  331. handle_table.Finalize();
  332. // Perform inherited finalization.
  333. KAutoObjectWithSlabHeapAndContainer<KProcess, KSynchronizationObject>::Finalize();
  334. }
  335. /**
  336. * Attempts to find a TLS page that contains a free slot for
  337. * use by a thread.
  338. *
  339. * @returns If a page with an available slot is found, then an iterator
  340. * pointing to the page is returned. Otherwise the end iterator
  341. * is returned instead.
  342. */
  343. static auto FindTLSPageWithAvailableSlots(std::vector<TLSPage>& tls_pages) {
  344. return std::find_if(tls_pages.begin(), tls_pages.end(),
  345. [](const auto& page) { return page.HasAvailableSlots(); });
  346. }
  347. VAddr KProcess::CreateTLSRegion() {
  348. KScopedSchedulerLock lock(kernel);
  349. if (auto tls_page_iter{FindTLSPageWithAvailableSlots(tls_pages)};
  350. tls_page_iter != tls_pages.cend()) {
  351. return *tls_page_iter->ReserveSlot();
  352. }
  353. Page* const tls_page_ptr{kernel.GetUserSlabHeapPages().Allocate()};
  354. ASSERT(tls_page_ptr);
  355. const VAddr start{page_table->GetKernelMapRegionStart()};
  356. const VAddr size{page_table->GetKernelMapRegionEnd() - start};
  357. const PAddr tls_map_addr{kernel.System().DeviceMemory().GetPhysicalAddr(tls_page_ptr)};
  358. const VAddr tls_page_addr{page_table
  359. ->AllocateAndMapMemory(1, PageSize, true, start, size / PageSize,
  360. KMemoryState::ThreadLocal,
  361. KMemoryPermission::ReadAndWrite,
  362. tls_map_addr)
  363. .ValueOr(0)};
  364. ASSERT(tls_page_addr);
  365. std::memset(tls_page_ptr, 0, PageSize);
  366. tls_pages.emplace_back(tls_page_addr);
  367. const auto reserve_result{tls_pages.back().ReserveSlot()};
  368. ASSERT(reserve_result.has_value());
  369. return *reserve_result;
  370. }
  371. void KProcess::FreeTLSRegion(VAddr tls_address) {
  372. KScopedSchedulerLock lock(kernel);
  373. const VAddr aligned_address = Common::AlignDown(tls_address, Core::Memory::PAGE_SIZE);
  374. auto iter =
  375. std::find_if(tls_pages.begin(), tls_pages.end(), [aligned_address](const auto& page) {
  376. return page.GetBaseAddress() == aligned_address;
  377. });
  378. // Something has gone very wrong if we're freeing a region
  379. // with no actual page available.
  380. ASSERT(iter != tls_pages.cend());
  381. iter->ReleaseSlot(tls_address);
  382. }
  383. void KProcess::LoadModule(CodeSet code_set, VAddr base_addr) {
  384. std::lock_guard lock{HLE::g_hle_lock};
  385. const auto ReprotectSegment = [&](const CodeSet::Segment& segment,
  386. KMemoryPermission permission) {
  387. page_table->SetCodeMemoryPermission(segment.addr + base_addr, segment.size, permission);
  388. };
  389. kernel.System().Memory().WriteBlock(*this, base_addr, code_set.memory.data(),
  390. code_set.memory.size());
  391. ReprotectSegment(code_set.CodeSegment(), KMemoryPermission::ReadAndExecute);
  392. ReprotectSegment(code_set.RODataSegment(), KMemoryPermission::Read);
  393. ReprotectSegment(code_set.DataSegment(), KMemoryPermission::ReadAndWrite);
  394. }
  395. bool KProcess::IsSignaled() const {
  396. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  397. return is_signaled;
  398. }
  399. KProcess::KProcess(KernelCore& kernel_)
  400. : KAutoObjectWithSlabHeapAndContainer{kernel_},
  401. page_table{std::make_unique<KPageTable>(kernel_.System())}, handle_table{kernel_},
  402. address_arbiter{kernel_.System()}, condition_var{kernel_.System()}, state_lock{kernel_} {}
  403. KProcess::~KProcess() = default;
  404. void KProcess::ChangeStatus(ProcessStatus new_status) {
  405. if (status == new_status) {
  406. return;
  407. }
  408. status = new_status;
  409. is_signaled = true;
  410. NotifyAvailable();
  411. }
  412. ResultCode KProcess::AllocateMainThreadStack(std::size_t stack_size) {
  413. ASSERT(stack_size);
  414. // The kernel always ensures that the given stack size is page aligned.
  415. main_thread_stack_size = Common::AlignUp(stack_size, PageSize);
  416. const VAddr start{page_table->GetStackRegionStart()};
  417. const std::size_t size{page_table->GetStackRegionEnd() - start};
  418. CASCADE_RESULT(main_thread_stack_top,
  419. page_table->AllocateAndMapMemory(
  420. main_thread_stack_size / PageSize, PageSize, false, start, size / PageSize,
  421. KMemoryState::Stack, KMemoryPermission::ReadAndWrite));
  422. main_thread_stack_top += main_thread_stack_size;
  423. return ResultSuccess;
  424. }
  425. } // namespace Kernel