MemoryManager.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Concepts.h>
  8. #include <AK/HashTable.h>
  9. #include <AK/NonnullOwnPtrVector.h>
  10. #include <AK/NonnullRefPtrVector.h>
  11. #include <AK/String.h>
  12. #include <Kernel/Arch/x86/PageFault.h>
  13. #include <Kernel/Arch/x86/TrapFrame.h>
  14. #include <Kernel/Forward.h>
  15. #include <Kernel/Locking/Spinlock.h>
  16. #include <Kernel/Memory/AllocationStrategy.h>
  17. #include <Kernel/Memory/PhysicalPage.h>
  18. #include <Kernel/Memory/PhysicalRegion.h>
  19. #include <Kernel/Memory/Region.h>
  20. #include <Kernel/Memory/VMObject.h>
  21. namespace Kernel::Memory {
  22. constexpr bool page_round_up_would_wrap(FlatPtr x)
  23. {
  24. return x > (explode_byte(0xFF) & ~0xFFF);
  25. }
  26. constexpr FlatPtr page_round_up(FlatPtr x)
  27. {
  28. FlatPtr rounded = (((FlatPtr)(x)) + PAGE_SIZE - 1) & (~(PAGE_SIZE - 1));
  29. // Rounding up >0xfffff000 wraps back to 0. That's never what we want.
  30. VERIFY(x == 0 || rounded != 0);
  31. return rounded;
  32. }
  33. constexpr FlatPtr page_round_down(FlatPtr x)
  34. {
  35. return ((FlatPtr)(x)) & ~(PAGE_SIZE - 1);
  36. }
  37. inline FlatPtr virtual_to_low_physical(FlatPtr virtual_)
  38. {
  39. return virtual_ - physical_to_virtual_offset;
  40. }
  41. enum class UsedMemoryRangeType {
  42. LowMemory = 0,
  43. Prekernel,
  44. Kernel,
  45. BootModule,
  46. PhysicalPages,
  47. };
  48. static constexpr StringView UserMemoryRangeTypeNames[] {
  49. "Low memory",
  50. "Prekernel",
  51. "Kernel",
  52. "Boot module",
  53. "Physical Pages"
  54. };
  55. struct UsedMemoryRange {
  56. UsedMemoryRangeType type {};
  57. PhysicalAddress start;
  58. PhysicalAddress end;
  59. };
  60. struct ContiguousReservedMemoryRange {
  61. PhysicalAddress start;
  62. PhysicalSize length {};
  63. };
  64. enum class PhysicalMemoryRangeType {
  65. Usable = 0,
  66. Reserved,
  67. ACPI_Reclaimable,
  68. ACPI_NVS,
  69. BadMemory,
  70. Unknown,
  71. };
  72. struct PhysicalMemoryRange {
  73. PhysicalMemoryRangeType type { PhysicalMemoryRangeType::Unknown };
  74. PhysicalAddress start;
  75. PhysicalSize length {};
  76. };
  77. #define MM Kernel::Memory::MemoryManager::the()
  78. struct MemoryManagerData {
  79. static ProcessorSpecificDataID processor_specific_data_id() { return ProcessorSpecificDataID::MemoryManager; }
  80. Spinlock<u8> m_quickmap_in_use;
  81. u32 m_quickmap_prev_flags;
  82. PhysicalAddress m_last_quickmap_pd;
  83. PhysicalAddress m_last_quickmap_pt;
  84. };
  85. extern RecursiveSpinlock s_mm_lock;
  86. // This class represents a set of committed physical pages.
  87. // When you ask MemoryManager to commit pages for you, you get one of these in return.
  88. // You can allocate pages from it via `take_one()`
  89. // It will uncommit any (unallocated) remaining pages when destroyed.
  90. class CommittedPhysicalPageSet {
  91. AK_MAKE_NONCOPYABLE(CommittedPhysicalPageSet);
  92. public:
  93. CommittedPhysicalPageSet(Badge<MemoryManager>, size_t page_count)
  94. : m_page_count(page_count)
  95. {
  96. }
  97. CommittedPhysicalPageSet(CommittedPhysicalPageSet&& other)
  98. : m_page_count(exchange(other.m_page_count, 0))
  99. {
  100. }
  101. ~CommittedPhysicalPageSet();
  102. bool is_empty() const { return m_page_count == 0; }
  103. size_t page_count() const { return m_page_count; }
  104. [[nodiscard]] NonnullRefPtr<PhysicalPage> take_one();
  105. void uncommit_one();
  106. void operator=(CommittedPhysicalPageSet&&) = delete;
  107. private:
  108. size_t m_page_count { 0 };
  109. };
  110. class MemoryManager {
  111. AK_MAKE_ETERNAL
  112. friend class PageDirectory;
  113. friend class AnonymousVMObject;
  114. friend class Region;
  115. friend class VMObject;
  116. public:
  117. static MemoryManager& the();
  118. static bool is_initialized();
  119. static void initialize(u32 cpu);
  120. static inline MemoryManagerData& get_data()
  121. {
  122. return ProcessorSpecific<MemoryManagerData>::get();
  123. }
  124. PageFaultResponse handle_page_fault(PageFault const&);
  125. void set_page_writable_direct(VirtualAddress, bool);
  126. void protect_readonly_after_init_memory();
  127. void unmap_text_after_init();
  128. void unmap_ksyms_after_init();
  129. static void enter_process_paging_scope(Process&);
  130. static void enter_space(AddressSpace&);
  131. bool validate_user_stack_no_lock(AddressSpace&, VirtualAddress) const;
  132. bool validate_user_stack(AddressSpace&, VirtualAddress) const;
  133. enum class ShouldZeroFill {
  134. No,
  135. Yes
  136. };
  137. Optional<CommittedPhysicalPageSet> commit_user_physical_pages(size_t page_count);
  138. void uncommit_user_physical_pages(Badge<CommittedPhysicalPageSet>, size_t page_count);
  139. NonnullRefPtr<PhysicalPage> allocate_committed_user_physical_page(Badge<CommittedPhysicalPageSet>, ShouldZeroFill = ShouldZeroFill::Yes);
  140. RefPtr<PhysicalPage> allocate_user_physical_page(ShouldZeroFill = ShouldZeroFill::Yes, bool* did_purge = nullptr);
  141. RefPtr<PhysicalPage> allocate_supervisor_physical_page();
  142. NonnullRefPtrVector<PhysicalPage> allocate_contiguous_supervisor_physical_pages(size_t size);
  143. void deallocate_physical_page(PhysicalAddress);
  144. OwnPtr<Region> allocate_contiguous_kernel_region(size_t, StringView name, Region::Access access, Region::Cacheable = Region::Cacheable::Yes);
  145. OwnPtr<Region> allocate_kernel_region(size_t, StringView name, Region::Access access, AllocationStrategy strategy = AllocationStrategy::Reserve, Region::Cacheable = Region::Cacheable::Yes);
  146. OwnPtr<Region> allocate_kernel_region(PhysicalAddress, size_t, StringView name, Region::Access access, Region::Cacheable = Region::Cacheable::Yes);
  147. OwnPtr<Region> allocate_kernel_region_with_vmobject(VMObject&, size_t, StringView name, Region::Access access, Region::Cacheable = Region::Cacheable::Yes);
  148. OwnPtr<Region> allocate_kernel_region_with_vmobject(VirtualRange const&, VMObject&, StringView name, Region::Access access, Region::Cacheable = Region::Cacheable::Yes);
  149. struct SystemMemoryInfo {
  150. PhysicalSize user_physical_pages { 0 };
  151. PhysicalSize user_physical_pages_used { 0 };
  152. PhysicalSize user_physical_pages_committed { 0 };
  153. PhysicalSize user_physical_pages_uncommitted { 0 };
  154. PhysicalSize super_physical_pages { 0 };
  155. PhysicalSize super_physical_pages_used { 0 };
  156. };
  157. SystemMemoryInfo get_system_memory_info()
  158. {
  159. SpinlockLocker lock(s_mm_lock);
  160. return m_system_memory_info;
  161. }
  162. template<IteratorFunction<VMObject&> Callback>
  163. static void for_each_vmobject(Callback callback)
  164. {
  165. VMObject::all_instances().with([&](auto& list) {
  166. for (auto& vmobject : list) {
  167. if (callback(vmobject) == IterationDecision::Break)
  168. break;
  169. }
  170. });
  171. }
  172. template<VoidFunction<VMObject&> Callback>
  173. static void for_each_vmobject(Callback callback)
  174. {
  175. VMObject::all_instances().with([&](auto& list) {
  176. for (auto& vmobject : list) {
  177. callback(vmobject);
  178. }
  179. });
  180. }
  181. static Region* find_user_region_from_vaddr(AddressSpace&, VirtualAddress);
  182. static Region* find_user_region_from_vaddr_no_lock(AddressSpace&, VirtualAddress);
  183. static void validate_syscall_preconditions(AddressSpace&, RegisterState const&);
  184. void dump_kernel_regions();
  185. PhysicalPage& shared_zero_page() { return *m_shared_zero_page; }
  186. PhysicalPage& lazy_committed_page() { return *m_lazy_committed_page; }
  187. PageDirectory& kernel_page_directory() { return *m_kernel_page_directory; }
  188. Vector<UsedMemoryRange> const& used_memory_ranges() { return m_used_memory_ranges; }
  189. bool is_allowed_to_mmap_to_userspace(PhysicalAddress, VirtualRange const&) const;
  190. PhysicalPageEntry& get_physical_page_entry(PhysicalAddress);
  191. PhysicalAddress get_physical_address(PhysicalPage const&);
  192. private:
  193. MemoryManager();
  194. ~MemoryManager();
  195. void initialize_physical_pages();
  196. void register_reserved_ranges();
  197. void register_region(Region&);
  198. void unregister_region(Region&);
  199. void protect_kernel_image();
  200. void parse_memory_map();
  201. static void flush_tlb_local(VirtualAddress, size_t page_count = 1);
  202. static void flush_tlb(PageDirectory const*, VirtualAddress, size_t page_count = 1);
  203. static Region* kernel_region_from_vaddr(VirtualAddress);
  204. static Region* find_region_from_vaddr(VirtualAddress);
  205. RefPtr<PhysicalPage> find_free_user_physical_page(bool);
  206. ALWAYS_INLINE u8* quickmap_page(PhysicalPage& page)
  207. {
  208. return quickmap_page(page.paddr());
  209. }
  210. u8* quickmap_page(PhysicalAddress const&);
  211. void unquickmap_page();
  212. PageDirectoryEntry* quickmap_pd(PageDirectory&, size_t pdpt_index);
  213. PageTableEntry* quickmap_pt(PhysicalAddress);
  214. PageTableEntry* pte(PageDirectory&, VirtualAddress);
  215. PageTableEntry* ensure_pte(PageDirectory&, VirtualAddress);
  216. void release_pte(PageDirectory&, VirtualAddress, bool);
  217. RefPtr<PageDirectory> m_kernel_page_directory;
  218. RefPtr<PhysicalPage> m_shared_zero_page;
  219. RefPtr<PhysicalPage> m_lazy_committed_page;
  220. SystemMemoryInfo m_system_memory_info;
  221. NonnullOwnPtrVector<PhysicalRegion> m_user_physical_regions;
  222. OwnPtr<PhysicalRegion> m_super_physical_region;
  223. OwnPtr<PhysicalRegion> m_physical_pages_region;
  224. PhysicalPageEntry* m_physical_page_entries { nullptr };
  225. size_t m_physical_page_entries_count { 0 };
  226. Region::ListInMemoryManager m_kernel_regions;
  227. Vector<UsedMemoryRange> m_used_memory_ranges;
  228. Vector<PhysicalMemoryRange> m_physical_memory_ranges;
  229. Vector<ContiguousReservedMemoryRange> m_reserved_memory_ranges;
  230. };
  231. inline bool is_user_address(VirtualAddress vaddr)
  232. {
  233. return vaddr.get() < USER_RANGE_CEILING;
  234. }
  235. inline bool is_user_range(VirtualAddress vaddr, size_t size)
  236. {
  237. if (vaddr.offset(size) < vaddr)
  238. return false;
  239. return is_user_address(vaddr) && is_user_address(vaddr.offset(size));
  240. }
  241. inline bool is_user_range(VirtualRange const& range)
  242. {
  243. return is_user_range(range.base(), range.size());
  244. }
  245. inline bool PhysicalPage::is_shared_zero_page() const
  246. {
  247. return this == &MM.shared_zero_page();
  248. }
  249. inline bool PhysicalPage::is_lazy_committed_page() const
  250. {
  251. return this == &MM.lazy_committed_page();
  252. }
  253. }