vm_manager.cpp 12 KB

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