mallocdefs.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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/AllOf.h>
  8. #include <AK/Array.h>
  9. #include <AK/InlineLinkedList.h>
  10. #include <AK/Types.h>
  11. #define MAGIC_PAGE_HEADER 0x42657274 // 'Bert'
  12. #define MAGIC_BIGALLOC_HEADER 0x42697267 // 'Birg'
  13. #define MALLOC_SCRUB_BYTE 0xdc
  14. #define FREE_SCRUB_BYTE 0xed
  15. static constexpr Array<unsigned short, 13> size_classes { 8, 16, 32, 64, 128, 256, 504, 1016, 2032, 4088, 8184, 16376, 32752 };
  16. static constexpr auto malloc_alignment = 8;
  17. static_assert(all_of(size_classes.begin(), size_classes.end(),
  18. [](const auto val) { return val % malloc_alignment == 0; }));
  19. struct CommonHeader {
  20. size_t m_magic;
  21. size_t m_size;
  22. };
  23. struct BigAllocationBlock : public CommonHeader {
  24. BigAllocationBlock(size_t size)
  25. {
  26. m_magic = MAGIC_BIGALLOC_HEADER;
  27. m_size = size;
  28. }
  29. unsigned char* m_slot[0];
  30. };
  31. struct FreelistEntry {
  32. FreelistEntry* next;
  33. };
  34. struct ChunkedBlock
  35. : public CommonHeader
  36. , public InlineLinkedListNode<ChunkedBlock> {
  37. static constexpr size_t block_size = 64 * KiB;
  38. static constexpr size_t block_mask = ~(block_size - 1);
  39. ChunkedBlock(size_t bytes_per_chunk)
  40. {
  41. m_magic = MAGIC_PAGE_HEADER;
  42. m_size = bytes_per_chunk;
  43. m_free_chunks = chunk_capacity();
  44. }
  45. ChunkedBlock* m_prev { nullptr };
  46. ChunkedBlock* m_next { nullptr };
  47. size_t m_next_lazy_freelist_index { 0 };
  48. FreelistEntry* m_freelist { nullptr };
  49. size_t m_free_chunks { 0 };
  50. [[gnu::aligned(8)]] unsigned char m_slot[0];
  51. void* chunk(size_t index)
  52. {
  53. return &m_slot[index * m_size];
  54. }
  55. bool is_full() const { return m_free_chunks == 0; }
  56. size_t bytes_per_chunk() const { return m_size; }
  57. size_t free_chunks() const { return m_free_chunks; }
  58. size_t used_chunks() const { return chunk_capacity() - m_free_chunks; }
  59. size_t chunk_capacity() const { return (block_size - sizeof(ChunkedBlock)) / m_size; }
  60. };