aboutsummaryrefslogtreecommitdiffstats
path: root/lib/librte_acl/tb_mem.c
blob: f14d7b4fa26ee6ae9b5148fbd20bf573b47954a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* SPDX-License-Identifier: BSD-3-Clause
 * Copyright(c) 2010-2014 Intel Corporation
 */

#include "tb_mem.h"

/*
 *  Memory management routines for temporary memory.
 *  That memory is used only during build phase and is released after
 *  build is finished.
 *  Note, that tb_pool/tb_alloc() are not supposed to return NULL.
 *  Instead, in the case of failure to allocate memory,
 *  it would do siglongjmp(pool->fail).
 *  It is responsibility of the caller to save the proper context/environment,
 *  in the pool->fail before calling tb_alloc() for the given pool first time.
 */

static struct tb_mem_block *
tb_pool(struct tb_mem_pool *pool, size_t sz)
{
	struct tb_mem_block *block;
	uint8_t *ptr;
	size_t size;

	size = sz + pool->alignment - 1;
	block = calloc(1, size + sizeof(*pool->block));
	if (block == NULL) {
		RTE_LOG(ERR, MALLOC, "%s(%zu)\n failed, currently allocated "
			"by pool: %zu bytes\n", __func__, sz, pool->alloc);
		siglongjmp(pool->fail, -ENOMEM);
		return NULL;
	}

	block->pool = pool;

	block->next = pool->block;
	pool->block = block;

	pool->alloc += size;

	ptr = (uint8_t *)(block + 1);
	block->mem = RTE_PTR_ALIGN_CEIL(ptr, pool->alignment);
	block->size = size - (block->mem - ptr);

	return block;
}

void *
tb_alloc(struct tb_mem_pool *pool, size_t size)
{
	struct tb_mem_block *block;
	void *ptr;
	size_t new_sz;

	size = RTE_ALIGN_CEIL(size, pool->alignment);

	block = pool->block;
	if (block == NULL || block->size < size) {
		new_sz = (size > pool->min_alloc) ? size : pool->min_alloc;
		block = tb_pool(pool, new_sz);
	}
	ptr = block->mem;
	block->size -= size;
	block->mem += size;
	return ptr;
}

void
tb_free_pool(struct tb_mem_pool *pool)
{
	struct tb_mem_block *next, *block;

	for (block = pool->block; block != NULL; block = next) {
		next = block->next;
		free(block);
	}
	pool->block = NULL;
	pool->alloc = 0;
}