vm_manager.cpp 13 KB

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