k_process.cpp 18 KB

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