feat: shell and signal demo as loadable user executable
[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 = (void*)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 (__SIGTEST(proc->sig_pending, _SIGCONT)) {
115         __SIGCLEAR(proc->sig_pending, _SIGSTOP);
116     } else if (__SIGTEST(proc->sig_pending, _SIGSTOP)) {
117         // 如果进程受到SIGSTOP,则该进程不给予调度。
118         return 0;
119     }
120
121     return 1;
122 }
123
124 void
125 check_sleepers()
126 {
127     struct proc_info* leader = sched_ctx._procs[0];
128     struct proc_info *pos, *n;
129     time_t now = clock_systime();
130     llist_for_each(pos, n, &leader->sleep.sleepers, sleep.sleepers)
131     {
132         if (PROC_TERMINATED(pos->state)) {
133             goto del;
134         }
135
136         time_t wtime = pos->sleep.wakeup_time;
137         time_t atime = pos->sleep.alarm_time;
138
139         if (wtime && now >= wtime) {
140             pos->sleep.wakeup_time = 0;
141             pos->state = PS_READY;
142         }
143
144         if (atime && now >= atime) {
145             pos->sleep.alarm_time = 0;
146             __SIGSET(pos->sig_pending, _SIGALRM);
147         }
148
149         if (!wtime && !atime) {
150         del:
151             llist_delete(&pos->sleep.sleepers);
152         }
153     }
154 }
155
156 void
157 schedule()
158 {
159     if (!sched_ctx.ptable_len) {
160         return;
161     }
162
163     // 上下文切换相当的敏感!我们不希望任何的中断打乱栈的顺序……
164     cpu_disable_interrupt();
165     struct proc_info* next;
166     int prev_ptr = sched_ctx.procs_index;
167     int ptr = prev_ptr;
168
169     if (!(__current->state & ~PS_RUNNING)) {
170         __current->state = PS_READY;
171     }
172
173     check_sleepers();
174
175     // round-robin scheduler
176 redo:
177     do {
178         ptr = (ptr + 1) % sched_ctx.ptable_len;
179         next = sched_ctx._procs[ptr];
180     } while (!next || (next->state != PS_READY && ptr != prev_ptr));
181
182     sched_ctx.procs_index = ptr;
183
184     if (next->state != PS_READY) {
185         // schedule the dummy process if we're out of choice
186         next = &dummy_proc;
187         goto done;
188     }
189
190     if (!can_schedule(next)) {
191         // 如果该进程不给予调度,则尝试重新选择
192         goto redo;
193     }
194
195 done:
196     run(next);
197 }
198
199 void
200 sched_yieldk()
201 {
202     cpu_enable_interrupt();
203     cpu_int(LUNAIX_SCHED);
204 }
205
206 __DEFINE_LXSYSCALL1(unsigned int, sleep, unsigned int, seconds)
207 {
208     if (!seconds) {
209         return 0;
210     }
211
212     if (__current->sleep.wakeup_time) {
213         return (__current->sleep.wakeup_time - clock_systime()) / 1000U;
214     }
215
216     struct proc_info* root_proc = sched_ctx._procs[0];
217     __current->sleep.wakeup_time = clock_systime() + seconds * 1000;
218
219     if (llist_empty(&__current->sleep.sleepers)) {
220         llist_append(&root_proc->sleep.sleepers, &__current->sleep.sleepers);
221     }
222
223     __current->intr_ctx.registers.eax = seconds;
224
225     block_current();
226     schedule();
227 }
228
229 __DEFINE_LXSYSCALL1(unsigned int, alarm, unsigned int, seconds)
230 {
231     time_t prev_ddl = __current->sleep.alarm_time;
232     time_t now = clock_systime();
233
234     __current->sleep.alarm_time = seconds ? now + seconds * 1000 : 0;
235
236     struct proc_info* root_proc = sched_ctx._procs[0];
237     if (llist_empty(&__current->sleep.sleepers)) {
238         llist_append(&root_proc->sleep.sleepers, &__current->sleep.sleepers);
239     }
240
241     return prev_ddl ? (prev_ddl - now) / 1000 : 0;
242 }
243
244 __DEFINE_LXSYSCALL1(void, exit, int, status)
245 {
246     terminate_proc(status);
247     schedule();
248 }
249
250 __DEFINE_LXSYSCALL(void, yield)
251 {
252     schedule();
253 }
254
255 pid_t
256 _wait(pid_t wpid, int* status, int options);
257
258 __DEFINE_LXSYSCALL1(pid_t, wait, int*, status)
259 {
260     return _wait(-1, status, 0);
261 }
262
263 __DEFINE_LXSYSCALL3(pid_t, waitpid, pid_t, pid, int*, status, int, options)
264 {
265     return _wait(pid, status, options);
266 }
267
268 __DEFINE_LXSYSCALL(int, geterrno)
269 {
270     return __current->k_status;
271 }
272
273 pid_t
274 _wait(pid_t wpid, int* status, int options)
275 {
276     pid_t cur = __current->pid;
277     int status_flags = 0;
278     struct proc_info *proc, *n;
279     if (llist_empty(&__current->children)) {
280         return -1;
281     }
282
283     wpid = wpid ? wpid : -__current->pgid;
284 repeat:
285     llist_for_each(proc, n, &__current->children, siblings)
286     {
287         if (!~wpid || proc->pid == wpid || proc->pgid == -wpid) {
288             if (proc->state == PS_TERMNAT && !options) {
289                 status_flags |= PEXITTERM;
290                 goto done;
291             }
292             if (proc->state == PS_READY && (options & WUNTRACED)) {
293                 status_flags |= PEXITSTOP;
294                 goto done;
295             }
296         }
297     }
298     if ((options & WNOHANG)) {
299         return 0;
300     }
301     // 放弃当前的运行机会
302     sched_yieldk();
303     goto repeat;
304
305 done:
306     status_flags |= PEXITSIG * (proc->sig_inprogress != 0);
307     if (status) {
308         *status = proc->exit_code | status_flags;
309     }
310     return destroy_process(proc->pid);
311 }
312
313 struct proc_info*
314 alloc_process()
315 {
316     pid_t i = 0;
317     for (; i < sched_ctx.ptable_len && sched_ctx._procs[i]; i++)
318         ;
319
320     if (i == MAX_PROCESS) {
321         panick("Panic in Ponyville shimmer!");
322     }
323
324     if (i == sched_ctx.ptable_len) {
325         sched_ctx.ptable_len++;
326     }
327
328     struct proc_info* proc = cake_grab(proc_pile);
329
330     proc->state = PS_CREATED;
331     proc->pid = i;
332     proc->mm.pid = i;
333     proc->created = clock_systime();
334     proc->pgid = proc->pid;
335     proc->fdtable = vzalloc(sizeof(struct v_fdtable));
336     proc->fxstate =
337       vzalloc_dma(512); // FXSAVE需要十六位对齐地址,使用DMA块(128位对齐)
338
339     llist_init_head(&proc->mm.regions);
340     llist_init_head(&proc->tasks);
341     llist_init_head(&proc->children);
342     llist_init_head(&proc->grp_member);
343     llist_init_head(&proc->sleep.sleepers);
344     waitq_init(&proc->waitqueue);
345
346     sched_ctx._procs[i] = proc;
347
348     return proc;
349 }
350
351 void
352 commit_process(struct proc_info* process)
353 {
354     assert(process == sched_ctx._procs[process->pid]);
355
356     if (process->state != PS_CREATED) {
357         __current->k_status = EINVAL;
358         return;
359     }
360
361     // every process is the child of first process (pid=1)
362     if (!process->parent) {
363         process->parent = sched_ctx._procs[1];
364     }
365
366     llist_append(&process->parent->children, &process->siblings);
367     llist_append(&sched_ctx._procs[0]->tasks, &process->tasks);
368
369     process->state = PS_READY;
370 }
371
372 // from <kernel/process.c>
373 extern void
374 __del_pagetable(pid_t pid, uintptr_t mount_point);
375
376 pid_t
377 destroy_process(pid_t pid)
378 {
379     int index = pid;
380     if (index <= 0 || index > sched_ctx.ptable_len) {
381         __current->k_status = EINVAL;
382         return;
383     }
384     struct proc_info* proc = sched_ctx._procs[index];
385     sched_ctx._procs[index] = 0;
386
387     llist_delete(&proc->siblings);
388     llist_delete(&proc->grp_member);
389     llist_delete(&proc->tasks);
390     llist_delete(&proc->sleep.sleepers);
391
392     taskfs_invalidate(pid);
393
394     if (proc->cwd) {
395         vfs_unref_dnode(proc->cwd);
396     }
397
398     for (size_t i = 0; i < VFS_MAX_FD; i++) {
399         struct v_fd* fd = proc->fdtable->fds[i];
400         if (fd) {
401             vfs_pclose(fd->file, pid);
402             vfs_free_fd(fd);
403         }
404     }
405
406     vfree(proc->fdtable);
407     vfree_dma(proc->fxstate);
408
409     vmm_mount_pd(VMS_MOUNT_1, proc->page_table);
410
411     struct mm_region *pos, *n;
412     llist_for_each(pos, n, &proc->mm.regions, head)
413     {
414         mem_sync_pages(VMS_MOUNT_1, pos, pos->start, pos->end - pos->start, 0);
415         region_release(pos);
416     }
417
418     __del_pagetable(pid, VMS_MOUNT_1);
419
420     vmm_unmount_pd(VMS_MOUNT_1);
421
422     cake_release(proc_pile, proc);
423
424     return pid;
425 }
426
427 void
428 terminate_proc(int exit_code)
429 {
430     __current->state = PS_TERMNAT;
431     __current->exit_code = exit_code;
432
433     __SIGSET(__current->parent->sig_pending, _SIGCHLD);
434 }
435
436 struct proc_info*
437 get_process(pid_t pid)
438 {
439     int index = pid;
440     if (index < 0 || index > sched_ctx.ptable_len) {
441         return NULL;
442     }
443     return sched_ctx._procs[index];
444 }
445
446 int
447 orphaned_proc(pid_t pid)
448 {
449     if (!pid)
450         return 0;
451     if (pid >= sched_ctx.ptable_len)
452         return 0;
453     struct proc_info* proc = sched_ctx._procs[pid];
454     struct proc_info* parent = proc->parent;
455
456     // 如果其父进程的状态是terminated 或 destroy中的一种
457     // 或者其父进程是在该进程之后创建的,那么该进程为孤儿进程
458     return PROC_TERMINATED(parent->state) || parent->created > proc->created;
459 }