k_process.cpp 18 KB

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