vm_manager.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. // Copyright 2015 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <map>
  6. #include <memory>
  7. #include <vector>
  8. #include "common/common_types.h"
  9. #include "core/hle/result.h"
  10. #include "core/memory.h"
  11. #include "core/memory_hook.h"
  12. namespace FileSys {
  13. enum class ProgramAddressSpaceType : u8;
  14. }
  15. namespace Kernel {
  16. enum class VMAType : u8 {
  17. /// VMA represents an unmapped region of the address space.
  18. Free,
  19. /// VMA is backed by a ref-counted allocate memory block.
  20. AllocatedMemoryBlock,
  21. /// VMA is backed by a raw, unmanaged pointer.
  22. BackingMemory,
  23. /// VMA is mapped to MMIO registers at a fixed PAddr.
  24. MMIO,
  25. // TODO(yuriks): Implement MemoryAlias to support MAP/UNMAP
  26. };
  27. /// Permissions for mapped memory blocks
  28. enum class VMAPermission : u8 {
  29. None = 0,
  30. Read = 1,
  31. Write = 2,
  32. Execute = 4,
  33. ReadWrite = Read | Write,
  34. ReadExecute = Read | Execute,
  35. WriteExecute = Write | Execute,
  36. ReadWriteExecute = Read | Write | Execute,
  37. };
  38. /// Set of values returned in MemoryInfo.state by svcQueryMemory.
  39. enum class MemoryState : u32 {
  40. Unmapped = 0x0,
  41. Io = 0x1,
  42. Normal = 0x2,
  43. CodeStatic = 0x3,
  44. CodeMutable = 0x4,
  45. Heap = 0x5,
  46. Shared = 0x6,
  47. ModuleCodeStatic = 0x8,
  48. ModuleCodeMutable = 0x9,
  49. IpcBuffer0 = 0xA,
  50. Mapped = 0xB,
  51. ThreadLocal = 0xC,
  52. TransferMemoryIsolated = 0xD,
  53. TransferMemory = 0xE,
  54. ProcessMemory = 0xF,
  55. IpcBuffer1 = 0x11,
  56. IpcBuffer3 = 0x12,
  57. KernelStack = 0x13,
  58. };
  59. /**
  60. * Represents a VMA in an address space. A VMA is a contiguous region of virtual addressing space
  61. * with homogeneous attributes across its extents. In this particular implementation each VMA is
  62. * also backed by a single host memory allocation.
  63. */
  64. struct VirtualMemoryArea {
  65. /// Virtual base address of the region.
  66. VAddr base = 0;
  67. /// Size of the region.
  68. u64 size = 0;
  69. VMAType type = VMAType::Free;
  70. VMAPermission permissions = VMAPermission::None;
  71. /// Tag returned by svcQueryMemory. Not otherwise used.
  72. MemoryState meminfo_state = MemoryState::Unmapped;
  73. // Settings for type = AllocatedMemoryBlock
  74. /// Memory block backing this VMA.
  75. std::shared_ptr<std::vector<u8>> backing_block = nullptr;
  76. /// Offset into the backing_memory the mapping starts from.
  77. std::size_t offset = 0;
  78. // Settings for type = BackingMemory
  79. /// Pointer backing this VMA. It will not be destroyed or freed when the VMA is removed.
  80. u8* backing_memory = nullptr;
  81. // Settings for type = MMIO
  82. /// Physical address of the register area this VMA maps to.
  83. PAddr paddr = 0;
  84. Memory::MemoryHookPointer mmio_handler = nullptr;
  85. /// Tests if this area can be merged to the right with `next`.
  86. bool CanBeMergedWith(const VirtualMemoryArea& next) const;
  87. };
  88. /**
  89. * Manages a process' virtual addressing space. This class maintains a list of allocated and free
  90. * regions in the address space, along with their attributes, and allows kernel clients to
  91. * manipulate it, adjusting the page table to match.
  92. *
  93. * This is similar in idea and purpose to the VM manager present in operating system kernels, with
  94. * the main difference being that it doesn't have to support swapping or memory mapping of files.
  95. * The implementation is also simplified by not having to allocate page frames. See these articles
  96. * about the Linux kernel for an explantion of the concept and implementation:
  97. * - http://duartes.org/gustavo/blog/post/how-the-kernel-manages-your-memory/
  98. * - http://duartes.org/gustavo/blog/post/page-cache-the-affair-between-memory-and-files/
  99. */
  100. class VMManager final {
  101. public:
  102. /**
  103. * A map covering the entirety of the managed address space, keyed by the `base` field of each
  104. * VMA. It must always be modified by splitting or merging VMAs, so that the invariant
  105. * `elem.base + elem.size == next.base` is preserved, and mergeable regions must always be
  106. * merged when possible so that no two similar and adjacent regions exist that have not been
  107. * merged.
  108. */
  109. std::map<VAddr, VirtualMemoryArea> vma_map;
  110. using VMAHandle = decltype(vma_map)::const_iterator;
  111. VMManager();
  112. ~VMManager();
  113. /// Clears the address space map, re-initializing with a single free area.
  114. void Reset(FileSys::ProgramAddressSpaceType type);
  115. /// Finds the VMA in which the given address is included in, or `vma_map.end()`.
  116. VMAHandle FindVMA(VAddr target) const;
  117. // TODO(yuriks): Should these functions actually return the handle?
  118. /**
  119. * Maps part of a ref-counted block of memory at a given address.
  120. *
  121. * @param target The guest address to start the mapping at.
  122. * @param block The block to be mapped.
  123. * @param offset Offset into `block` to map from.
  124. * @param size Size of the mapping.
  125. * @param state MemoryState tag to attach to the VMA.
  126. */
  127. ResultVal<VMAHandle> MapMemoryBlock(VAddr target, std::shared_ptr<std::vector<u8>> block,
  128. std::size_t offset, u64 size, MemoryState state);
  129. /**
  130. * Maps an unmanaged host memory pointer at a given address.
  131. *
  132. * @param target The guest address to start the mapping at.
  133. * @param memory The memory to be mapped.
  134. * @param size Size of the mapping.
  135. * @param state MemoryState tag to attach to the VMA.
  136. */
  137. ResultVal<VMAHandle> MapBackingMemory(VAddr target, u8* memory, u64 size, MemoryState state);
  138. /**
  139. * Maps a memory-mapped IO region at a given address.
  140. *
  141. * @param target The guest address to start the mapping at.
  142. * @param paddr The physical address where the registers are present.
  143. * @param size Size of the mapping.
  144. * @param state MemoryState tag to attach to the VMA.
  145. * @param mmio_handler The handler that will implement read and write for this MMIO region.
  146. */
  147. ResultVal<VMAHandle> MapMMIO(VAddr target, PAddr paddr, u64 size, MemoryState state,
  148. Memory::MemoryHookPointer mmio_handler);
  149. /// Unmaps a range of addresses, splitting VMAs as necessary.
  150. ResultCode UnmapRange(VAddr target, u64 size);
  151. /// Changes the permissions of the given VMA.
  152. VMAHandle Reprotect(VMAHandle vma, VMAPermission new_perms);
  153. /// Changes the permissions of a range of addresses, splitting VMAs as necessary.
  154. ResultCode ReprotectRange(VAddr target, u64 size, VMAPermission new_perms);
  155. /**
  156. * Scans all VMAs and updates the page table range of any that use the given vector as backing
  157. * memory. This should be called after any operation that causes reallocation of the vector.
  158. */
  159. void RefreshMemoryBlockMappings(const std::vector<u8>* block);
  160. /// Dumps the address space layout to the log, for debugging
  161. void LogLayout() const;
  162. /// Gets the total memory usage, used by svcGetInfo
  163. u64 GetTotalMemoryUsage() const;
  164. /// Gets the total heap usage, used by svcGetInfo
  165. u64 GetTotalHeapUsage() const;
  166. /// Gets the address space base address
  167. VAddr GetAddressSpaceBaseAddress() const;
  168. /// Gets the address space end address
  169. VAddr GetAddressSpaceEndAddress() const;
  170. /// Gets the total address space address size in bytes
  171. u64 GetAddressSpaceSize() const;
  172. /// Gets the address space width in bits.
  173. u64 GetAddressSpaceWidth() const;
  174. /// Gets the base address of the code region.
  175. VAddr GetCodeRegionBaseAddress() const;
  176. /// Gets the end address of the code region.
  177. VAddr GetCodeRegionEndAddress() const;
  178. /// Gets the total size of the code region in bytes.
  179. u64 GetCodeRegionSize() const;
  180. /// Gets the base address of the heap region.
  181. VAddr GetHeapRegionBaseAddress() const;
  182. /// Gets the end address of the heap region;
  183. VAddr GetHeapRegionEndAddress() const;
  184. /// Gets the total size of the heap region in bytes.
  185. u64 GetHeapRegionSize() const;
  186. /// Gets the base address of the map region.
  187. VAddr GetMapRegionBaseAddress() const;
  188. /// Gets the end address of the map region.
  189. VAddr GetMapRegionEndAddress() const;
  190. /// Gets the total size of the map region in bytes.
  191. u64 GetMapRegionSize() const;
  192. /// Gets the base address of the new map region.
  193. VAddr GetNewMapRegionBaseAddress() const;
  194. /// Gets the end address of the new map region.
  195. VAddr GetNewMapRegionEndAddress() const;
  196. /// Gets the total size of the new map region in bytes.
  197. u64 GetNewMapRegionSize() const;
  198. /// Gets the base address of the TLS IO region.
  199. VAddr GetTLSIORegionBaseAddress() const;
  200. /// Gets the end address of the TLS IO region.
  201. VAddr GetTLSIORegionEndAddress() const;
  202. /// Gets the total size of the TLS IO region in bytes.
  203. u64 GetTLSIORegionSize() const;
  204. /// Each VMManager has its own page table, which is set as the main one when the owning process
  205. /// is scheduled.
  206. Memory::PageTable page_table;
  207. private:
  208. using VMAIter = decltype(vma_map)::iterator;
  209. /// Converts a VMAHandle to a mutable VMAIter.
  210. VMAIter StripIterConstness(const VMAHandle& iter);
  211. /// Unmaps the given VMA.
  212. VMAIter Unmap(VMAIter vma);
  213. /**
  214. * Carves a VMA of a specific size at the specified address by splitting Free VMAs while doing
  215. * the appropriate error checking.
  216. */
  217. ResultVal<VMAIter> CarveVMA(VAddr base, u64 size);
  218. /**
  219. * Splits the edges of the given range of non-Free VMAs so that there is a VMA split at each
  220. * end of the range.
  221. */
  222. ResultVal<VMAIter> CarveVMARange(VAddr base, u64 size);
  223. /**
  224. * Splits a VMA in two, at the specified offset.
  225. * @returns the right side of the split, with the original iterator becoming the left side.
  226. */
  227. VMAIter SplitVMA(VMAIter vma, u64 offset_in_vma);
  228. /**
  229. * Checks for and merges the specified VMA with adjacent ones if possible.
  230. * @returns the merged VMA or the original if no merging was possible.
  231. */
  232. VMAIter MergeAdjacent(VMAIter vma);
  233. /// Updates the pages corresponding to this VMA so they match the VMA's attributes.
  234. void UpdatePageTableForVMA(const VirtualMemoryArea& vma);
  235. /// Initializes memory region ranges to adhere to a given address space type.
  236. void InitializeMemoryRegionRanges(FileSys::ProgramAddressSpaceType type);
  237. /// Clears the underlying map and page table.
  238. void Clear();
  239. /// Clears out the VMA map, unmapping any previously mapped ranges.
  240. void ClearVMAMap();
  241. /// Clears out the page table
  242. void ClearPageTable();
  243. u32 address_space_width = 0;
  244. VAddr address_space_base = 0;
  245. VAddr address_space_end = 0;
  246. VAddr code_region_base = 0;
  247. VAddr code_region_end = 0;
  248. VAddr heap_region_base = 0;
  249. VAddr heap_region_end = 0;
  250. VAddr map_region_base = 0;
  251. VAddr map_region_end = 0;
  252. VAddr new_map_region_base = 0;
  253. VAddr new_map_region_end = 0;
  254. VAddr tls_io_region_base = 0;
  255. VAddr tls_io_region_end = 0;
  256. };
  257. } // namespace Kernel