process.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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_scheduler.h"
  18. #include "core/hle/kernel/k_thread.h"
  19. #include "core/hle/kernel/kernel.h"
  20. #include "core/hle/kernel/memory/memory_block_manager.h"
  21. #include "core/hle/kernel/memory/page_table.h"
  22. #include "core/hle/kernel/memory/slab_heap.h"
  23. #include "core/hle/kernel/process.h"
  24. #include "core/hle/kernel/resource_limit.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.GetIdealCore(), 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 = ResourceLimit::Create(kernel);
  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<ResourceLimit> Process::GetResourceLimit() const {
  115. return resource_limit;
  116. }
  117. u64 Process::GetTotalPhysicalMemoryAvailable() const {
  118. const u64 capacity{resource_limit->GetCurrentResourceValue(ResourceType::PhysicalMemory) +
  119. page_table->GetTotalHeapSize() + GetSystemResourceSize() + image_size +
  120. main_thread_stack_size};
  121. if (capacity < memory_usage_capacity) {
  122. return capacity;
  123. }
  124. return memory_usage_capacity;
  125. }
  126. u64 Process::GetTotalPhysicalMemoryAvailableWithoutSystemResource() const {
  127. return GetTotalPhysicalMemoryAvailable() - GetSystemResourceSize();
  128. }
  129. u64 Process::GetTotalPhysicalMemoryUsed() const {
  130. return image_size + main_thread_stack_size + page_table->GetTotalHeapSize() +
  131. GetSystemResourceSize();
  132. }
  133. u64 Process::GetTotalPhysicalMemoryUsedWithoutSystemResource() const {
  134. return GetTotalPhysicalMemoryUsed() - GetSystemResourceUsage();
  135. }
  136. void Process::RegisterThread(const KThread* thread) {
  137. thread_list.push_back(thread);
  138. }
  139. void Process::UnregisterThread(const KThread* thread) {
  140. thread_list.remove(thread);
  141. }
  142. ResultCode Process::ClearSignalState() {
  143. KScopedSchedulerLock lock(system.Kernel());
  144. if (status == ProcessStatus::Exited) {
  145. LOG_ERROR(Kernel, "called on a terminated process instance.");
  146. return ERR_INVALID_STATE;
  147. }
  148. if (!is_signaled) {
  149. LOG_ERROR(Kernel, "called on a process instance that isn't signaled.");
  150. return ERR_INVALID_STATE;
  151. }
  152. is_signaled = false;
  153. return RESULT_SUCCESS;
  154. }
  155. ResultCode Process::LoadFromMetadata(const FileSys::ProgramMetadata& metadata,
  156. std::size_t code_size) {
  157. program_id = metadata.GetTitleID();
  158. ideal_core = metadata.GetMainThreadCore();
  159. is_64bit_process = metadata.Is64BitProgram();
  160. system_resource_size = metadata.GetSystemResourceSize();
  161. image_size = code_size;
  162. // Initialize proces address space
  163. if (const ResultCode result{
  164. page_table->InitializeForProcess(metadata.GetAddressSpaceType(), false, 0x8000000,
  165. code_size, Memory::MemoryManager::Pool::Application)};
  166. result.IsError()) {
  167. return result;
  168. }
  169. // Map process code region
  170. if (const ResultCode result{page_table->MapProcessCode(
  171. page_table->GetCodeRegionStart(), code_size / Memory::PageSize,
  172. Memory::MemoryState::Code, Memory::MemoryPermission::None)};
  173. result.IsError()) {
  174. return result;
  175. }
  176. // Initialize process capabilities
  177. const auto& caps{metadata.GetKernelCapabilities()};
  178. if (const ResultCode result{
  179. capabilities.InitializeForUserProcess(caps.data(), caps.size(), *page_table)};
  180. result.IsError()) {
  181. return result;
  182. }
  183. // Set memory usage capacity
  184. switch (metadata.GetAddressSpaceType()) {
  185. case FileSys::ProgramAddressSpaceType::Is32Bit:
  186. case FileSys::ProgramAddressSpaceType::Is36Bit:
  187. case FileSys::ProgramAddressSpaceType::Is39Bit:
  188. memory_usage_capacity = page_table->GetHeapRegionEnd() - page_table->GetHeapRegionStart();
  189. break;
  190. case FileSys::ProgramAddressSpaceType::Is32BitNoMap:
  191. memory_usage_capacity = page_table->GetHeapRegionEnd() - page_table->GetHeapRegionStart() +
  192. page_table->GetAliasRegionEnd() - page_table->GetAliasRegionStart();
  193. break;
  194. default:
  195. UNREACHABLE();
  196. }
  197. // Set initial resource limits
  198. resource_limit->SetLimitValue(
  199. ResourceType::PhysicalMemory,
  200. kernel.MemoryManager().GetSize(Memory::MemoryManager::Pool::Application));
  201. resource_limit->SetLimitValue(ResourceType::Threads, 608);
  202. resource_limit->SetLimitValue(ResourceType::Events, 700);
  203. resource_limit->SetLimitValue(ResourceType::TransferMemory, 128);
  204. resource_limit->SetLimitValue(ResourceType::Sessions, 894);
  205. ASSERT(resource_limit->Reserve(ResourceType::PhysicalMemory, code_size));
  206. // Create TLS region
  207. tls_region_address = CreateTLSRegion();
  208. return handle_table.SetSize(capabilities.GetHandleTableSize());
  209. }
  210. void Process::Run(s32 main_thread_priority, u64 stack_size) {
  211. AllocateMainThreadStack(stack_size);
  212. const std::size_t heap_capacity{memory_usage_capacity - main_thread_stack_size - image_size};
  213. ASSERT(!page_table->SetHeapCapacity(heap_capacity).IsError());
  214. ChangeStatus(ProcessStatus::Running);
  215. SetupMainThread(system, *this, main_thread_priority, main_thread_stack_top);
  216. resource_limit->Reserve(ResourceType::Threads, 1);
  217. resource_limit->Reserve(ResourceType::PhysicalMemory, main_thread_stack_size);
  218. }
  219. void Process::PrepareForTermination() {
  220. ChangeStatus(ProcessStatus::Exiting);
  221. const auto stop_threads = [this](const std::vector<std::shared_ptr<KThread>>& thread_list) {
  222. for (auto& thread : thread_list) {
  223. if (thread->GetOwnerProcess() != this)
  224. continue;
  225. if (thread.get() == kernel.CurrentScheduler()->GetCurrentThread())
  226. continue;
  227. // TODO(Subv): When are the other running/ready threads terminated?
  228. ASSERT_MSG(thread->GetState() == ThreadState::Waiting,
  229. "Exiting processes with non-waiting threads is currently unimplemented");
  230. thread->Stop();
  231. }
  232. };
  233. stop_threads(system.GlobalSchedulerContext().GetThreadList());
  234. FreeTLSRegion(tls_region_address);
  235. tls_region_address = 0;
  236. ChangeStatus(ProcessStatus::Exited);
  237. }
  238. /**
  239. * Attempts to find a TLS page that contains a free slot for
  240. * use by a thread.
  241. *
  242. * @returns If a page with an available slot is found, then an iterator
  243. * pointing to the page is returned. Otherwise the end iterator
  244. * is returned instead.
  245. */
  246. static auto FindTLSPageWithAvailableSlots(std::vector<TLSPage>& tls_pages) {
  247. return std::find_if(tls_pages.begin(), tls_pages.end(),
  248. [](const auto& page) { return page.HasAvailableSlots(); });
  249. }
  250. VAddr Process::CreateTLSRegion() {
  251. KScopedSchedulerLock lock(system.Kernel());
  252. if (auto tls_page_iter{FindTLSPageWithAvailableSlots(tls_pages)};
  253. tls_page_iter != tls_pages.cend()) {
  254. return *tls_page_iter->ReserveSlot();
  255. }
  256. Memory::Page* const tls_page_ptr{kernel.GetUserSlabHeapPages().Allocate()};
  257. ASSERT(tls_page_ptr);
  258. const VAddr start{page_table->GetKernelMapRegionStart()};
  259. const VAddr size{page_table->GetKernelMapRegionEnd() - start};
  260. const PAddr tls_map_addr{system.DeviceMemory().GetPhysicalAddr(tls_page_ptr)};
  261. const VAddr tls_page_addr{
  262. page_table
  263. ->AllocateAndMapMemory(1, Memory::PageSize, true, start, size / Memory::PageSize,
  264. Memory::MemoryState::ThreadLocal,
  265. Memory::MemoryPermission::ReadAndWrite, tls_map_addr)
  266. .ValueOr(0)};
  267. ASSERT(tls_page_addr);
  268. std::memset(tls_page_ptr, 0, Memory::PageSize);
  269. tls_pages.emplace_back(tls_page_addr);
  270. const auto reserve_result{tls_pages.back().ReserveSlot()};
  271. ASSERT(reserve_result.has_value());
  272. return *reserve_result;
  273. }
  274. void Process::FreeTLSRegion(VAddr tls_address) {
  275. KScopedSchedulerLock lock(system.Kernel());
  276. const VAddr aligned_address = Common::AlignDown(tls_address, Core::Memory::PAGE_SIZE);
  277. auto iter =
  278. std::find_if(tls_pages.begin(), tls_pages.end(), [aligned_address](const auto& page) {
  279. return page.GetBaseAddress() == aligned_address;
  280. });
  281. // Something has gone very wrong if we're freeing a region
  282. // with no actual page available.
  283. ASSERT(iter != tls_pages.cend());
  284. iter->ReleaseSlot(tls_address);
  285. }
  286. void Process::LoadModule(CodeSet code_set, VAddr base_addr) {
  287. std::lock_guard lock{HLE::g_hle_lock};
  288. const auto ReprotectSegment = [&](const CodeSet::Segment& segment,
  289. Memory::MemoryPermission permission) {
  290. page_table->SetCodeMemoryPermission(segment.addr + base_addr, segment.size, permission);
  291. };
  292. system.Memory().WriteBlock(*this, base_addr, code_set.memory.data(), code_set.memory.size());
  293. ReprotectSegment(code_set.CodeSegment(), Memory::MemoryPermission::ReadAndExecute);
  294. ReprotectSegment(code_set.RODataSegment(), Memory::MemoryPermission::Read);
  295. ReprotectSegment(code_set.DataSegment(), Memory::MemoryPermission::ReadAndWrite);
  296. }
  297. bool Process::IsSignaled() const {
  298. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  299. return is_signaled;
  300. }
  301. Process::Process(Core::System& system)
  302. : KSynchronizationObject{system.Kernel()},
  303. page_table{std::make_unique<Memory::PageTable>(system)}, handle_table{system.Kernel()},
  304. address_arbiter{system}, condition_var{system}, system{system} {}
  305. Process::~Process() = default;
  306. void Process::ChangeStatus(ProcessStatus new_status) {
  307. if (status == new_status) {
  308. return;
  309. }
  310. status = new_status;
  311. is_signaled = true;
  312. NotifyAvailable();
  313. }
  314. ResultCode Process::AllocateMainThreadStack(std::size_t stack_size) {
  315. ASSERT(stack_size);
  316. // The kernel always ensures that the given stack size is page aligned.
  317. main_thread_stack_size = Common::AlignUp(stack_size, Memory::PageSize);
  318. const VAddr start{page_table->GetStackRegionStart()};
  319. const std::size_t size{page_table->GetStackRegionEnd() - start};
  320. CASCADE_RESULT(main_thread_stack_top,
  321. page_table->AllocateAndMapMemory(
  322. main_thread_stack_size / Memory::PageSize, Memory::PageSize, false, start,
  323. size / Memory::PageSize, Memory::MemoryState::Stack,
  324. Memory::MemoryPermission::ReadAndWrite));
  325. main_thread_stack_top += main_thread_stack_size;
  326. return RESULT_SUCCESS;
  327. }
  328. } // namespace Kernel