kmalloc.cpp 18 KB

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