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