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