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