MemoryManager.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 <Kernel/Forward.h>
  13. #include <Kernel/Library/NonnullLockRefPtrVector.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. struct KmallocGlobalData;
  22. namespace Kernel::Memory {
  23. class PageDirectoryEntry;
  24. class PageTableEntry;
  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"sv,
  43. "Kernel"sv,
  44. "Boot module"sv,
  45. "Physical Pages"sv
  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<LockRank::None> m_quickmap_in_use {};
  74. InterruptsState m_quickmap_previous_interrupts_state;
  75. };
  76. // This class represents a set of committed physical pages.
  77. // When you ask MemoryManager to commit pages for you, you get one of these in return.
  78. // You can allocate pages from it via `take_one()`
  79. // It will uncommit any (unallocated) remaining pages when destroyed.
  80. class CommittedPhysicalPageSet {
  81. AK_MAKE_NONCOPYABLE(CommittedPhysicalPageSet);
  82. public:
  83. CommittedPhysicalPageSet(Badge<MemoryManager>, size_t page_count)
  84. : m_page_count(page_count)
  85. {
  86. }
  87. CommittedPhysicalPageSet(CommittedPhysicalPageSet&& other)
  88. : m_page_count(exchange(other.m_page_count, 0))
  89. {
  90. }
  91. ~CommittedPhysicalPageSet();
  92. bool is_empty() const { return m_page_count == 0; }
  93. size_t page_count() const { return m_page_count; }
  94. [[nodiscard]] NonnullRefPtr<PhysicalPage> take_one();
  95. void uncommit_one();
  96. void operator=(CommittedPhysicalPageSet&&) = delete;
  97. private:
  98. size_t m_page_count { 0 };
  99. };
  100. class MemoryManager {
  101. friend class PageDirectory;
  102. friend class AnonymousVMObject;
  103. friend class Region;
  104. friend class RegionTree;
  105. friend class VMObject;
  106. friend struct ::KmallocGlobalData;
  107. public:
  108. static MemoryManager& the();
  109. static bool is_initialized();
  110. static void initialize(u32 cpu);
  111. static inline MemoryManagerData& get_data()
  112. {
  113. return ProcessorSpecific<MemoryManagerData>::get();
  114. }
  115. PageFaultResponse handle_page_fault(PageFault const&);
  116. void set_page_writable_direct(VirtualAddress, bool);
  117. void protect_readonly_after_init_memory();
  118. void unmap_prekernel();
  119. void unmap_text_after_init();
  120. void protect_ksyms_after_init();
  121. static void enter_process_address_space(Process&);
  122. static void enter_address_space(AddressSpace&);
  123. bool validate_user_stack(AddressSpace&, VirtualAddress) const;
  124. enum class ShouldZeroFill {
  125. No,
  126. Yes
  127. };
  128. ErrorOr<CommittedPhysicalPageSet> commit_physical_pages(size_t page_count);
  129. void uncommit_physical_pages(Badge<CommittedPhysicalPageSet>, size_t page_count);
  130. NonnullRefPtr<PhysicalPage> allocate_committed_physical_page(Badge<CommittedPhysicalPageSet>, ShouldZeroFill = ShouldZeroFill::Yes);
  131. ErrorOr<NonnullRefPtr<PhysicalPage>> allocate_physical_page(ShouldZeroFill = ShouldZeroFill::Yes, bool* did_purge = nullptr);
  132. ErrorOr<Vector<NonnullRefPtr<PhysicalPage>>> allocate_contiguous_physical_pages(size_t size);
  133. void deallocate_physical_page(PhysicalAddress);
  134. ErrorOr<NonnullOwnPtr<Region>> allocate_contiguous_kernel_region(size_t, StringView name, Region::Access access, Region::Cacheable = Region::Cacheable::Yes);
  135. ErrorOr<NonnullOwnPtr<Memory::Region>> allocate_dma_buffer_page(StringView name, Memory::Region::Access access, RefPtr<Memory::PhysicalPage>& dma_buffer_page);
  136. ErrorOr<NonnullOwnPtr<Memory::Region>> allocate_dma_buffer_page(StringView name, Memory::Region::Access access);
  137. ErrorOr<NonnullOwnPtr<Memory::Region>> allocate_dma_buffer_pages(size_t size, StringView name, Memory::Region::Access access, Vector<NonnullRefPtr<Memory::PhysicalPage>>& dma_buffer_pages);
  138. ErrorOr<NonnullOwnPtr<Memory::Region>> allocate_dma_buffer_pages(size_t size, StringView name, Memory::Region::Access access);
  139. ErrorOr<NonnullOwnPtr<Region>> allocate_kernel_region(size_t, StringView name, Region::Access access, AllocationStrategy strategy = AllocationStrategy::Reserve, Region::Cacheable = Region::Cacheable::Yes);
  140. ErrorOr<NonnullOwnPtr<Region>> allocate_kernel_region(PhysicalAddress, size_t, StringView name, Region::Access access, Region::Cacheable = Region::Cacheable::Yes);
  141. ErrorOr<NonnullOwnPtr<Region>> allocate_kernel_region_with_vmobject(VMObject&, size_t, StringView name, Region::Access access, Region::Cacheable = Region::Cacheable::Yes);
  142. ErrorOr<NonnullOwnPtr<Region>> allocate_unbacked_region_anywhere(size_t size, size_t alignment);
  143. ErrorOr<NonnullOwnPtr<Region>> create_identity_mapped_region(PhysicalAddress, size_t);
  144. struct SystemMemoryInfo {
  145. PhysicalSize physical_pages { 0 };
  146. PhysicalSize physical_pages_used { 0 };
  147. PhysicalSize physical_pages_committed { 0 };
  148. PhysicalSize physical_pages_uncommitted { 0 };
  149. };
  150. SystemMemoryInfo get_system_memory_info();
  151. template<IteratorFunction<VMObject&> Callback>
  152. static void for_each_vmobject(Callback callback)
  153. {
  154. VMObject::all_instances().with([&](auto& list) {
  155. for (auto& vmobject : list) {
  156. if (callback(vmobject) == IterationDecision::Break)
  157. break;
  158. }
  159. });
  160. }
  161. template<VoidFunction<VMObject&> Callback>
  162. static void for_each_vmobject(Callback callback)
  163. {
  164. VMObject::all_instances().with([&](auto& list) {
  165. for (auto& vmobject : list) {
  166. callback(vmobject);
  167. }
  168. });
  169. }
  170. static Region* find_user_region_from_vaddr(AddressSpace&, VirtualAddress);
  171. static void validate_syscall_preconditions(Process&, RegisterState const&);
  172. void dump_kernel_regions();
  173. PhysicalPage& shared_zero_page() { return *m_shared_zero_page; }
  174. PhysicalPage& lazy_committed_page() { return *m_lazy_committed_page; }
  175. PageDirectory& kernel_page_directory() { return *m_kernel_page_directory; }
  176. template<typename Callback>
  177. void for_each_used_memory_range(Callback callback)
  178. {
  179. m_global_data.template with([&](auto& global_data) {
  180. for (auto& range : global_data.used_memory_ranges)
  181. callback(range);
  182. });
  183. }
  184. bool is_allowed_to_read_physical_memory_for_userspace(PhysicalAddress, size_t read_length) 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 unregister_kernel_region(Region&);
  195. void protect_kernel_image();
  196. void parse_memory_map();
  197. static void flush_tlb_local(VirtualAddress, size_t page_count = 1);
  198. static void flush_tlb(PageDirectory const*, VirtualAddress, size_t page_count = 1);
  199. static Region* kernel_region_from_vaddr(VirtualAddress);
  200. static Region* find_region_from_vaddr(VirtualAddress);
  201. RefPtr<PhysicalPage> find_free_physical_page(bool);
  202. ALWAYS_INLINE u8* quickmap_page(PhysicalPage& page)
  203. {
  204. return quickmap_page(page.paddr());
  205. }
  206. u8* quickmap_page(PhysicalAddress const&);
  207. void unquickmap_page();
  208. PageDirectoryEntry* quickmap_pd(PageDirectory&, size_t pdpt_index);
  209. PageTableEntry* quickmap_pt(PhysicalAddress);
  210. PageTableEntry* pte(PageDirectory&, VirtualAddress);
  211. PageTableEntry* ensure_pte(PageDirectory&, VirtualAddress);
  212. enum class IsLastPTERelease {
  213. Yes,
  214. No
  215. };
  216. void release_pte(PageDirectory&, VirtualAddress, IsLastPTERelease);
  217. // NOTE: These are outside of GlobalData as they are only assigned on startup,
  218. // and then never change. Atomic ref-counting covers that case without
  219. // the need for additional synchronization.
  220. LockRefPtr<PageDirectory> m_kernel_page_directory;
  221. RefPtr<PhysicalPage> m_shared_zero_page;
  222. RefPtr<PhysicalPage> m_lazy_committed_page;
  223. // NOTE: These are outside of GlobalData as they are initialized on startup,
  224. // and then never change.
  225. PhysicalPageEntry* m_physical_page_entries { nullptr };
  226. size_t m_physical_page_entries_count { 0 };
  227. struct GlobalData {
  228. GlobalData();
  229. SystemMemoryInfo system_memory_info;
  230. Vector<NonnullOwnPtr<PhysicalRegion>> physical_regions;
  231. OwnPtr<PhysicalRegion> physical_pages_region;
  232. RegionTree region_tree;
  233. Vector<UsedMemoryRange> used_memory_ranges;
  234. Vector<PhysicalMemoryRange> physical_memory_ranges;
  235. Vector<ContiguousReservedMemoryRange> reserved_memory_ranges;
  236. };
  237. SpinlockProtected<GlobalData, LockRank::None> m_global_data;
  238. };
  239. inline bool is_user_address(VirtualAddress vaddr)
  240. {
  241. return vaddr.get() < USER_RANGE_CEILING;
  242. }
  243. inline bool is_user_range(VirtualAddress vaddr, size_t size)
  244. {
  245. if (vaddr.offset(size) < vaddr)
  246. return false;
  247. if (!is_user_address(vaddr))
  248. return false;
  249. if (size <= 1)
  250. return true;
  251. return is_user_address(vaddr.offset(size - 1));
  252. }
  253. inline bool is_user_range(VirtualRange const& range)
  254. {
  255. return is_user_range(range.base(), range.size());
  256. }
  257. inline bool PhysicalPage::is_shared_zero_page() const
  258. {
  259. return this == &MM.shared_zero_page();
  260. }
  261. inline bool PhysicalPage::is_lazy_committed_page() const
  262. {
  263. return this == &MM.lazy_committed_page();
  264. }
  265. inline ErrorOr<Memory::VirtualRange> expand_range_to_page_boundaries(FlatPtr address, size_t size)
  266. {
  267. if ((address + size) < address)
  268. return EINVAL;
  269. auto base = VirtualAddress { address }.page_base();
  270. auto end = TRY(Memory::page_round_up(address + size));
  271. return Memory::VirtualRange { base, end - base.get() };
  272. }
  273. }