vm_manager.h 8.4 KB

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