kmalloc.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. /*
  27. * Really really *really* Q&D malloc() and free() implementations
  28. * just to get going. Don't ever let anyone see this shit. :^)
  29. */
  30. #include <AK/Assertions.h>
  31. #include <AK/NonnullOwnPtrVector.h>
  32. #include <AK/Optional.h>
  33. #include <AK/StringView.h>
  34. #include <AK/Types.h>
  35. #include <Kernel/Arch/i386/CPU.h>
  36. #include <Kernel/Heap/Heap.h>
  37. #include <Kernel/Heap/kmalloc.h>
  38. #include <Kernel/KSyms.h>
  39. #include <Kernel/Panic.h>
  40. #include <Kernel/Process.h>
  41. #include <Kernel/Scheduler.h>
  42. #include <Kernel/SpinLock.h>
  43. #include <Kernel/StdLib.h>
  44. #include <Kernel/VM/MemoryManager.h>
  45. #define SANITIZE_KMALLOC
  46. #define CHUNK_SIZE 32
  47. #define POOL_SIZE (2 * MiB)
  48. #define ETERNAL_RANGE_SIZE (2 * MiB)
  49. static RecursiveSpinLock s_lock; // needs to be recursive because of dump_backtrace()
  50. static void kmalloc_allocate_backup_memory();
  51. struct KmallocGlobalHeap {
  52. struct ExpandGlobalHeap {
  53. KmallocGlobalHeap& m_global_heap;
  54. ExpandGlobalHeap(KmallocGlobalHeap& global_heap)
  55. : m_global_heap(global_heap)
  56. {
  57. }
  58. bool m_adding { false };
  59. bool add_memory(size_t allocation_request)
  60. {
  61. if (!MemoryManager::is_initialized()) {
  62. klog() << "kmalloc(): Cannot expand heap before MM is initialized!";
  63. return false;
  64. }
  65. ASSERT(!m_adding);
  66. TemporaryChange change(m_adding, true);
  67. // At this point we have very little memory left. Any attempt to
  68. // kmalloc() could fail, so use our backup memory first, so we
  69. // can't really reliably allocate even a new region of memory.
  70. // This is why we keep a backup region, which we can
  71. auto region = move(m_global_heap.m_backup_memory);
  72. if (!region) {
  73. // Be careful to not log too much here. We don't want to trigger
  74. // any further calls to kmalloc(). We're already out of memory
  75. // and don't have any backup memory, either!
  76. klog() << "kmalloc(): Cannot expand heap: no backup memory";
  77. return false;
  78. }
  79. // At this point we should have at least enough memory from the
  80. // backup region to be able to log properly
  81. klog() << "kmalloc(): Adding memory to heap at " << region->vaddr() << ", bytes: " << region->size();
  82. auto& subheap = m_global_heap.m_heap.add_subheap(region->vaddr().as_ptr(), region->size());
  83. m_global_heap.m_subheap_memory.append(region.release_nonnull());
  84. // Since we pulled in our backup heap, make sure we allocate another
  85. // backup heap before returning. Otherwise we potentially lose
  86. // the ability to expand the heap next time we get called.
  87. ScopeGuard guard([&]() {
  88. // We may need to defer allocating backup memory because the
  89. // heap expansion may have been triggered while holding some
  90. // other spinlock. If the expansion happens to need the same
  91. // spinlock we would deadlock. So, if we're in any lock, defer
  92. Processor::current().deferred_call_queue(kmalloc_allocate_backup_memory);
  93. });
  94. // Now that we added our backup memory, check if the backup heap
  95. // was big enough to likely satisfy the request
  96. if (subheap.free_bytes() < allocation_request) {
  97. // Looks like we probably need more
  98. size_t memory_size = page_round_up(decltype(m_global_heap.m_heap)::calculate_memory_for_bytes(allocation_request));
  99. // Add some more to the new heap. We're already using it for other
  100. // allocations not including the original allocation_request
  101. // that triggered heap expansion. If we don't allocate
  102. memory_size += 1 * MiB;
  103. region = MM.allocate_kernel_region(memory_size, "kmalloc subheap", Region::Access::Read | Region::Access::Write, AllocationStrategy::AllocateNow);
  104. if (region) {
  105. klog() << "kmalloc(): Adding even more memory to heap at " << region->vaddr() << ", bytes: " << region->size();
  106. m_global_heap.m_heap.add_subheap(region->vaddr().as_ptr(), region->size());
  107. m_global_heap.m_subheap_memory.append(region.release_nonnull());
  108. } else {
  109. klog() << "kmalloc(): Could not expand heap to satisfy allocation of " << allocation_request << " bytes";
  110. return false;
  111. }
  112. }
  113. return true;
  114. }
  115. bool remove_memory(void* memory)
  116. {
  117. // This is actually relatively unlikely to happen, because it requires that all
  118. // allocated memory in a subheap to be freed. Only then the subheap can be removed...
  119. for (size_t i = 0; i < m_global_heap.m_subheap_memory.size(); i++) {
  120. if (m_global_heap.m_subheap_memory[i].vaddr().as_ptr() == memory) {
  121. auto region = m_global_heap.m_subheap_memory.take(i);
  122. if (!m_global_heap.m_backup_memory) {
  123. klog() << "kmalloc(): Using removed memory as backup: " << region->vaddr() << ", bytes: " << region->size();
  124. m_global_heap.m_backup_memory = move(region);
  125. } else {
  126. klog() << "kmalloc(): Queue removing memory from heap at " << region->vaddr() << ", bytes: " << region->size();
  127. Processor::deferred_call_queue([this, region = move(region)]() mutable {
  128. // We need to defer freeing the region to prevent a potential
  129. // deadlock since we are still holding the kmalloc lock
  130. // We don't really need to do anything other than holding
  131. // onto the region. Unless we already used the backup
  132. // memory, in which case we want to use the region as the
  133. // new backup.
  134. ScopedSpinLock lock(s_lock);
  135. if (!m_global_heap.m_backup_memory) {
  136. klog() << "kmalloc(): Queued memory region at " << region->vaddr() << ", bytes: " << region->size() << " will be used as new backup";
  137. m_global_heap.m_backup_memory = move(region);
  138. } else {
  139. klog() << "kmalloc(): Queued memory region at " << region->vaddr() << ", bytes: " << region->size() << " will be freed now";
  140. }
  141. });
  142. }
  143. return true;
  144. }
  145. }
  146. klog() << "kmalloc(): Cannot remove memory from heap: " << VirtualAddress(memory);
  147. return false;
  148. }
  149. };
  150. typedef ExpandableHeap<CHUNK_SIZE, KMALLOC_SCRUB_BYTE, KFREE_SCRUB_BYTE, ExpandGlobalHeap> HeapType;
  151. HeapType m_heap;
  152. NonnullOwnPtrVector<Region> m_subheap_memory;
  153. OwnPtr<Region> m_backup_memory;
  154. KmallocGlobalHeap(u8* memory, size_t memory_size)
  155. : m_heap(memory, memory_size, ExpandGlobalHeap(*this))
  156. {
  157. }
  158. void allocate_backup_memory()
  159. {
  160. if (m_backup_memory)
  161. return;
  162. m_backup_memory = MM.allocate_kernel_region(1 * MiB, "kmalloc subheap", Region::Access::Read | Region::Access::Write, AllocationStrategy::AllocateNow);
  163. }
  164. size_t backup_memory_bytes() const
  165. {
  166. return m_backup_memory ? m_backup_memory->size() : 0;
  167. }
  168. };
  169. READONLY_AFTER_INIT static KmallocGlobalHeap* g_kmalloc_global;
  170. static u8 g_kmalloc_global_heap[sizeof(KmallocGlobalHeap)];
  171. // Treat the heap as logically separate from .bss
  172. __attribute__((section(".heap"))) static u8 kmalloc_eternal_heap[ETERNAL_RANGE_SIZE];
  173. __attribute__((section(".heap"))) static u8 kmalloc_pool_heap[POOL_SIZE];
  174. static size_t g_kmalloc_bytes_eternal = 0;
  175. static size_t g_kmalloc_call_count;
  176. static size_t g_kfree_call_count;
  177. bool g_dump_kmalloc_stacks;
  178. static u8* s_next_eternal_ptr;
  179. READONLY_AFTER_INIT static u8* s_end_of_eternal_range;
  180. static void kmalloc_allocate_backup_memory()
  181. {
  182. g_kmalloc_global->allocate_backup_memory();
  183. }
  184. void kmalloc_enable_expand()
  185. {
  186. g_kmalloc_global->allocate_backup_memory();
  187. }
  188. UNMAP_AFTER_INIT void kmalloc_init()
  189. {
  190. // Zero out heap since it's placed after end_of_kernel_bss.
  191. memset(kmalloc_eternal_heap, 0, sizeof(kmalloc_eternal_heap));
  192. memset(kmalloc_pool_heap, 0, sizeof(kmalloc_pool_heap));
  193. g_kmalloc_global = new (g_kmalloc_global_heap) KmallocGlobalHeap(kmalloc_pool_heap, sizeof(kmalloc_pool_heap));
  194. s_lock.initialize();
  195. s_next_eternal_ptr = kmalloc_eternal_heap;
  196. s_end_of_eternal_range = s_next_eternal_ptr + sizeof(kmalloc_pool_heap);
  197. }
  198. void* kmalloc_eternal(size_t size)
  199. {
  200. size = round_up_to_power_of_two(size, sizeof(void*));
  201. ScopedSpinLock lock(s_lock);
  202. void* ptr = s_next_eternal_ptr;
  203. s_next_eternal_ptr += size;
  204. ASSERT(s_next_eternal_ptr < s_end_of_eternal_range);
  205. g_kmalloc_bytes_eternal += size;
  206. return ptr;
  207. }
  208. void* kmalloc_impl(size_t size)
  209. {
  210. ScopedSpinLock lock(s_lock);
  211. ++g_kmalloc_call_count;
  212. if (g_dump_kmalloc_stacks && Kernel::g_kernel_symbols_available) {
  213. dbgln("kmalloc({})", size);
  214. Kernel::dump_backtrace();
  215. }
  216. void* ptr = g_kmalloc_global->m_heap.allocate(size);
  217. if (!ptr) {
  218. PANIC("kmalloc: Out of memory (requested size: {})", size);
  219. }
  220. return ptr;
  221. }
  222. void kfree(void* ptr)
  223. {
  224. if (!ptr)
  225. return;
  226. ScopedSpinLock lock(s_lock);
  227. ++g_kfree_call_count;
  228. g_kmalloc_global->m_heap.deallocate(ptr);
  229. }
  230. void* krealloc(void* ptr, size_t new_size)
  231. {
  232. ScopedSpinLock lock(s_lock);
  233. return g_kmalloc_global->m_heap.reallocate(ptr, new_size);
  234. }
  235. void* operator new(size_t size)
  236. {
  237. return kmalloc(size);
  238. }
  239. void* operator new[](size_t size)
  240. {
  241. return kmalloc(size);
  242. }
  243. void get_kmalloc_stats(kmalloc_stats& stats)
  244. {
  245. ScopedSpinLock lock(s_lock);
  246. stats.bytes_allocated = g_kmalloc_global->m_heap.allocated_bytes();
  247. stats.bytes_free = g_kmalloc_global->m_heap.free_bytes() + g_kmalloc_global->backup_memory_bytes();
  248. stats.bytes_eternal = g_kmalloc_bytes_eternal;
  249. stats.kmalloc_call_count = g_kmalloc_call_count;
  250. stats.kfree_call_count = g_kfree_call_count;
  251. }