MemoryManager.h 10 KB

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