vm_manager.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 <iterator>
  6. #include <utility>
  7. #include "common/assert.h"
  8. #include "common/logging/log.h"
  9. #include "core/arm/arm_interface.h"
  10. #include "core/core.h"
  11. #include "core/hle/kernel/errors.h"
  12. #include "core/hle/kernel/vm_manager.h"
  13. #include "core/memory.h"
  14. #include "core/memory_hook.h"
  15. #include "core/memory_setup.h"
  16. namespace Kernel {
  17. static const char* GetMemoryStateName(MemoryState state) {
  18. static constexpr const char* names[] = {
  19. "Unmapped", "Io",
  20. "Normal", "CodeStatic",
  21. "CodeMutable", "Heap",
  22. "Shared", "Unknown1",
  23. "ModuleCodeStatic", "ModuleCodeMutable",
  24. "IpcBuffer0", "Mapped",
  25. "ThreadLocal", "TransferMemoryIsolated",
  26. "TransferMemory", "ProcessMemory",
  27. "Unknown2", "IpcBuffer1",
  28. "IpcBuffer3", "KernelStack",
  29. };
  30. return names[static_cast<int>(state)];
  31. }
  32. bool VirtualMemoryArea::CanBeMergedWith(const VirtualMemoryArea& next) const {
  33. ASSERT(base + size == next.base);
  34. if (permissions != next.permissions || meminfo_state != next.meminfo_state ||
  35. type != next.type) {
  36. return false;
  37. }
  38. if (type == VMAType::AllocatedMemoryBlock &&
  39. (backing_block != next.backing_block || offset + size != next.offset)) {
  40. return false;
  41. }
  42. if (type == VMAType::BackingMemory && backing_memory + size != next.backing_memory) {
  43. return false;
  44. }
  45. if (type == VMAType::MMIO && paddr + size != next.paddr) {
  46. return false;
  47. }
  48. return true;
  49. }
  50. VMManager::VMManager() {
  51. Reset();
  52. }
  53. VMManager::~VMManager() {
  54. Reset();
  55. }
  56. void VMManager::Reset() {
  57. vma_map.clear();
  58. // Initialize the map with a single free region covering the entire managed space.
  59. VirtualMemoryArea initial_vma;
  60. initial_vma.size = MAX_ADDRESS;
  61. vma_map.emplace(initial_vma.base, initial_vma);
  62. page_table.pointers.fill(nullptr);
  63. page_table.special_regions.clear();
  64. page_table.attributes.fill(Memory::PageType::Unmapped);
  65. UpdatePageTableForVMA(initial_vma);
  66. }
  67. VMManager::VMAHandle VMManager::FindVMA(VAddr target) const {
  68. if (target >= MAX_ADDRESS) {
  69. return vma_map.end();
  70. } else {
  71. return std::prev(vma_map.upper_bound(target));
  72. }
  73. }
  74. ResultVal<VMManager::VMAHandle> VMManager::MapMemoryBlock(VAddr target,
  75. std::shared_ptr<std::vector<u8>> block,
  76. size_t offset, u64 size,
  77. MemoryState state) {
  78. ASSERT(block != nullptr);
  79. ASSERT(offset + size <= block->size());
  80. // This is the appropriately sized VMA that will turn into our allocation.
  81. CASCADE_RESULT(VMAIter vma_handle, CarveVMA(target, size));
  82. VirtualMemoryArea& final_vma = vma_handle->second;
  83. ASSERT(final_vma.size == size);
  84. auto& system = Core::System::GetInstance();
  85. system.ArmInterface(0).MapBackingMemory(target, size, block->data() + offset,
  86. VMAPermission::ReadWriteExecute);
  87. system.ArmInterface(1).MapBackingMemory(target, size, block->data() + offset,
  88. VMAPermission::ReadWriteExecute);
  89. system.ArmInterface(2).MapBackingMemory(target, size, block->data() + offset,
  90. VMAPermission::ReadWriteExecute);
  91. system.ArmInterface(3).MapBackingMemory(target, size, block->data() + offset,
  92. VMAPermission::ReadWriteExecute);
  93. final_vma.type = VMAType::AllocatedMemoryBlock;
  94. final_vma.permissions = VMAPermission::ReadWrite;
  95. final_vma.meminfo_state = state;
  96. final_vma.backing_block = std::move(block);
  97. final_vma.offset = offset;
  98. UpdatePageTableForVMA(final_vma);
  99. return MakeResult<VMAHandle>(MergeAdjacent(vma_handle));
  100. }
  101. ResultVal<VMManager::VMAHandle> VMManager::MapBackingMemory(VAddr target, u8* memory, u64 size,
  102. MemoryState state) {
  103. ASSERT(memory != nullptr);
  104. // This is the appropriately sized VMA that will turn into our allocation.
  105. CASCADE_RESULT(VMAIter vma_handle, CarveVMA(target, size));
  106. VirtualMemoryArea& final_vma = vma_handle->second;
  107. ASSERT(final_vma.size == size);
  108. auto& system = Core::System::GetInstance();
  109. system.ArmInterface(0).MapBackingMemory(target, size, memory, VMAPermission::ReadWriteExecute);
  110. system.ArmInterface(1).MapBackingMemory(target, size, memory, VMAPermission::ReadWriteExecute);
  111. system.ArmInterface(2).MapBackingMemory(target, size, memory, VMAPermission::ReadWriteExecute);
  112. system.ArmInterface(3).MapBackingMemory(target, size, memory, VMAPermission::ReadWriteExecute);
  113. final_vma.type = VMAType::BackingMemory;
  114. final_vma.permissions = VMAPermission::ReadWrite;
  115. final_vma.meminfo_state = state;
  116. final_vma.backing_memory = memory;
  117. UpdatePageTableForVMA(final_vma);
  118. return MakeResult<VMAHandle>(MergeAdjacent(vma_handle));
  119. }
  120. ResultVal<VMManager::VMAHandle> VMManager::MapMMIO(VAddr target, PAddr paddr, u64 size,
  121. MemoryState state,
  122. Memory::MemoryHookPointer mmio_handler) {
  123. // This is the appropriately sized VMA that will turn into our allocation.
  124. CASCADE_RESULT(VMAIter vma_handle, CarveVMA(target, size));
  125. VirtualMemoryArea& final_vma = vma_handle->second;
  126. ASSERT(final_vma.size == size);
  127. final_vma.type = VMAType::MMIO;
  128. final_vma.permissions = VMAPermission::ReadWrite;
  129. final_vma.meminfo_state = state;
  130. final_vma.paddr = paddr;
  131. final_vma.mmio_handler = std::move(mmio_handler);
  132. UpdatePageTableForVMA(final_vma);
  133. return MakeResult<VMAHandle>(MergeAdjacent(vma_handle));
  134. }
  135. VMManager::VMAIter VMManager::Unmap(VMAIter vma_handle) {
  136. VirtualMemoryArea& vma = vma_handle->second;
  137. vma.type = VMAType::Free;
  138. vma.permissions = VMAPermission::None;
  139. vma.meminfo_state = MemoryState::Unmapped;
  140. vma.backing_block = nullptr;
  141. vma.offset = 0;
  142. vma.backing_memory = nullptr;
  143. vma.paddr = 0;
  144. UpdatePageTableForVMA(vma);
  145. return MergeAdjacent(vma_handle);
  146. }
  147. ResultCode VMManager::UnmapRange(VAddr target, u64 size) {
  148. CASCADE_RESULT(VMAIter vma, CarveVMARange(target, size));
  149. const VAddr target_end = target + size;
  150. const VMAIter end = vma_map.end();
  151. // The comparison against the end of the range must be done using addresses since VMAs can be
  152. // merged during this process, causing invalidation of the iterators.
  153. while (vma != end && vma->second.base < target_end) {
  154. vma = std::next(Unmap(vma));
  155. }
  156. ASSERT(FindVMA(target)->second.size >= size);
  157. auto& system = Core::System::GetInstance();
  158. system.ArmInterface(0).UnmapMemory(target, size);
  159. system.ArmInterface(1).UnmapMemory(target, size);
  160. system.ArmInterface(2).UnmapMemory(target, size);
  161. system.ArmInterface(3).UnmapMemory(target, size);
  162. return RESULT_SUCCESS;
  163. }
  164. VMManager::VMAHandle VMManager::Reprotect(VMAHandle vma_handle, VMAPermission new_perms) {
  165. VMAIter iter = StripIterConstness(vma_handle);
  166. VirtualMemoryArea& vma = iter->second;
  167. vma.permissions = new_perms;
  168. UpdatePageTableForVMA(vma);
  169. return MergeAdjacent(iter);
  170. }
  171. ResultCode VMManager::ReprotectRange(VAddr target, u64 size, VMAPermission new_perms) {
  172. CASCADE_RESULT(VMAIter vma, CarveVMARange(target, size));
  173. const VAddr target_end = target + size;
  174. const VMAIter end = vma_map.end();
  175. // The comparison against the end of the range must be done using addresses since VMAs can be
  176. // merged during this process, causing invalidation of the iterators.
  177. while (vma != end && vma->second.base < target_end) {
  178. vma = std::next(StripIterConstness(Reprotect(vma, new_perms)));
  179. }
  180. return RESULT_SUCCESS;
  181. }
  182. void VMManager::RefreshMemoryBlockMappings(const std::vector<u8>* block) {
  183. // If this ever proves to have a noticeable performance impact, allow users of the function to
  184. // specify a specific range of addresses to limit the scan to.
  185. for (const auto& p : vma_map) {
  186. const VirtualMemoryArea& vma = p.second;
  187. if (block == vma.backing_block.get()) {
  188. UpdatePageTableForVMA(vma);
  189. }
  190. }
  191. }
  192. void VMManager::LogLayout() const {
  193. for (const auto& p : vma_map) {
  194. const VirtualMemoryArea& vma = p.second;
  195. LOG_DEBUG(Kernel, "{:016X} - {:016X} size: {:016X} {}{}{} {}", vma.base,
  196. vma.base + vma.size, vma.size,
  197. (u8)vma.permissions & (u8)VMAPermission::Read ? 'R' : '-',
  198. (u8)vma.permissions & (u8)VMAPermission::Write ? 'W' : '-',
  199. (u8)vma.permissions & (u8)VMAPermission::Execute ? 'X' : '-',
  200. GetMemoryStateName(vma.meminfo_state));
  201. }
  202. }
  203. VMManager::VMAIter VMManager::StripIterConstness(const VMAHandle& iter) {
  204. // This uses a neat C++ trick to convert a const_iterator to a regular iterator, given
  205. // non-const access to its container.
  206. return vma_map.erase(iter, iter); // Erases an empty range of elements
  207. }
  208. ResultVal<VMManager::VMAIter> VMManager::CarveVMA(VAddr base, u64 size) {
  209. ASSERT_MSG((size & Memory::PAGE_MASK) == 0, "non-page aligned size: 0x{:016X}", size);
  210. ASSERT_MSG((base & Memory::PAGE_MASK) == 0, "non-page aligned base: 0x{:016X}", base);
  211. VMAIter vma_handle = StripIterConstness(FindVMA(base));
  212. if (vma_handle == vma_map.end()) {
  213. // Target address is outside the range managed by the kernel
  214. return ERR_INVALID_ADDRESS;
  215. }
  216. const VirtualMemoryArea& vma = vma_handle->second;
  217. if (vma.type != VMAType::Free) {
  218. // Region is already allocated
  219. return ERR_INVALID_ADDRESS_STATE;
  220. }
  221. const VAddr start_in_vma = base - vma.base;
  222. const VAddr end_in_vma = start_in_vma + size;
  223. if (end_in_vma > vma.size) {
  224. // Requested allocation doesn't fit inside VMA
  225. return ERR_INVALID_ADDRESS_STATE;
  226. }
  227. if (end_in_vma != vma.size) {
  228. // Split VMA at the end of the allocated region
  229. SplitVMA(vma_handle, end_in_vma);
  230. }
  231. if (start_in_vma != 0) {
  232. // Split VMA at the start of the allocated region
  233. vma_handle = SplitVMA(vma_handle, start_in_vma);
  234. }
  235. return MakeResult<VMAIter>(vma_handle);
  236. }
  237. ResultVal<VMManager::VMAIter> VMManager::CarveVMARange(VAddr target, u64 size) {
  238. ASSERT_MSG((size & Memory::PAGE_MASK) == 0, "non-page aligned size: 0x{:016X}", size);
  239. ASSERT_MSG((target & Memory::PAGE_MASK) == 0, "non-page aligned base: 0x{:016X}", target);
  240. const VAddr target_end = target + size;
  241. ASSERT(target_end >= target);
  242. ASSERT(target_end <= MAX_ADDRESS);
  243. ASSERT(size > 0);
  244. VMAIter begin_vma = StripIterConstness(FindVMA(target));
  245. const VMAIter i_end = vma_map.lower_bound(target_end);
  246. if (std::any_of(begin_vma, i_end,
  247. [](const auto& entry) { return entry.second.type == VMAType::Free; })) {
  248. return ERR_INVALID_ADDRESS_STATE;
  249. }
  250. if (target != begin_vma->second.base) {
  251. begin_vma = SplitVMA(begin_vma, target - begin_vma->second.base);
  252. }
  253. VMAIter end_vma = StripIterConstness(FindVMA(target_end));
  254. if (end_vma != vma_map.end() && target_end != end_vma->second.base) {
  255. end_vma = SplitVMA(end_vma, target_end - end_vma->second.base);
  256. }
  257. return MakeResult<VMAIter>(begin_vma);
  258. }
  259. VMManager::VMAIter VMManager::SplitVMA(VMAIter vma_handle, u64 offset_in_vma) {
  260. VirtualMemoryArea& old_vma = vma_handle->second;
  261. VirtualMemoryArea new_vma = old_vma; // Make a copy of the VMA
  262. // For now, don't allow no-op VMA splits (trying to split at a boundary) because it's probably
  263. // a bug. This restriction might be removed later.
  264. ASSERT(offset_in_vma < old_vma.size);
  265. ASSERT(offset_in_vma > 0);
  266. old_vma.size = offset_in_vma;
  267. new_vma.base += offset_in_vma;
  268. new_vma.size -= offset_in_vma;
  269. switch (new_vma.type) {
  270. case VMAType::Free:
  271. break;
  272. case VMAType::AllocatedMemoryBlock:
  273. new_vma.offset += offset_in_vma;
  274. break;
  275. case VMAType::BackingMemory:
  276. new_vma.backing_memory += offset_in_vma;
  277. break;
  278. case VMAType::MMIO:
  279. new_vma.paddr += offset_in_vma;
  280. break;
  281. }
  282. ASSERT(old_vma.CanBeMergedWith(new_vma));
  283. return vma_map.emplace_hint(std::next(vma_handle), new_vma.base, new_vma);
  284. }
  285. VMManager::VMAIter VMManager::MergeAdjacent(VMAIter iter) {
  286. const VMAIter next_vma = std::next(iter);
  287. if (next_vma != vma_map.end() && iter->second.CanBeMergedWith(next_vma->second)) {
  288. iter->second.size += next_vma->second.size;
  289. vma_map.erase(next_vma);
  290. }
  291. if (iter != vma_map.begin()) {
  292. VMAIter prev_vma = std::prev(iter);
  293. if (prev_vma->second.CanBeMergedWith(iter->second)) {
  294. prev_vma->second.size += iter->second.size;
  295. vma_map.erase(iter);
  296. iter = prev_vma;
  297. }
  298. }
  299. return iter;
  300. }
  301. void VMManager::UpdatePageTableForVMA(const VirtualMemoryArea& vma) {
  302. switch (vma.type) {
  303. case VMAType::Free:
  304. Memory::UnmapRegion(page_table, vma.base, vma.size);
  305. break;
  306. case VMAType::AllocatedMemoryBlock:
  307. Memory::MapMemoryRegion(page_table, vma.base, vma.size,
  308. vma.backing_block->data() + vma.offset);
  309. break;
  310. case VMAType::BackingMemory:
  311. Memory::MapMemoryRegion(page_table, vma.base, vma.size, vma.backing_memory);
  312. break;
  313. case VMAType::MMIO:
  314. Memory::MapIoRegion(page_table, vma.base, vma.size, vma.mmio_handler);
  315. break;
  316. }
  317. }
  318. u64 VMManager::GetTotalMemoryUsage() const {
  319. LOG_WARNING(Kernel, "(STUBBED) called");
  320. return 0xF8000000;
  321. }
  322. u64 VMManager::GetTotalHeapUsage() const {
  323. LOG_WARNING(Kernel, "(STUBBED) called");
  324. return 0x0;
  325. }
  326. VAddr VMManager::GetAddressSpaceBaseAddr() const {
  327. LOG_WARNING(Kernel, "(STUBBED) called");
  328. return 0x8000000;
  329. }
  330. u64 VMManager::GetAddressSpaceSize() const {
  331. LOG_WARNING(Kernel, "(STUBBED) called");
  332. return MAX_ADDRESS;
  333. }
  334. } // namespace Kernel