DArena

Native arena allocator

Context

_images/ditaa-e983fdf7be885c1214a38122e1409f3a4499373e.png
#include <xo/arena/DArena.hpp>

Arena memory layout

 <------------------------reserved-------------------------->
 <------------committed-----------><-------uncommitted------>
 <--allocated--><----available---->

 XXXXXXXXXXXXXXX___________________..........................
^               ^                  ^                         ^
lo              free               limit                     hi

 [X] allocated:   handed out; used bytes plus per-alloc overhead
 [_] available:   committed, not yet handed out
 [.] uncommitted: mapped in virtual memory, not backed by memory

 so: allocated + available = committed,
     committed + uncommitted = reserved

Representation for a single allocation

               free_(pre)
                   v

                   <-------------z1--------------->
          < guard ><  hz  ><     req_z     >< dz  >< guard >

used <==  +++++++++0000zzzz@@@@@@@@@@@@@@@@@ppppppp+++++++++ ==> avail

                   ^       ^                                ^
                   header  mem                              |
                   ^                                        |
                   last_header_                   free_(post)

           [+] guard surrounding each allocation, for simple sanitize checks
           [0] unused header bits (available for application metadata)
           [z] record allocation size
           [@] new allocated memory
           [p] padding (to uintptr_t alignment)

Class

class DArena

represent arena allocator state

Provides minimal RAII functionality around memory mapping. For allocation implementation see IAllocator_DArena

Member Variables

group Mm-arena-instance-vars

Variables

ArenaConfig config_

arena configuration

size_type page_z_ = 0

size of a VM page (obtained automatically via getpagesize()). Likely 4k

size_type arena_align_z_ = 0

alignment for this arena. In practice will be either page_z_ or cfg.hugepage_z_

std::byte *lo_ = nullptr

arena owns memory in range [lo_, hi_)

size_type committed_z_ = 0

prefix of this size is committed. Remainder mapped but uncommitted.

header_type *last_header_ = nullptr

if config_.store_header_flag_: Pointer to header for last allocation.

std::byte *free_ = nullptr

free pointer. Memory in range [lo_, free_) current in use

std::byte *limit_ = nullptr

soft limit; end of committed virtual memory Memory in range [lo_, limit_) is committed (backed by physical memory)

std::byte *hi_ = nullptr

hard limit; end of reserved virtual memory Memory in range [limit_, hi_) is uncommitted

uint32_t error_count_ = 0

count runtime errors. Each error updates last_error_

AllocError last_error_

capture some error details if/when error

Type Traits

group arena type traits

Typedefs

using size_type = std::size_t

an amount of memory

using value_type = std::byte*

allocation pointer; use for allocation results

using range_type = std::pair<value_type, value_type>

a contiguous memory range

using header_type = AllocHeader

type for allocation header (if enabled)

using typeseq = xo::reflect::typeseq

integer identifying a type (see xo::facet::typeid<T>())

Enums

enum class alloc_mode : uint8_t

mode argument for _alloc

Values:

enumerator standard

ordinary alloc. Most common mode

enumerator super

begin a sequence of suballocs that share a single alloc header

enumerator sub_incomplete

make a subsidiary allocation on behalf of a preceding super alloc. Will be followed by at least one more suballoc call.

enumerator sub_complete

make a subsidiary allocation that completes preceding super alloc.

struct Checkpoint
#include <DArena.hpp>

Checkpoint for unwinding arena state.

Constructors

group arena constructors and destructors

Functions

static bool validate(const ArenaConfig &cfg, MapInfo *info, bool debug_flag, bool throw_flag)

check whether config is admits map()

static DArena map(const ArenaConfig &cfg)

create arena per configuration cfg.

DArena() = default

null ctor

DArena(const ArenaConfig &cfg)

create arena from cfg. Will reserve memory for allocation

DArena(const ArenaConfig &cfg, size_type page_z, size_type arena_align_z, value_type lo, value_type hi)

ctor from already-mapped (but not committed) address range [lo,hi]

DArena(const DArena &other) = delete

DArena is not copyable

DArena(DArena &&other)

move ctor

~DArena()

dtor releases mapped memory

DArena &operator=(DArena &&other)

move-assignment

Methods

group Mm-arena-methods

Functions

static inline bool is_gc_eligible()

false -> not eligible for GC (allocates own memory + not moveable)

static DArena *obj2arena(const void *obj, size_type base_align_z)

recover DArena address from a pointer to its interior Requires:

  • x belongs to a DArena that has base_align_z_ = 2^k for some specific k > 0. To remove all doubt: all arenas to which x might belong, must be using the same value for base_align_z_.

Note that the requirement isn’t verifiable at runtime.

inline const ArenaConfig &config() const noexcept

The configuration this arena was mapped with.

config_ is public &#8212; DArena is a struct with no access specifiers &#8212; so this adds no reach. It exists to give generic code a NAME to depend on: DHandleStore is templated on its storage type and requires alloc headers, and spelling that as storage_.config_.store_header_flag_ would pin every future Storage to this member layout.

inline std::string_view name() const noexcept

