WKern
Loading...
Searching...
No Matches
alloc.c
Go to the documentation of this file.
1/*
2WKern - A Bare Metal OS / Kernel I am maKing (For Fun)
3Copyright (C) 2025 Wdboyes13
4
5This program is free software: you can redistribute it and/or modify
6it under the terms of the GNU General Public License as published by
7the Free Software Foundation, either version 3 of the License, or
8any later version.
9
10This program is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with this program. If not, see <https://www.gnu.org/licenses/>.
17*/
18#include <global.h>
19#include <types/nums.h>
20typedef struct BlocK {
21 size_t size;
22 struct BlocK *next;
23 int free;
25
26#define HEAP_START ((char *)0x100000)
27#define HEAP_SIZE (512 * 1024)
28
29static char *heap = HEAP_START;
30static blocK_t *free_list = NULL;
31
35void KheapInit() {
36 free_list = (blocK_t *)heap;
37 free_list->size = HEAP_SIZE - sizeof(blocK_t);
38 free_list->next = NULL;
39 free_list->free = 1;
40}
41
48void *Kmalloc(size_t size, size_t align) {
49 size = (size + align - 1) & ~(align - 1);
50 blocK_t *curr = free_list;
51 while (curr) {
52 if (curr->free && curr->size >= size) {
53 if (curr->size >= size + sizeof(blocK_t) + 8) {
54 // Split the blocK
55 blocK_t *new_blocK = (blocK_t *)((char *)(curr + 1) + size);
56 new_blocK->size = curr->size - size - sizeof(blocK_t);
57 new_blocK->next = curr->next;
58 new_blocK->free = 1;
59
60 curr->size = size;
61 curr->next = new_blocK;
62 }
63 curr->free = 0;
64 return (void *)(curr + 1);
65 }
66 curr = curr->next;
67 }
68 return NULL;
69}
70
75void Kfree(void *ptr) {
76 if (!ptr) {
77 return;
78 }
79 blocK_t *blocK = (blocK_t *)ptr - 1;
80 blocK->free = 1;
81}
#define HEAP_SIZE
Definition alloc.c:27
void * Kmalloc(size_t size, size_t align)
Allocate memory.
Definition alloc.c:48
void Kfree(void *ptr)
Free allocated memory.
Definition alloc.c:75
void KheapInit()
Initialize Memory Heap.
Definition alloc.c:35
struct BlocK blocK_t
#define HEAP_START
Definition alloc.c:26
#define NULL
Definition global.h:39
Definition alloc.c:20
struct BlocK * next
Definition alloc.c:22
size_t size
Definition alloc.c:21
int free
Definition alloc.c:23