2#include "gaia/config/config.h"
8#include "gaia/cnt/fwd_llist.h"
9#include "gaia/cnt/sarray.h"
10#include "gaia/core/bit_utils.h"
11#include "gaia/core/dyn_singleton.h"
12#include "gaia/core/utility.h"
13#include "gaia/mem/mem_alloc.h"
14#include "gaia/meta/type_info.h"
15#include "gaia/util/logging.h"
19 static constexpr uint32_t MemoryBlockAlignment = 16;
22 static constexpr uint32_t MemoryBlockBytesDefault = 32768;
24 static constexpr uint32_t MemoryBlockUsableOffset =
sizeof(uintptr_t);
33 template <
typename T, u
int32_t RequestedBlockSize>
35 static constexpr uint32_t next_multiple_of_alignment(uint32_t num) {
36 return (num + (MemoryBlockAlignment - 1)) & uint32_t(-(int32_t)MemoryBlockAlignment);
38 static constexpr uint32_t calculate_block_size() {
39 if constexpr (RequestedBlockSize == 0)
40 return next_multiple_of_alignment(MemoryBlockBytesDefault);
42 return next_multiple_of_alignment(RequestedBlockSize);
45 static constexpr uint32_t MemoryBlockBytes = calculate_block_size();
46 static constexpr uint16_t NBlocks = 48;
47 static constexpr uint16_t NBlocks_Bits = (uint16_t)core::count_bits(NBlocks);
48 static constexpr uint32_t InvalidBlockId = NBlocks + 1;
49 static constexpr uint32_t BlockArrayBytes = ((uint32_t)NBlocks_Bits * (uint32_t)NBlocks + 7) / 8;
75 void write_block_idx(uint32_t blockIdx, uint32_t value) {
76 const uint32_t bitPosition = blockIdx * NBlocks_Bits;
78 GAIA_ASSERT(bitPosition < NBlocks * NBlocks_Bits);
79 GAIA_ASSERT(value <= InvalidBlockId);
81 BitView{{(uint8_t*)
m_blocks.data(), BlockArrayBytes}}.set(bitPosition, (uint8_t)value);
84 uint8_t read_block_idx(uint32_t blockIdx)
const {
85 const uint32_t bitPosition = blockIdx * NBlocks_Bits;
87 GAIA_ASSERT(bitPosition < NBlocks * NBlocks_Bits);
89 return BitView{{(uint8_t*)
m_blocks.data(), BlockArrayBytes}}.get(bitPosition);
94 auto StoreBlockAddress = [&](uint32_t index) {
97 uint8_t* pMemoryBlock = (uint8_t*)
m_data + (index * MemoryBlockBytes);
98 GAIA_ASSERT((uintptr_t)pMemoryBlock % MemoryBlockAlignment == 0);
100 return (
void*)(pMemoryBlock + MemoryBlockUsableOffset);
104 GAIA_ASSERT(!full() &&
"Trying to allocate too many blocks!");
110 write_block_idx(index, index);
112 return StoreBlockAddress(index);
123 return StoreBlockAddress(index);
131 auto ReadBlockAddress = [&](
void* pMemory) {
133 const auto* pMemoryBlock = (uint8_t*)pMemory - MemoryBlockUsableOffset;
135 [[maybe_unused]]
const auto* pPage = (
Page**)pMemoryBlock;
136 GAIA_ASSERT(*pPage ==
this);
137 const auto blckAddr = (uintptr_t)pMemoryBlock;
138 GAIA_ASSERT(blckAddr % 16 == 0);
139 const auto dataAddr = (uintptr_t)
m_data;
140 const auto blockIdx = (uint32_t)((blckAddr - dataAddr) / MemoryBlockBytes);
143 const auto blockIdx = ReadBlockAddress(pBlock);
147 write_block_idx(blockIdx, InvalidBlockId);
156 GAIA_NODISCARD uint32_t used_blocks_cnt()
const {
160 GAIA_NODISCARD
bool full()
const {
161 return used_blocks_cnt() >= NBlocks;
164 GAIA_NODISCARD
bool empty()
const {
165 return used_blocks_cnt() == 0;
169 template <
typename T, u
int32_t RequestedBlockSize>
176 GAIA_NODISCARD
bool empty()
const {
193 template <
typename T, u
int32_t RequestedBlockSize>
194 class PagedAllocatorImpl;
197 template <
typename T, u
int32_t RequestedBlockSize = 0>
202 template <
typename T, u
int32_t RequestedBlockSize>
204 friend ::gaia::mem::PagedAllocator<T, RequestedBlockSize>;
206 inline static char s_strPageData[256]{};
207 inline static char s_strMemPage[256]{};
215 bool m_isDone =
false;
221 auto ct_name = meta::type_info::name<T>();
222 const auto ct_name_len = (uint32_t)ct_name.size();
223 GAIA_STRCPY(s_strPageData, 256,
"PageData_");
224 memcpy((
void*)&s_strPageData[9], (
const void*)ct_name.data(), ct_name_len);
225 s_strPageData[9 + ct_name_len] = 0;
226 GAIA_STRCPY(s_strMemPage, 256,
"MemPage_");
227 memcpy((
void*)&s_strMemPage[8], (
const void*)ct_name.data(), ct_name_len);
228 s_strMemPage[8 + ct_name_len] = 0;
235 auto memStats =
stats();
236 if (memStats.mem_total != 0) {
237 GAIA_ASSERT2(
false,
"Paged allocator leaking memory");
238 GAIA_LOG_W(
"Paged allocator leaking memory!");
254 void*
alloc([[maybe_unused]] uint32_t dummy) {
255 void* pBlock =
nullptr;
259 GAIA_ASSERT(pPage ==
nullptr || !pPage->full());
260 if (pPage ==
nullptr) {
262 pPage = alloc_page();
267 pBlock = pPage->alloc_block();
280 GAIA_CLANG_WARNING_PUSH()
282 GAIA_CLANG_WARNING_DISABLE("-Wcast-align")
287 const auto pageAddr = *(uintptr_t*)((uint8_t*)pBlock - MemoryBlockUsableOffset);
288 GAIA_ASSERT(pageAddr % MemoryBlockAlignment == 0);
289 auto* pPage = (
Page*)pageAddr;
290 const bool wasFull = pPage->full();
292#if GAIA_ASSERT_ENABLED
294 const auto res = m_pages.
pagesFull.has(pPage);
295 GAIA_ASSERT(res &&
"Memory page couldn't be found among full pages");
297 const auto res = m_pages.
pagesFree.has(pPage);
298 GAIA_ASSERT(res &&
"Memory page couldn't be found among free pages");
303 pPage->free_block(pBlock);
316 if (pPage->empty()) {
325 GAIA_CLANG_WARNING_POP()
335 for (
const auto& page: m_pages.
pagesFree)
336 stats.
mem_used += page.used_blocks_cnt() * (size_t)Page::MemoryBlockBytes;
344 auto* pPage = &(*it);
358 auto memStats =
stats();
359 GAIA_LOG_N(
"PagedAllocator %p stats", (
void*)
this);
360 GAIA_LOG_N(
" Allocated: %" PRIu64
" B", memStats.mem_total);
361 GAIA_LOG_N(
" Used: %" PRIu64
" B", memStats.mem_total - memStats.mem_used);
362 GAIA_LOG_N(
" Overhead: %" PRIu64
" B", memStats.mem_used);
364 " Utilization: %.1f%%",
365 memStats.mem_total != 0 ? 100.0 * ((
double)memStats.mem_used / (
double)memStats.mem_total) : 0.0);
366 GAIA_LOG_N(
" Pages: %u", memStats.num_pages);
367 GAIA_LOG_N(
" Free pages: %u", memStats.num_pages_free);
371 static Page* alloc_page() {
372 const uint32_t size = Page::NBlocks * Page::MemoryBlockBytes;
373 auto* pPageData = mem::AllocHelper::alloc_alig<uint8_t>(&s_strPageData[0], MemoryBlockAlignment, size);
374 auto* pMemoryPage = mem::AllocHelper::alloc<Page>(&s_strMemPage[0]);
375 return new (pMemoryPage) Page(pPageData);
378 static void free_page(Page* pMemoryPage) {
379 GAIA_ASSERT(pMemoryPage !=
nullptr);
381 mem::AllocHelper::free_alig(&s_strPageData[0], pMemoryPage->m_data);
382 pMemoryPage->~MemoryPage();
383 mem::AllocHelper::free(&s_strMemPage[0], pMemoryPage);
390 void try_delete_this() {
Array of elements of type.
Definition sarray_impl.h:26
Gaia-ECS is a header-only library which means we want to avoid using global static variables because ...
Definition dyn_singleton.h:21
Definition paged_allocator.h:203
void diag() const
Performs diagnostics of the memory used.
Definition paged_allocator.h:357
void free(void *pBlock)
Releases memory allocated for pointer.
Definition paged_allocator.h:285
MemoryPageStats stats() const
Returns allocator statistics.
Definition paged_allocator.h:328
void * alloc(uint32_t dummy)
Allocates memory.
Definition paged_allocator.h:254
void flush()
Flushes unused memory.
Definition paged_allocator.h:342
Pointer wrapper for writing memory in defined way (not causing undefined behavior)
Definition mem_alloc.h:260
Checks if endianess was detected correctly at compile-time.
Definition bitset.h:9
Each fwd_llist node either has to inherit from fwd_llist_base or it has to provide get_fwd_llist_link...
Definition fwd_llist.h:26
Forward list container. No memory allocation is performed because the list is stored directly inside ...
Definition fwd_llist.h:85
Definition bit_utils.h:11
Definition paged_allocator.h:170
cnt::fwd_llist< MemoryPage< T, RequestedBlockSize > > pagesFull
List of full pages.
Definition paged_allocator.h:174
cnt::fwd_llist< MemoryPage< T, RequestedBlockSize > > pagesFree
List of available pages.
Definition paged_allocator.h:172
Definition paged_allocator.h:181
uint32_t num_pages_free
Number of free pages.
Definition paged_allocator.h:189
uint64_t mem_used
Memory actively used.
Definition paged_allocator.h:185
uint64_t mem_total
Total allocated memory.
Definition paged_allocator.h:183
uint32_t num_pages
Number of allocated pages.
Definition paged_allocator.h:187
Definition paged_allocator.h:34
void free_block(void *pBlock)
Release the block allocated by this page.
Definition paged_allocator.h:127
BlockArray m_blocks
Implicit list of blocks.
Definition paged_allocator.h:56
uint32_t m_nextFreeBlock
Index of the next block to recycle.
Definition paged_allocator.h:63
uint32_t m_freeBlocks
Number of blocks to recycle.
Definition paged_allocator.h:65
uint32_t m_usedBlocks
Number of used blocks out of NBlocks.
Definition paged_allocator.h:61
MemoryPage(void *ptr)
Free bits to use in the future.
Definition paged_allocator.h:69
uint32_t m_blockCnt
Number of blocks in the block array.
Definition paged_allocator.h:59
GAIA_NODISCARD void * alloc_block()
Allocate a new block for this page.
Definition paged_allocator.h:93