vm_manager.cpp 12 KB

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