kmalloc.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. /*
  7. * Really really *really* Q&D malloc() and free() implementations
  8. * just to get going. Don't ever let anyone see this shit. :^)
  9. */
  10. #include <AK/Assertions.h>
  11. #include <AK/NonnullOwnPtrVector.h>
  12. #include <AK/Types.h>
  13. #include <Kernel/Debug.h>
  14. #include <Kernel/Heap/Heap.h>
  15. #include <Kernel/Heap/kmalloc.h>
  16. #include <Kernel/KSyms.h>
  17. #include <Kernel/Panic.h>
  18. #include <Kernel/PerformanceManager.h>
  19. #include <Kernel/Process.h>
  20. #include <Kernel/Scheduler.h>
  21. #include <Kernel/Sections.h>
  22. #include <Kernel/SpinLock.h>
  23. #include <Kernel/StdLib.h>
  24. #include <Kernel/VM/MemoryManager.h>
  25. #define CHUNK_SIZE 32
  26. #define POOL_SIZE (2 * MiB)
  27. #define ETERNAL_RANGE_SIZE (3 * MiB)
  28. namespace std {
  29. const nothrow_t nothrow;
  30. }
  31. static RecursiveSpinLock s_lock; // needs to be recursive because of dump_backtrace()
  32. static void kmalloc_allocate_backup_memory();
  33. struct KmallocGlobalHeap {
  34. struct ExpandGlobalHeap {
  35. KmallocGlobalHeap& m_global_heap;
  36. ExpandGlobalHeap(KmallocGlobalHeap& global_heap)
  37. : m_global_heap(global_heap)
  38. {
  39. }
  40. bool m_adding { false };
  41. bool add_memory(size_t allocation_request)
  42. {
  43. if (!MemoryManager::is_initialized()) {
  44. if constexpr (KMALLOC_DEBUG) {
  45. dmesgln("kmalloc: Cannot expand heap before MM is initialized!");
  46. }
  47. return false;
  48. }
  49. VERIFY(!m_adding);
  50. TemporaryChange change(m_adding, true);
  51. // At this point we have very little memory left. Any attempt to
  52. // kmalloc() could fail, so use our backup memory first, so we
  53. // can't really reliably allocate even a new region of memory.
  54. // This is why we keep a backup region, which we can
  55. auto region = move(m_global_heap.m_backup_memory);
  56. if (!region) {
  57. // Be careful to not log too much here. We don't want to trigger
  58. // any further calls to kmalloc(). We're already out of memory
  59. // and don't have any backup memory, either!
  60. if constexpr (KMALLOC_DEBUG) {
  61. dmesgln("kmalloc: Cannot expand heap: no backup memory");
  62. }
  63. return false;
  64. }
  65. // At this point we should have at least enough memory from the
  66. // backup region to be able to log properly
  67. if constexpr (KMALLOC_DEBUG) {
  68. dmesgln("kmalloc: Adding memory to heap at {}, bytes: {}", region->vaddr(), region->size());
  69. }
  70. auto& subheap = m_global_heap.m_heap.add_subheap(region->vaddr().as_ptr(), region->size());
  71. m_global_heap.m_subheap_memory.append(region.release_nonnull());
  72. // Since we pulled in our backup heap, make sure we allocate another
  73. // backup heap before returning. Otherwise we potentially lose
  74. // the ability to expand the heap next time we get called.
  75. ScopeGuard guard([&]() {
  76. // We may need to defer allocating backup memory because the
  77. // heap expansion may have been triggered while holding some
  78. // other spinlock. If the expansion happens to need the same
  79. // spinlock we would deadlock. So, if we're in any lock, defer
  80. Processor::current().deferred_call_queue(kmalloc_allocate_backup_memory);
  81. });
  82. // Now that we added our backup memory, check if the backup heap
  83. // was big enough to likely satisfy the request
  84. if (subheap.free_bytes() < allocation_request) {
  85. // Looks like we probably need more
  86. size_t memory_size = page_round_up(decltype(m_global_heap.m_heap)::calculate_memory_for_bytes(allocation_request));
  87. // Add some more to the new heap. We're already using it for other
  88. // allocations not including the original allocation_request
  89. // that triggered heap expansion. If we don't allocate
  90. memory_size += 1 * MiB;
  91. region = MM.allocate_kernel_region(memory_size, "kmalloc subheap", Region::Access::Read | Region::Access::Write, AllocationStrategy::AllocateNow);
  92. if (region) {
  93. dbgln("kmalloc: Adding even more memory to heap at {}, bytes: {}", region->vaddr(), region->size());
  94. m_global_heap.m_heap.add_subheap(region->vaddr().as_ptr(), region->size());
  95. m_global_heap.m_subheap_memory.append(region.release_nonnull());
  96. } else {
  97. dbgln("kmalloc: Could not expand heap to satisfy allocation of {} bytes", allocation_request);
  98. return false;
  99. }
  100. }
  101. return true;
  102. }
  103. bool remove_memory(void* memory)
  104. {
  105. // This is actually relatively unlikely to happen, because it requires that all
  106. // allocated memory in a subheap to be freed. Only then the subheap can be removed...
  107. for (size_t i = 0; i < m_global_heap.m_subheap_memory.size(); i++) {
  108. if (m_global_heap.m_subheap_memory[i].vaddr().as_ptr() == memory) {
  109. auto region = m_global_heap.m_subheap_memory.take(i);
  110. if (!m_global_heap.m_backup_memory) {
  111. if constexpr (KMALLOC_DEBUG) {
  112. dmesgln("kmalloc: Using removed memory as backup: {}, bytes: {}", region->vaddr(), region->size());
  113. }
  114. m_global_heap.m_backup_memory = move(region);
  115. } else {
  116. if constexpr (KMALLOC_DEBUG) {
  117. dmesgln("kmalloc: Queue removing memory from heap at {}, bytes: {}", region->vaddr(), region->size());
  118. }
  119. Processor::deferred_call_queue([this, region = move(region)]() mutable {
  120. // We need to defer freeing the region to prevent a potential
  121. // deadlock since we are still holding the kmalloc lock
  122. // We don't really need to do anything other than holding
  123. // onto the region. Unless we already used the backup
  124. // memory, in which case we want to use the region as the
  125. // new backup.
  126. ScopedSpinLock lock(s_lock);
  127. if (!m_global_heap.m_backup_memory) {
  128. if constexpr (KMALLOC_DEBUG) {
  129. dmesgln("kmalloc: Queued memory region at {}, bytes: {} will be used as new backup", region->vaddr(), region->size());
  130. }
  131. m_global_heap.m_backup_memory = move(region);
  132. } else {
  133. if constexpr (KMALLOC_DEBUG) {
  134. dmesgln("kmalloc: Queued memory region at {}, bytes: {} will be freed now", region->vaddr(), region->size());
  135. }
  136. }
  137. });
  138. }
  139. return true;
  140. }
  141. }
  142. if constexpr (KMALLOC_DEBUG) {
  143. dmesgln("kmalloc: Cannot remove memory from heap: {}", VirtualAddress(memory));
  144. }
  145. return false;
  146. }
  147. };
  148. typedef ExpandableHeap<CHUNK_SIZE, KMALLOC_SCRUB_BYTE, KFREE_SCRUB_BYTE, ExpandGlobalHeap> HeapType;
  149. HeapType m_heap;
  150. NonnullOwnPtrVector<Region> m_subheap_memory;
  151. OwnPtr<Region> m_backup_memory;
  152. KmallocGlobalHeap(u8* memory, size_t memory_size)
  153. : m_heap(memory, memory_size, ExpandGlobalHeap(*this))
  154. {
  155. }
  156. void allocate_backup_memory()
  157. {
  158. if (m_backup_memory)
  159. return;
  160. m_backup_memory = MM.allocate_kernel_region(1 * MiB, "kmalloc subheap", Region::Access::Read | Region::Access::Write, AllocationStrategy::AllocateNow);
  161. }
  162. size_t backup_memory_bytes() const
  163. {
  164. return m_backup_memory ? m_backup_memory->size() : 0;
  165. }
  166. };
  167. READONLY_AFTER_INIT static KmallocGlobalHeap* g_kmalloc_global;
  168. static u8 g_kmalloc_global_heap[sizeof(KmallocGlobalHeap)];
  169. // Treat the heap as logically separate from .bss
  170. __attribute__((section(".heap"))) static u8 kmalloc_eternal_heap[ETERNAL_RANGE_SIZE];
  171. __attribute__((section(".heap"))) static u8 kmalloc_pool_heap[POOL_SIZE];
  172. static size_t g_kmalloc_bytes_eternal = 0;
  173. static size_t g_kmalloc_call_count;
  174. static size_t g_kfree_call_count;
  175. static size_t g_nested_kfree_calls;
  176. bool g_dump_kmalloc_stacks;
  177. static u8* s_next_eternal_ptr;
  178. READONLY_AFTER_INIT static u8* s_end_of_eternal_range;
  179. static void kmalloc_allocate_backup_memory()
  180. {
  181. g_kmalloc_global->allocate_backup_memory();
  182. }
  183. void kmalloc_enable_expand()
  184. {
  185. g_kmalloc_global->allocate_backup_memory();
  186. }
  187. static inline void kmalloc_verify_nospinlock_held()
  188. {
  189. // Catch bad callers allocating under spinlock.
  190. if constexpr (KMALLOC_VERIFY_NO_SPINLOCK_HELD) {
  191. VERIFY(!Processor::current().in_critical());
  192. }
  193. }
  194. UNMAP_AFTER_INIT void kmalloc_init()
  195. {
  196. // Zero out heap since it's placed after end_of_kernel_bss.
  197. memset(kmalloc_eternal_heap, 0, sizeof(kmalloc_eternal_heap));
  198. memset(kmalloc_pool_heap, 0, sizeof(kmalloc_pool_heap));
  199. g_kmalloc_global = new (g_kmalloc_global_heap) KmallocGlobalHeap(kmalloc_pool_heap, sizeof(kmalloc_pool_heap));
  200. s_lock.initialize();
  201. s_next_eternal_ptr = kmalloc_eternal_heap;
  202. s_end_of_eternal_range = s_next_eternal_ptr + sizeof(kmalloc_eternal_heap);
  203. }
  204. void* kmalloc_eternal(size_t size)
  205. {
  206. kmalloc_verify_nospinlock_held();
  207. size = round_up_to_power_of_two(size, sizeof(void*));
  208. ScopedSpinLock lock(s_lock);
  209. void* ptr = s_next_eternal_ptr;
  210. s_next_eternal_ptr += size;
  211. VERIFY(s_next_eternal_ptr < s_end_of_eternal_range);
  212. g_kmalloc_bytes_eternal += size;
  213. return ptr;
  214. }
  215. void* kmalloc(size_t size)
  216. {
  217. kmalloc_verify_nospinlock_held();
  218. ScopedSpinLock lock(s_lock);
  219. ++g_kmalloc_call_count;
  220. if (g_dump_kmalloc_stacks && Kernel::g_kernel_symbols_available) {
  221. dbgln("kmalloc({})", size);
  222. Kernel::dump_backtrace();
  223. }
  224. void* ptr = g_kmalloc_global->m_heap.allocate(size);
  225. if (!ptr) {
  226. PANIC("kmalloc: Out of memory (requested size: {})", size);
  227. }
  228. Thread* current_thread = Thread::current();
  229. if (!current_thread)
  230. current_thread = Processor::idle_thread();
  231. if (current_thread)
  232. PerformanceManager::add_kmalloc_perf_event(*current_thread, size, (FlatPtr)ptr);
  233. return ptr;
  234. }
  235. void kfree(void* ptr)
  236. {
  237. if (!ptr)
  238. return;
  239. kmalloc_verify_nospinlock_held();
  240. ScopedSpinLock lock(s_lock);
  241. ++g_kfree_call_count;
  242. ++g_nested_kfree_calls;
  243. if (g_nested_kfree_calls == 1) {
  244. Thread* current_thread = Thread::current();
  245. if (!current_thread)
  246. current_thread = Processor::idle_thread();
  247. if (current_thread)
  248. PerformanceManager::add_kfree_perf_event(*current_thread, 0, (FlatPtr)ptr);
  249. }
  250. g_kmalloc_global->m_heap.deallocate(ptr);
  251. --g_nested_kfree_calls;
  252. }
  253. void* krealloc(void* ptr, size_t new_size)
  254. {
  255. kmalloc_verify_nospinlock_held();
  256. ScopedSpinLock lock(s_lock);
  257. return g_kmalloc_global->m_heap.reallocate(ptr, new_size);
  258. }
  259. size_t kmalloc_good_size(size_t size)
  260. {
  261. return size;
  262. }
  263. void* operator new(size_t size)
  264. {
  265. void* ptr = kmalloc(size);
  266. VERIFY(ptr);
  267. return ptr;
  268. }
  269. void* operator new(size_t size, const std::nothrow_t&) noexcept
  270. {
  271. return kmalloc(size);
  272. }
  273. void* operator new[](size_t size)
  274. {
  275. void* ptr = kmalloc(size);
  276. VERIFY(ptr);
  277. return ptr;
  278. }
  279. void* operator new[](size_t size, const std::nothrow_t&) noexcept
  280. {
  281. return kmalloc(size);
  282. }
  283. void operator delete(void* ptr) noexcept
  284. {
  285. return kfree(ptr);
  286. }
  287. void operator delete(void* ptr, size_t) noexcept
  288. {
  289. return kfree(ptr);
  290. }
  291. void operator delete[](void* ptr) noexcept
  292. {
  293. return kfree(ptr);
  294. }
  295. void operator delete[](void* ptr, size_t) noexcept
  296. {
  297. return kfree(ptr);
  298. }
  299. void get_kmalloc_stats(kmalloc_stats& stats)
  300. {
  301. ScopedSpinLock lock(s_lock);
  302. stats.bytes_allocated = g_kmalloc_global->m_heap.allocated_bytes();
  303. stats.bytes_free = g_kmalloc_global->m_heap.free_bytes() + g_kmalloc_global->backup_memory_bytes();
  304. stats.bytes_eternal = g_kmalloc_bytes_eternal;
  305. stats.kmalloc_call_count = g_kmalloc_call_count;
  306. stats.kfree_call_count = g_kfree_call_count;
  307. }