1 /* -----------------------------------------------------------------------------
2 $Id: Arena.c,v 1.1 2001/10/18 14:41:01 simonmar Exp $
3 (c) The University of Glasgow 2001
5 Arena allocation. Arenas provide fast memory allocation at the
6 expense of fine-grained recycling of storage: memory may be
7 only be returned to the system by freeing the entire arena, it
8 isn't possible to return individual objects within an arena.
10 Do not assume that sequentially allocated objects will be adjacent
13 Quirks: this allocator makes use of the RTS block allocator. If
14 the current block doesn't have enough room for the requested
15 object, then a new block is allocated. This means that allocating
16 large objects will tend to result in wasted space at the end of
17 each block. In the worst case, half of the allocated space is
18 wasted. This allocator is therefore best suited to situations in
19 which most allocations are small.
20 -------------------------------------------------------------------------- */
24 #include "BlockAlloc.h"
27 // Each arena struct is allocated using malloc().
30 StgWord *free; // ptr to next free byte in current block
31 StgWord *lim; // limit (== last free byte + 1)
34 // We like to keep track of how many blocks we've allocated for
35 // Storage.c:memInventory().
36 static long arena_blocks = 0;
44 arena = stgMallocBytes(sizeof(Arena), "newArena");
45 arena->current = allocBlock();
46 arena->current->link = NULL;
47 arena->free = arena->current->start;
48 arena->lim = arena->current->start + BLOCK_SIZE_W;
54 // Allocate some memory in an arena
56 arenaAlloc( Arena *arena, size_t size )
63 // round up to word size...
64 size_w = (size + sizeof(W_) - 1) / sizeof(W_);
66 if ( arena->free + size_w < arena->lim ) {
67 // enough room in the current block...
69 arena->free += size_w;
72 // allocate a fresh block...
73 req_blocks = (lnat)BLOCK_ROUND_UP(size_w*sizeof(W_)) / BLOCK_SIZE;
74 bd = allocGroup(req_blocks);
75 arena_blocks += req_blocks;
81 bd->link = arena->current;
83 arena->free = bd->free + size_w;
84 arena->lim = bd->free + bd->blocks * BLOCK_SIZE_W;
89 // Free an entire arena
91 arenaFree( Arena *arena )
95 for (bd = arena->current; bd != NULL; bd = next) {
97 arena_blocks -= bd->blocks;
98 ASSERT(arena_blocks >= 0);