vm_manager.h 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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/mmio.h"
  11. namespace Kernel {
  12. enum class VMAType : u8 {
  13. /// VMA represents an unmapped region of the address space.
  14. Free,
  15. /// VMA is backed by a ref-counted allocate memory block.
  16. AllocatedMemoryBlock,
  17. /// VMA is backed by a raw, unmanaged pointer.
  18. BackingMemory,
  19. /// VMA is mapped to MMIO registers at a fixed PAddr.
  20. MMIO,
  21. // TODO(yuriks): Implement MemoryAlias to support MAP/UNMAP
  22. };
  23. /// Permissions for mapped memory blocks
  24. enum class VMAPermission : u8 {
  25. None = 0,
  26. Read = 1,
  27. Write = 2,
  28. Execute = 4,
  29. ReadWrite = Read | Write,
  30. ReadExecute = Read | Execute,
  31. WriteExecute = Write | Execute,
  32. ReadWriteExecute = Read | Write | Execute,
  33. };
  34. /// Set of values returned in MemoryInfo.state by svcQueryMemory.
  35. enum class MemoryState : u8 {
  36. Free = 0,
  37. Reserved = 1,
  38. IO = 2,
  39. Static = 3,
  40. Code = 4,
  41. Private = 5,
  42. Shared = 6,
  43. Continuous = 7,
  44. Aliased = 8,
  45. Alias = 9,
  46. AliasCode = 10,
  47. Locked = 11,
  48. };
  49. /**
  50. * Represents a VMA in an address space. A VMA is a contiguous region of virtual addressing space
  51. * with homogeneous attributes across its extents. In this particular implementation each VMA is
  52. * also backed by a single host memory allocation.
  53. */
  54. struct VirtualMemoryArea {
  55. /// Virtual base address of the region.
  56. VAddr base = 0;
  57. /// Size of the region.
  58. u64 size = 0;
  59. VMAType type = VMAType::Free;
  60. VMAPermission permissions = VMAPermission::None;
  61. /// Tag returned by svcQueryMemory. Not otherwise used.
  62. MemoryState meminfo_state = MemoryState::Free;
  63. // Settings for type = AllocatedMemoryBlock
  64. /// Memory block backing this VMA.
  65. std::shared_ptr<std::vector<u8>> backing_block = nullptr;
  66. /// Offset into the backing_memory the mapping starts from.
  67. size_t offset = 0;
  68. // Settings for type = BackingMemory
  69. /// Pointer backing this VMA. It will not be destroyed or freed when the VMA is removed.
  70. u8* backing_memory = nullptr;
  71. // Settings for type = MMIO
  72. /// Physical address of the register area this VMA maps to.
  73. PAddr paddr = 0;
  74. Memory::MMIORegionPointer mmio_handler = nullptr;
  75. /// Tests if this area can be merged to the right with `next`.
  76. bool CanBeMergedWith(const VirtualMemoryArea& next) const;
  77. };
  78. /**
  79. * Manages a process' virtual addressing space. This class maintains a list of allocated and free
  80. * regions in the address space, along with their attributes, and allows kernel clients to
  81. * manipulate it, adjusting the page table to match.
  82. *
  83. * This is similar in idea and purpose to the VM manager present in operating system kernels, with
  84. * the main difference being that it doesn't have to support swapping or memory mapping of files.
  85. * The implementation is also simplified by not having to allocate page frames. See these articles
  86. * about the Linux kernel for an explantion of the concept and implementation:
  87. * - http://duartes.org/gustavo/blog/post/how-the-kernel-manages-your-memory/
  88. * - http://duartes.org/gustavo/blog/post/page-cache-the-affair-between-memory-and-files/
  89. */
  90. class VMManager final {
  91. // TODO(yuriks): Make page tables switchable to support multiple VMManagers
  92. public:
  93. /**
  94. * The maximum amount of address space managed by the kernel. Addresses above this are never
  95. * used.
  96. * @note This is the limit used by the New 3DS kernel. Old 3DS used 0x20000000.
  97. */
  98. static const VAddr MAX_ADDRESS = 0x8000000000;
  99. /**
  100. * A map covering the entirety of the managed address space, keyed by the `base` field of each
  101. * VMA. It must always be modified by splitting or merging VMAs, so that the invariant
  102. * `elem.base + elem.size == next.base` is preserved, and mergeable regions must always be
  103. * merged when possible so that no two similar and adjacent regions exist that have not been
  104. * merged.
  105. */
  106. std::map<VAddr, VirtualMemoryArea> vma_map;
  107. using VMAHandle = decltype(vma_map)::const_iterator;
  108. VMManager();
  109. ~VMManager();
  110. /// Clears the address space map, re-initializing with a single free area.
  111. void Reset();
  112. /// Finds the VMA in which the given address is included in, or `vma_map.end()`.
  113. VMAHandle FindVMA(VAddr target) const;
  114. // TODO(yuriks): Should these functions actually return the handle?
  115. /**
  116. * Maps part of a ref-counted block of memory at a given address.
  117. *
  118. * @param target The guest address to start the mapping at.
  119. * @param block The block to be mapped.
  120. * @param offset Offset into `block` to map from.
  121. * @param size Size of the mapping.
  122. * @param state MemoryState tag to attach to the VMA.
  123. */
  124. ResultVal<VMAHandle> MapMemoryBlock(VAddr target, std::shared_ptr<std::vector<u8>> block,
  125. size_t offset, u64 size, MemoryState state);
  126. /**
  127. * Maps an unmanaged host memory pointer at a given address.
  128. *
  129. * @param target The guest address to start the mapping at.
  130. * @param memory The memory to be mapped.
  131. * @param size Size of the mapping.
  132. * @param state MemoryState tag to attach to the VMA.
  133. */
  134. ResultVal<VMAHandle> MapBackingMemory(VAddr target, u8* memory, u64 size, MemoryState state);
  135. /**
  136. * Maps a memory-mapped IO region at a given address.
  137. *
  138. * @param target The guest address to start the mapping at.
  139. * @param paddr The physical address where the registers are present.
  140. * @param size Size of the mapping.
  141. * @param state MemoryState tag to attach to the VMA.
  142. * @param mmio_handler The handler that will implement read and write for this MMIO region.
  143. */
  144. ResultVal<VMAHandle> MapMMIO(VAddr target, PAddr paddr, u64 size, MemoryState state,
  145. Memory::MMIORegionPointer mmio_handler);
  146. /// Unmaps a range of addresses, splitting VMAs as necessary.
  147. ResultCode UnmapRange(VAddr target, u64 size);
  148. /// Changes the permissions of the given VMA.
  149. VMAHandle Reprotect(VMAHandle vma, VMAPermission new_perms);
  150. /// Changes the permissions of a range of addresses, splitting VMAs as necessary.
  151. ResultCode ReprotectRange(VAddr target, u64 size, VMAPermission new_perms);
  152. /**
  153. * Scans all VMAs and updates the page table range of any that use the given vector as backing
  154. * memory. This should be called after any operation that causes reallocation of the vector.
  155. */
  156. void RefreshMemoryBlockMappings(const std::vector<u8>* block);
  157. /// Dumps the address space layout to the log, for debugging
  158. void LogLayout(Log::Level log_level) const;
  159. private:
  160. using VMAIter = decltype(vma_map)::iterator;
  161. /// Converts a VMAHandle to a mutable VMAIter.
  162. VMAIter StripIterConstness(const VMAHandle& iter);
  163. /// Unmaps the given VMA.
  164. VMAIter Unmap(VMAIter vma);
  165. /**
  166. * Carves a VMA of a specific size at the specified address by splitting Free VMAs while doing
  167. * the appropriate error checking.
  168. */
  169. ResultVal<VMAIter> CarveVMA(VAddr base, u64 size);
  170. /**
  171. * Splits the edges of the given range of non-Free VMAs so that there is a VMA split at each
  172. * end of the range.
  173. */
  174. ResultVal<VMAIter> CarveVMARange(VAddr base, u64 size);
  175. /**
  176. * Splits a VMA in two, at the specified offset.
  177. * @returns the right side of the split, with the original iterator becoming the left side.
  178. */
  179. VMAIter SplitVMA(VMAIter vma, u64 offset_in_vma);
  180. /**
  181. * Checks for and merges the specified VMA with adjacent ones if possible.
  182. * @returns the merged VMA or the original if no merging was possible.
  183. */
  184. VMAIter MergeAdjacent(VMAIter vma);
  185. /// Updates the pages corresponding to this VMA so they match the VMA's attributes.
  186. void UpdatePageTableForVMA(const VirtualMemoryArea& vma);
  187. };
  188. }