This arena’s name, as configured.

Borrowed from config_, so valid as long as the arena is.

inline size_type reserved() const noexcept

Reserved memory, in bytes. This is the maximum size of this arena.

inline size_type allocated() const noexcept

Allocated memory in bytes: memory consumed by allocs from this arena, including administrative overhead (alloc headers + guard bytes)

inline size_type committed() const noexcept

Committed memory in bytes: amount of memory actually backed by physical memory

inline size_type available() const noexcept

Available committed memory. This is the amount of memory guaranteed to be usable for future allocs from this arena.

inline size_type page_z() const noexcept

VM page size for this arena (likely 4KB)

inline size_type preamble_z() const noexcept

per-arena overhead, within mapped memory

inline size_type alloc_header_z() const noexcept

per-allocation overhead

inline size_type guard_z() const noexcept
inline size_type padded_guard_z() const noexcept
inline size_type per_alloc_overhead_z() const noexcept
inline const AllocError &last_error() const noexcept

Last error encountered by this arena

inline bool contains(const void *addr) const noexcept

True iff address addr is owned by this arena, i.e. falls within [lo_, hi_)

inline bool contains_allocated(const void *addr) const noexcept

True iff address addr is owned by this arena and in allocated regions

inline bool is_mapped() const noexcept

true if arena is mapped i.e. has a reserved address range

DArenaIterator begin() const noexcept

@ret iterator pointing to the first allocation in this arena

DArenaIterator end() const noexcept

@ret iterator pointing to just after the last allocation in this arena

AllocHeader *begin_header() const noexcept

@ret header for first allocation in this arena

AllocHeader *end_header() const noexcept

@ret location of header for next (not yet performed!) allocation in this arena

void visit_pools(const MemorySizeVisitor &fn) const

report memory use for this arena to fn. For DArena reporting just one pool = arena’s memory range

header_type *obj2hdr(void *obj) noexcept

get header from allocated object address

const header_type *obj2hdr(void *obj) const noexcept

get header from allocated object address (const version)

AllocInfo alloc_info(value_type mem) const noexcept

report alloc book-keeping info for allocation at mem

Require:

  1. mem is address returned by allocation on this arena i.e. by IAllocator_DArena::alloc() or IAllocator_DArena::alloc_super()

  2. mem has not been invalidated since it was allocated i.e. by call to DArena::clear

Note: non-const, may stash error details

template<typename T>
inline void *alloc_for(size_type n = sizeof(T))

convenience template for allocating for a T-instance

value_type alloc(typeseq t, size_type z)

allocate at least z bytes of memory. Return nullptr and capture error if unable to satisfy request. May expand committed memory, as long as resulting committed size is no larger than reserved size

value_type super_alloc(typeseq t, size_type z)

when store_header_flag enabled: like alloc(), but combine memory consumed by this alloc plus following consecutive sub_alloc()’s into a single header. otherwise equivalent to alloc()

value_type sub_alloc(size_type z, bool complete_flag)

when store_header_flag enabled: follow preceding super_alloc() by one or more sub_allocs(). accumulate total allocated size (including padding) into single header. All sub_allocs() except the last must set complete_flag to false. The last sub_alloc() must set complete_flag to true.

value_type alloc_copy(value_type src)

alloc copy of src

void capture_error(error err, const char *src_fn, size_type target_z = 0) const

capture error information: advance error count + set last_error

value_type _alloc(std::size_t req_z, alloc_mode mode, typeseq tseq, uint32_t age, const char *src_fn)

alloc driver. shared by alloc(), super_alloc(), sub_alloc()

bool expand(size_type z, const char *src_fn) noexcept

expand committed space in arena d to size at least z, on behalf of src_fn In practice will round up to a multiple of page_z_.

void establish_meta_pointer() noexcept

store pointer back to this DArena (arena storage begins with pointer to DArena itself)

void fixup_meta_pointer() noexcept

Correct meta pointer, after moving this DArena. Only acts if arena owns committed storage

void establish_initial_guard() noexcept

create initial guard:

inline Checkpoint checkpoint() noexcept

checkpoint arena state. Revert to the same state with restore

inline void restore(Checkpoint ckp) noexcept

restore arena state to previously-established checkpoint

void scrub() noexcept

zero out all allocated memory. Likely use case is diagnostics

void clear() noexcept

discard all allocated memory, return to empty state Promise:

  • committed memory unchanged

  • available memory = committed memory

void unmap() noexcept

release backing memory and reset bookkeeping to the empty state.

Unmaps [lo_, hi_) (if mapped) and zeroes the bookkeeping fields {lo_, committed_z_, last_header_, free_, limit_, hi_, error_count_, last_error_}. config_ (and page_z_/arena_align_z_) are left intact.

Idempotent: a second call is a no-op (lo_ has been cleared). Invoked by ~DArena(); also safe to call on a live arena.

Note: application code must not rely on observing the zeroed state after destruction (that would be UB) &#8212; the zeroing is defensive, to avoid leaving dangling pointers behind.

void swap(DArena &other) noexcept

swap contents (including configuration) with another arena