feat: cake (slab) allocator, for dynamic continuous physical page allocation
[lunaix-os.git] / lunaix-os / kernel / mm / valloc.c
1 #include <lunaix/mm/cake.h>
2
3 #define MAX_CLASS 6
4
5 static char piles_names[MAX_CLASS][PILE_NAME_MAXLEN] = {
6     "valloc_128", "valloc_256", "valloc_512",
7     "valloc_1k",  "valloc_2k",  "valloc_4k"
8 };
9
10 static struct cake_pile* piles[MAX_CLASS];
11
12 void
13 valloc_init()
14 {
15     for (size_t i = 0; i < MAX_CLASS; i++) {
16         int size = 1 << (i + 7);
17         piles[i] = cake_new_pile(&piles_names[i], size, size > 1024 ? 8 : 1);
18     }
19 }
20
21 void*
22 valloc(unsigned int size)
23 {
24     size_t i = 0;
25     for (; i < MAX_CLASS; i++) {
26         if (piles[i]->piece_size > size) {
27             goto found_class;
28         }
29     }
30
31     return NULL;
32
33 found_class:
34     return cake_grab(piles[i]);
35 }
36
37 void
38 vfree(void* ptr)
39 {
40     size_t i = 0;
41     for (; i < MAX_CLASS; i++) {
42         if (cake_release(piles[i], ptr)) {
43             return;
44         }
45     }
46 }