vm_manager.cpp 13 KB

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