feat: disk read/write support for both ATA and ATAPI device
[lunaix-os.git] / lunaix-os / kernel / mm / valloc.c
1 #include <klibc/string.h>
2 #include <lunaix/mm/cake.h>
3 #include <lunaix/mm/valloc.h>
4
5 #define MAX_CLASS 6
6
7 static char piles_names[MAX_CLASS][PILE_NAME_MAXLEN] = {
8     "valloc_16",  "valloc_32",  "valloc_64",
9     "valloc_128", "valloc_256", "valloc_512"
10 };
11
12 static char piles_names_dma[MAX_CLASS][PILE_NAME_MAXLEN] = {
13     "valloc_dma_128", "valloc_dma_512", "valloc_dma_512",
14     "valloc_dma_1k",  "valloc_dma_2k",  "valloc_dma_4k"
15 };
16
17 static struct cake_pile* piles[MAX_CLASS];
18 static struct cake_pile* piles_dma[MAX_CLASS];
19
20 void
21 valloc_init()
22 {
23     for (size_t i = 0; i < MAX_CLASS; i++) {
24         int size = 1 << (i + 4);
25         piles[i] = cake_new_pile(&piles_names[i], size, 1, 0);
26     }
27
28     // DMA 内存保证128字节对齐
29     for (size_t i = 0; i < MAX_CLASS; i++) {
30         int size = 1 << (i + 7);
31         piles_dma[i] = cake_new_pile(
32           &piles_names_dma[i], size, size > 1024 ? 8 : 1, PILE_CACHELINE);
33     }
34 }
35
36 void*
37 __valloc(unsigned int size, struct cake_pile** segregate_list)
38 {
39     size_t i = 0;
40     for (; i < MAX_CLASS; i++) {
41         if (segregate_list[i]->piece_size >= size) {
42             goto found_class;
43         }
44     }
45
46     return NULL;
47
48 found_class:
49     return cake_grab(segregate_list[i]);
50 }
51
52 void
53 __vfree(void* ptr, struct cake_pile** segregate_list)
54 {
55     size_t i = 0;
56     for (; i < MAX_CLASS; i++) {
57         if (cake_release(segregate_list[i], ptr)) {
58             return;
59         }
60     }
61 }
62
63 void*
64 valloc(unsigned int size)
65 {
66     return __valloc(size, &piles);
67 }
68
69 void*
70 vcalloc(unsigned int size)
71 {
72     void* ptr = __valloc(size, &piles);
73     memset(ptr, 0, size);
74     return ptr;
75 }
76
77 void
78 vfree(void* ptr)
79 {
80     __vfree(ptr, &piles);
81 }
82
83 void*
84 valloc_dma(unsigned int size)
85 {
86     return __valloc(size, &piles_dma);
87 }
88
89 void*
90 vcalloc_dma(unsigned int size)
91 {
92     void* ptr = __valloc(size, &piles_dma);
93     memset(ptr, 0, size);
94     return ptr;
95 }
96
97 void
98 vfree_dma(void* ptr)
99 {
100     __vfree(ptr, &piles_dma);
101 }