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