MemoryManager.h 11 KB

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