Merge branch 'master' of github.com:Minep/lunaix-os
[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)); // kernel/asm/x86/interrupt.S
63 }
64
65 int
66 can_schedule(struct proc_info* proc)
67 {
68     if (__SIGTEST(proc->sig_pending, _SIGCONT)) {
69         __SIGCLEAR(proc->sig_pending, _SIGSTOP);
70     } else if (__SIGTEST(proc->sig_pending, _SIGSTOP)) {
71         // 如果进程受到SIGSTOP,则该进程不给予调度。
72         return 0;
73     }
74
75     return 1;
76 }
77
78 void
79 check_sleepers()
80 {
81     struct proc_info* leader = &sched_ctx._procs[0];
82     struct proc_info *pos, *n;
83     time_t now = clock_systime();
84     llist_for_each(pos, n, &leader->sleep.sleepers, sleep.sleepers)
85     {
86         if (PROC_TERMINATED(pos->state)) {
87             goto del;
88         }
89
90         time_t wtime = pos->sleep.wakeup_time;
91         time_t atime = pos->sleep.alarm_time;
92
93         if (wtime && now >= wtime) {
94             pos->sleep.wakeup_time = 0;
95             pos->state = PS_STOPPED;
96         }
97
98         if (atime && now >= atime) {
99             pos->sleep.alarm_time = 0;
100             __SIGSET(pos->sig_pending, _SIGALRM);
101         }
102
103         if (!wtime && !atime) {
104         del:
105             llist_delete(&pos->sleep.sleepers);
106         }
107     }
108 }
109
110 void
111 schedule()
112 {
113     if (!sched_ctx.ptable_len) {
114         return;
115     }
116
117     // 上下文切换相当的敏感!我们不希望任何的中断打乱栈的顺序……
118     cpu_disable_interrupt();
119     struct proc_info* next;
120     int prev_ptr = sched_ctx.procs_index;
121     int ptr = prev_ptr;
122
123     if (!(__current->state & ~PS_RUNNING)) {
124         __current->state = PS_STOPPED;
125     }
126
127     check_sleepers();
128
129     // round-robin scheduler
130 redo:
131     do {
132         ptr = (ptr + 1) % sched_ctx.ptable_len;
133         next = &sched_ctx._procs[ptr];
134     } while (next->state != PS_STOPPED && ptr != prev_ptr);
135
136     sched_ctx.procs_index = ptr;
137
138     if (!can_schedule(next)) {
139         // 如果该进程不给予调度,则尝试重新选择
140         goto redo;
141     }
142
143     run(next);
144 }
145
146 __DEFINE_LXSYSCALL1(unsigned int, sleep, unsigned int, seconds)
147 {
148     if (!seconds) {
149         return 0;
150     }
151
152     if (__current->sleep.wakeup_time) {
153         return (__current->sleep.wakeup_time - clock_systime()) / 1000U;
154     }
155
156     __current->sleep.wakeup_time = clock_systime() + seconds * 1000;
157     llist_append(&sched_ctx._procs[0].sleep.sleepers,
158                  &__current->sleep.sleepers);
159
160     __current->intr_ctx.registers.eax = seconds;
161     __current->state = PS_BLOCKED;
162     schedule();
163 }
164
165 __DEFINE_LXSYSCALL1(unsigned int, alarm, unsigned int, seconds)
166 {
167     time_t prev_ddl = __current->sleep.alarm_time;
168     time_t now = clock_systime();
169
170     __current->sleep.alarm_time = seconds ? now + seconds * 1000 : 0;
171
172     if (llist_empty(&__current->sleep.sleepers)) {
173         llist_append(&sched_ctx._procs[0].sleep.sleepers,
174                      &__current->sleep.sleepers);
175     }
176
177     return prev_ddl ? (prev_ddl - now) / 1000 : 0;
178 }
179
180 __DEFINE_LXSYSCALL1(void, exit, int, status)
181 {
182     terminate_proc(status);
183     schedule();
184 }
185
186 __DEFINE_LXSYSCALL(void, yield)
187 {
188     schedule();
189 }
190
191 pid_t
192 _wait(pid_t wpid, int* status, int options);
193
194 __DEFINE_LXSYSCALL1(pid_t, wait, int*, status)
195 {
196     return _wait(-1, status, 0);
197 }
198
199 __DEFINE_LXSYSCALL3(pid_t, waitpid, pid_t, pid, int*, status, int, options)
200 {
201     return _wait(pid, status, options);
202 }
203
204 pid_t
205 _wait(pid_t wpid, int* status, int options)
206 {
207     pid_t cur = __current->pid;
208     int status_flags = 0;
209     struct proc_info *proc, *n;
210     if (llist_empty(&__current->children)) {
211         return -1;
212     }
213
214     wpid = wpid ? wpid : -__current->pgid;
215     cpu_enable_interrupt();
216 repeat:
217     llist_for_each(proc, n, &__current->children, siblings)
218     {
219         if (!~wpid || proc->pid == wpid || proc->pgid == -wpid) {
220             if (proc->state == PS_TERMNAT && !options) {
221                 status_flags |= PEXITTERM;
222                 goto done;
223             }
224             if (proc->state == PS_STOPPED && (options & WUNTRACED)) {
225                 status_flags |= PEXITSTOP;
226                 goto done;
227             }
228         }
229     }
230     if ((options & WNOHANG)) {
231         return 0;
232     }
233     // 放弃当前的运行机会
234     sched_yield();
235     goto repeat;
236
237 done:
238     cpu_disable_interrupt();
239     status_flags |= PEXITSIG * (proc->sig_inprogress != 0);
240     *status = proc->exit_code | status_flags;
241     return destroy_process(proc->pid);
242 }
243
244 struct proc_info*
245 alloc_process()
246 {
247     pid_t i = 0;
248     for (; i < sched_ctx.ptable_len && sched_ctx._procs[i].state != PS_DESTROY;
249          i++)
250         ;
251
252     if (i == MAX_PROCESS) {
253         panick("Panic in Ponyville shimmer!");
254     }
255
256     if (i == sched_ctx.ptable_len) {
257         sched_ctx.ptable_len++;
258     }
259
260     struct proc_info* proc = &sched_ctx._procs[i];
261     memset(proc, 0, sizeof(*proc));
262
263     proc->state = PS_CREATED;
264     proc->pid = i;
265     proc->created = clock_systime();
266     proc->pgid = proc->pid;
267
268     llist_init_head(&proc->mm.regions);
269     llist_init_head(&proc->children);
270     llist_init_head(&proc->grp_member);
271     llist_init_head(&proc->sleep.sleepers);
272
273     return proc;
274 }
275
276 void
277 commit_process(struct proc_info* process)
278 {
279     assert(process == &sched_ctx._procs[process->pid]);
280
281     if (process->state != PS_CREATED) {
282         __current->k_status = LXINVL;
283         return;
284     }
285
286     // every process is the child of first process (pid=1)
287     if (!process->parent) {
288         process->parent = &sched_ctx._procs[1];
289     }
290
291     llist_append(&process->parent->children, &process->siblings);
292
293     process->state = PS_STOPPED;
294 }
295
296 // from <kernel/process.c>
297 extern void
298 __del_pagetable(pid_t pid, uintptr_t mount_point);
299
300 pid_t
301 destroy_process(pid_t pid)
302 {
303     int index = pid;
304     if (index <= 0 || index > sched_ctx.ptable_len) {
305         __current->k_status = LXINVLDPID;
306         return;
307     }
308     struct proc_info* proc = &sched_ctx._procs[index];
309     proc->state = PS_DESTROY;
310     llist_delete(&proc->siblings);
311
312     struct mm_region *pos, *n;
313     llist_for_each(pos, n, &proc->mm.regions.head, head)
314     {
315         lxfree(pos);
316     }
317
318     vmm_mount_pd(PD_MOUNT_1, proc->page_table);
319
320     __del_pagetable(pid, PD_MOUNT_1);
321
322     vmm_unmount_pd(PD_MOUNT_1);
323
324     return pid;
325 }
326
327 void
328 terminate_proc(int exit_code)
329 {
330     __current->state = PS_TERMNAT;
331     __current->exit_code = exit_code;
332
333     __SIGSET(__current->parent->sig_pending, _SIGCHLD);
334 }
335
336 struct proc_info*
337 get_process(pid_t pid)
338 {
339     int index = pid;
340     if (index < 0 || index > sched_ctx.ptable_len) {
341         return NULL;
342     }
343     return &sched_ctx._procs[index];
344 }
345
346 int
347 orphaned_proc(pid_t pid)
348 {
349     if (!pid)
350         return 0;
351     if (pid >= sched_ctx.ptable_len)
352         return 0;
353     struct proc_info* proc = &sched_ctx._procs[pid];
354     struct proc_info* parent = proc->parent;
355
356     // 如果其父进程的状态是terminated 或 destroy中的一种
357     // 或者其父进程是在该进程之后创建的,那么该进程为孤儿进程
358     return PROC_TERMINATED(parent->state) || parent->created > proc->created;
359 }