malloc.cpp 17 KB

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