vm_manager.cpp 12 KB

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