feat: msync(2)
[lunaix-os.git] / lunaix-os / kernel / process / 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/fs/taskfs.h>
8 #include <lunaix/mm/cake.h>
9 #include <lunaix/mm/kalloc.h>
10 #include <lunaix/mm/mmap.h>
11 #include <lunaix/mm/pmm.h>
12 #include <lunaix/mm/valloc.h>
13 #include <lunaix/mm/vmm.h>
14 #include <lunaix/process.h>
15 #include <lunaix/sched.h>
16 #include <lunaix/signal.h>
17 #include <lunaix/spike.h>
18 #include <lunaix/status.h>
19 #include <lunaix/syscall.h>
20 #include <lunaix/syslog.h>
21
22 volatile struct proc_info* __current;
23
24 static struct proc_info dummy_proc;
25
26 struct proc_info dummy;
27
28 struct scheduler sched_ctx;
29
30 struct cake_pile* proc_pile;
31
32 LOG_MODULE("SCHED")
33
34 void
35 sched_init_dummy();
36
37 void
38 sched_init()
39 {
40     proc_pile = cake_new_pile("proc", sizeof(struct proc_info), 1, 0);
41     cake_set_constructor(proc_pile, cake_ctor_zeroing);
42
43     sched_ctx = (struct scheduler){ ._procs = vzalloc(PROC_TABLE_SIZE),
44                                     .ptable_len = 0,
45                                     .procs_index = 0 };
46
47     // TODO initialize dummy_proc
48     sched_init_dummy();
49 }
50
51 #define DUMMY_STACK_SIZE 2048
52
53 void
54 sched_init_dummy()
55 {
56     // This surely need to be simplified or encapsulated!
57     // It is a living nightmare!
58
59     extern void my_dummy();
60     static char dummy_stack[DUMMY_STACK_SIZE] __attribute__((aligned(16)));
61
62     // memset to 0
63     dummy_proc = (struct proc_info){};
64     dummy_proc.intr_ctx = (isr_param){
65         .registers = { .ds = KDATA_SEG,
66                        .es = KDATA_SEG,
67                        .fs = KDATA_SEG,
68                        .gs = KDATA_SEG,
69                        .esp = (void*)dummy_stack + DUMMY_STACK_SIZE - 20 },
70         .cs = KCODE_SEG,
71         .eip = (void*)my_dummy,
72         .ss = KDATA_SEG,
73         .eflags = cpu_reflags() | 0x0200
74     };
75
76     *(u32_t*)(&dummy_stack[DUMMY_STACK_SIZE - 4]) = dummy_proc.intr_ctx.eflags;
77     *(u32_t*)(&dummy_stack[DUMMY_STACK_SIZE - 8]) = KCODE_SEG;
78     *(u32_t*)(&dummy_stack[DUMMY_STACK_SIZE - 12]) = dummy_proc.intr_ctx.eip;
79
80     dummy_proc.page_table = cpu_rcr3();
81     dummy_proc.state = PS_READY;
82     dummy_proc.parent = &dummy_proc;
83     dummy_proc.pid = KERNEL_PID;
84
85     __current = &dummy_proc;
86 }
87
88 void
89 run(struct proc_info* proc)
90 {
91     proc->state = PS_RUNNING;
92
93     /*
94         将tss.esp0设置为上次调度前的esp值。
95         当处理信号时,上下文信息是不会恢复的,而是保存在用户栈中,然后直接跳转进位于用户空间的sig_wrapper进行
96           信号的处理。当用户自定义的信号处理函数返回时,sigreturn的系统调用才开始进行上下文的恢复(或者说是进行
97           另一次调度。
98         由于这中间没有进行地址空间的交换,所以第二次跳转使用的是同一个内核栈,而之前默认tss.esp0的值是永远指向最顶部
99         这样一来就有可能会覆盖更早的上下文信息(比如嵌套的信号捕获函数)
100     */
101     tss_update_esp(proc->intr_ctx.registers.esp);
102
103     apic_done_servicing();
104
105     asm volatile("pushl %0\n"
106                  "jmp switch_to\n" ::"r"(proc)
107                  : "memory"); // kernel/asm/x86/interrupt.S
108 }
109
110 int
111 can_schedule(struct proc_info* proc)
112 {
113     if (__SIGTEST(proc->sig_pending, _SIGCONT)) {
114         __SIGCLEAR(proc->sig_pending, _SIGSTOP);
115     } else if (__SIGTEST(proc->sig_pending, _SIGSTOP)) {
116         // 如果进程受到SIGSTOP,则该进程不给予调度。
117         return 0;
118     }
119
120     return 1;
121 }
122
123 void
124 check_sleepers()
125 {
126     struct proc_info* leader = sched_ctx._procs[0];
127     struct proc_info *pos, *n;
128     time_t now = clock_systime();
129     llist_for_each(pos, n, &leader->sleep.sleepers, sleep.sleepers)
130     {
131         if (PROC_TERMINATED(pos->state)) {
132             goto del;
133         }
134
135         time_t wtime = pos->sleep.wakeup_time;
136         time_t atime = pos->sleep.alarm_time;
137
138         if (wtime && now >= wtime) {
139             pos->sleep.wakeup_time = 0;
140             pos->state = PS_READY;
141         }
142
143         if (atime && now >= atime) {
144             pos->sleep.alarm_time = 0;
145             __SIGSET(pos->sig_pending, _SIGALRM);
146         }
147
148         if (!wtime && !atime) {
149         del:
150             llist_delete(&pos->sleep.sleepers);
151         }
152     }
153 }
154
155 void
156 schedule()
157 {
158     if (!sched_ctx.ptable_len) {
159         return;
160     }
161
162     // 上下文切换相当的敏感!我们不希望任何的中断打乱栈的顺序……
163     cpu_disable_interrupt();
164     struct proc_info* next;
165     int prev_ptr = sched_ctx.procs_index;
166     int ptr = prev_ptr;
167
168     if (!(__current->state & ~PS_RUNNING)) {
169         __current->state = PS_READY;
170     }
171
172     check_sleepers();
173
174     // round-robin scheduler
175 redo:
176     do {
177         ptr = (ptr + 1) % sched_ctx.ptable_len;
178         next = sched_ctx._procs[ptr];
179     } while (!next || (next->state != PS_READY && ptr != prev_ptr));
180
181     sched_ctx.procs_index = ptr;
182
183     if (next->state != PS_READY) {
184         // schedule the dummy process if we're out of choice
185         next = &dummy_proc;
186         goto done;
187     }
188
189     if (!can_schedule(next)) {
190         // 如果该进程不给予调度,则尝试重新选择
191         goto redo;
192     }
193
194 done:
195     run(next);
196 }
197
198 void
199 sched_yieldk()
200 {
201     cpu_enable_interrupt();
202     cpu_int(LUNAIX_SCHED);
203 }
204
205 __DEFINE_LXSYSCALL1(unsigned int, sleep, unsigned int, seconds)
206 {
207     if (!seconds) {
208         return 0;
209     }
210
211     if (__current->sleep.wakeup_time) {
212         return (__current->sleep.wakeup_time - clock_systime()) / 1000U;
213     }
214
215     struct proc_info* root_proc = sched_ctx._procs[0];
216     __current->sleep.wakeup_time = clock_systime() + seconds * 1000;
217     llist_append(&root_proc->sleep.sleepers, &__current->sleep.sleepers);
218
219     __current->intr_ctx.registers.eax = seconds;
220
221     block_current();
222     schedule();
223 }
224
225 __DEFINE_LXSYSCALL1(unsigned int, alarm, unsigned int, seconds)
226 {
227     time_t prev_ddl = __current->sleep.alarm_time;
228     time_t now = clock_systime();
229
230     __current->sleep.alarm_time = seconds ? now + seconds * 1000 : 0;
231
232     struct proc_info* root_proc = sched_ctx._procs[0];
233     if (llist_empty(&__current->sleep.sleepers)) {
234         llist_append(&root_proc->sleep.sleepers, &__current->sleep.sleepers);
235     }
236
237     return prev_ddl ? (prev_ddl - now) / 1000 : 0;
238 }
239
240 __DEFINE_LXSYSCALL1(void, exit, int, status)
241 {
242     terminate_proc(status);
243     schedule();
244 }
245
246 __DEFINE_LXSYSCALL(void, yield)
247 {
248     schedule();
249 }
250
251 pid_t
252 _wait(pid_t wpid, int* status, int options);
253
254 __DEFINE_LXSYSCALL1(pid_t, wait, int*, status)
255 {
256     return _wait(-1, status, 0);
257 }
258
259 __DEFINE_LXSYSCALL3(pid_t, waitpid, pid_t, pid, int*, status, int, options)
260 {
261     return _wait(pid, status, options);
262 }
263
264 __DEFINE_LXSYSCALL(int, geterrno)
265 {
266     return __current->k_status;
267 }
268
269 pid_t
270 _wait(pid_t wpid, int* status, int options)
271 {
272     pid_t cur = __current->pid;
273     int status_flags = 0;
274     struct proc_info *proc, *n;
275     if (llist_empty(&__current->children)) {
276         return -1;
277     }
278
279     wpid = wpid ? wpid : -__current->pgid;
280 repeat:
281     llist_for_each(proc, n, &__current->children, siblings)
282     {
283         if (!~wpid || proc->pid == wpid || proc->pgid == -wpid) {
284             if (proc->state == PS_TERMNAT && !options) {
285                 status_flags |= PEXITTERM;
286                 goto done;
287             }
288             if (proc->state == PS_READY && (options & WUNTRACED)) {
289                 status_flags |= PEXITSTOP;
290                 goto done;
291             }
292         }
293     }
294     if ((options & WNOHANG)) {
295         return 0;
296     }
297     // 放弃当前的运行机会
298     sched_yieldk();
299     goto repeat;
300
301 done:
302     status_flags |= PEXITSIG * (proc->sig_inprogress != 0);
303     if (status) {
304         *status = proc->exit_code | status_flags;
305     }
306     return destroy_process(proc->pid);
307 }
308
309 struct proc_info*
310 alloc_process()
311 {
312     pid_t i = 0;
313     for (; i < sched_ctx.ptable_len && sched_ctx._procs[i]; i++)
314         ;
315
316     if (i == MAX_PROCESS) {
317         panick("Panic in Ponyville shimmer!");
318     }
319
320     if (i == sched_ctx.ptable_len) {
321         sched_ctx.ptable_len++;
322     }
323
324     struct proc_info* proc = cake_grab(proc_pile);
325
326     proc->state = PS_CREATED;
327     proc->pid = i;
328     proc->created = clock_systime();
329     proc->pgid = proc->pid;
330     proc->fdtable = vzalloc(sizeof(struct v_fdtable));
331     proc->fxstate =
332       vzalloc_dma(512); // FXSAVE需要十六位对齐地址,使用DMA块(128位对齐)
333
334     llist_init_head(&proc->mm.regions);
335     llist_init_head(&proc->tasks);
336     llist_init_head(&proc->children);
337     llist_init_head(&proc->grp_member);
338     llist_init_head(&proc->sleep.sleepers);
339     waitq_init(&proc->waitqueue);
340
341     sched_ctx._procs[i] = proc;
342
343     return proc;
344 }
345
346 void
347 commit_process(struct proc_info* process)
348 {
349     assert(process == sched_ctx._procs[process->pid]);
350
351     if (process->state != PS_CREATED) {
352         __current->k_status = EINVAL;
353         return;
354     }
355
356     // every process is the child of first process (pid=1)
357     if (!process->parent) {
358         process->parent = sched_ctx._procs[1];
359     }
360
361     llist_append(&process->parent->children, &process->siblings);
362     llist_append(&sched_ctx._procs[0]->tasks, &process->tasks);
363
364     process->state = PS_READY;
365 }
366
367 // from <kernel/process.c>
368 extern void
369 __del_pagetable(pid_t pid, uintptr_t mount_point);
370
371 pid_t
372 destroy_process(pid_t pid)
373 {
374     int index = pid;
375     if (index <= 0 || index > sched_ctx.ptable_len) {
376         __current->k_status = EINVAL;
377         return;
378     }
379     struct proc_info* proc = sched_ctx._procs[index];
380     sched_ctx._procs[index] = 0;
381
382     llist_delete(&proc->siblings);
383     llist_delete(&proc->grp_member);
384     llist_delete(&proc->tasks);
385     llist_delete(&proc->sleep.sleepers);
386
387     taskfs_invalidate(pid);
388
389     if (proc->cwd) {
390         vfs_unref_dnode(proc->cwd);
391     }
392
393     for (size_t i = 0; i < VFS_MAX_FD; i++) {
394         struct v_fd* fd = proc->fdtable->fds[i];
395         if (fd) {
396             vfs_pclose(fd->file, pid);
397             vfs_free_fd(fd);
398         }
399     }
400
401     vfree(proc->fdtable);
402     vfree_dma(proc->fxstate);
403
404     vmm_mount_pd(VMS_MOUNT_1, proc->page_table);
405
406     struct mm_region *pos, *n;
407     llist_for_each(pos, n, &proc->mm.regions, head)
408     {
409         mem_sync_pages(VMS_MOUNT_1, pos, pos->start, pos->end - pos->start, 0);
410         vfree(pos);
411     }
412
413     __del_pagetable(pid, VMS_MOUNT_1);
414
415     vmm_unmount_pd(VMS_MOUNT_1);
416
417     cake_release(proc_pile, proc);
418
419     return pid;
420 }
421
422 void
423 terminate_proc(int exit_code)
424 {
425     __current->state = PS_TERMNAT;
426     __current->exit_code = exit_code;
427
428     __SIGSET(__current->parent->sig_pending, _SIGCHLD);
429 }
430
431 struct proc_info*
432 get_process(pid_t pid)
433 {
434     int index = pid;
435     if (index < 0 || index > sched_ctx.ptable_len) {
436         return NULL;
437     }
438     return sched_ctx._procs[index];
439 }
440
441 int
442 orphaned_proc(pid_t pid)
443 {
444     if (!pid)
445         return 0;
446     if (pid >= sched_ctx.ptable_len)
447         return 0;
448     struct proc_info* proc = sched_ctx._procs[pid];
449     struct proc_info* parent = proc->parent;
450
451     // 如果其父进程的状态是terminated 或 destroy中的一种
452     // 或者其父进程是在该进程之后创建的,那么该进程为孤儿进程
453     return PROC_TERMINATED(parent->state) || parent->created > proc->created;
454 }