feat: kill(2) implementation
[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 = PROC_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, _SIGKILL)) {
69         // 如果进程受到SIGKILL,则直接终止,该进程不给予调度。
70         terminate_proc(PEXITNUM(PEXITSIG, _SIGKILL));
71         return 0;
72     } else if (__SIGTEST(proc->sig_pending, _SIGCONT)) {
73         __SIGCLEAR(proc->sig_pending, _SIGSTOP);
74     } else if (__SIGTEST(proc->sig_pending, _SIGSTOP)) {
75         // 如果进程受到SIGSTOP,则该进程不给予调度。
76         return 0;
77     }
78
79     return 1;
80 }
81
82 void
83 schedule()
84 {
85     if (!sched_ctx.ptable_len) {
86         return;
87     }
88
89     // 上下文切换相当的敏感!我们不希望任何的中断打乱栈的顺序……
90     cpu_disable_interrupt();
91     struct proc_info* next;
92     int prev_ptr = sched_ctx.procs_index;
93     int ptr = prev_ptr;
94
95     if (!(__current->state & ~PROC_RUNNING)) {
96         __current->state = PROC_STOPPED;
97     }
98
99     // round-robin scheduler
100 redo:
101     do {
102         ptr = (ptr + 1) % sched_ctx.ptable_len;
103         next = &sched_ctx._procs[ptr];
104     } while (next->state != PROC_STOPPED && ptr != prev_ptr);
105
106     sched_ctx.procs_index = ptr;
107
108     if (!can_schedule(next)) {
109         // 如果该进程不给予调度,则尝试重新选择
110         goto redo;
111     }
112
113     run(next);
114 }
115
116 static void
117 proc_timer_callback(struct proc_info* proc)
118 {
119     proc->timer = NULL;
120     proc->state = PROC_STOPPED;
121 }
122
123 __DEFINE_LXSYSCALL1(unsigned int, sleep, unsigned int, seconds)
124 {
125     // FIXME: sleep的实现或许需要改一下。专门绑一个计时器好像没有必要……
126     if (!seconds) {
127         return 0;
128     }
129
130     if (__current->timer) {
131         return __current->timer->counter / timer_context()->running_frequency;
132     }
133
134     struct lx_timer* timer =
135       timer_run_second(seconds, proc_timer_callback, __current, 0);
136     __current->timer = timer;
137     __current->intr_ctx.registers.eax = seconds;
138     __current->state = PROC_BLOCKED;
139     schedule();
140 }
141
142 __DEFINE_LXSYSCALL1(void, exit, int, status)
143 {
144     terminate_proc(status);
145     schedule();
146 }
147
148 __DEFINE_LXSYSCALL(void, yield)
149 {
150     schedule();
151 }
152
153 pid_t
154 _wait(pid_t wpid, int* status, int options);
155
156 __DEFINE_LXSYSCALL1(pid_t, wait, int*, status)
157 {
158     return _wait(-1, status, 0);
159 }
160
161 __DEFINE_LXSYSCALL3(pid_t, waitpid, pid_t, pid, int*, status, int, options)
162 {
163     return _wait(pid, status, options);
164 }
165
166 pid_t
167 _wait(pid_t wpid, int* status, int options)
168 {
169     pid_t cur = __current->pid;
170     int status_flags = 0;
171     struct proc_info *proc, *n;
172     if (llist_empty(&__current->children)) {
173         return -1;
174     }
175
176     wpid = wpid ? wpid : -__current->pgid;
177     cpu_enable_interrupt();
178 repeat:
179     llist_for_each(proc, n, &__current->children, siblings)
180     {
181         if (!~wpid || proc->pid == wpid || proc->pgid == -wpid) {
182             if (proc->state == PROC_TERMNAT && !options) {
183                 status_flags |= PEXITTERM;
184                 goto done;
185             }
186             if (proc->state == PROC_STOPPED && (options & WUNTRACED)) {
187                 status_flags |= PEXITSTOP;
188                 goto done;
189             }
190         }
191     }
192     if ((options & WNOHANG)) {
193         return 0;
194     }
195     // 放弃当前的运行机会
196     sched_yield();
197     goto repeat;
198
199 done:
200     cpu_disable_interrupt();
201     status_flags |= PEXITSIG * (proc->sig_inprogress != 0);
202     *status = proc->exit_code | status_flags;
203     return destroy_process(proc->pid);
204 }
205
206 struct proc_info*
207 alloc_process()
208 {
209     pid_t i = 0;
210     for (;
211          i < sched_ctx.ptable_len && sched_ctx._procs[i].state != PROC_DESTROY;
212          i++)
213         ;
214
215     if (i == MAX_PROCESS) {
216         panick("Panic in Ponyville shimmer!");
217     }
218
219     if (i == sched_ctx.ptable_len) {
220         sched_ctx.ptable_len++;
221     }
222
223     struct proc_info* proc = &sched_ctx._procs[i];
224     memset(proc, 0, sizeof(*proc));
225
226     proc->state = PROC_CREATED;
227     proc->pid = i;
228     proc->created = clock_systime();
229     proc->pgid = proc->pid;
230
231     llist_init_head(&proc->mm.regions);
232     llist_init_head(&proc->children);
233     llist_init_head(&proc->grp_member);
234
235     return proc;
236 }
237
238 void
239 commit_process(struct proc_info* process)
240 {
241     assert(process == &sched_ctx._procs[process->pid]);
242
243     if (process->state != PROC_CREATED) {
244         __current->k_status = LXINVL;
245         return;
246     }
247
248     // every process is the child of first process (pid=1)
249     if (!process->parent) {
250         process->parent = &sched_ctx._procs[1];
251     }
252
253     llist_append(&process->parent->children, &process->siblings);
254
255     process->state = PROC_STOPPED;
256 }
257
258 // from <kernel/process.c>
259 extern void
260 __del_pagetable(pid_t pid, uintptr_t mount_point);
261
262 pid_t
263 destroy_process(pid_t pid)
264 {
265     int index = pid;
266     if (index <= 0 || index > sched_ctx.ptable_len) {
267         __current->k_status = LXINVLDPID;
268         return;
269     }
270     struct proc_info* proc = &sched_ctx._procs[index];
271     proc->state = PROC_DESTROY;
272     llist_delete(&proc->siblings);
273
274     struct mm_region *pos, *n;
275     llist_for_each(pos, n, &proc->mm.regions.head, head)
276     {
277         lxfree(pos);
278     }
279
280     vmm_mount_pd(PD_MOUNT_1, proc->page_table);
281
282     __del_pagetable(pid, PD_MOUNT_1);
283
284     vmm_unmount_pd(PD_MOUNT_1);
285
286     return pid;
287 }
288
289 void
290 terminate_proc(int exit_code)
291 {
292     __current->state = PROC_TERMNAT;
293     __current->exit_code = exit_code;
294
295     __SIGSET(__current->parent->sig_pending, _SIGCHLD);
296 }
297
298 struct proc_info*
299 get_process(pid_t pid)
300 {
301     int index = pid;
302     if (index < 0 || index > sched_ctx.ptable_len) {
303         return NULL;
304     }
305     return &sched_ctx._procs[index];
306 }
307
308 int
309 orphaned_proc(pid_t pid)
310 {
311     if (!pid)
312         return 0;
313     if (pid >= sched_ctx.ptable_len)
314         return 0;
315     struct proc_info* proc = &sched_ctx._procs[pid];
316     struct proc_info* parent = proc->parent;
317
318     // 如果其父进程的状态是terminated 或 destroy中的一种
319     // 或者其父进程是在该进程之后创建的,那么该进程为孤儿进程
320     return (parent->state & PROC_TERMMASK) || parent->created > proc->created;
321 }