blob: cd7c614e7faed774105fdb6ba53036f5cd12cad2 [file] [log] [blame]
Wedson Almeida Filho987c0ff2018-06-20 16:34:38 +01001#include "alloc.h"
2
3#include "dlog.h"
4#include "spinlock.h"
5
6static size_t alloc_base;
7static size_t alloc_limit;
8static struct spinlock alloc_lock = SPINLOCK_INIT;
9
10/*
11 * Initializes the allocator.
12 */
13void halloc_init(size_t base, size_t size)
14{
15 alloc_base = base;
16 alloc_limit = base + size;
17}
18
19/*
20 * Allocates the requested amount of memory. Return NULL when there isn't enough
21 * free memory.
22 */
23void *halloc(size_t size)
24{
25 return halloc_aligned(size, 2 * sizeof(size_t));
26}
27
28/*
29 * Frees the provided memory.
30 *
31 * Currently unimplemented.
32 */
33void hfree(void *ptr)
34{
35 dlog("Attempted to free pointer %p\n", ptr);
36}
37
38/*
39 * Allocates the requested amount of memory, with the requested alignment.
40 *
41 * Alignment must be a power of two. Returns NULL when there isn't enough free
42 * memory.
43 */
44void *halloc_aligned(size_t size, size_t align)
45{
46 size_t begin;
47 size_t end;
48
49 sl_lock(&alloc_lock);
50
51 begin = (alloc_base + align - 1) & ~(align - 1);
52 end = begin + size;
53
54 /* Check for overflows, and that there is enough free mem. */
55 if (end > begin && begin >= alloc_base && end <= alloc_limit)
56 alloc_base = end;
57 else
58 begin = 0;
59
60 sl_unlock(&alloc_lock);
61
62 return (void *)begin;
63}