1
0
Fork 0
mirror of https://git.rwth-aachen.de/acs/public/villas/node/ synced 2025-03-16 00:00:02 +01:00
VILLASnode/lib/pool.c

60 lines
1.4 KiB
C
Raw Normal View History

/** Memory pool for fixed size objects.
*
* @author Steffen Vogel <stvogel@eonerc.rwth-aachen.de>
* @copyright 2017, Institute for Automation of Complex Power Systems, EONERC
*********************************************************************************/
#include "utils.h"
#include "pool.h"
#include "memory.h"
#include "kernel/kernel.h"
2017-03-27 13:22:54 +02:00
int pool_init(struct pool *p, size_t cnt, size_t blocksz, struct memtype *m)
{
2016-10-19 01:35:41 -04:00
int ret;
2017-03-12 17:04:43 -03:00
assert(p->state == STATE_DESTROYED);
2016-10-19 01:35:41 -04:00
/* Make sure that we use a block size that is aligned to the size of a cache line */
p->alignment = kernel_get_cacheline_size();
p->blocksz = p->alignment * CEIL(blocksz, p->alignment);
p->len = cnt * p->blocksz;
p->mem = m;
void *buffer = memory_alloc_aligned(m, p->len, p->alignment);
if (!buffer)
serror("Failed to allocate memory for memory pool");
else
2017-02-12 14:12:35 -03:00
debug(LOG_POOL | 4, "Allocated %#zx bytes for memory pool", p->len);
p->buffer_off = (char*) buffer - (char*) p;
2016-10-19 01:35:41 -04:00
ret = queue_init(&p->queue, LOG2_CEIL(cnt), m);
2016-10-19 01:35:41 -04:00
if (ret)
return ret;
for (int i = 0; i < cnt; i++)
queue_push(&p->queue, (char *) buffer + i * p->blocksz);
p->state = STATE_INITIALIZED;
2016-10-19 01:35:41 -04:00
return 0;
}
int pool_destroy(struct pool *p)
{
int ret;
if (p->state == STATE_DESTROYED)
return 0;
2016-10-16 02:33:36 -04:00
queue_destroy(&p->queue);
void *buffer = (char*) p + p->buffer_off;
2017-04-06 12:12:56 +02:00
ret = memory_free(p->mem, buffer, p->len);
if (ret == 0)
p->state = STATE_DESTROYED;
return ret;
2017-03-27 13:22:54 +02:00
}