From 14df85a638cb8bf6427e0fa31687dd4ce4f1b0ac Mon Sep 17 00:00:00 2001 From: Peterino2 Date: Sat, 24 Oct 2026 16:18:43 -0700 Subject: [PATCH] Bump arena- new checkpointing system --- engine/lib/p2/src/structures/bump-arena.zig | 460 +++++++++++--------- 1 file changed, 244 insertions(+), 216 deletions(-) diff --git a/engine/lib/p2/src/structures/bump-arena.zig b/engine/lib/p2/src/structures/bump-arena.zig index 80b8a2f..62a043a 100644 --- a/engine/lib/p2/src/structures/bump-arena.zig +++ b/engine/lib/p2/src/structures/bump-arena.zig @@ -7,253 +7,281 @@ const stats = @import("stats.zig"); // 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 // deinit, rewound and reset blocks go to free lists and get reused. -pub const BumpArenaAdvanced = struct { - /// usable bytes in a standard block. allocations that do not fit get a - /// 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); +pub const BumpArenaOptions = struct { + /// most checkpoints that can be live at once, taking more panics. + max_checkpoints: usize = 256, + /// tracks live checkpoints and asserts on rewinding an invalidated one. + validate_checkpoints: bool = std.debug.runtime_safety, +}; - const Block = struct { - // 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, +pub const BumpArenaAdvanced = BumpArenaAdvancedOptions(.{}); - 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 { - return @as([*]u8, @ptrCast(self)) + header_size; - } + /// usable bytes in a standard block. allocations that do not fit get a + /// 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. - fn memory(self: *Block) []u8 { - return @as([*]u8, @ptrCast(self))[0 .. header_size + self.size]; - } - }; + const Block = struct { + // 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, - pub const ResetMode = enum { - retain_capacity, - free_all, - }; + const header_size = block_alignment.forward(@sizeOf(Block)); - // newest block, allocations bump into this one. - current: ?*Block = null, - // 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, + fn data(self: *Block) [*]u8 { + return @as([*]u8, @ptrCast(self)) + header_size; + } - allocatedBytes: usize = 0, - allocCount: usize = 0, - reservedBytes: usize = 0, - - 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, + // the whole allocation including the header, for returning it to the backing allocator. + fn memory(self: *Block) []u8 { + return @as([*]u8, @ptrCast(self))[0 .. header_size + self.size]; + } }; - } - pub fn init(backing: std.mem.Allocator) @This() { - return .{ - .backing = backing, + pub const ResetMode = enum { + retain_capacity, + free_all, }; - } - pub fn deinit(self: *@This()) void { - self.destroyList(self.current); - for (self.free_blocks) |head| self.destroyList(head); - self.* = undefined; - } + // newest block, allocations bump into this one. + current: ?*Block = null, + // free lists indexed by size class, sizeClass(block.size) + 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()`; - /// memory allocated after the checkpoint is invalid once it is rewound. - /// Checkpoints must be rewound in the reverse order they were taken. - pub fn checkpoint(self: *@This()) BumpCheckpoint { - self.depth += 1; - return .{ - .arena = self, - .block = self.current, - .used = if (self.current) |block| block.used else 0, - .allocatedBytes = self.allocatedBytes, - .allocCount = self.allocCount, - .depth = self.depth, + allocatedBytes: usize = 0, + allocCount: usize = 0, + reservedBytes: usize = 0, + + backing: std.mem.Allocator, + + pub const vtable: std.mem.Allocator.VTable = .{ + .alloc = alloc, + .free = free, + .resize = resize, + .remap = std.mem.Allocator.noRemap, }; - } - fn rewind(self: *@This(), cp: BumpCheckpoint) void { - std.debug.assert(self.depth == cp.depth); // checkpoints rewound out of order - 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); + pub fn usage(self: *@This()) usize { + return self.allocatedBytes; } - // 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; + pub fn getStatistics(self: *@This()) stats.PoolStatistics { + return .{ + .statName = "BumpArenaAdvanced", + .instanceCount = self.allocCount, + .memoryReserved = self.reservedBytes, + .memoryUsed = self.allocatedBytes, + }; + } - const offset = fitInBlock(block, len, ptr_align).?; - return self.commit(block, offset, len); - } + pub fn init(backing: std.mem.Allocator) @This() { + return .{ + .backing = backing, + }; + } - 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; - } + pub fn deinit(self: *@This()) void { + self.destroyList(self.current); + for (self.free_blocks) |head| self.destroyList(head); + self.* = undefined; + } - // 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; - } + /// Saves the current write position. Rewind with `defer checkpoint.rewind()`; + /// memory allocated after the checkpoint is invalid once it is rewound. + /// Checkpoints may be rewound in any order and more than once. Rewinding one + /// invalidates every checkpoint taken after it, and reset invalidates all. + /// Checkpoints that are never rewound are simply dropped. + pub fn checkpoint(self: *Self) Checkpoint { + self.next_id += 1; + 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 { - return std.math.log2(size) - std.math.log2(BlockSize); - } + fn rewind(self: *Self, cp: Checkpoint) void { + 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. - 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; + 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. + // 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; - 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()); + // marks released bytes as undefined so use after rewind shows up in safe builds. + fn poison(block: *Block, from: usize) void { + if (std.debug.runtime_safety) @memset(block.data()[from..block.used], undefined); } - } - // marks released bytes as undefined so use after rewind shows up in safe builds. - fn poison(block: *Block, from: usize) void { - if (std.debug.runtime_safety) @memset(block.data()[from..block.used], undefined); - } - - 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); + 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); } - if (mode == .free_all) { - for (&self.free_blocks) |*head| { - self.destroyList(head.*); - head.* = null; + + 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 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. -pub const BumpCheckpoint = struct { - arena: *BumpArenaAdvanced, - block: ?*BumpArenaAdvanced.Block, - used: usize, - allocatedBytes: usize, - allocCount: usize, - depth: u32, + /// A saved write position, see checkpoint. + pub const Checkpoint = struct { + arena: *Self, + block: ?*Block, + used: usize, + allocatedBytes: usize, + allocCount: usize, + id: u64, - pub fn rewind(self: BumpCheckpoint) void { - self.arena.rewind(self); - } -}; + pub fn rewind(self: Checkpoint) void { + self.arena.rewind(self); + } + }; + }; +} + +pub const BumpCheckpoint = BumpArenaAdvanced.Checkpoint; // mutex based, threadsafe BumpArenaAdvanced. does not support checkpoints, // rewinding would release other threads' allocations.