refactor: Optimize the context switch overhead
[lunaix-os.git] / lunaix-os / kernel / k_init.c
1 #include <lunaix/common.h>
2 #include <lunaix/device.h>
3 #include <lunaix/foptions.h>
4 #include <lunaix/input.h>
5 #include <lunaix/isrm.h>
6 #include <lunaix/lxconsole.h>
7 #include <lunaix/mm/cake.h>
8 #include <lunaix/mm/mmio.h>
9 #include <lunaix/mm/page.h>
10 #include <lunaix/mm/pmm.h>
11 #include <lunaix/mm/valloc.h>
12 #include <lunaix/mm/vmm.h>
13 #include <lunaix/process.h>
14 #include <lunaix/sched.h>
15 #include <lunaix/spike.h>
16 #include <lunaix/syscall.h>
17 #include <lunaix/tty/tty.h>
18 #include <lunaix/types.h>
19
20 #include <arch/x86/boot/multiboot.h>
21 #include <arch/x86/idt.h>
22 #include <arch/x86/interrupts.h>
23
24 #include <klibc/stdio.h>
25 #include <klibc/string.h>
26
27 extern u8_t __kernel_start;
28 extern u8_t __kernel_end;
29 extern u8_t __init_hhk_end;
30
31 #define PP_KERN_SHARED (PP_FGSHARED | PP_TKERN)
32
33 // Set remotely by kernel/asm/x86/prologue.S
34 multiboot_info_t* _k_init_mb_info;
35
36 x86_page_table* __kernel_ptd;
37
38 extern void
39 __proc0(); /* proc0.c */
40
41 void
42 spawn_proc0();
43
44 void
45 setup_memory(multiboot_memory_map_t* map, size_t map_size);
46
47 void
48 _kernel_pre_init()
49 {
50     // interrupts
51     _init_idt();
52     isrm_init();
53     intr_routine_init();
54
55     // memory
56     pmm_init(MEM_1MB + (_k_init_mb_info->mem_upper << 10));
57     vmm_init();
58
59     unsigned int map_size =
60       _k_init_mb_info->mmap_length / sizeof(multiboot_memory_map_t);
61
62     setup_memory((multiboot_memory_map_t*)_k_init_mb_info->mmap_addr, map_size);
63 }
64
65 void
66 _kernel_init()
67 {
68     int errno = 0;
69
70     // allocators
71     cake_init();
72     valloc_init();
73
74     sched_init();
75
76     // crt
77     tty_init(ioremap(VGA_FRAMEBUFFER, PG_SIZE));
78     tty_set_theme(VGA_COLOR_WHITE, VGA_COLOR_BLACK);
79
80     // file system & device subsys
81     vfs_init();
82     fsm_init();
83     input_init();
84
85     vfs_export_attributes();
86
87     lxconsole_init();
88
89     if ((errno = vfs_mount_root("ramfs", NULL))) {
90         panickf("Fail to mount root. (errno=%d)", errno);
91     }
92
93     vfs_mount("/dev", "devfs", NULL, 0);
94     vfs_mount("/sys", "twifs", NULL, MNT_RO);
95     vfs_mount("/task", "taskfs", NULL, MNT_RO);
96
97     lxconsole_spawn_ttydev();
98     device_init_builtin();
99
100     syscall_install();
101
102     spawn_proc0();
103 }
104
105 /**
106  * @brief 创建并运行proc0进程
107  *
108  */
109 void
110 spawn_proc0()
111 {
112     struct proc_info* proc0 = alloc_process();
113
114     /**
115      * @brief
116      * 注意:这里和视频中说的不一样,属于我之后的一点微调。
117      * 在视频中,spawn_proc0是在_kernel_post_init的末尾才调用的。并且是直接跳转到_proc0
118      *
119      * 但是我后来发现,上述的方法会产生竞态条件。这是因为spawn_proc0被调用的时候,时钟中断已经开启,
120      * 而中断的产生会打乱栈的布局,从而使得下面的上下文设置代码产生未定义行为(Undefined
121      * Behaviour)。 为了保险起见,有两种办法:
122      *      1. 在创建proc0进程前关闭中断
123      *      2. 将_kernel_post_init搬进proc0进程
124      * (_kernel_post_init已经更名为init_platform)
125      *
126      * 目前的解决方案是2
127      */
128
129     proc0->parent = proc0;
130
131     // 方案1:必须在读取eflags之后禁用。否则当进程被调度时,中断依然是关闭的!
132     // cpu_disable_interrupt();
133
134     /* Ok... 首先fork进我们的零号进程,而后由那里,我们fork进init进程。 */
135
136     // 把当前虚拟地址空间(内核)复制一份。
137     proc0->page_table = vmm_dup_vmspace(proc0->pid);
138
139     // 直接切换到新的拷贝,进行配置。
140     cpu_ldvmspace(proc0->page_table);
141
142     // 为内核创建一个专属栈空间。
143     for (size_t i = 0; i < (KSTACK_SIZE >> PG_SIZE_BITS); i++) {
144         ptr_t pa = pmm_alloc_page(KERNEL_PID, 0);
145         vmm_set_mapping(VMS_SELF,
146                         KSTACK_START + (i << PG_SIZE_BITS),
147                         pa,
148                         PG_PREM_RW,
149                         VMAP_NULL);
150     }
151
152     struct exec_param* execp =
153       (struct exec_param*)(KSTACK_TOP - sizeof(struct exec_param));
154     isr_param* isrp = (isr_param*)((ptr_t)execp - sizeof(isr_param));
155
156     *execp = (struct exec_param){ .cs = KCODE_SEG,
157                                   .eip = (ptr_t)__proc0,
158                                   .ss = KDATA_SEG,
159                                   .eflags = cpu_reflags() };
160     *isrp = (isr_param){ .registers = { .ds = KDATA_SEG,
161                                         .es = KDATA_SEG,
162                                         .fs = KDATA_SEG,
163                                         .gs = KDATA_SEG },
164                          .execp = execp };
165
166     proc0->intr_ctx = isrp;
167
168     // 加载x87默认配置
169     asm volatile("fninit\n"
170                  "fxsave (%%eax)" ::"a"(proc0->fxstate)
171                  : "memory");
172
173     // 向调度器注册进程。
174     commit_process(proc0);
175
176     // 由于时钟中断与APIC未就绪,我们需要手动进行第一次调度。这里也会同时隐式地恢复我们的eflags.IF位
177     proc0->state = PS_RUNNING;
178     asm volatile("pushl %0\n"
179                  "jmp switch_to\n" ::"r"(proc0));
180
181     /* Should not return */
182     assert_msg(0, "Unexpected Return");
183 }
184
185 // 按照 Memory map 标识可用的物理页
186 void
187 setup_memory(multiboot_memory_map_t* map, size_t map_size)
188 {
189
190     // First pass, to mark the physical pages
191     for (unsigned int i = 0; i < map_size; i++) {
192         multiboot_memory_map_t mmap = map[i];
193         if (mmap.type == MULTIBOOT_MEMORY_AVAILABLE) {
194             // 整数向上取整除法
195             ptr_t pg = map[i].addr_low + 0x0fffU;
196             pmm_mark_chunk_free(pg >> PG_SIZE_BITS,
197                                 map[i].len_low >> PG_SIZE_BITS);
198         }
199     }
200
201     // 将内核占据的页,包括前1MB,hhk_init 设为已占用
202     size_t pg_count = V2P(&__kernel_end) >> PG_SIZE_BITS;
203     pmm_mark_chunk_occupied(KERNEL_PID, 0, pg_count, PP_FGLOCKED);
204
205     // reserve higher half
206     for (size_t i = L1_INDEX(KERNEL_MM_BASE); i < 1023; i++) {
207         assert(vmm_set_mapping(VMS_SELF, i << 22, 0, 0, VMAP_NOMAP));
208     }
209 }