process.cpp 16 KB

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