summaryrefslogtreecommitdiffstats
path: root/src/kernel/heapmgr.C
blob: cac6999b518142361725d9c2bc7ea3c02c08587a (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
80
81
82
83
84
85
86
87
88
#include <kernel/heapmgr.H>
#include <util/singleton.H>
#include <kernel/console.H>
#include <kernel/pagemgr.H>

void HeapManager::init()
{
    Singleton<HeapManager>::instance();
}

void* HeapManager::allocate(size_t n)
{
    HeapManager& hmgr = Singleton<HeapManager>::instance();
    return hmgr._allocate(n);
}

void HeapManager::free(void* p)
{
    HeapManager& hmgr = Singleton<HeapManager>::instance();
    return hmgr._free(p);
}

void* HeapManager::_allocate(size_t n)
{
    size_t which_bucket = 0;
    while (n > (size_t)((1 << (which_bucket + 4)) - 8)) which_bucket++;

    chunk_t* chunk = (chunk_t*)NULL;
    chunk = pop_bucket(which_bucket);
    if (NULL == chunk)
    {
	newPage();
	return _allocate(n);
    }
    else
    {
	return &chunk->next;
    }
}

void HeapManager::_free(void* p)
{
    if (NULL == p) return;

    chunk_t* chunk = (chunk_t*)(((size_t*)p)-1);
    push_bucket(chunk, chunk->len);
}

HeapManager::chunk_t* HeapManager::pop_bucket(size_t n)
{
    if (n >= BUCKETS) return NULL;

    chunk_t* c = first_chunk[n].pop();

    if (NULL == c)
    {
	// Couldn't allocate from the correct size bucket, so split up an
	// item from the next sized bucket.
	c = pop_bucket(n+1);
	if (NULL != c)
	{
	    chunk_t* c1 = (chunk_t*)(((uint8_t*)c) + (1 << (n + 4)));
	    c->len = n;
	    c1->len = n;
	    push_bucket(c1, n);
	}
    }

    return c;
}

void HeapManager::push_bucket(chunk_t* c, size_t n)
{
    if (n >= BUCKETS) return;
    first_chunk[n].push(c);
}

void HeapManager::newPage()
{
    void* page = PageManager::allocatePage();
    chunk_t * c = (chunk_t*)page;
    for (int i = 0; i < (PageManager::PAGESIZE / (1 << (BUCKETS + 3))); i++)
    {
	c->len = BUCKETS-1;
	push_bucket(c, BUCKETS-1);
	c = (chunk_t*)(((uint8_t*)c) + (1 << (BUCKETS + 3)));
    }
}
OpenPOWER on IntegriCloud