feat: open(2), close(2), mkdir(2) and readdir(2) syscall
[lunaix-os.git] / lunaix-os / kernel / sched.c
1 #include <arch/x86/interrupts.h>
2 #include <arch/x86/tss.h>
3
4 #include <hal/apic.h>
5 #include <hal/cpu.h>
6
7 #include <lunaix/mm/kalloc.h>
8 #include <lunaix/mm/pmm.h>
9 #include <lunaix/mm/valloc.h>
10 #include <lunaix/mm/vmm.h>
11 #include <lunaix/process.h>
12 #include <lunaix/sched.h>
13 #include <lunaix/signal.h>
14 #include <lunaix/spike.h>
15 #include <lunaix/status.h>
16 #include <lunaix/syscall.h>
17 #include <lunaix/syslog.h>
18
19 #define MAX_PROCESS 512
20
21 volatile struct proc_info* __current;
22
23 struct proc_info dummy;
24
25 struct scheduler sched_ctx;
26
27 LOG_MODULE("SCHED")
28
29 void
30 sched_init()
31 {
32     size_t pg_size = ROUNDUP(sizeof(struct proc_info) * MAX_PROCESS, 0x1000);
33
34     for (size_t i = 0; i <= pg_size; i += 4096) {
35         uintptr_t pa = pmm_alloc_page(KERNEL_PID, PP_FGPERSIST);
36         vmm_set_mapping(
37           PD_REFERENCED, PROC_START + i, pa, PG_PREM_RW, VMAP_NULL);
38     }
39
40     sched_ctx = (struct scheduler){ ._procs = (struct proc_info*)PROC_START,
41                                     .ptable_len = 0,
42                                     .procs_index = 0 };
43 }
44
45 void
46 run(struct proc_info* proc)
47 {
48     proc->state = PS_RUNNING;
49
50     /*
51         将tss.esp0设置为上次调度前的esp值。
52         当处理信号时,上下文信息是不会恢复的,而是保存在用户栈中,然后直接跳转进位于用户空间的sig_wrapper进行
53           信号的处理。当用户自定义的信号处理函数返回时,sigreturn的系统调用才开始进行上下文的恢复(或者说是进行
54           另一次调度。
55         由于这中间没有进行地址空间的交换,所以第二次跳转使用的是同一个内核栈,而之前默认tss.esp0的值是永远指向最顶部
56         这样一来就有可能会覆盖更早的上下文信息(比如嵌套的信号捕获函数)
57     */
58     tss_update_esp(proc->intr_ctx.registers.esp);
59
60     apic_done_servicing();
61
62     asm volatile("pushl %0\n"
63                  "jmp switch_to\n" ::"r"(proc)
64                  : "memory"); // kernel/asm/x86/interrupt.S
65 }
66
67 int
68 can_schedule(struct proc_info* proc)
69 {
70     if (__SIGTEST(proc->sig_pending, _SIGCONT)) {
71         __SIGCLEAR(proc->sig_pending, _SIGSTOP);
72     } else if (__SIGTEST(proc->sig_pending, _SIGSTOP)) {
73         // 如果进程受到SIGSTOP,则该进程不给予调度。
74         return 0;
75     }
76
77     return 1;
78 }
79
80 void
81 check_sleepers()
82 {
83     struct proc_info* leader = &sched_ctx._procs[0];
84     struct proc_info *pos, *n;
85     time_t now = clock_systime();
86     llist_for_each(pos, n, &leader->sleep.sleepers, sleep.sleepers)
87     {
88         if (PROC_TERMINATED(pos->state)) {
89             goto del;
90         }
91
92         time_t wtime = pos->sleep.wakeup_time;
93         time_t atime = pos->sleep.alarm_time;
94
95         if (wtime && now >= wtime) {
96             pos->sleep.wakeup_time = 0;
97             pos->state = PS_STOPPED;
98         }
99
100         if (atime && now >= atime) {
101             pos->sleep.alarm_time = 0;
102             __SIGSET(pos->sig_pending, _SIGALRM);
103         }
104
105         if (!wtime && !atime) {
106         del:
107             llist_delete(&pos->sleep.sleepers);
108         }
109     }
110 }
111
112 void
113 schedule()
114 {
115     if (!sched_ctx.ptable_len) {
116         return;
117     }
118
119     // 上下文切换相当的敏感!我们不希望任何的中断打乱栈的顺序……
120     cpu_disable_interrupt();
121     struct proc_info* next;
122     int prev_ptr = sched_ctx.procs_index;
123     int ptr = prev_ptr;
124
125     if (!(__current->state & ~PS_RUNNING)) {
126         __current->state = PS_STOPPED;
127     }
128
129     check_sleepers();
130
131     // round-robin scheduler
132 redo:
133     do {
134         ptr = (ptr + 1) % sched_ctx.ptable_len;
135         next = &sched_ctx._procs[ptr];
136     } while (next->state != PS_STOPPED && ptr != prev_ptr);
137
138     sched_ctx.procs_index = ptr;
139
140     if (!can_schedule(next)) {
141         // 如果该进程不给予调度,则尝试重新选择
142         goto redo;
143     }
144
145     run(next);
146 }
147
148 __DEFINE_LXSYSCALL1(unsigned int, sleep, unsigned int, seconds)
149 {
150     if (!seconds) {
151         return 0;
152     }
153
154     if (__current->sleep.wakeup_time) {
155         return (__current->sleep.wakeup_time - clock_systime()) / 1000U;
156     }
157
158     __current->sleep.wakeup_time = clock_systime() + seconds * 1000;
159     llist_append(&sched_ctx._procs[0].sleep.sleepers,
160                  &__current->sleep.sleepers);
161
162     __current->intr_ctx.registers.eax = seconds;
163     __current->state = PS_BLOCKED;
164     schedule();
165 }
166
167 __DEFINE_LXSYSCALL1(unsigned int, alarm, unsigned int, seconds)
168 {
169     time_t prev_ddl = __current->sleep.alarm_time;
170     time_t now = clock_systime();
171
172     __current->sleep.alarm_time = seconds ? now + seconds * 1000 : 0;
173
174     if (llist_empty(&__current->sleep.sleepers)) {
175         llist_append(&sched_ctx._procs[0].sleep.sleepers,
176                      &__current->sleep.sleepers);
177     }
178
179     return prev_ddl ? (prev_ddl - now) / 1000 : 0;
180 }
181
182 __DEFINE_LXSYSCALL1(void, exit, int, status)
183 {
184     terminate_proc(status);
185     schedule();
186 }
187
188 __DEFINE_LXSYSCALL(void, yield)
189 {
190     schedule();
191 }
192
193 pid_t
194 _wait(pid_t wpid, int* status, int options);
195
196 __DEFINE_LXSYSCALL1(pid_t, wait, int*, status)
197 {
198     return _wait(-1, status, 0);
199 }
200
201 __DEFINE_LXSYSCALL3(pid_t, waitpid, pid_t, pid, int*, status, int, options)
202 {
203     return _wait(pid, status, options);
204 }
205
206 pid_t
207 _wait(pid_t wpid, int* status, int options)
208 {
209     pid_t cur = __current->pid;
210     int status_flags = 0;
211     struct proc_info *proc, *n;
212     if (llist_empty(&__current->children)) {
213         return -1;
214     }
215
216     wpid = wpid ? wpid : -__current->pgid;
217     cpu_enable_interrupt();
218 repeat:
219     llist_for_each(proc, n, &__current->children, siblings)
220     {
221         if (!~wpid || proc->pid == wpid || proc->pgid == -wpid) {
222             if (proc->state == PS_TERMNAT && !options) {
223                 status_flags |= PEXITTERM;
224                 goto done;
225             }
226             if (proc->state == PS_STOPPED && (options & WUNTRACED)) {
227                 status_flags |= PEXITSTOP;
228                 goto done;
229             }
230         }
231     }
232     if ((options & WNOHANG)) {
233         return 0;
234     }
235     // 放弃当前的运行机会
236     sched_yield();
237     goto repeat;
238
239 done:
240     cpu_disable_interrupt();
241     status_flags |= PEXITSIG * (proc->sig_inprogress != 0);
242     if (status) {
243         *status = proc->exit_code | status_flags;
244     }
245     return destroy_process(proc->pid);
246 }
247
248 struct proc_info*
249 alloc_process()
250 {
251     pid_t i = 0;
252     for (; i < sched_ctx.ptable_len && sched_ctx._procs[i].state != PS_DESTROY;
253          i++)
254         ;
255
256     if (i == MAX_PROCESS) {
257         panick("Panic in Ponyville shimmer!");
258     }
259
260     if (i == sched_ctx.ptable_len) {
261         sched_ctx.ptable_len++;
262     }
263
264     struct proc_info* proc = &sched_ctx._procs[i];
265     memset(proc, 0, sizeof(*proc));
266
267     proc->state = PS_CREATED;
268     proc->pid = i;
269     proc->created = clock_systime();
270     proc->pgid = proc->pid;
271     proc->fdtable = vzalloc(sizeof(struct v_fdtable));
272
273     llist_init_head(&proc->mm.regions);
274     llist_init_head(&proc->children);
275     llist_init_head(&proc->grp_member);
276     llist_init_head(&proc->sleep.sleepers);
277
278     return proc;
279 }
280
281 void
282 commit_process(struct proc_info* process)
283 {
284     assert(process == &sched_ctx._procs[process->pid]);
285
286     if (process->state != PS_CREATED) {
287         __current->k_status = EINVAL;
288         return;
289     }
290
291     // every process is the child of first process (pid=1)
292     if (!process->parent) {
293         process->parent = &sched_ctx._procs[1];
294     }
295
296     llist_append(&process->parent->children, &process->siblings);
297
298     process->state = PS_STOPPED;
299 }
300
301 // from <kernel/process.c>
302 extern void
303 __del_pagetable(pid_t pid, uintptr_t mount_point);
304
305 pid_t
306 destroy_process(pid_t pid)
307 {
308     int index = pid;
309     if (index <= 0 || index > sched_ctx.ptable_len) {
310         __current->k_status = EINVAL;
311         return;
312     }
313     struct proc_info* proc = &sched_ctx._procs[index];
314     proc->state = PS_DESTROY;
315     llist_delete(&proc->siblings);
316
317     struct mm_region *pos, *n;
318     llist_for_each(pos, n, &proc->mm.regions.head, head)
319     {
320         lxfree(pos);
321     }
322
323     vmm_mount_pd(PD_MOUNT_1, proc->page_table);
324
325     __del_pagetable(pid, PD_MOUNT_1);
326
327     vmm_unmount_pd(PD_MOUNT_1);
328
329     return pid;
330 }
331
332 void
333 terminate_proc(int exit_code)
334 {
335     __current->state = PS_TERMNAT;
336     __current->exit_code = exit_code;
337
338     __SIGSET(__current->parent->sig_pending, _SIGCHLD);
339 }
340
341 struct proc_info*
342 get_process(pid_t pid)
343 {
344     int index = pid;
345     if (index < 0 || index > sched_ctx.ptable_len) {
346         return NULL;
347     }
348     return &sched_ctx._procs[index];
349 }
350
351 int
352 orphaned_proc(pid_t pid)
353 {
354     if (!pid)
355         return 0;
356     if (pid >= sched_ctx.ptable_len)
357         return 0;
358     struct proc_info* proc = &sched_ctx._procs[pid];
359     struct proc_info* parent = proc->parent;
360
361     // 如果其父进程的状态是terminated 或 destroy中的一种
362     // 或者其父进程是在该进程之后创建的,那么该进程为孤儿进程
363     return PROC_TERMINATED(parent->state) || parent->created > proc->created;
364 }