2 * Memory Pool implementation logic.
8 #define BLOCK_GROWTH_SIZE 1024*1024 - sizeof(struct mp_block);
11 * Allocate a new mp_block and insert it after the block specified in
12 * `insert_after`. If `insert_after` is NULL, then insert block at the
13 * head of the linked list.
15 static struct mp_block *mem_pool_alloc_block(struct mem_pool *mem_pool, size_t block_alloc, struct mp_block *insert_after)
19 mem_pool->pool_alloc += sizeof(struct mp_block) + block_alloc;
20 p = xmalloc(st_add(sizeof(struct mp_block), block_alloc));
22 p->next_free = (char *)p->space;
23 p->end = p->next_free + block_alloc;
26 p->next_block = insert_after->next_block;
27 insert_after->next_block = p;
29 p->next_block = mem_pool->mp_block;
30 mem_pool->mp_block = p;
36 void mem_pool_init(struct mem_pool **mem_pool, size_t initial_size)
38 struct mem_pool *pool;
43 pool = xcalloc(1, sizeof(*pool));
45 pool->block_alloc = BLOCK_GROWTH_SIZE;
48 mem_pool_alloc_block(pool, initial_size, NULL);
53 void mem_pool_discard(struct mem_pool *mem_pool, int invalidate_memory)
55 struct mp_block *block, *block_to_free;
57 block = mem_pool->mp_block;
60 block_to_free = block;
61 block = block->next_block;
63 if (invalidate_memory)
64 memset(block_to_free->space, 0xDD, ((char *)block_to_free->end) - ((char *)block_to_free->space));
72 void *mem_pool_alloc(struct mem_pool *mem_pool, size_t len)
74 struct mp_block *p = NULL;
77 /* round up to a 'uintmax_t' alignment */
78 if (len & (sizeof(uintmax_t) - 1))
79 len += sizeof(uintmax_t) - (len & (sizeof(uintmax_t) - 1));
81 if (mem_pool->mp_block &&
82 mem_pool->mp_block->end - mem_pool->mp_block->next_free >= len)
83 p = mem_pool->mp_block;
86 if (len >= (mem_pool->block_alloc / 2))
87 return mem_pool_alloc_block(mem_pool, len, mem_pool->mp_block);
89 p = mem_pool_alloc_block(mem_pool, mem_pool->block_alloc, NULL);
97 void *mem_pool_calloc(struct mem_pool *mem_pool, size_t count, size_t size)
99 size_t len = st_mult(count, size);
100 void *r = mem_pool_alloc(mem_pool, len);
105 int mem_pool_contains(struct mem_pool *mem_pool, void *mem)
109 /* Check if memory is allocated in a block */
110 for (p = mem_pool->mp_block; p; p = p->next_block)
111 if ((mem >= ((void *)p->space)) &&
112 (mem < ((void *)p->end)))
118 void mem_pool_combine(struct mem_pool *dst, struct mem_pool *src)
122 /* Append the blocks from src to dst */
123 if (dst->mp_block && src->mp_block) {
125 * src and dst have blocks, append
126 * blocks from src to dst.
129 while (p->next_block)
132 p->next_block = src->mp_block;
133 } else if (src->mp_block) {
135 * src has blocks, dst is empty.
137 dst->mp_block = src->mp_block;
139 /* src is empty, nothing to do. */
142 dst->pool_alloc += src->pool_alloc;
144 src->mp_block = NULL;