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