kmalloc.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/Types.h>
  8. #include <Kernel/Debug.h>
  9. #include <Kernel/Heap/Heap.h>
  10. #include <Kernel/Heap/kmalloc.h>
  11. #include <Kernel/KSyms.h>
  12. #include <Kernel/Locking/Spinlock.h>
  13. #include <Kernel/Memory/MemoryManager.h>
  14. #include <Kernel/Panic.h>
  15. #include <Kernel/PerformanceManager.h>
  16. #include <Kernel/Sections.h>
  17. #include <Kernel/StdLib.h>
  18. #if ARCH(I386)
  19. static constexpr size_t CHUNK_SIZE = 32;
  20. #else
  21. static constexpr size_t CHUNK_SIZE = 64;
  22. #endif
  23. static constexpr size_t INITIAL_KMALLOC_MEMORY_SIZE = 2 * MiB;
  24. // Treat the heap as logically separate from .bss
  25. __attribute__((section(".heap"))) static u8 initial_kmalloc_memory[INITIAL_KMALLOC_MEMORY_SIZE];
  26. namespace std {
  27. const nothrow_t nothrow;
  28. }
  29. static RecursiveSpinlock s_lock; // needs to be recursive because of dump_backtrace()
  30. struct KmallocSubheap {
  31. KmallocSubheap(u8* base, size_t size)
  32. : allocator(base, size)
  33. {
  34. }
  35. IntrusiveListNode<KmallocSubheap> list_node;
  36. using List = IntrusiveList<&KmallocSubheap::list_node>;
  37. Heap<CHUNK_SIZE, KMALLOC_SCRUB_BYTE, KFREE_SCRUB_BYTE> allocator;
  38. };
  39. class KmallocSlabBlock {
  40. public:
  41. static constexpr size_t block_size = 64 * KiB;
  42. static constexpr FlatPtr block_mask = ~(block_size - 1);
  43. KmallocSlabBlock(size_t slab_size)
  44. : m_slab_size(slab_size)
  45. , m_slab_count((block_size - sizeof(KmallocSlabBlock)) / slab_size)
  46. {
  47. for (size_t i = 0; i < m_slab_count; ++i) {
  48. auto* freelist_entry = (FreelistEntry*)(void*)(&m_data[i * slab_size]);
  49. freelist_entry->next = m_freelist;
  50. m_freelist = freelist_entry;
  51. }
  52. }
  53. void* allocate()
  54. {
  55. VERIFY(m_freelist);
  56. ++m_allocated_slabs;
  57. return exchange(m_freelist, m_freelist->next);
  58. }
  59. void deallocate(void* ptr)
  60. {
  61. VERIFY(ptr >= &m_data && ptr < ((u8*)this + block_size));
  62. --m_allocated_slabs;
  63. auto* freelist_entry = (FreelistEntry*)ptr;
  64. freelist_entry->next = m_freelist;
  65. m_freelist = freelist_entry;
  66. }
  67. bool is_full() const
  68. {
  69. return m_freelist == nullptr;
  70. }
  71. size_t allocated_bytes() const
  72. {
  73. return m_allocated_slabs * m_slab_size;
  74. }
  75. size_t free_bytes() const
  76. {
  77. return (m_slab_count - m_allocated_slabs) * m_slab_size;
  78. }
  79. IntrusiveListNode<KmallocSlabBlock> list_node;
  80. using List = IntrusiveList<&KmallocSlabBlock::list_node>;
  81. private:
  82. struct FreelistEntry {
  83. FreelistEntry* next;
  84. };
  85. FreelistEntry* m_freelist { nullptr };
  86. size_t m_slab_size { 0 };
  87. size_t m_slab_count { 0 };
  88. size_t m_allocated_slabs { 0 };
  89. [[gnu::aligned(16)]] u8 m_data[];
  90. };
  91. class KmallocSlabheap {
  92. public:
  93. KmallocSlabheap(size_t slab_size)
  94. : m_slab_size(slab_size)
  95. {
  96. }
  97. size_t slab_size() const { return m_slab_size; }
  98. void* allocate()
  99. {
  100. if (m_usable_blocks.is_empty()) {
  101. // FIXME: This allocation wastes `block_size` bytes due to the implementation of kmalloc_aligned().
  102. // Handle this with a custom VM+page allocator instead of using kmalloc_aligned().
  103. auto* slot = kmalloc_aligned(KmallocSlabBlock::block_size, KmallocSlabBlock::block_size);
  104. if (!slot) {
  105. // FIXME: Dare to return nullptr!
  106. PANIC("OOM while growing slabheap ({})", m_slab_size);
  107. }
  108. auto* block = new (slot) KmallocSlabBlock(m_slab_size);
  109. m_usable_blocks.append(*block);
  110. }
  111. auto* block = m_usable_blocks.first();
  112. auto* ptr = block->allocate();
  113. if (block->is_full())
  114. m_full_blocks.append(*block);
  115. memset(ptr, KMALLOC_SCRUB_BYTE, m_slab_size);
  116. return ptr;
  117. }
  118. void deallocate(void* ptr)
  119. {
  120. memset(ptr, KFREE_SCRUB_BYTE, m_slab_size);
  121. auto* block = (KmallocSlabBlock*)((FlatPtr)ptr & KmallocSlabBlock::block_mask);
  122. bool block_was_full = block->is_full();
  123. block->deallocate(ptr);
  124. if (block_was_full)
  125. m_usable_blocks.append(*block);
  126. }
  127. size_t allocated_bytes() const
  128. {
  129. size_t total = m_full_blocks.size_slow() * KmallocSlabBlock::block_size;
  130. for (auto const& slab_block : m_usable_blocks)
  131. total += slab_block.allocated_bytes();
  132. return total;
  133. }
  134. size_t free_bytes() const
  135. {
  136. size_t total = 0;
  137. for (auto const& slab_block : m_usable_blocks)
  138. total += slab_block.free_bytes();
  139. return total;
  140. }
  141. private:
  142. size_t m_slab_size { 0 };
  143. KmallocSlabBlock::List m_usable_blocks;
  144. KmallocSlabBlock::List m_full_blocks;
  145. };
  146. struct KmallocGlobalData {
  147. static constexpr size_t minimum_subheap_size = 1 * MiB;
  148. KmallocGlobalData(u8* initial_heap, size_t initial_heap_size)
  149. {
  150. add_subheap(initial_heap, initial_heap_size);
  151. }
  152. void add_subheap(u8* storage, size_t storage_size)
  153. {
  154. dbgln("Adding kmalloc subheap @ {} with size {}", storage, storage_size);
  155. static_assert(sizeof(KmallocSubheap) <= PAGE_SIZE);
  156. auto* subheap = new (storage) KmallocSubheap(storage + PAGE_SIZE, storage_size - PAGE_SIZE);
  157. subheaps.append(*subheap);
  158. }
  159. void* allocate(size_t size)
  160. {
  161. VERIFY(!expansion_in_progress);
  162. for (auto& slabheap : slabheaps) {
  163. if (size <= slabheap.slab_size())
  164. return slabheap.allocate();
  165. }
  166. for (auto& subheap : subheaps) {
  167. if (auto* ptr = subheap.allocator.allocate(size))
  168. return ptr;
  169. }
  170. if (!try_expand(size)) {
  171. PANIC("OOM when trying to expand kmalloc heap.");
  172. }
  173. return allocate(size);
  174. }
  175. void deallocate(void* ptr, size_t size)
  176. {
  177. VERIFY(!expansion_in_progress);
  178. VERIFY(is_valid_kmalloc_address(VirtualAddress { ptr }));
  179. for (auto& slabheap : slabheaps) {
  180. if (size <= slabheap.slab_size())
  181. return slabheap.deallocate(ptr);
  182. }
  183. for (auto& subheap : subheaps) {
  184. if (subheap.allocator.contains(ptr)) {
  185. subheap.allocator.deallocate(ptr);
  186. return;
  187. }
  188. }
  189. PANIC("Bogus pointer passed to kfree_sized({:p}, {})", ptr, size);
  190. }
  191. size_t allocated_bytes() const
  192. {
  193. size_t total = 0;
  194. for (auto const& subheap : subheaps)
  195. total += subheap.allocator.allocated_bytes();
  196. for (auto const& slabheap : slabheaps)
  197. total += slabheap.allocated_bytes();
  198. return total;
  199. }
  200. size_t free_bytes() const
  201. {
  202. size_t total = 0;
  203. for (auto const& subheap : subheaps)
  204. total += subheap.allocator.free_bytes();
  205. for (auto const& slabheap : slabheaps)
  206. total += slabheap.free_bytes();
  207. return total;
  208. }
  209. bool try_expand(size_t allocation_request)
  210. {
  211. VERIFY(!expansion_in_progress);
  212. TemporaryChange change(expansion_in_progress, true);
  213. auto new_subheap_base = expansion_data->next_virtual_address;
  214. Checked<size_t> padded_allocation_request = allocation_request;
  215. padded_allocation_request *= 2;
  216. padded_allocation_request += PAGE_SIZE;
  217. if (padded_allocation_request.has_overflow()) {
  218. PANIC("Integer overflow during kmalloc heap expansion");
  219. }
  220. auto rounded_allocation_request = Memory::page_round_up(padded_allocation_request.value());
  221. if (rounded_allocation_request.is_error()) {
  222. PANIC("Integer overflow computing pages for kmalloc heap expansion");
  223. }
  224. size_t new_subheap_size = max(minimum_subheap_size, rounded_allocation_request.value());
  225. dbgln("Unable to allocate {}, expanding kmalloc heap", allocation_request);
  226. if (!expansion_data->virtual_range.contains(new_subheap_base, new_subheap_size)) {
  227. // FIXME: Dare to return false and allow kmalloc() to fail!
  228. PANIC("Out of address space when expanding kmalloc heap.");
  229. }
  230. auto physical_pages_or_error = MM.commit_user_physical_pages(new_subheap_size / PAGE_SIZE);
  231. if (physical_pages_or_error.is_error()) {
  232. // FIXME: Dare to return false!
  233. PANIC("Out of physical pages when expanding kmalloc heap.");
  234. }
  235. auto physical_pages = physical_pages_or_error.release_value();
  236. expansion_data->next_virtual_address = expansion_data->next_virtual_address.offset(new_subheap_size);
  237. auto cpu_supports_nx = Processor::current().has_feature(CPUFeature::NX);
  238. SpinlockLocker mm_locker(Memory::s_mm_lock);
  239. SpinlockLocker pd_locker(MM.kernel_page_directory().get_lock());
  240. for (auto vaddr = new_subheap_base; !physical_pages.is_empty(); vaddr = vaddr.offset(PAGE_SIZE)) {
  241. // FIXME: We currently leak physical memory when mapping it into the kmalloc heap.
  242. auto& page = physical_pages.take_one().leak_ref();
  243. auto* pte = MM.pte(MM.kernel_page_directory(), vaddr);
  244. VERIFY(pte);
  245. pte->set_physical_page_base(page.paddr().get());
  246. pte->set_global(true);
  247. pte->set_user_allowed(false);
  248. pte->set_writable(true);
  249. if (cpu_supports_nx)
  250. pte->set_execute_disabled(true);
  251. pte->set_present(true);
  252. }
  253. add_subheap(new_subheap_base.as_ptr(), new_subheap_size);
  254. return true;
  255. }
  256. void enable_expansion()
  257. {
  258. // FIXME: This range can be much bigger on 64-bit, but we need to figure something out for 32-bit.
  259. auto virtual_range = MM.kernel_page_directory().range_allocator().try_allocate_anywhere(64 * MiB, 1 * MiB);
  260. expansion_data = KmallocGlobalData::ExpansionData {
  261. .virtual_range = virtual_range.value(),
  262. .next_virtual_address = virtual_range.value().base(),
  263. };
  264. // Make sure the entire kmalloc VM range is backed by page tables.
  265. // This avoids having to deal with lazy page table allocation during heap expansion.
  266. SpinlockLocker mm_locker(Memory::s_mm_lock);
  267. SpinlockLocker pd_locker(MM.kernel_page_directory().get_lock());
  268. for (auto vaddr = virtual_range.value().base(); vaddr < virtual_range.value().end(); vaddr = vaddr.offset(PAGE_SIZE)) {
  269. MM.ensure_pte(MM.kernel_page_directory(), vaddr);
  270. }
  271. }
  272. struct ExpansionData {
  273. Memory::VirtualRange virtual_range;
  274. VirtualAddress next_virtual_address;
  275. };
  276. Optional<ExpansionData> expansion_data;
  277. bool is_valid_kmalloc_address(VirtualAddress vaddr) const
  278. {
  279. if (vaddr.as_ptr() >= initial_kmalloc_memory && vaddr.as_ptr() < (initial_kmalloc_memory + INITIAL_KMALLOC_MEMORY_SIZE))
  280. return true;
  281. if (!expansion_data.has_value())
  282. return false;
  283. return expansion_data->virtual_range.contains(vaddr);
  284. }
  285. KmallocSubheap::List subheaps;
  286. KmallocSlabheap slabheaps[6] = { 16, 32, 64, 128, 256, 512 };
  287. bool expansion_in_progress { false };
  288. };
  289. READONLY_AFTER_INIT static KmallocGlobalData* g_kmalloc_global;
  290. alignas(KmallocGlobalData) static u8 g_kmalloc_global_heap[sizeof(KmallocGlobalData)];
  291. static size_t g_kmalloc_call_count;
  292. static size_t g_kfree_call_count;
  293. static size_t g_nested_kfree_calls;
  294. bool g_dump_kmalloc_stacks;
  295. void kmalloc_enable_expand()
  296. {
  297. g_kmalloc_global->enable_expansion();
  298. }
  299. static inline void kmalloc_verify_nospinlock_held()
  300. {
  301. // Catch bad callers allocating under spinlock.
  302. if constexpr (KMALLOC_VERIFY_NO_SPINLOCK_HELD) {
  303. VERIFY(!Processor::in_critical());
  304. }
  305. }
  306. UNMAP_AFTER_INIT void kmalloc_init()
  307. {
  308. // Zero out heap since it's placed after end_of_kernel_bss.
  309. memset(initial_kmalloc_memory, 0, sizeof(initial_kmalloc_memory));
  310. g_kmalloc_global = new (g_kmalloc_global_heap) KmallocGlobalData(initial_kmalloc_memory, sizeof(initial_kmalloc_memory));
  311. s_lock.initialize();
  312. }
  313. void* kmalloc(size_t size)
  314. {
  315. kmalloc_verify_nospinlock_held();
  316. SpinlockLocker lock(s_lock);
  317. ++g_kmalloc_call_count;
  318. if (g_dump_kmalloc_stacks && Kernel::g_kernel_symbols_available) {
  319. dbgln("kmalloc({})", size);
  320. Kernel::dump_backtrace();
  321. }
  322. void* ptr = g_kmalloc_global->allocate(size);
  323. Thread* current_thread = Thread::current();
  324. if (!current_thread)
  325. current_thread = Processor::idle_thread();
  326. if (current_thread) {
  327. // FIXME: By the time we check this, we have already allocated above.
  328. // This means that in the case of an infinite recursion, we can't catch it this way.
  329. VERIFY(current_thread->is_allocation_enabled());
  330. PerformanceManager::add_kmalloc_perf_event(*current_thread, size, (FlatPtr)ptr);
  331. }
  332. return ptr;
  333. }
  334. void kfree_sized(void* ptr, size_t size)
  335. {
  336. if (!ptr)
  337. return;
  338. VERIFY(size > 0);
  339. kmalloc_verify_nospinlock_held();
  340. SpinlockLocker lock(s_lock);
  341. ++g_kfree_call_count;
  342. ++g_nested_kfree_calls;
  343. if (g_nested_kfree_calls == 1) {
  344. Thread* current_thread = Thread::current();
  345. if (!current_thread)
  346. current_thread = Processor::idle_thread();
  347. if (current_thread) {
  348. VERIFY(current_thread->is_allocation_enabled());
  349. PerformanceManager::add_kfree_perf_event(*current_thread, 0, (FlatPtr)ptr);
  350. }
  351. }
  352. g_kmalloc_global->deallocate(ptr, size);
  353. --g_nested_kfree_calls;
  354. }
  355. size_t kmalloc_good_size(size_t size)
  356. {
  357. return size;
  358. }
  359. void* kmalloc_aligned(size_t size, size_t alignment)
  360. {
  361. Checked<size_t> real_allocation_size = size;
  362. real_allocation_size += alignment;
  363. real_allocation_size += sizeof(ptrdiff_t) + sizeof(size_t);
  364. void* ptr = kmalloc(real_allocation_size.value());
  365. if (ptr == nullptr)
  366. return nullptr;
  367. size_t max_addr = (size_t)ptr + alignment;
  368. void* aligned_ptr = (void*)(max_addr - (max_addr % alignment));
  369. ((ptrdiff_t*)aligned_ptr)[-1] = (ptrdiff_t)((u8*)aligned_ptr - (u8*)ptr);
  370. ((size_t*)aligned_ptr)[-2] = real_allocation_size.value();
  371. return aligned_ptr;
  372. }
  373. void* operator new(size_t size)
  374. {
  375. void* ptr = kmalloc(size);
  376. VERIFY(ptr);
  377. return ptr;
  378. }
  379. void* operator new(size_t size, const std::nothrow_t&) noexcept
  380. {
  381. return kmalloc(size);
  382. }
  383. void* operator new(size_t size, std::align_val_t al)
  384. {
  385. void* ptr = kmalloc_aligned(size, (size_t)al);
  386. VERIFY(ptr);
  387. return ptr;
  388. }
  389. void* operator new(size_t size, std::align_val_t al, const std::nothrow_t&) noexcept
  390. {
  391. return kmalloc_aligned(size, (size_t)al);
  392. }
  393. void* operator new[](size_t size)
  394. {
  395. void* ptr = kmalloc(size);
  396. VERIFY(ptr);
  397. return ptr;
  398. }
  399. void* operator new[](size_t size, const std::nothrow_t&) noexcept
  400. {
  401. return kmalloc(size);
  402. }
  403. void operator delete(void*) noexcept
  404. {
  405. // All deletes in kernel code should have a known size.
  406. VERIFY_NOT_REACHED();
  407. }
  408. void operator delete(void* ptr, size_t size) noexcept
  409. {
  410. return kfree_sized(ptr, size);
  411. }
  412. void operator delete(void* ptr, size_t, std::align_val_t) noexcept
  413. {
  414. return kfree_aligned(ptr);
  415. }
  416. void operator delete[](void*) noexcept
  417. {
  418. // All deletes in kernel code should have a known size.
  419. VERIFY_NOT_REACHED();
  420. }
  421. void operator delete[](void* ptr, size_t size) noexcept
  422. {
  423. return kfree_sized(ptr, size);
  424. }
  425. void get_kmalloc_stats(kmalloc_stats& stats)
  426. {
  427. SpinlockLocker lock(s_lock);
  428. stats.bytes_allocated = g_kmalloc_global->allocated_bytes();
  429. stats.bytes_free = g_kmalloc_global->free_bytes();
  430. stats.kmalloc_call_count = g_kmalloc_call_count;
  431. stats.kfree_call_count = g_kfree_call_count;
  432. }