Merge branch 'master' into sata-ahci-dev
[lunaix-os.git] / lunaix-os / kernel / mm / kalloc.c
1 /**
2  * @file kalloc.c
3  * @author Lunaixsky
4  * @brief Implicit free list implementation of malloc family, for kernel use.
5  *
6  * This version of code is however the simplest and yet insecured, thread unsafe
7  * it just to demonstrate how the malloc/free works behind the curtain
8  * @version 0.1
9  * @date 2022-03-05
10  *
11  * @copyright Copyright (c) 2022
12  *
13  */
14 #include <lunaix/mm/dmm.h>
15 #include <lunaix/mm/kalloc.h>
16 #include <lunaix/mm/vmm.h>
17
18 #include <lunaix/common.h>
19 #include <lunaix/spike.h>
20
21 #include <klibc/string.h>
22
23 #include <stdint.h>
24
25 extern uint8_t __kernel_heap_start;
26
27 void*
28 lx_malloc_internal(heap_context_t* heap, size_t size);
29
30 void
31 place_chunk(uint8_t* ptr, size_t size);
32
33 void
34 lx_free_internal(void* ptr);
35
36 void*
37 coalesce(uint8_t* chunk_ptr);
38
39 void*
40 lx_grow_heap(heap_context_t* heap, size_t sz);
41
42 /*
43     At the beginning, we allocate an empty page and put our initial marker
44
45     | 4/1 | 0/1 |
46     ^     ^ brk
47     start
48
49     Then, expand the heap further, with HEAP_INIT_SIZE (evaluated to 4096, i.e.,
50    1 pg size) This will allocate as much pages and override old epilogue marker
51    with a free region hdr and put new epilogue marker. These are handled by
52    lx_grow_heap which is internally used by alloc to expand the heap at many
53    moment when needed.
54
55     | 4/1 | 4096/0 |   .......   | 4096/0 | 0/1 |
56     ^     ^ brk_old                       ^
57     start                                 brk
58
59     Note: the brk always point to the beginning of epilogue.
60 */
61
62 static heap_context_t kheap;
63
64 int
65 kalloc_init()
66 {
67     kheap.start = KHEAP_START;
68     kheap.brk = NULL;
69     kheap.max_addr =
70       (void*)PROC_START; // 在新的布局中,堆结束的地方即为进程表开始的地方
71
72     for (size_t i = 0; i < KHEAP_SIZE_MB >> 2; i++) {
73         vmm_set_mapping(PD_REFERENCED,
74                         (uintptr_t)kheap.start + (i << 22),
75                         0,
76                         PG_PREM_RW,
77                         VMAP_NOMAP);
78     }
79
80     if (!dmm_init(&kheap)) {
81         return 0;
82     }
83
84     SW(kheap.start, PACK(4, M_ALLOCATED));
85     SW(kheap.start + WSIZE, PACK(0, M_ALLOCATED));
86     kheap.brk += WSIZE;
87
88     return lx_grow_heap(&kheap, HEAP_INIT_SIZE) != NULL;
89 }
90
91 void*
92 lxmalloc(size_t size)
93 {
94     mutex_lock(&kheap.lock);
95     void* r = lx_malloc_internal(&kheap, size);
96     mutex_unlock(&kheap.lock);
97
98     return r;
99 }
100
101 void*
102 lxcalloc(size_t n, size_t elem)
103 {
104     size_t pd = n * elem;
105
106     // overflow detection
107     if (pd < elem || pd < n) {
108         return NULL;
109     }
110
111     void* ptr = lxmalloc(pd);
112     if (!ptr) {
113         return NULL;
114     }
115
116     return memset(ptr, 0, pd);
117 }
118
119 void
120 lxfree(void* ptr)
121 {
122     if (!ptr) {
123         return;
124     }
125     mutex_lock(&kheap.lock);
126
127     uint8_t* chunk_ptr = (uint8_t*)ptr - WSIZE;
128     uint32_t hdr = LW(chunk_ptr);
129     size_t sz = CHUNK_S(hdr);
130     uint8_t* next_hdr = chunk_ptr + sz;
131
132     // make sure the ptr we are 'bout to free makes sense
133     //   the size trick is stolen from glibc's malloc/malloc.c:4437 ;P
134
135     assert_msg(((uintptr_t)ptr < (uintptr_t)(-sz)) && !((uintptr_t)ptr & 0x3),
136                "free(): invalid pointer");
137
138     assert_msg(sz > WSIZE, "free(): invalid size");
139
140     SW(chunk_ptr, hdr & ~M_ALLOCATED);
141     SW(FPTR(chunk_ptr, sz), hdr & ~M_ALLOCATED);
142     SW(next_hdr, LW(next_hdr) | M_PREV_FREE);
143
144     coalesce(chunk_ptr);
145
146     mutex_unlock(&kheap.lock);
147 }
148
149 void*
150 lx_malloc_internal(heap_context_t* heap, size_t size)
151 {
152     // Simplest first fit approach.
153
154     if (!size) {
155         return NULL;
156     }
157
158     uint8_t* ptr = heap->start;
159     // round to largest 4B aligned value
160     //  and space for header
161     size = ROUNDUP(size + WSIZE, BOUNDARY);
162     while (ptr < (uint8_t*)heap->brk) {
163         uint32_t header = *((uint32_t*)ptr);
164         size_t chunk_size = CHUNK_S(header);
165         if (!chunk_size && CHUNK_A(header)) {
166             break;
167         }
168         if (chunk_size >= size && !CHUNK_A(header)) {
169             // found!
170             place_chunk(ptr, size);
171             return BPTR(ptr);
172         }
173         ptr += chunk_size;
174     }
175
176     // if heap is full (seems to be!), then allocate more space (if it's
177     // okay...)
178     if ((ptr = lx_grow_heap(heap, size))) {
179         place_chunk(ptr, size);
180         return BPTR(ptr);
181     }
182
183     // Well, we are officially OOM!
184     return NULL;
185 }
186
187 void
188 place_chunk(uint8_t* ptr, size_t size)
189 {
190     uint32_t header = *((uint32_t*)ptr);
191     size_t chunk_size = CHUNK_S(header);
192     *((uint32_t*)ptr) = PACK(size, CHUNK_PF(header) | M_ALLOCATED);
193     uint8_t* n_hdrptr = (uint8_t*)(ptr + size);
194     uint32_t diff = chunk_size - size;
195
196     if (!diff) {
197         // if the current free block is fully occupied
198         uint32_t n_hdr = LW(n_hdrptr);
199         // notify the next block about our avaliability
200         SW(n_hdrptr, n_hdr & ~0x2);
201     } else {
202         // if there is remaining free space left
203         uint32_t remainder_hdr = PACK(diff, M_NOT_ALLOCATED | M_PREV_ALLOCATED);
204         SW(n_hdrptr, remainder_hdr);
205         SW(FPTR(n_hdrptr, diff), remainder_hdr);
206
207         /*
208             | xxxx |      |         |
209
210                         |
211                         v
212
213             | xxxx |                |
214         */
215         coalesce(n_hdrptr);
216     }
217 }
218
219 void*
220 coalesce(uint8_t* chunk_ptr)
221 {
222     uint32_t hdr = LW(chunk_ptr);
223     uint32_t pf = CHUNK_PF(hdr);
224     uint32_t sz = CHUNK_S(hdr);
225
226     uint32_t n_hdr = LW(chunk_ptr + sz);
227
228     if (CHUNK_A(n_hdr) && pf) {
229         // case 1: prev is free
230         uint32_t prev_ftr = LW(chunk_ptr - WSIZE);
231         size_t prev_chunk_sz = CHUNK_S(prev_ftr);
232         uint32_t new_hdr = PACK(prev_chunk_sz + sz, CHUNK_PF(prev_ftr));
233         SW(chunk_ptr - prev_chunk_sz, new_hdr);
234         SW(FPTR(chunk_ptr, sz), new_hdr);
235         chunk_ptr -= prev_chunk_sz;
236     } else if (!CHUNK_A(n_hdr) && !pf) {
237         // case 2: next is free
238         size_t next_chunk_sz = CHUNK_S(n_hdr);
239         uint32_t new_hdr = PACK(next_chunk_sz + sz, pf);
240         SW(chunk_ptr, new_hdr);
241         SW(FPTR(chunk_ptr, sz + next_chunk_sz), new_hdr);
242     } else if (!CHUNK_A(n_hdr) && pf) {
243         // case 3: both free
244         uint32_t prev_ftr = LW(chunk_ptr - WSIZE);
245         size_t next_chunk_sz = CHUNK_S(n_hdr);
246         size_t prev_chunk_sz = CHUNK_S(prev_ftr);
247         uint32_t new_hdr =
248           PACK(next_chunk_sz + prev_chunk_sz + sz, CHUNK_PF(prev_ftr));
249         SW(chunk_ptr - prev_chunk_sz, new_hdr);
250         SW(FPTR(chunk_ptr, sz + next_chunk_sz), new_hdr);
251         chunk_ptr -= prev_chunk_sz;
252     }
253
254     // (fall through) case 4: prev and next are not free
255     return chunk_ptr;
256 }
257
258 void*
259 lx_grow_heap(heap_context_t* heap, size_t sz)
260 {
261     void* start;
262
263     // The "+ WSIZE" capture the overhead for epilogue marker
264     if (!(start = lxsbrk(heap, sz + WSIZE, 0))) {
265         return NULL;
266     }
267     sz = ROUNDUP(sz, BOUNDARY);
268
269     // minus the overhead for epilogue, keep the invariant.
270     heap->brk -= WSIZE;
271
272     uint32_t old_marker = *((uint32_t*)start);
273     uint32_t free_hdr = PACK(sz, CHUNK_PF(old_marker));
274     SW(start, free_hdr);
275     SW(FPTR(start, sz), free_hdr);
276     SW(NEXT_CHK(start), PACK(0, M_ALLOCATED | M_PREV_FREE));
277
278     return coalesce(start);
279 }