fix: argv, envp passing
[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     do {
188         ptr = (ptr + 1) % sched_ctx.ptable_len;
189         next = sched_ctx._procs[ptr];
190
191         if (!(found = can_schedule(next))) {
192             if (ptr == prev_ptr) {
193                 next = &dummy_proc;
194                 goto done;
195             }
196         }
197     } while (!found);
198
199     sched_ctx.procs_index = ptr;
200
201 done:
202     run(next);
203 }
204
205 void
206 sched_yieldk()
207 {
208     cpu_enable_interrupt();
209     cpu_int(LUNAIX_SCHED);
210 }
211
212 __DEFINE_LXSYSCALL1(unsigned int, sleep, unsigned int, seconds)
213 {
214     if (!seconds) {
215         return 0;
216     }
217
218     if (__current->sleep.wakeup_time) {
219         return (__current->sleep.wakeup_time - clock_systime()) / 1000U;
220     }
221
222     struct proc_info* root_proc = sched_ctx._procs[0];
223     __current->sleep.wakeup_time = clock_systime() + seconds * 1000;
224
225     if (llist_empty(&__current->sleep.sleepers)) {
226         llist_append(&root_proc->sleep.sleepers, &__current->sleep.sleepers);
227     }
228
229     __current->intr_ctx.registers.eax = seconds;
230
231     block_current();
232     schedule();
233
234     return 0;
235 }
236
237 __DEFINE_LXSYSCALL1(unsigned int, alarm, unsigned int, seconds)
238 {
239     time_t prev_ddl = __current->sleep.alarm_time;
240     time_t now = clock_systime();
241
242     __current->sleep.alarm_time = seconds ? now + seconds * 1000 : 0;
243
244     struct proc_info* root_proc = sched_ctx._procs[0];
245     if (llist_empty(&__current->sleep.sleepers)) {
246         llist_append(&root_proc->sleep.sleepers, &__current->sleep.sleepers);
247     }
248
249     return prev_ddl ? (prev_ddl - now) / 1000 : 0;
250 }
251
252 __DEFINE_LXSYSCALL1(void, exit, int, status)
253 {
254     terminate_proc(status);
255     schedule();
256 }
257
258 __DEFINE_LXSYSCALL(void, yield)
259 {
260     schedule();
261 }
262
263 pid_t
264 _wait(pid_t wpid, int* status, int options);
265
266 __DEFINE_LXSYSCALL1(pid_t, wait, int*, status)
267 {
268     return _wait(-1, status, 0);
269 }
270
271 __DEFINE_LXSYSCALL3(pid_t, waitpid, pid_t, pid, int*, status, int, options)
272 {
273     return _wait(pid, status, options);
274 }
275
276 __DEFINE_LXSYSCALL(int, geterrno)
277 {
278     return __current->k_status;
279 }
280
281 pid_t
282 _wait(pid_t wpid, int* status, int options)
283 {
284     pid_t cur = __current->pid;
285     int status_flags = 0;
286     struct proc_info *proc, *n;
287     if (llist_empty(&__current->children)) {
288         return -1;
289     }
290
291     wpid = wpid ? wpid : -__current->pgid;
292 repeat:
293     llist_for_each(proc, n, &__current->children, siblings)
294     {
295         if (!~wpid || proc->pid == wpid || proc->pgid == -wpid) {
296             if (proc->state == PS_TERMNAT && !options) {
297                 status_flags |= PEXITTERM;
298                 goto done;
299             }
300             if (proc->state == PS_READY && (options & WUNTRACED)) {
301                 status_flags |= PEXITSTOP;
302                 goto done;
303             }
304         }
305     }
306     if ((options & WNOHANG)) {
307         return 0;
308     }
309     // 放弃当前的运行机会
310     sched_yieldk();
311     goto repeat;
312
313 done:
314     if (status) {
315         *status = proc->exit_code | status_flags;
316     }
317     return destroy_process(proc->pid);
318 }
319
320 struct proc_info*
321 alloc_process()
322 {
323     pid_t i = 0;
324     for (; i < sched_ctx.ptable_len && sched_ctx._procs[i]; i++)
325         ;
326
327     if (i == MAX_PROCESS) {
328         panick("Panic in Ponyville shimmer!");
329     }
330
331     if (i == sched_ctx.ptable_len) {
332         sched_ctx.ptable_len++;
333     }
334
335     struct proc_info* proc = cake_grab(proc_pile);
336
337     proc->state = PS_CREATED;
338     proc->pid = i;
339     proc->mm.pid = i;
340     proc->created = clock_systime();
341     proc->pgid = proc->pid;
342     proc->fdtable = vzalloc(sizeof(struct v_fdtable));
343     proc->fxstate =
344       vzalloc_dma(512); // FXSAVE需要十六位对齐地址,使用DMA块(128位对齐)
345
346     llist_init_head(&proc->mm.regions);
347     llist_init_head(&proc->tasks);
348     llist_init_head(&proc->children);
349     llist_init_head(&proc->grp_member);
350     llist_init_head(&proc->sleep.sleepers);
351     waitq_init(&proc->waitqueue);
352
353     sched_ctx._procs[i] = proc;
354
355     return proc;
356 }
357
358 void
359 commit_process(struct proc_info* process)
360 {
361     assert(process == sched_ctx._procs[process->pid]);
362
363     if (process->state != PS_CREATED) {
364         __current->k_status = EINVAL;
365         return;
366     }
367
368     // every process is the child of first process (pid=1)
369     if (!process->parent) {
370         process->parent = sched_ctx._procs[1];
371     }
372
373     llist_append(&process->parent->children, &process->siblings);
374     llist_append(&sched_ctx._procs[0]->tasks, &process->tasks);
375
376     process->state = PS_READY;
377 }
378
379 // from <kernel/process.c>
380 extern void
381 __del_pagetable(pid_t pid, ptr_t mount_point);
382
383 pid_t
384 destroy_process(pid_t pid)
385 {
386     int index = pid;
387     if (index <= 0 || index > sched_ctx.ptable_len) {
388         __current->k_status = EINVAL;
389         return -1;
390     }
391
392     struct proc_info* proc = sched_ctx._procs[index];
393     sched_ctx._procs[index] = 0;
394
395     llist_delete(&proc->siblings);
396     llist_delete(&proc->grp_member);
397     llist_delete(&proc->tasks);
398     llist_delete(&proc->sleep.sleepers);
399
400     taskfs_invalidate(pid);
401
402     if (proc->cwd) {
403         vfs_unref_dnode(proc->cwd);
404     }
405
406     for (size_t i = 0; i < VFS_MAX_FD; i++) {
407         struct v_fd* fd = proc->fdtable->fds[i];
408         if (fd) {
409             vfs_pclose(fd->file, pid);
410             vfs_free_fd(fd);
411         }
412     }
413
414     vfree(proc->fdtable);
415     vfree_dma(proc->fxstate);
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->state) || parent->created > proc->created;
467 }