Bump arena- new checkpointing system

This commit is contained in:
Peterino2 2026-10-24 16:18:43 -07:00
parent 1a07a5388c
commit 14df85a638
1 changed files with 244 additions and 216 deletions

View File

@ -7,253 +7,281 @@ const stats = @import("stats.zig");
// memory comes from a linked list of blocks taken from the backing allocator. // memory comes from a linked list of blocks taken from the backing allocator.
// blocks are never returned to the backing allocator until reset(.free_all) or // blocks are never returned to the backing allocator until reset(.free_all) or
// deinit, rewound and reset blocks go to free lists and get reused. // deinit, rewound and reset blocks go to free lists and get reused.
pub const BumpArenaAdvanced = struct { pub const BumpArenaOptions = struct {
/// usable bytes in a standard block. allocations that do not fit get a /// most checkpoints that can be live at once, taking more panics.
/// power of two sized block of their own. max_checkpoints: usize = 256,
pub const BlockSize = 8192 * 2; /// tracks live checkpoints and asserts on rewinding an invalidated one.
const block_alignment: std.mem.Alignment = .@"16"; validate_checkpoints: bool = std.debug.runtime_safety,
const size_classes = @bitSizeOf(usize) - std.math.log2(BlockSize); };
const Block = struct { pub const BumpArenaAdvanced = BumpArenaAdvancedOptions(.{});
// the block allocated before this one, or the next block in a free list.
prev: ?*Block,
// usable bytes after the header, BlockSize << n
size: usize,
used: usize,
const header_size = block_alignment.forward(@sizeOf(Block)); pub fn BumpArenaAdvancedOptions(comptime options: BumpArenaOptions) type {
return struct {
const Self = @This();
fn data(self: *Block) [*]u8 { /// usable bytes in a standard block. allocations that do not fit get a
return @as([*]u8, @ptrCast(self)) + header_size; /// power of two sized block of their own.
} pub const BlockSize = 8192 * 2;
const block_alignment: std.mem.Alignment = .@"16";
const size_classes = @bitSizeOf(usize) - std.math.log2(BlockSize);
// the whole allocation including the header, for returning it to the backing allocator. const Block = struct {
fn memory(self: *Block) []u8 { // the block allocated before this one, or the next block in a free list.
return @as([*]u8, @ptrCast(self))[0 .. header_size + self.size]; prev: ?*Block,
} // usable bytes after the header, BlockSize << n
}; size: usize,
used: usize,
pub const ResetMode = enum { const header_size = block_alignment.forward(@sizeOf(Block));
retain_capacity,
free_all,
};
// newest block, allocations bump into this one. fn data(self: *Block) [*]u8 {
current: ?*Block = null, return @as([*]u8, @ptrCast(self)) + header_size;
// free lists indexed by size class, sizeClass(block.size) }
free_blocks: [size_classes]?*Block = @splat(null),
// live checkpoints, used to assert they are rewound in LIFO order.
depth: u32 = 0,
allocatedBytes: usize = 0, // the whole allocation including the header, for returning it to the backing allocator.
allocCount: usize = 0, fn memory(self: *Block) []u8 {
reservedBytes: usize = 0, return @as([*]u8, @ptrCast(self))[0 .. header_size + self.size];
}
backing: std.mem.Allocator,
pub const vtable: std.mem.Allocator.VTable = .{
.alloc = alloc,
.free = free,
.resize = resize,
.remap = std.mem.Allocator.noRemap,
};
pub fn usage(self: *@This()) usize {
return self.allocatedBytes;
}
pub fn getStatistics(self: *@This()) stats.PoolStatistics {
return .{
.statName = "BumpArenaAdvanced",
.instanceCount = self.allocCount,
.memoryReserved = self.reservedBytes,
.memoryUsed = self.allocatedBytes,
}; };
}
pub fn init(backing: std.mem.Allocator) @This() { pub const ResetMode = enum {
return .{ retain_capacity,
.backing = backing, free_all,
}; };
}
pub fn deinit(self: *@This()) void { // newest block, allocations bump into this one.
self.destroyList(self.current); current: ?*Block = null,
for (self.free_blocks) |head| self.destroyList(head); // free lists indexed by size class, sizeClass(block.size)
self.* = undefined; free_blocks: [size_classes]?*Block = @splat(null),
} // ids of the checkpoints still on the timeline, ascending. rewinding drops
// every id newer than the target, those checkpoints are invalid.
live: [if (options.validate_checkpoints) options.max_checkpoints else 0]u64 = undefined,
live_len: usize = 0,
next_id: u64 = 0,
/// Saves the current write position. Rewind with `defer checkpoint.rewind()`; allocatedBytes: usize = 0,
/// memory allocated after the checkpoint is invalid once it is rewound. allocCount: usize = 0,
/// Checkpoints must be rewound in the reverse order they were taken. reservedBytes: usize = 0,
pub fn checkpoint(self: *@This()) BumpCheckpoint {
self.depth += 1; backing: std.mem.Allocator,
return .{
.arena = self, pub const vtable: std.mem.Allocator.VTable = .{
.block = self.current, .alloc = alloc,
.used = if (self.current) |block| block.used else 0, .free = free,
.allocatedBytes = self.allocatedBytes, .resize = resize,
.allocCount = self.allocCount, .remap = std.mem.Allocator.noRemap,
.depth = self.depth,
}; };
}
fn rewind(self: *@This(), cp: BumpCheckpoint) void { pub fn usage(self: *@This()) usize {
std.debug.assert(self.depth == cp.depth); // checkpoints rewound out of order return self.allocatedBytes;
self.depth -= 1;
while (self.current != cp.block) {
const block = self.current.?;
self.current = block.prev;
self.retireBlock(block);
}
if (cp.block) |block| {
poison(block, cp.used);
block.used = cp.used;
}
self.allocatedBytes = cp.allocatedBytes;
self.allocCount = cp.allocCount;
}
pub fn allocBytes(self: *@This(), len: usize, ptr_align: std.mem.Alignment, ret_addr: usize) ?[*]u8 {
if (self.current) |block| {
if (fitInBlock(block, len, ptr_align)) |offset| return self.commit(block, offset, len);
} }
// new allocation exceeds the remaining size of this block, or there is no block yet. pub fn getStatistics(self: *@This()) stats.PoolStatistics {
// block data is only block_alignment aligned, stricter alignments may need padding. return .{
const padding = if (ptr_align.toByteUnits() > block_alignment.toByteUnits()) ptr_align.toByteUnits() - 1 else 0; .statName = "BumpArenaAdvanced",
const needed = std.math.add(usize, len, padding) catch return null; .instanceCount = self.allocCount,
const size = if (needed <= BlockSize) BlockSize else std.math.ceilPowerOfTwo(usize, needed) catch return null; .memoryReserved = self.reservedBytes,
const block = self.acquireBlock(size, ret_addr) orelse return null; .memoryUsed = self.allocatedBytes,
block.used = 0; };
block.prev = self.current; }
self.current = block;
const offset = fitInBlock(block, len, ptr_align).?; pub fn init(backing: std.mem.Allocator) @This() {
return self.commit(block, offset, len); return .{
} .backing = backing,
};
}
fn commit(self: *@This(), block: *Block, offset: usize, len: usize) [*]u8 { pub fn deinit(self: *@This()) void {
block.used = offset + len; self.destroyList(self.current);
self.allocatedBytes += len; for (self.free_blocks) |head| self.destroyList(head);
self.allocCount += 1; self.* = undefined;
return block.data() + offset; }
}
// Offset of a `len` byte allocation after the block's used bytes, or null /// Saves the current write position. Rewind with `defer checkpoint.rewind()`;
// if it does not fit. Aligns the address rather than the offset. /// memory allocated after the checkpoint is invalid once it is rewound.
fn fitInBlock(block: *Block, len: usize, alignment: std.mem.Alignment) ?usize { /// Checkpoints may be rewound in any order and more than once. Rewinding one
if (len > block.size) return null; /// invalidates every checkpoint taken after it, and reset invalidates all.
const base = @intFromPtr(block.data()); /// Checkpoints that are never rewound are simply dropped.
const aligned = alignment.forward(base + block.used) - base; pub fn checkpoint(self: *Self) Checkpoint {
if (aligned + len > block.size) return null; self.next_id += 1;
return aligned; if (options.validate_checkpoints) {
} if (self.live_len == options.max_checkpoints) @panic("BumpArenaAdvanced: too many live checkpoints, raise max_checkpoints");
self.live[self.live_len] = self.next_id;
self.live_len += 1;
}
return .{
.arena = self,
.block = self.current,
.used = if (self.current) |block| block.used else 0,
.allocatedBytes = self.allocatedBytes,
.allocCount = self.allocCount,
.id = self.next_id,
};
}
fn sizeClass(size: usize) usize { fn rewind(self: *Self, cp: Checkpoint) void {
return std.math.log2(size) - std.math.log2(BlockSize); if (options.validate_checkpoints) {
} while (self.live_len > 0 and self.live[self.live_len - 1] > cp.id) self.live_len -= 1;
// the checkpoint was invalidated by rewinding an older one, or by reset.
std.debug.assert(self.live_len > 0 and self.live[self.live_len - 1] == cp.id);
}
// a free block with at least `size` usable bytes, or a new one from the backing allocator. while (self.current != cp.block) {
fn acquireBlock(self: *@This(), size: usize, ret_addr: usize) ?*Block { const block = self.current.?;
for (self.free_blocks[sizeClass(size)..]) |*head| { self.current = block.prev;
if (head.*) |block| { self.retireBlock(block);
head.* = block.prev; }
return block; if (cp.block) |block| {
poison(block, cp.used);
block.used = cp.used;
}
self.allocatedBytes = cp.allocatedBytes;
self.allocCount = cp.allocCount;
}
pub fn allocBytes(self: *@This(), len: usize, ptr_align: std.mem.Alignment, ret_addr: usize) ?[*]u8 {
if (self.current) |block| {
if (fitInBlock(block, len, ptr_align)) |offset| return self.commit(block, offset, len);
}
// new allocation exceeds the remaining size of this block, or there is no block yet.
// block data is only block_alignment aligned, stricter alignments may need padding.
const padding = if (ptr_align.toByteUnits() > block_alignment.toByteUnits()) ptr_align.toByteUnits() - 1 else 0;
const needed = std.math.add(usize, len, padding) catch return null;
const size = if (needed <= BlockSize) BlockSize else std.math.ceilPowerOfTwo(usize, needed) catch return null;
const block = self.acquireBlock(size, ret_addr) orelse return null;
block.used = 0;
block.prev = self.current;
self.current = block;
const offset = fitInBlock(block, len, ptr_align).?;
return self.commit(block, offset, len);
}
fn commit(self: *@This(), block: *Block, offset: usize, len: usize) [*]u8 {
block.used = offset + len;
self.allocatedBytes += len;
self.allocCount += 1;
return block.data() + offset;
}
// Offset of a `len` byte allocation after the block's used bytes, or null
// if it does not fit. Aligns the address rather than the offset.
fn fitInBlock(block: *Block, len: usize, alignment: std.mem.Alignment) ?usize {
if (len > block.size) return null;
const base = @intFromPtr(block.data());
const aligned = alignment.forward(base + block.used) - base;
if (aligned + len > block.size) return null;
return aligned;
}
fn sizeClass(size: usize) usize {
return std.math.log2(size) - std.math.log2(BlockSize);
}
// a free block with at least `size` usable bytes, or a new one from the backing allocator.
fn acquireBlock(self: *@This(), size: usize, ret_addr: usize) ?*Block {
for (self.free_blocks[sizeClass(size)..]) |*head| {
if (head.*) |block| {
head.* = block.prev;
return block;
}
}
const bytes = self.backing.rawAlloc(Block.header_size + size, block_alignment, ret_addr) orelse return null;
self.reservedBytes += Block.header_size + size;
const block: *Block = @ptrCast(@alignCast(bytes));
block.size = size;
return block;
}
// moves a block to its free list, it stays allocated.
fn retireBlock(self: *@This(), block: *Block) void {
poison(block, 0);
const class = sizeClass(block.size);
block.prev = self.free_blocks[class];
self.free_blocks[class] = block;
}
fn destroyList(self: *@This(), head: ?*Block) void {
var it = head;
while (it) |block| {
it = block.prev;
self.reservedBytes -= block.memory().len;
self.backing.rawFree(block.memory(), block_alignment, @returnAddress());
} }
} }
const bytes = self.backing.rawAlloc(Block.header_size + size, block_alignment, ret_addr) orelse return null; // marks released bytes as undefined so use after rewind shows up in safe builds.
self.reservedBytes += Block.header_size + size; fn poison(block: *Block, from: usize) void {
const block: *Block = @ptrCast(@alignCast(bytes)); if (std.debug.runtime_safety) @memset(block.data()[from..block.used], undefined);
block.size = size;
return block;
}
// moves a block to its free list, it stays allocated.
fn retireBlock(self: *@This(), block: *Block) void {
poison(block, 0);
const class = sizeClass(block.size);
block.prev = self.free_blocks[class];
self.free_blocks[class] = block;
}
fn destroyList(self: *@This(), head: ?*Block) void {
var it = head;
while (it) |block| {
it = block.prev;
self.reservedBytes -= block.memory().len;
self.backing.rawFree(block.memory(), block_alignment, @returnAddress());
} }
}
// marks released bytes as undefined so use after rewind shows up in safe builds. fn alloc(ctx: *anyopaque, len: usize, ptr_align: std.mem.Alignment, ret_addr: usize) ?[*]u8 {
fn poison(block: *Block, from: usize) void { const self: *@This() = @ptrCast(@alignCast(ctx));
if (std.debug.runtime_safety) @memset(block.data()[from..block.used], undefined); return self.allocBytes(len, ptr_align, ret_addr);
}
fn alloc(ctx: *anyopaque, len: usize, ptr_align: std.mem.Alignment, ret_addr: usize) ?[*]u8 {
const self: *@This() = @ptrCast(@alignCast(ctx));
return self.allocBytes(len, ptr_align, ret_addr);
}
pub fn free(ctx: *anyopaque, buf: []u8, buf_align: std.mem.Alignment, ret_addr: usize) void {
// it's a bump allocator, it does nothing on free.
_ = ctx;
_ = buf;
_ = buf_align;
_ = ret_addr;
}
// do not support resize in place.
pub fn resize(ctx: *anyopaque, buf: []u8, buf_align: std.mem.Alignment, new_len: usize, ret_addr: usize) bool {
_ = ctx;
_ = buf;
_ = buf_align;
_ = new_len;
_ = ret_addr;
return false;
}
pub fn allocator(self: *@This()) std.mem.Allocator {
return .{ .ptr = self, .vtable = &vtable };
}
/// Releases every allocation. `.retain_capacity` keeps the blocks for reuse,
/// `.free_all` returns them to the backing allocator. No checkpoints may be live.
pub fn reset(self: *@This(), mode: ResetMode) void {
std.debug.assert(self.depth == 0); // reset with a live checkpoint
while (self.current) |block| {
self.current = block.prev;
self.retireBlock(block);
} }
if (mode == .free_all) {
for (&self.free_blocks) |*head| { pub fn free(ctx: *anyopaque, buf: []u8, buf_align: std.mem.Alignment, ret_addr: usize) void {
self.destroyList(head.*); // it's a bump allocator, it does nothing on free.
head.* = null; _ = ctx;
_ = buf;
_ = buf_align;
_ = ret_addr;
}
// do not support resize in place.
pub fn resize(ctx: *anyopaque, buf: []u8, buf_align: std.mem.Alignment, new_len: usize, ret_addr: usize) bool {
_ = ctx;
_ = buf;
_ = buf_align;
_ = new_len;
_ = ret_addr;
return false;
}
pub fn allocator(self: *@This()) std.mem.Allocator {
return .{ .ptr = self, .vtable = &vtable };
}
/// Releases every allocation and invalidates every checkpoint. `.retain_capacity`
/// keeps the blocks for reuse, `.free_all` returns them to the backing allocator.
pub fn reset(self: *@This(), mode: ResetMode) void {
self.live_len = 0;
while (self.current) |block| {
self.current = block.prev;
self.retireBlock(block);
} }
if (mode == .free_all) {
for (&self.free_blocks) |*head| {
self.destroyList(head.*);
head.* = null;
}
}
self.allocatedBytes = 0;
self.allocCount = 0;
} }
self.allocatedBytes = 0;
self.allocCount = 0;
}
};
/// A saved write position of a BumpArenaAdvanced, see BumpArenaAdvanced.checkpoint. /// A saved write position, see checkpoint.
pub const BumpCheckpoint = struct { pub const Checkpoint = struct {
arena: *BumpArenaAdvanced, arena: *Self,
block: ?*BumpArenaAdvanced.Block, block: ?*Block,
used: usize, used: usize,
allocatedBytes: usize, allocatedBytes: usize,
allocCount: usize, allocCount: usize,
depth: u32, id: u64,
pub fn rewind(self: BumpCheckpoint) void { pub fn rewind(self: Checkpoint) void {
self.arena.rewind(self); self.arena.rewind(self);
} }
}; };
};
}
pub const BumpCheckpoint = BumpArenaAdvanced.Checkpoint;
// mutex based, threadsafe BumpArenaAdvanced. does not support checkpoints, // mutex based, threadsafe BumpArenaAdvanced. does not support checkpoints,
// rewinding would release other threads' allocations. // rewinding would release other threads' allocations.