MemoryManager.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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/VMObject.h>
  20. namespace Kernel {
  21. class PageDirectoryEntry;
  22. }
  23. struct KmallocGlobalData;
  24. namespace Kernel::Memory {
  25. ErrorOr<FlatPtr> page_round_up(FlatPtr x);
  26. constexpr FlatPtr page_round_down(FlatPtr x)
  27. {
  28. return ((FlatPtr)(x)) & ~(PAGE_SIZE - 1);
  29. }
  30. inline FlatPtr virtual_to_low_physical(FlatPtr virtual_)
  31. {
  32. return virtual_ - physical_to_virtual_offset;
  33. }
  34. enum class UsedMemoryRangeType {
  35. LowMemory = 0,
  36. Kernel,
  37. BootModule,
  38. PhysicalPages,
  39. __Count
  40. };
  41. static constexpr StringView UserMemoryRangeTypeNames[] {
  42. "Low memory",
  43. "Kernel",
  44. "Boot module",
  45. "Physical Pages"
  46. };
  47. static_assert(array_size(UserMemoryRangeTypeNames) == to_underlying(UsedMemoryRangeType::__Count));
  48. struct UsedMemoryRange {
  49. UsedMemoryRangeType type {};
  50. PhysicalAddress start;
  51. PhysicalAddress end;
  52. };
  53. struct ContiguousReservedMemoryRange {
  54. PhysicalAddress start;
  55. PhysicalSize length {};
  56. };
  57. enum class PhysicalMemoryRangeType {
  58. Usable = 0,
  59. Reserved,
  60. ACPI_Reclaimable,
  61. ACPI_NVS,
  62. BadMemory,
  63. Unknown,
  64. };
  65. struct PhysicalMemoryRange {
  66. PhysicalMemoryRangeType type { PhysicalMemoryRangeType::Unknown };
  67. PhysicalAddress start;
  68. PhysicalSize length {};
  69. };
  70. #define MM Kernel::Memory::MemoryManager::the()
  71. struct MemoryManagerData {
  72. static ProcessorSpecificDataID processor_specific_data_id() { return ProcessorSpecificDataID::MemoryManager; }
  73. Spinlock m_quickmap_in_use;
  74. u32 m_quickmap_prev_flags;
  75. PhysicalAddress m_last_quickmap_pd;
  76. PhysicalAddress m_last_quickmap_pt;
  77. };
  78. // NOLINTNEXTLINE(readability-redundant-declaration) FIXME: Why do we declare this here *and* in Thread.h?
  79. extern RecursiveSpinlock s_mm_lock;
  80. // This class represents a set of committed physical pages.
  81. // When you ask MemoryManager to commit pages for you, you get one of these in return.
  82. // You can allocate pages from it via `take_one()`
  83. // It will uncommit any (unallocated) remaining pages when destroyed.
  84. class CommittedPhysicalPageSet {
  85. AK_MAKE_NONCOPYABLE(CommittedPhysicalPageSet);
  86. public:
  87. CommittedPhysicalPageSet(Badge<MemoryManager>, size_t page_count)
  88. : m_page_count(page_count)
  89. {
  90. }
  91. CommittedPhysicalPageSet(CommittedPhysicalPageSet&& other)
  92. : m_page_count(exchange(other.m_page_count, 0))
  93. {
  94. }
  95. ~CommittedPhysicalPageSet();
  96. bool is_empty() const { return m_page_count == 0; }
  97. size_t page_count() const { return m_page_count; }
  98. [[nodiscard]] NonnullRefPtr<PhysicalPage> take_one();
  99. void uncommit_one();
  100. void operator=(CommittedPhysicalPageSet&&) = delete;
  101. private:
  102. size_t m_page_count { 0 };
  103. };
  104. class MemoryManager {
  105. friend class PageDirectory;
  106. friend class AnonymousVMObject;
  107. friend class Region;
  108. friend class VMObject;
  109. friend struct ::KmallocGlobalData;
  110. public:
  111. static MemoryManager& the();
  112. static bool is_initialized();
  113. static void initialize(u32 cpu);
  114. static inline MemoryManagerData& get_data()
  115. {
  116. return ProcessorSpecific<MemoryManagerData>::get();
  117. }
  118. PageFaultResponse handle_page_fault(PageFault const&);
  119. void set_page_writable_direct(VirtualAddress, bool);
  120. void protect_readonly_after_init_memory();
  121. void unmap_prekernel();
  122. void unmap_text_after_init();
  123. void protect_ksyms_after_init();
  124. static void enter_process_address_space(Process&);
  125. static void enter_address_space(AddressSpace&);
  126. bool validate_user_stack_no_lock(AddressSpace&, VirtualAddress) const;
  127. bool validate_user_stack(AddressSpace&, VirtualAddress) const;
  128. enum class ShouldZeroFill {
  129. No,
  130. Yes
  131. };
  132. ErrorOr<CommittedPhysicalPageSet> commit_user_physical_pages(size_t page_count);
  133. void uncommit_user_physical_pages(Badge<CommittedPhysicalPageSet>, size_t page_count);
  134. NonnullRefPtr<PhysicalPage> allocate_committed_user_physical_page(Badge<CommittedPhysicalPageSet>, ShouldZeroFill = ShouldZeroFill::Yes);
  135. RefPtr<PhysicalPage> allocate_user_physical_page(ShouldZeroFill = ShouldZeroFill::Yes, bool* did_purge = nullptr);
  136. RefPtr<PhysicalPage> allocate_supervisor_physical_page();
  137. NonnullRefPtrVector<PhysicalPage> allocate_contiguous_supervisor_physical_pages(size_t size);
  138. void deallocate_physical_page(PhysicalAddress);
  139. ErrorOr<NonnullOwnPtr<Region>> allocate_contiguous_kernel_region(size_t, StringView name, Region::Access access, Region::Cacheable = Region::Cacheable::Yes);
  140. ErrorOr<NonnullOwnPtr<Memory::Region>> allocate_dma_buffer_page(StringView name, Memory::Region::Access access, RefPtr<Memory::PhysicalPage>& dma_buffer_page);
  141. ErrorOr<NonnullOwnPtr<Memory::Region>> allocate_dma_buffer_page(StringView name, Memory::Region::Access access);
  142. ErrorOr<NonnullOwnPtr<Memory::Region>> allocate_dma_buffer_pages(size_t size, StringView name, Memory::Region::Access access, NonnullRefPtrVector<Memory::PhysicalPage>& dma_buffer_pages);
  143. ErrorOr<NonnullOwnPtr<Memory::Region>> allocate_dma_buffer_pages(size_t size, StringView name, Memory::Region::Access access);
  144. ErrorOr<NonnullOwnPtr<Region>> allocate_kernel_region(size_t, StringView name, Region::Access access, AllocationStrategy strategy = AllocationStrategy::Reserve, Region::Cacheable = Region::Cacheable::Yes);
  145. ErrorOr<NonnullOwnPtr<Region>> allocate_kernel_region(PhysicalAddress, size_t, StringView name, Region::Access access, Region::Cacheable = Region::Cacheable::Yes);
  146. ErrorOr<NonnullOwnPtr<Region>> allocate_kernel_region_with_vmobject(VMObject&, size_t, StringView name, Region::Access access, Region::Cacheable = Region::Cacheable::Yes);
  147. ErrorOr<NonnullOwnPtr<Region>> allocate_kernel_region_with_vmobject(VirtualRange const&, VMObject&, StringView name, Region::Access access, Region::Cacheable = Region::Cacheable::Yes);
  148. struct SystemMemoryInfo {
  149. PhysicalSize user_physical_pages { 0 };
  150. PhysicalSize user_physical_pages_used { 0 };
  151. PhysicalSize user_physical_pages_committed { 0 };
  152. PhysicalSize user_physical_pages_uncommitted { 0 };
  153. PhysicalSize super_physical_pages { 0 };
  154. PhysicalSize super_physical_pages_used { 0 };
  155. };
  156. SystemMemoryInfo get_system_memory_info()
  157. {
  158. SpinlockLocker lock(s_mm_lock);
  159. return m_system_memory_info;
  160. }
  161. template<IteratorFunction<VMObject&> Callback>
  162. static void for_each_vmobject(Callback callback)
  163. {
  164. VMObject::all_instances().with([&](auto& list) {
  165. for (auto& vmobject : list) {
  166. if (callback(vmobject) == IterationDecision::Break)
  167. break;
  168. }
  169. });
  170. }
  171. template<VoidFunction<VMObject&> Callback>
  172. static void for_each_vmobject(Callback callback)
  173. {
  174. VMObject::all_instances().with([&](auto& list) {
  175. for (auto& vmobject : list) {
  176. callback(vmobject);
  177. }
  178. });
  179. }
  180. static Region* find_user_region_from_vaddr(AddressSpace&, VirtualAddress);
  181. static Region* find_user_region_from_vaddr_no_lock(AddressSpace&, VirtualAddress);
  182. static void validate_syscall_preconditions(AddressSpace&, RegisterState const&);
  183. void dump_kernel_regions();
  184. PhysicalPage& shared_zero_page() { return *m_shared_zero_page; }
  185. PhysicalPage& lazy_committed_page() { return *m_lazy_committed_page; }
  186. PageDirectory& kernel_page_directory() { return *m_kernel_page_directory; }
  187. Vector<UsedMemoryRange> const& used_memory_ranges() { return m_used_memory_ranges; }
  188. bool is_allowed_to_read_physical_memory_for_userspace(PhysicalAddress, size_t read_length) const;
  189. PhysicalPageEntry& get_physical_page_entry(PhysicalAddress);
  190. PhysicalAddress get_physical_address(PhysicalPage const&);
  191. void copy_physical_page(PhysicalPage&, u8 page_buffer[PAGE_SIZE]);
  192. IterationDecision for_each_physical_memory_range(Function<IterationDecision(PhysicalMemoryRange const&)>);
  193. private:
  194. MemoryManager();
  195. ~MemoryManager();
  196. void initialize_physical_pages();
  197. void register_reserved_ranges();
  198. void register_kernel_region(Region&);
  199. void unregister_kernel_region(Region&);
  200. void protect_kernel_image();
  201. void parse_memory_map();
  202. static void flush_tlb_local(VirtualAddress, size_t page_count = 1);
  203. static void flush_tlb(PageDirectory const*, VirtualAddress, size_t page_count = 1);
  204. static Region* kernel_region_from_vaddr(VirtualAddress);
  205. static Region* find_region_from_vaddr(VirtualAddress);
  206. RefPtr<PhysicalPage> find_free_user_physical_page(bool);
  207. ALWAYS_INLINE u8* quickmap_page(PhysicalPage& page)
  208. {
  209. return quickmap_page(page.paddr());
  210. }
  211. u8* quickmap_page(PhysicalAddress const&);
  212. void unquickmap_page();
  213. PageDirectoryEntry* quickmap_pd(PageDirectory&, size_t pdpt_index);
  214. PageTableEntry* quickmap_pt(PhysicalAddress);
  215. PageTableEntry* pte(PageDirectory&, VirtualAddress);
  216. PageTableEntry* ensure_pte(PageDirectory&, VirtualAddress);
  217. enum class IsLastPTERelease {
  218. Yes,
  219. No
  220. };
  221. void release_pte(PageDirectory&, VirtualAddress, IsLastPTERelease);
  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. IntrusiveRedBlackTree<&Region::m_tree_node> 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. inline ErrorOr<Memory::VirtualRange> expand_range_to_page_boundaries(FlatPtr address, size_t size)
  263. {
  264. if ((address + size) < address)
  265. return EINVAL;
  266. auto base = VirtualAddress { address }.page_base();
  267. auto end = TRY(Memory::page_round_up(address + size));
  268. return Memory::VirtualRange { base, end - base.get() };
  269. }
  270. }