1/*
2 * Copyright 2017, Data61
3 * Commonwealth Scientific and Industrial Research Organisation (CSIRO)
4 * ABN 41 687 119 230.
5 *
6 * This software may be distributed and modified according to the terms of
7 * the BSD 2-Clause license. Note that NO WARRANTY is provided.
8 * See "LICENSE_BSD2.txt" for details.
9 *
10 * @TAG(DATA61_BSD)
11 */
12
13#include <allocman/mspace/fixed_pool.h>
14#include <allocman/allocman.h>
15#include <allocman/util.h>
16#include <stdlib.h>
17
18static k_r_malloc_header_t *_morecore(size_t cookie, mspace_k_r_malloc_t *k_r_malloc, size_t new_units)
19{
20    size_t new_size;
21    k_r_malloc_header_t *new_header;
22    mspace_fixed_pool_t *fixed_pool = (mspace_fixed_pool_t*)cookie;
23    new_size = new_units * sizeof(k_r_malloc_header_t);
24    if (new_size > fixed_pool->remaining) {
25        return NULL;
26    }
27    new_header = (k_r_malloc_header_t*)fixed_pool->pool_ptr;
28    fixed_pool->pool_ptr += new_size;
29    fixed_pool->remaining -= new_size;
30    return new_header;
31}
32
33void mspace_fixed_pool_create(mspace_fixed_pool_t *fixed_pool, struct mspace_fixed_pool_config config)
34{
35    size_t padding;
36    fixed_pool->pool_ptr = (uintptr_t)config.pool;
37    fixed_pool->remaining = config.size;
38    padding = fixed_pool->pool_ptr % sizeof(k_r_malloc_header_t);
39    fixed_pool->pool_ptr += padding;
40    fixed_pool->remaining -= padding;
41    mspace_k_r_malloc_init(&fixed_pool->k_r_malloc, (size_t)fixed_pool, _morecore);
42}
43
44void *_mspace_fixed_pool_alloc(struct allocman *alloc, void *_fixed_pool, size_t bytes, int *error)
45{
46    void *ret;
47    mspace_fixed_pool_t *fixed_pool = (mspace_fixed_pool_t*)_fixed_pool;
48    ret = mspace_k_r_malloc_alloc(&fixed_pool->k_r_malloc, bytes);
49    if (ret == NULL) {
50        SET_ERROR(error, 1);
51    } else {
52        SET_ERROR(error, 0);
53    }
54    return ret;
55}
56
57void _mspace_fixed_pool_free(struct allocman *alloc, void *_fixed_pool, void *ptr, size_t bytes)
58{
59    mspace_fixed_pool_t *fixed_pool = (mspace_fixed_pool_t*)_fixed_pool;
60    mspace_k_r_malloc_free(&fixed_pool->k_r_malloc, ptr);
61}
62