kmalloc.cpp 18 KB

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