refactor: one more step towards arch-agnostic design
[lunaix-os.git] / lunaix-os / kernel / boot_helper.c
1 #include <klibc/string.h>
2 #include <lunaix/boot_generic.h>
3 #include <lunaix/mm/page.h>
4 #include <lunaix/mm/pmm.h>
5 #include <lunaix/mm/vmm.h>
6 #include <lunaix/spike.h>
7 #include <sys/mm/mempart.h>
8
9 /**
10  * @brief Reserve memory for kernel bootstrapping initialization
11  *
12  * @param bhctx
13  */
14 void
15 boot_begin(struct boot_handoff* bhctx)
16 {
17     bhctx->prepare(bhctx);
18
19     struct boot_mmapent *mmap = bhctx->mem.mmap, *mmapent;
20     for (size_t i = 0; i < bhctx->mem.mmap_len; i++) {
21         mmapent = &mmap[i];
22         size_t size_pg = PN(ROUNDUP(mmapent->size, PG_SIZE));
23
24         if (mmapent->type == BOOT_MMAP_FREE) {
25             pmm_mark_chunk_free(PN(mmapent->start), size_pg);
26             continue;
27         }
28
29         ptr_t pa = PG_ALIGN(mmapent->start);
30         for (size_t j = 0; j < size_pg && pa < KERNEL_EXEC;
31              j++, pa += PM_PAGE_SIZE) {
32             vmm_set_mapping(VMS_SELF, pa, pa, PG_PREM_RW, VMAP_IGNORE);
33         }
34     }
35 }
36
37 extern u8_t __kexec_boot_end; /* link/linker.ld */
38
39 /**
40  * @brief Release memory for kernel bootstrapping initialization
41  *
42  * @param bhctx
43  */
44 void
45 boot_end(struct boot_handoff* bhctx)
46 {
47     struct boot_mmapent *mmap = bhctx->mem.mmap, *mmapent;
48     for (size_t i = 0; i < bhctx->mem.mmap_len; i++) {
49         mmapent = &mmap[i];
50         size_t size_pg = PN(ROUNDUP(mmapent->size, PG_SIZE));
51
52         if (mmapent->start >= KERNEL_EXEC || mmapent->type == BOOT_MMAP_FREE) {
53             continue;
54         }
55
56         if (mmapent->type == BOOT_MMAP_RCLM) {
57             pmm_mark_chunk_free(PN(mmapent->start), size_pg);
58         }
59
60         ptr_t pa = PG_ALIGN(mmapent->start);
61         for (size_t j = 0; j < size_pg && pa < KERNEL_EXEC;
62              j++, pa += PM_PAGE_SIZE) {
63             vmm_del_mapping(VMS_SELF, pa);
64         }
65     }
66
67     bhctx->release(bhctx);
68 }
69
70 /**
71  * @brief Clean up the boot stage code and data
72  *
73  */
74 void
75 boot_cleanup()
76 {
77     // clean up
78     for (size_t i = 0; i < (ptr_t)(&__kexec_boot_end); i += PG_SIZE) {
79         vmm_del_mapping(VMS_SELF, (ptr_t)i);
80         pmm_free_page(KERNEL_PID, (ptr_t)i);
81     }
82 }