summaryrefslogtreecommitdiff
path: root/website-kernel/arch/mem.c
blob: 4b9a0b0aa4404adc6887ef243e0dd16c44072c04 (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <int.h>
#include <sys.h>
#include <log.h>

static struct mempage_t *root;

static inline size_t round_size(size_t size, size_t round) {
    return size + (round - size % round) % round;
}

static void merge_free_list() {
    struct mempage_t *node = root;
    while (node && node->next) {
        if ((char*)node + node->size == (char *)node->next) {
            node->size += node->next->size;
            node->next = node->next->next;
        } else {
            node = node->next;
        }
    }
}

void set_root(struct mempage_t *incoming_root) {
    root = incoming_root;
}

void *kmalloc(size_t size) {
    size = sizeof(size_t) + round_size(size, sizeof(struct mempage_t));
    struct mempage_t *parent = NULL;
    struct mempage_t *node = root;
    while (node != NULL) {
        if (node->size >= size) {
            goto allocate;
        }
        parent = node;
        node = node->next;
    }
    return NULL;

allocate:
    if (node->size - size >= sizeof(struct mempage_t)) {
        struct mempage_t *old_next = node->next;
        node->next = (struct mempage_t *)((uintptr_t)node + (uintptr_t)size);

        node->next->next = old_next;
        node->next->size = node->size - size;
    }

    if (parent)
        parent->next = node->next;
    else
        root = node->next;

    *(size_t *)node = size;
    return (size_t *)node + 1;
}

void kfree(void *ptr) {
    size_t size = *((size_t *)ptr - 1);
    ptr = (size_t *)ptr - 1;

    struct mempage_t *parent = NULL;
    struct mempage_t *node = root;
    while (node && (uintptr_t)node < (uintptr_t)ptr) {
        parent = node;
        node = node->next;
    }

    struct mempage_t *this = ptr;
    this->size = size;
    this->next = NULL;
    if (!parent) {
        root = this;
    } else {
        parent->next = this;
    }

    this->next = node;

    merge_free_list();
}
void memcpy(void *src, void *dst, size_t size) {
    uint8_t *a = src;
    uint8_t *b = dst;

    for(size_t i = 0; i < size; i++, a++, b++) {
        *b = *a;
    }
}
void memzero(void *ptr, size_t size) {
    for (size_t i = 0; i < size; i++) {
        ((uint8_t *)ptr)[i] = 0;
    }
}

int memcmp(const void *s1, const void *s2, size_t n) {
    const unsigned char *p1 = (const unsigned char *)s1;
    const unsigned char *p2 = (const unsigned char *)s2;

    for (size_t i = 0; i < n; i++) {
        if (p1[i] != p2[i]) {
            return p1[i] - p2[i];
        }
    }

    return 0;
}