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