MemoryManager.h 11 KB

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