Merge branch 'master' into sata-ahci-dev
[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_16",  "valloc_32",  "valloc_64",
7     "valloc_128", "valloc_256", "valloc_512"
8 };
9
10 static char piles_names_dma[MAX_CLASS][PILE_NAME_MAXLEN] = {
11     "valloc_dma_128", "valloc_dma_512", "valloc_dma_512",
12     "valloc_dma_1k",  "valloc_dma_2k",  "valloc_dma_4k"
13 };
14
15 static struct cake_pile* piles[MAX_CLASS];
16 static struct cake_pile* piles_dma[MAX_CLASS];
17
18 void
19 valloc_init()
20 {
21     for (size_t i = 0; i < MAX_CLASS; i++) {
22         int size = 1 << (i + 4);
23         piles[i] = cake_new_pile(&piles_names[i], size, 1, 0);
24     }
25
26     // DMA 内存保证128字节对齐
27     for (size_t i = 0; i < MAX_CLASS; i++) {
28         int size = 1 << (i + 7);
29         piles_dma[i] = cake_new_pile(
30           &piles_names_dma[i], size, size > 1024 ? 8 : 1, PILE_CACHELINE);
31     }
32 }
33
34 void*
35 __valloc(unsigned int size, struct cake_pile** segregate_list)
36 {
37     size_t i = 0;
38     for (; i < MAX_CLASS; i++) {
39         if (segregate_list[i]->piece_size >= size) {
40             goto found_class;
41         }
42     }
43
44     return NULL;
45
46 found_class:
47     return cake_grab(segregate_list[i]);
48 }
49
50 void
51 __vfree(void* ptr, struct cake_pile** segregate_list)
52 {
53     size_t i = 0;
54     for (; i < MAX_CLASS; i++) {
55         if (cake_release(segregate_list[i], ptr)) {
56             return;
57         }
58     }
59 }
60
61 void*
62 valloc(unsigned int size)
63 {
64     return __valloc(size, &piles);
65 }
66
67 void
68 vfree(void* ptr)
69 {
70     __vfree(ptr, &piles);
71 }
72
73 void*
74 valloc_dma(unsigned int size)
75 {
76     return __valloc(size, &piles_dma);
77 }
78
79 void
80 vfree_dma(void* ptr)
81 {
82     __vfree(ptr, &piles_dma);
83 }