mallocdefs.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/IntrusiveList.h>
  8. #include <AK/Types.h>
  9. #define MAGIC_PAGE_HEADER 0x42657274 // 'Bert'
  10. #define MAGIC_BIGALLOC_HEADER 0x42697267 // 'Birg'
  11. #define MALLOC_SCRUB_BYTE 0xdc
  12. #define FREE_SCRUB_BYTE 0xed
  13. #define PAGE_ROUND_UP(x) ((((size_t)(x)) + PAGE_SIZE - 1) & (~(PAGE_SIZE - 1)))
  14. static constexpr unsigned short size_classes[] = { 16, 32, 64, 128, 256, 496, 1008, 2032, 4080, 8176, 16368, 32752, 0 };
  15. static constexpr size_t num_size_classes = (sizeof(size_classes) / sizeof(unsigned short)) - 1;
  16. #ifndef NO_TLS
  17. extern "C" {
  18. extern __thread bool s_allocation_enabled;
  19. }
  20. #endif
  21. consteval bool check_size_classes_alignment()
  22. {
  23. for (size_t i = 0; i < num_size_classes; i++) {
  24. if ((size_classes[i] % 16) != 0)
  25. return false;
  26. }
  27. return true;
  28. }
  29. static_assert(check_size_classes_alignment());
  30. struct CommonHeader {
  31. size_t m_magic;
  32. size_t m_size;
  33. };
  34. struct BigAllocationBlock : public CommonHeader {
  35. BigAllocationBlock(size_t size)
  36. {
  37. m_magic = MAGIC_BIGALLOC_HEADER;
  38. m_size = size;
  39. }
  40. alignas(16) unsigned char* m_slot[0];
  41. };
  42. struct FreelistEntry {
  43. FreelistEntry* next;
  44. };
  45. struct ChunkedBlock : public CommonHeader {
  46. static constexpr size_t block_size = 64 * KiB;
  47. static constexpr size_t block_mask = ~(block_size - 1);
  48. ChunkedBlock(size_t bytes_per_chunk)
  49. {
  50. m_magic = MAGIC_PAGE_HEADER;
  51. m_size = bytes_per_chunk;
  52. m_free_chunks = chunk_capacity();
  53. }
  54. IntrusiveListNode<ChunkedBlock> m_list_node;
  55. size_t m_next_lazy_freelist_index { 0 };
  56. FreelistEntry* m_freelist { nullptr };
  57. size_t m_free_chunks { 0 };
  58. alignas(16) unsigned char m_slot[0];
  59. void* chunk(size_t index)
  60. {
  61. return &m_slot[index * m_size];
  62. }
  63. bool is_full() const { return m_free_chunks == 0; }
  64. size_t bytes_per_chunk() const { return m_size; }
  65. size_t free_chunks() const { return m_free_chunks; }
  66. size_t used_chunks() const { return chunk_capacity() - m_free_chunks; }
  67. size_t chunk_capacity() const { return (block_size - sizeof(ChunkedBlock)) / m_size; }
  68. using List = IntrusiveList<&ChunkedBlock::m_list_node>;
  69. };