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