malloc.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. #include <AK/InlineLinkedList.h>
  27. #include <AK/LogStream.h>
  28. #include <AK/ScopedValueRollback.h>
  29. #include <AK/Vector.h>
  30. #include <LibThread/Lock.h>
  31. #include <assert.h>
  32. #include <mallocdefs.h>
  33. #include <serenity.h>
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #include <sys/internals.h>
  38. #include <sys/mman.h>
  39. // FIXME: Thread safety.
  40. //#define MALLOC_DEBUG
  41. #define RECYCLE_BIG_ALLOCATIONS
  42. #define MAGIC_PAGE_HEADER 0x42657274 // 'Bert'
  43. #define MAGIC_BIGALLOC_HEADER 0x42697267 // 'Birg'
  44. #define PAGE_ROUND_UP(x) ((((size_t)(x)) + PAGE_SIZE - 1) & (~(PAGE_SIZE - 1)))
  45. ALWAYS_INLINE static void ue_notify_malloc(const void* ptr, size_t size)
  46. {
  47. send_secret_data_to_userspace_emulator(1, size, (FlatPtr)ptr);
  48. }
  49. ALWAYS_INLINE static void ue_notify_free(const void* ptr)
  50. {
  51. send_secret_data_to_userspace_emulator(2, (FlatPtr)ptr, 0);
  52. }
  53. static LibThread::Lock& malloc_lock()
  54. {
  55. static u32 lock_storage[sizeof(LibThread::Lock) / sizeof(u32)];
  56. return *reinterpret_cast<LibThread::Lock*>(&lock_storage);
  57. }
  58. constexpr size_t number_of_chunked_blocks_to_keep_around_per_size_class = 4;
  59. constexpr size_t number_of_big_blocks_to_keep_around_per_size_class = 8;
  60. static bool s_log_malloc = false;
  61. static bool s_scrub_malloc = true;
  62. static bool s_scrub_free = true;
  63. static bool s_profiling = false;
  64. static unsigned short size_classes[] = { 8, 16, 32, 64, 128, 252, 508, 1016, 2036, 4090, 8188, 16376, 32756, 0 };
  65. static constexpr size_t num_size_classes = sizeof(size_classes) / sizeof(unsigned short);
  66. struct MallocStats {
  67. size_t number_of_malloc_calls;
  68. size_t number_of_big_allocator_hits;
  69. size_t number_of_big_allocator_purge_hits;
  70. size_t number_of_big_allocs;
  71. size_t number_of_empty_block_hits;
  72. size_t number_of_empty_block_purge_hits;
  73. size_t number_of_block_allocs;
  74. size_t number_of_blocks_full;
  75. size_t number_of_free_calls;
  76. size_t number_of_big_allocator_keeps;
  77. size_t number_of_big_allocator_frees;
  78. size_t number_of_freed_full_blocks;
  79. size_t number_of_keeps;
  80. size_t number_of_frees;
  81. };
  82. static MallocStats g_malloc_stats = {};
  83. constexpr size_t block_size = 64 * KiB;
  84. constexpr size_t block_mask = ~(block_size - 1);
  85. struct CommonHeader {
  86. size_t m_magic;
  87. size_t m_size;
  88. };
  89. struct BigAllocationBlock : public CommonHeader {
  90. BigAllocationBlock(size_t size)
  91. {
  92. m_magic = MAGIC_BIGALLOC_HEADER;
  93. m_size = size;
  94. }
  95. unsigned char* m_slot[0];
  96. };
  97. struct FreelistEntry {
  98. FreelistEntry* next;
  99. };
  100. struct ChunkedBlock
  101. : public CommonHeader
  102. , public InlineLinkedListNode<ChunkedBlock> {
  103. ChunkedBlock(size_t bytes_per_chunk)
  104. {
  105. m_magic = MAGIC_PAGE_HEADER;
  106. m_size = bytes_per_chunk;
  107. m_free_chunks = chunk_capacity();
  108. m_freelist = (FreelistEntry*)chunk(0);
  109. for (size_t i = 0; i < chunk_capacity(); ++i) {
  110. auto* entry = (FreelistEntry*)chunk(i);
  111. if (i != chunk_capacity() - 1)
  112. entry->next = (FreelistEntry*)chunk(i + 1);
  113. else
  114. entry->next = nullptr;
  115. }
  116. }
  117. ChunkedBlock* m_prev { nullptr };
  118. ChunkedBlock* m_next { nullptr };
  119. FreelistEntry* m_freelist { nullptr };
  120. unsigned short m_free_chunks { 0 };
  121. [[gnu::aligned(8)]] unsigned char m_slot[0];
  122. void* chunk(size_t index)
  123. {
  124. return &m_slot[index * m_size];
  125. }
  126. bool is_full() const { return m_free_chunks == 0; }
  127. size_t bytes_per_chunk() const { return m_size; }
  128. size_t free_chunks() const { return m_free_chunks; }
  129. size_t used_chunks() const { return chunk_capacity() - m_free_chunks; }
  130. size_t chunk_capacity() const { return (block_size - sizeof(ChunkedBlock)) / m_size; }
  131. };
  132. struct Allocator {
  133. size_t size { 0 };
  134. size_t block_count { 0 };
  135. size_t empty_block_count { 0 };
  136. ChunkedBlock* empty_blocks[number_of_chunked_blocks_to_keep_around_per_size_class] { nullptr };
  137. InlineLinkedList<ChunkedBlock> usable_blocks;
  138. InlineLinkedList<ChunkedBlock> full_blocks;
  139. };
  140. struct BigAllocator {
  141. Vector<BigAllocationBlock*, number_of_big_blocks_to_keep_around_per_size_class> blocks;
  142. };
  143. // Allocators will be initialized in __malloc_init.
  144. // We can not rely on global constructors to initialize them,
  145. // because they must be initialized before other global constructors
  146. // are run. Similarly, we can not allow global destructors to destruct
  147. // them. We could have used AK::NeverDestoyed to prevent the latter,
  148. // but it would have not helped with the former.
  149. static u8 g_allocators_storage[sizeof(Allocator) * num_size_classes];
  150. static u8 g_big_allocators_storage[sizeof(BigAllocator)];
  151. static inline Allocator (&allocators())[num_size_classes]
  152. {
  153. return reinterpret_cast<Allocator(&)[num_size_classes]>(g_allocators_storage);
  154. }
  155. static inline BigAllocator (&big_allocators())[1]
  156. {
  157. return reinterpret_cast<BigAllocator(&)[1]>(g_big_allocators_storage);
  158. }
  159. static Allocator* allocator_for_size(size_t size, size_t& good_size)
  160. {
  161. for (size_t i = 0; size_classes[i]; ++i) {
  162. if (size <= size_classes[i]) {
  163. good_size = size_classes[i];
  164. return &allocators()[i];
  165. }
  166. }
  167. good_size = PAGE_ROUND_UP(size);
  168. return nullptr;
  169. }
  170. #ifdef RECYCLE_BIG_ALLOCATIONS
  171. static BigAllocator* big_allocator_for_size(size_t size)
  172. {
  173. if (size == 65536)
  174. return &big_allocators()[0];
  175. return nullptr;
  176. }
  177. #endif
  178. extern "C" {
  179. static void* os_alloc(size_t size, const char* name)
  180. {
  181. auto* ptr = serenity_mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_PURGEABLE, 0, 0, block_size, name);
  182. ASSERT(ptr != MAP_FAILED);
  183. return ptr;
  184. }
  185. static void os_free(void* ptr, size_t size)
  186. {
  187. int rc = munmap(ptr, size);
  188. assert(rc == 0);
  189. }
  190. static void* malloc_impl(size_t size)
  191. {
  192. LOCKER(malloc_lock());
  193. if (s_log_malloc)
  194. dbgprintf("LibC: malloc(%zu)\n", size);
  195. if (!size)
  196. return nullptr;
  197. g_malloc_stats.number_of_malloc_calls++;
  198. size_t good_size;
  199. auto* allocator = allocator_for_size(size, good_size);
  200. if (!allocator) {
  201. size_t real_size = round_up_to_power_of_two(sizeof(BigAllocationBlock) + size, block_size);
  202. #ifdef RECYCLE_BIG_ALLOCATIONS
  203. if (auto* allocator = big_allocator_for_size(real_size)) {
  204. if (!allocator->blocks.is_empty()) {
  205. g_malloc_stats.number_of_big_allocator_hits++;
  206. auto* block = allocator->blocks.take_last();
  207. int rc = madvise(block, real_size, MADV_SET_NONVOLATILE);
  208. bool this_block_was_purged = rc == 1;
  209. if (rc < 0) {
  210. perror("madvise");
  211. ASSERT_NOT_REACHED();
  212. }
  213. if (mprotect(block, real_size, PROT_READ | PROT_WRITE) < 0) {
  214. perror("mprotect");
  215. ASSERT_NOT_REACHED();
  216. }
  217. if (this_block_was_purged) {
  218. g_malloc_stats.number_of_big_allocator_purge_hits++;
  219. new (block) BigAllocationBlock(real_size);
  220. }
  221. ue_notify_malloc(&block->m_slot[0], size);
  222. return &block->m_slot[0];
  223. }
  224. }
  225. #endif
  226. g_malloc_stats.number_of_big_allocs++;
  227. auto* block = (BigAllocationBlock*)os_alloc(real_size, "malloc: BigAllocationBlock");
  228. new (block) BigAllocationBlock(real_size);
  229. ue_notify_malloc(&block->m_slot[0], size);
  230. return &block->m_slot[0];
  231. }
  232. ChunkedBlock* block = nullptr;
  233. for (block = allocator->usable_blocks.head(); block; block = block->next()) {
  234. if (block->free_chunks())
  235. break;
  236. }
  237. if (!block && allocator->empty_block_count) {
  238. g_malloc_stats.number_of_empty_block_hits++;
  239. block = allocator->empty_blocks[--allocator->empty_block_count];
  240. int rc = madvise(block, block_size, MADV_SET_NONVOLATILE);
  241. bool this_block_was_purged = rc == 1;
  242. if (rc < 0) {
  243. perror("madvise");
  244. ASSERT_NOT_REACHED();
  245. }
  246. rc = mprotect(block, block_size, PROT_READ | PROT_WRITE);
  247. if (rc < 0) {
  248. perror("mprotect");
  249. ASSERT_NOT_REACHED();
  250. }
  251. if (this_block_was_purged) {
  252. g_malloc_stats.number_of_empty_block_purge_hits++;
  253. new (block) ChunkedBlock(good_size);
  254. }
  255. allocator->usable_blocks.append(block);
  256. }
  257. if (!block) {
  258. g_malloc_stats.number_of_block_allocs++;
  259. char buffer[64];
  260. snprintf(buffer, sizeof(buffer), "malloc: ChunkedBlock(%zu)", good_size);
  261. block = (ChunkedBlock*)os_alloc(block_size, buffer);
  262. new (block) ChunkedBlock(good_size);
  263. allocator->usable_blocks.append(block);
  264. ++allocator->block_count;
  265. }
  266. --block->m_free_chunks;
  267. void* ptr = block->m_freelist;
  268. block->m_freelist = block->m_freelist->next;
  269. if (block->is_full()) {
  270. g_malloc_stats.number_of_blocks_full++;
  271. #ifdef MALLOC_DEBUG
  272. dbgprintf("Block %p is now full in size class %zu\n", block, good_size);
  273. #endif
  274. allocator->usable_blocks.remove(block);
  275. allocator->full_blocks.append(block);
  276. }
  277. #ifdef MALLOC_DEBUG
  278. dbgprintf("LibC: allocated %p (chunk in block %p, size %zu)\n", ptr, block, block->bytes_per_chunk());
  279. #endif
  280. if (s_scrub_malloc)
  281. memset(ptr, MALLOC_SCRUB_BYTE, block->m_size);
  282. ue_notify_malloc(ptr, size);
  283. return ptr;
  284. }
  285. static void free_impl(void* ptr)
  286. {
  287. ScopedValueRollback rollback(errno);
  288. if (!ptr)
  289. return;
  290. g_malloc_stats.number_of_free_calls++;
  291. LOCKER(malloc_lock());
  292. void* block_base = (void*)((FlatPtr)ptr & block_mask);
  293. size_t magic = *(size_t*)block_base;
  294. if (magic == MAGIC_BIGALLOC_HEADER) {
  295. auto* block = (BigAllocationBlock*)block_base;
  296. #ifdef RECYCLE_BIG_ALLOCATIONS
  297. if (auto* allocator = big_allocator_for_size(block->m_size)) {
  298. if (allocator->blocks.size() < number_of_big_blocks_to_keep_around_per_size_class) {
  299. g_malloc_stats.number_of_big_allocator_keeps++;
  300. allocator->blocks.append(block);
  301. size_t this_block_size = block->m_size;
  302. if (mprotect(block, this_block_size, PROT_NONE) < 0) {
  303. perror("mprotect");
  304. ASSERT_NOT_REACHED();
  305. }
  306. if (madvise(block, this_block_size, MADV_SET_VOLATILE) != 0) {
  307. perror("madvise");
  308. ASSERT_NOT_REACHED();
  309. }
  310. return;
  311. }
  312. }
  313. #endif
  314. g_malloc_stats.number_of_big_allocator_frees++;
  315. os_free(block, block->m_size);
  316. return;
  317. }
  318. assert(magic == MAGIC_PAGE_HEADER);
  319. auto* block = (ChunkedBlock*)block_base;
  320. #ifdef MALLOC_DEBUG
  321. dbgprintf("LibC: freeing %p in allocator %p (size=%u, used=%u)\n", ptr, block, block->bytes_per_chunk(), block->used_chunks());
  322. #endif
  323. if (s_scrub_free)
  324. memset(ptr, FREE_SCRUB_BYTE, block->bytes_per_chunk());
  325. auto* entry = (FreelistEntry*)ptr;
  326. entry->next = block->m_freelist;
  327. block->m_freelist = entry;
  328. if (block->is_full()) {
  329. size_t good_size;
  330. auto* allocator = allocator_for_size(block->m_size, good_size);
  331. #ifdef MALLOC_DEBUG
  332. dbgprintf("Block %p no longer full in size class %u\n", block, good_size);
  333. #endif
  334. g_malloc_stats.number_of_freed_full_blocks++;
  335. allocator->full_blocks.remove(block);
  336. allocator->usable_blocks.prepend(block);
  337. }
  338. ++block->m_free_chunks;
  339. if (!block->used_chunks()) {
  340. size_t good_size;
  341. auto* allocator = allocator_for_size(block->m_size, good_size);
  342. if (allocator->block_count < number_of_chunked_blocks_to_keep_around_per_size_class) {
  343. #ifdef MALLOC_DEBUG
  344. dbgprintf("Keeping block %p around for size class %u\n", block, good_size);
  345. #endif
  346. g_malloc_stats.number_of_keeps++;
  347. allocator->usable_blocks.remove(block);
  348. allocator->empty_blocks[allocator->empty_block_count++] = block;
  349. mprotect(block, block_size, PROT_NONE);
  350. madvise(block, block_size, MADV_SET_VOLATILE);
  351. return;
  352. }
  353. #ifdef MALLOC_DEBUG
  354. dbgprintf("Releasing block %p for size class %u\n", block, good_size);
  355. #endif
  356. g_malloc_stats.number_of_frees++;
  357. allocator->usable_blocks.remove(block);
  358. --allocator->block_count;
  359. os_free(block, block_size);
  360. }
  361. }
  362. [[gnu::flatten]] void* malloc(size_t size)
  363. {
  364. void* ptr = malloc_impl(size);
  365. if (s_profiling)
  366. perf_event(PERF_EVENT_MALLOC, size, reinterpret_cast<FlatPtr>(ptr));
  367. return ptr;
  368. }
  369. [[gnu::flatten]] void free(void* ptr)
  370. {
  371. if (s_profiling)
  372. perf_event(PERF_EVENT_FREE, reinterpret_cast<FlatPtr>(ptr), 0);
  373. free_impl(ptr);
  374. ue_notify_free(ptr);
  375. }
  376. void* calloc(size_t count, size_t size)
  377. {
  378. size_t new_size = count * size;
  379. auto* ptr = malloc(new_size);
  380. if (ptr)
  381. memset(ptr, 0, new_size);
  382. return ptr;
  383. }
  384. size_t malloc_size(void* ptr)
  385. {
  386. if (!ptr)
  387. return 0;
  388. LOCKER(malloc_lock());
  389. void* page_base = (void*)((FlatPtr)ptr & block_mask);
  390. auto* header = (const CommonHeader*)page_base;
  391. auto size = header->m_size;
  392. if (header->m_magic == MAGIC_BIGALLOC_HEADER)
  393. size -= sizeof(CommonHeader);
  394. return size;
  395. }
  396. void* realloc(void* ptr, size_t size)
  397. {
  398. if (!ptr)
  399. return malloc(size);
  400. if (!size)
  401. return nullptr;
  402. LOCKER(malloc_lock());
  403. auto existing_allocation_size = malloc_size(ptr);
  404. if (size <= existing_allocation_size)
  405. return ptr;
  406. auto* new_ptr = malloc(size);
  407. if (new_ptr) {
  408. memcpy(new_ptr, ptr, min(existing_allocation_size, size));
  409. free(ptr);
  410. }
  411. return new_ptr;
  412. }
  413. void __malloc_init()
  414. {
  415. new (&malloc_lock()) LibThread::Lock();
  416. if (getenv("LIBC_NOSCRUB_MALLOC"))
  417. s_scrub_malloc = false;
  418. if (getenv("LIBC_NOSCRUB_FREE"))
  419. s_scrub_free = false;
  420. if (getenv("LIBC_LOG_MALLOC"))
  421. s_log_malloc = true;
  422. if (getenv("LIBC_PROFILE_MALLOC"))
  423. s_profiling = true;
  424. for (size_t i = 0; i < num_size_classes; ++i) {
  425. new (&allocators()[i]) Allocator();
  426. allocators()[i].size = size_classes[i];
  427. }
  428. new (&big_allocators()[0])(BigAllocator);
  429. }
  430. void serenity_dump_malloc_stats()
  431. {
  432. dbg() << "# malloc() calls: " << g_malloc_stats.number_of_malloc_calls;
  433. dbg();
  434. dbg() << "big alloc hits: " << g_malloc_stats.number_of_big_allocator_hits;
  435. dbg() << "big alloc hits that were purged: " << g_malloc_stats.number_of_big_allocator_purge_hits;
  436. dbg() << "big allocs: " << g_malloc_stats.number_of_big_allocs;
  437. dbg();
  438. dbg() << "empty block hits: " << g_malloc_stats.number_of_empty_block_hits;
  439. dbg() << "empty block hits that were purged: " << g_malloc_stats.number_of_empty_block_purge_hits;
  440. dbg() << "block allocs: " << g_malloc_stats.number_of_block_allocs;
  441. dbg() << "filled blocks: " << g_malloc_stats.number_of_blocks_full;
  442. dbg();
  443. dbg() << "# free() calls: " << g_malloc_stats.number_of_free_calls;
  444. dbg();
  445. dbg() << "big alloc keeps: " << g_malloc_stats.number_of_big_allocator_keeps;
  446. dbg() << "big alloc frees: " << g_malloc_stats.number_of_big_allocator_frees;
  447. dbg();
  448. dbg() << "full block frees: " << g_malloc_stats.number_of_freed_full_blocks;
  449. dbg() << "number of keeps: " << g_malloc_stats.number_of_keeps;
  450. dbg() << "number of frees: " << g_malloc_stats.number_of_frees;
  451. }
  452. }