2#include "gaia/config/config.h"
9#include "gaia/cnt/fwd_llist.h"
10#include "gaia/cnt/sarray.h"
11#include "gaia/core/bit_utils.h"
12#include "gaia/core/dyn_singleton.h"
13#include "gaia/core/utility.h"
14#include "gaia/mem/mem_alloc.h"
15#include "gaia/meta/type_info.h"
16#include "gaia/util/logging.h"
21 static constexpr uint32_t MemoryBlockAlignment = 16;
24 static constexpr uint32_t MemoryBlockBytesDefault = 32768;
26 static constexpr uint32_t MemoryBlockUsableOffset =
sizeof(uintptr_t);
41 template <
typename T, u
int32_t RequestedBlockSize>
47 return (num + (MemoryBlockAlignment - 1)) & uint32_t(-(int32_t)MemoryBlockAlignment);
52 if constexpr (RequestedBlockSize == 0)
67 static constexpr uint8_t FreedBlockPattern = 0xDD;
68 static constexpr uintptr_t FreedPageMarker = ~(uintptr_t)0;
128 auto StoreBlockAddress = [&](uint32_t index) {
132 GAIA_ASSERT((uintptr_t)pMemoryBlock % MemoryBlockAlignment == 0);
134 return (
void*)(pMemoryBlock + MemoryBlockUsableOffset);
138 GAIA_ASSERT(!
full() &&
"Trying to allocate too many blocks!");
146 return StoreBlockAddress(index);
157 return StoreBlockAddress(index);
166 auto ReadBlockAddress = [&](
void* pMemory) {
168 const auto* pMemoryBlock = (uint8_t*)pMemory - MemoryBlockUsableOffset;
169#if GAIA_ASSERT_ENABLED
171 GAIA_ASSERT(pageAddr == (uintptr_t)
this);
173 const auto blckAddr = (uintptr_t)pMemoryBlock;
174 GAIA_ASSERT(blckAddr % 16 == 0);
175 const auto dataAddr = (uintptr_t)
m_data;
179 const auto blockIdx = ReadBlockAddress(pBlock);
183 std::memset(pBlock, FreedBlockPattern,
MemoryBlockBytes - MemoryBlockUsableOffset);
205 GAIA_NODISCARD
bool full()
const {
217#if GAIA_ASSERT_ENABLED
222 GAIA_ASSERT(((uintptr_t)
m_data % MemoryBlockAlignment) == 0);
224 uint64_t freeMask = 0;
229 const auto bit = uint64_t(1) << next;
230 GAIA_ASSERT((freeMask & bit) == 0 &&
"Free list contains a cycle");
240 GAIA_ASSERT(((uintptr_t)pMemoryBlock % MemoryBlockAlignment) == 0);
243 const bool isFree = (freeMask & (uint64_t(1) << i)) != 0;
245 GAIA_ASSERT(pageAddr == (isFree ? FreedPageMarker : (uintptr_t)
this));
255 template <
typename T, u
int32_t RequestedBlockSize>
283 template <
typename T, u
int32_t RequestedBlockSize>
284 class PagedAllocatorImpl;
291 template <
typename T, u
int32_t RequestedBlockSize = 0>
297 template <
typename T, u
int32_t RequestedBlockSize>
298 class PagedAllocatorImpl {
299 friend ::gaia::mem::PagedAllocator<T, RequestedBlockSize>;
301 inline static char s_strPageData[256]{};
302 inline static char s_strMemPage[256]{};
304 using Page = MemoryPage<T, RequestedBlockSize>;
305 using PageContainer = MemoryPageContainer<T, RequestedBlockSize>;
308 PageContainer m_pages;
310 bool m_isDone =
false;
313 PagedAllocatorImpl() {
316 auto ct_name = meta::type_info::name<T>();
317 const auto ct_name_len = (uint32_t)ct_name.size();
318 GAIA_STRCPY(s_strPageData, 256,
"PageData_");
319 memcpy((
void*)&s_strPageData[9], (
const void*)ct_name.data(), ct_name_len);
320 s_strPageData[9 + ct_name_len] = 0;
321 GAIA_STRCPY(s_strMemPage, 256,
"MemPage_");
322 memcpy((
void*)&s_strMemPage[8], (
const void*)ct_name.data(), ct_name_len);
323 s_strMemPage[8 + ct_name_len] = 0;
330 auto memStats = stats();
331 if (memStats.mem_total != 0) {
332 GAIA_ASSERT2(
false,
"Paged allocator leaking memory");
333 GAIA_LOG_W(
"Paged allocator leaking memory!");
339 ~PagedAllocatorImpl() {
343 PagedAllocatorImpl(PagedAllocatorImpl&& world) =
delete;
344 PagedAllocatorImpl(
const PagedAllocatorImpl& world) =
delete;
345 PagedAllocatorImpl& operator=(PagedAllocatorImpl&&) =
delete;
346 PagedAllocatorImpl& operator=(
const PagedAllocatorImpl&) =
delete;
349 void* alloc([[maybe_unused]] uint32_t dummy) {
350 const detail::ArenaLock arenaLock;
351 void* pBlock =
nullptr;
354 auto* pPage = m_pages.pagesFree.first;
355 GAIA_ASSERT(pPage ==
nullptr || !pPage->full());
356 if (pPage ==
nullptr) {
358 pPage = alloc_page();
359 m_pages.pagesFree.link(pPage);
363 pBlock = pPage->alloc_block();
368 m_pages.pagesFree.unlink(pPage);
370 m_pages.pagesFull.link(pPage);
377 GAIA_CLANG_WARNING_PUSH()
379 GAIA_CLANG_WARNING_DISABLE("-Wcast-align")
382 void free(
void* pBlock) {
383 const detail::ArenaLock arenaLock;
385 const auto pageAddr = *(uintptr_t*)((uint8_t*)pBlock - MemoryBlockUsableOffset);
386 GAIA_ASSERT(pageAddr % MemoryBlockAlignment == 0);
387 auto* pPage = (Page*)pageAddr;
388 const bool wasFull = pPage->full();
390#if GAIA_ASSERT_ENABLED
392 const auto res = m_pages.pagesFull.has(pPage);
393 GAIA_ASSERT(res &&
"Memory page couldn't be found among full pages");
395 const auto res = m_pages.pagesFree.has(pPage);
396 GAIA_ASSERT(res &&
"Memory page couldn't be found among free pages");
401 pPage->free_block(pBlock);
406 m_pages.pagesFull.unlink(pPage);
408 m_pages.pagesFree.link(pPage);
416 if (pPage->empty()) {
417 GAIA_ASSERT(!m_pages.pagesFree.empty());
418 m_pages.pagesFree.unlink(pPage);
425 GAIA_CLANG_WARNING_POP()
428 MemoryPageStats stats()
const {
429 MemoryPageStats stats{};
431 stats.num_pages = (uint32_t)m_pages.pagesFree.size() + (uint32_t)m_pages.pagesFull.size();
432 stats.num_pages_free = (uint32_t)m_pages.pagesFree.size();
433 stats.mem_total = stats.num_pages * (size_t)Page::MemoryBlockBytes * Page::NBlocks;
434 stats.mem_used = m_pages.pagesFull.size() * (size_t)Page::MemoryBlockBytes * Page::NBlocks;
435 for (
const auto& page: m_pages.pagesFree)
436 stats.mem_used += page.used_blocks_cnt() * (size_t)Page::MemoryBlockBytes;
443 const detail::ArenaLock arenaLock;
444 for (
auto it = m_pages.pagesFree.begin(); it != m_pages.pagesFree.end();) {
445 auto* pPage = &(*it);
452 m_pages.pagesFree.unlink(pPage);
461 auto memStats = stats();
462 GAIA_LOG_N(
"PagedAllocator %p stats", (
void*)
this);
463 GAIA_LOG_N(
" Allocated: %" PRIu64
" B", memStats.mem_total);
464 GAIA_LOG_N(
" Used: %" PRIu64
" B", memStats.mem_total - memStats.mem_used);
465 GAIA_LOG_N(
" Overhead: %" PRIu64
" B", memStats.mem_used);
467 " Utilization: %.1f%%",
468 memStats.mem_total != 0 ? 100.0 * ((
double)memStats.mem_used / (
double)memStats.mem_total) : 0.0);
469 GAIA_LOG_N(
" Pages: %u", memStats.num_pages);
470 GAIA_LOG_N(
" Free pages: %u", memStats.num_pages_free);
473 void verify()
const {
474#if GAIA_ASSERT_ENABLED
475 for (
const auto& page: m_pages.pagesFree) {
476 GAIA_ASSERT(page.get_fwd_llist_link().linked());
477 GAIA_ASSERT(!page.full());
481 for (
const auto& page: m_pages.pagesFull) {
482 GAIA_ASSERT(page.get_fwd_llist_link().linked());
483 GAIA_ASSERT(page.full());
490 static Page* alloc_page() {
491 const uint32_t size = Page::NBlocks * Page::MemoryBlockBytes;
492 auto* pPageData = mem::AllocHelper::alloc_alig<uint8_t>(&s_strPageData[0], MemoryBlockAlignment, size);
493 auto* pMemoryPage = mem::AllocHelper::alloc<Page>(&s_strMemPage[0]);
494 return new (pMemoryPage) Page(pPageData);
497 static void free_page(Page* pMemoryPage) {
498 GAIA_ASSERT(pMemoryPage !=
nullptr);
500 mem::AllocHelper::free_alig(&s_strPageData[0], pMemoryPage->m_data);
501 pMemoryPage->~MemoryPage();
502 mem::AllocHelper::free(&s_strMemPage[0], pMemoryPage);
509 void try_delete_this() {
Array with variable size of elements of type.
Definition darray_impl.h:27
GAIA_NODISCARD bool empty() const noexcept
Checks whether the container has no elements.
Definition darray_impl.h:510
GAIA_NODISCARD pointer data() noexcept
Returns a pointer to the element storage.
Definition darray_impl.h:193
Gaia-ECS is a header-only library which means we want to avoid using global static variables because ...
Definition dyn_singleton.h:29
Pointer wrapper for writing memory in defined way (not causing undefined behavior)
Definition mem_alloc.h:423
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:29
Provides packed access to fixed-width unsigned values stored in a byte span.
Definition bit_utils.h:13
Lists the non-full and full pages belonging to an allocator.
Definition paged_allocator.h:256
cnt::fwd_llist< MemoryPage< T, RequestedBlockSize > > pagesFull
List of full pages.
Definition paged_allocator.h:260
GAIA_NODISCARD bool empty() const
Reports whether the container has no pages.
Definition paged_allocator.h:264
cnt::fwd_llist< MemoryPage< T, RequestedBlockSize > > pagesFree
List of available pages.
Definition paged_allocator.h:258
Aggregate statistics for a paged allocator.
Definition paged_allocator.h:270
uint32_t num_pages_free
Number of free pages.
Definition paged_allocator.h:278
uint64_t mem_used
Memory actively used.
Definition paged_allocator.h:274
uint64_t mem_total
Total allocated memory.
Definition paged_allocator.h:272
uint32_t num_pages
Number of allocated pages.
Definition paged_allocator.h:276
Fixed-capacity page of equal-sized blocks.
Definition paged_allocator.h:42
uint8_t read_block_idx(uint32_t blockIdx) const
Reads one link from the packed recycled-block list.
Definition paged_allocator.h:117
static constexpr uint16_t NBlocks
Maximum number of blocks in a page.
Definition paged_allocator.h:61
void free_block(void *pBlock)
Release the block allocated by this page.
Definition paged_allocator.h:162
void write_block_idx(uint32_t blockIdx, uint32_t value)
Writes one link in the packed recycled-block list.
Definition paged_allocator.h:105
BlockArray m_blocks
Implicit list of blocks.
Definition paged_allocator.h:81
static constexpr uint32_t calculate_block_size()
Selects and aligns the configured block size.
Definition paged_allocator.h:51
uint32_t m_nextFreeBlock
Index of the next block to recycle.
Definition paged_allocator.h:88
void verify() const
Verifies page invariants in assertion-enabled builds.
Definition paged_allocator.h:216
uint32_t m_freeBlocks
Number of blocks to recycle.
Definition paged_allocator.h:90
GAIA_NODISCARD bool empty() const
Reports whether no page blocks are allocated.
Definition paged_allocator.h:211
GAIA_NODISCARD bool full() const
Reports whether all page blocks are allocated.
Definition paged_allocator.h:205
uint32_t m_usedBlocks
Number of used blocks out of NBlocks.
Definition paged_allocator.h:86
static constexpr uint32_t BlockArrayBytes
Bytes occupied by the packed block-index array.
Definition paged_allocator.h:71
static constexpr uint32_t MemoryBlockBytes
Size of one block in bytes.
Definition paged_allocator.h:59
MemoryPage(void *ptr)
Free bits to use in the future.
Definition paged_allocator.h:96
uint32_t m_blockCnt
Number of blocks in the block array.
Definition paged_allocator.h:84
GAIA_NODISCARD uint32_t used_blocks_cnt() const
Returns the number of live blocks.
Definition paged_allocator.h:199
static constexpr uint32_t InvalidBlockId
Sentinel terminating the recycled-block list.
Definition paged_allocator.h:65
static constexpr uint16_t NBlocks_Bits
Bits required to encode a block index.
Definition paged_allocator.h:63
GAIA_NODISCARD void * alloc_block()
Allocate a new block for this page.
Definition paged_allocator.h:127
static constexpr uint32_t next_multiple_of_alignment(uint32_t num)
Rounds a size up to MemoryBlockAlignment.
Definition paged_allocator.h:46