kmalloc.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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/Process.h>
  40. #include <Kernel/Scheduler.h>
  41. #include <Kernel/SpinLock.h>
  42. #include <Kernel/StdLib.h>
  43. #include <Kernel/VM/MemoryManager.h>
  44. #define SANITIZE_KMALLOC
  45. #define CHUNK_SIZE 32
  46. #define POOL_SIZE (2 * MiB)
  47. #define ETERNAL_RANGE_SIZE (2 * MiB)
  48. static RecursiveSpinLock s_lock; // needs to be recursive because of dump_backtrace()
  49. struct KmallocGlobalHeap {
  50. struct ExpandGlobalHeap {
  51. KmallocGlobalHeap& m_global_heap;
  52. ExpandGlobalHeap(KmallocGlobalHeap& global_heap)
  53. : m_global_heap(global_heap)
  54. {
  55. }
  56. bool m_adding { false };
  57. bool add_memory(size_t allocation_request)
  58. {
  59. if (!MemoryManager::is_initialized()) {
  60. klog() << "kmalloc(): Cannot expand heap before MM is initialized!";
  61. return false;
  62. }
  63. ASSERT(!m_adding);
  64. TemporaryChange change(m_adding, true);
  65. // At this point we have very little memory left. Any attempt to
  66. // kmalloc() could fail, so use our backup memory first, so we
  67. // can't really reliably allocate even a new region of memory.
  68. // This is why we keep a backup region, which we can
  69. auto region = move(m_global_heap.m_backup_memory);
  70. if (!region) {
  71. // Be careful to not log too much here. We don't want to trigger
  72. // any further calls to kmalloc(). We're already out of memory
  73. // and don't have any backup memory, either!
  74. klog() << "kmalloc(): Cannot expand heap: no backup memory";
  75. return false;
  76. }
  77. // At this point we should have at least enough memory from the
  78. // backup region to be able to log properly
  79. klog() << "kmalloc(): Adding memory to heap at " << region->vaddr() << ", bytes: " << region->size();
  80. auto& subheap = m_global_heap.m_heap.add_subheap(region->vaddr().as_ptr(), region->size());
  81. m_global_heap.m_subheap_memory.append(region.release_nonnull());
  82. // Since we pulled in our backup heap, make sure we allocate another
  83. // backup heap before returning. Otherwise we potentially lose
  84. // the ability to expand the heap next time we get called.
  85. ScopeGuard guard([&]() {
  86. m_global_heap.allocate_backup_memory();
  87. });
  88. // Now that we added our backup memory, check if the backup heap
  89. // was big enough to likely satisfy the request
  90. if (subheap.free_bytes() < allocation_request) {
  91. // Looks like we probably need more
  92. size_t memory_size = PAGE_ROUND_UP(decltype(m_global_heap.m_heap)::calculate_memory_for_bytes(allocation_request));
  93. // Add some more to the new heap. We're already using it for other
  94. // allocations not including the original allocation_request
  95. // that triggered heap expansion. If we don't allocate
  96. memory_size += 1 * MiB;
  97. region = MM.allocate_kernel_region(memory_size, "kmalloc subheap", Region::Access::Read | Region::Access::Write);
  98. if (region) {
  99. klog() << "kmalloc(): Adding even more memory to heap at " << region->vaddr() << ", bytes: " << region->size();
  100. m_global_heap.m_heap.add_subheap(region->vaddr().as_ptr(), region->size());
  101. m_global_heap.m_subheap_memory.append(region.release_nonnull());
  102. } else {
  103. klog() << "kmalloc(): Could not expand heap to satisfy allocation of " << allocation_request << " bytes";
  104. return false;
  105. }
  106. }
  107. return true;
  108. }
  109. bool remove_memory(void* memory)
  110. {
  111. // This is actually relatively unlikely to happen, because it requires that all
  112. // allocated memory in a subheap to be freed. Only then the subheap can be removed...
  113. for (size_t i = 0; i < m_global_heap.m_subheap_memory.size(); i++) {
  114. if (m_global_heap.m_subheap_memory[i].vaddr().as_ptr() == memory) {
  115. auto region = m_global_heap.m_subheap_memory.take(i);
  116. if (!m_global_heap.m_backup_memory) {
  117. klog() << "kmalloc(): Using removed memory as backup: " << region->vaddr() << ", bytes: " << region->size();
  118. m_global_heap.m_backup_memory = move(region);
  119. } else {
  120. klog() << "kmalloc(): Queue removing memory from heap at " << region->vaddr() << ", bytes: " << region->size();
  121. Processor::deferred_call_queue([this, region = move(region)]() mutable {
  122. // We need to defer freeing the region to prevent a potential
  123. // deadlock since we are still holding the kmalloc lock
  124. // We don't really need to do anything other than holding
  125. // onto the region. Unless we already used the backup
  126. // memory, in which case we want to use the region as the
  127. // new backup.
  128. ScopedSpinLock lock(s_lock);
  129. if (!m_global_heap.m_backup_memory) {
  130. klog() << "kmalloc(): Queued memory region at " << region->vaddr() << ", bytes: " << region->size() << " will be used as new backup";
  131. m_global_heap.m_backup_memory = move(region);
  132. } else {
  133. klog() << "kmalloc(): Queued memory region at " << region->vaddr() << ", bytes: " << region->size() << " will be freed now";
  134. }
  135. });
  136. }
  137. return true;
  138. }
  139. }
  140. klog() << "kmalloc(): Cannot remove memory from heap: " << VirtualAddress(memory);
  141. return false;
  142. }
  143. };
  144. typedef ExpandableHeap<CHUNK_SIZE, KMALLOC_SCRUB_BYTE, KFREE_SCRUB_BYTE, ExpandGlobalHeap> HeapType;
  145. HeapType m_heap;
  146. NonnullOwnPtrVector<Region> m_subheap_memory;
  147. OwnPtr<Region> m_backup_memory;
  148. KmallocGlobalHeap(u8* memory, size_t memory_size)
  149. : m_heap(memory, memory_size, ExpandGlobalHeap(*this))
  150. {
  151. }
  152. void allocate_backup_memory()
  153. {
  154. if (m_backup_memory)
  155. return;
  156. m_backup_memory = MM.allocate_kernel_region(1 * MiB, "kmalloc subheap", Region::Access::Read | Region::Access::Write);
  157. }
  158. size_t backup_memory_bytes() const
  159. {
  160. return m_backup_memory ? m_backup_memory->size() : 0;
  161. }
  162. };
  163. static KmallocGlobalHeap* g_kmalloc_global;
  164. // We need to make sure to not stomp on global variables or other parts
  165. // of the kernel image!
  166. extern u32 end_of_kernel_image;
  167. u8* const kmalloc_start = (u8*)PAGE_ROUND_UP(&end_of_kernel_image);
  168. u8* const kmalloc_end = kmalloc_start + (ETERNAL_RANGE_SIZE + POOL_SIZE) + sizeof(KmallocGlobalHeap);
  169. #define ETERNAL_BASE (kmalloc_start + sizeof(KmallocGlobalHeap))
  170. #define KMALLOC_BASE (ETERNAL_BASE + ETERNAL_RANGE_SIZE)
  171. static size_t g_kmalloc_bytes_eternal = 0;
  172. static size_t g_kmalloc_call_count;
  173. static size_t g_kfree_call_count;
  174. bool g_dump_kmalloc_stacks;
  175. static u8* s_next_eternal_ptr;
  176. static u8* s_end_of_eternal_range;
  177. void kmalloc_enable_expand()
  178. {
  179. g_kmalloc_global->allocate_backup_memory();
  180. }
  181. void kmalloc_init()
  182. {
  183. memset((void*)KMALLOC_BASE, 0, POOL_SIZE);
  184. g_kmalloc_global = new (kmalloc_start) KmallocGlobalHeap(KMALLOC_BASE, POOL_SIZE); // Place heap at kmalloc_start
  185. s_lock.initialize();
  186. s_next_eternal_ptr = (u8*)ETERNAL_BASE;
  187. s_end_of_eternal_range = s_next_eternal_ptr + ETERNAL_RANGE_SIZE;
  188. }
  189. void* kmalloc_eternal(size_t size)
  190. {
  191. size = round_up_to_power_of_two(size, sizeof(void*));
  192. ScopedSpinLock lock(s_lock);
  193. void* ptr = s_next_eternal_ptr;
  194. s_next_eternal_ptr += size;
  195. ASSERT(s_next_eternal_ptr < s_end_of_eternal_range);
  196. g_kmalloc_bytes_eternal += size;
  197. return ptr;
  198. }
  199. void* kmalloc_impl(size_t size)
  200. {
  201. ScopedSpinLock lock(s_lock);
  202. ++g_kmalloc_call_count;
  203. if (g_dump_kmalloc_stacks && Kernel::g_kernel_symbols_available) {
  204. dbg() << "kmalloc(" << size << ")";
  205. Kernel::dump_backtrace();
  206. }
  207. void* ptr = g_kmalloc_global->m_heap.allocate(size);
  208. if (!ptr) {
  209. klog() << "kmalloc(): PANIC! Out of memory (no suitable block for size " << size << ")";
  210. Kernel::dump_backtrace();
  211. Processor::halt();
  212. }
  213. return ptr;
  214. }
  215. void kfree(void* ptr)
  216. {
  217. if (!ptr)
  218. return;
  219. ScopedSpinLock lock(s_lock);
  220. ++g_kfree_call_count;
  221. g_kmalloc_global->m_heap.deallocate(ptr);
  222. }
  223. void* krealloc(void* ptr, size_t new_size)
  224. {
  225. ScopedSpinLock lock(s_lock);
  226. return g_kmalloc_global->m_heap.reallocate(ptr, new_size);
  227. }
  228. void* operator new(size_t size)
  229. {
  230. return kmalloc(size);
  231. }
  232. void* operator new[](size_t size)
  233. {
  234. return kmalloc(size);
  235. }
  236. void get_kmalloc_stats(kmalloc_stats& stats)
  237. {
  238. ScopedSpinLock lock(s_lock);
  239. stats.bytes_allocated = g_kmalloc_global->m_heap.allocated_bytes();
  240. stats.bytes_free = g_kmalloc_global->m_heap.free_bytes() + g_kmalloc_global->backup_memory_bytes();
  241. stats.bytes_eternal = g_kmalloc_bytes_eternal;
  242. stats.kmalloc_call_count = g_kmalloc_call_count;
  243. stats.kfree_call_count = g_kfree_call_count;
  244. }