aa75714b0dcc9aeb6378a61d79ac48ef4264a9bb
[lunaix-os.git] / lunaix-os / kernel / process / sched.c
1 #include <sys/abi.h>
2 #include <sys/interrupts.h>
3 #include <sys/mm/mempart.h>
4
5 #include <hal/intc.h>
6 #include <sys/cpu.h>
7
8 #include <lunaix/fs/taskfs.h>
9 #include <lunaix/mm/cake.h>
10 #include <lunaix/mm/mmap.h>
11 #include <lunaix/mm/pmm.h>
12 #include <lunaix/mm/valloc.h>
13 #include <lunaix/mm/vmm.h>
14 #include <lunaix/process.h>
15 #include <lunaix/sched.h>
16 #include <lunaix/signal.h>
17 #include <lunaix/spike.h>
18 #include <lunaix/status.h>
19 #include <lunaix/syscall.h>
20 #include <lunaix/syslog.h>
21
22 #include <klibc/string.h>
23
24 volatile struct proc_info* __current;
25
26 static struct proc_info dummy_proc;
27
28 struct proc_info dummy;
29
30 struct scheduler sched_ctx;
31
32 struct cake_pile* proc_pile;
33
34 LOG_MODULE("SCHED")
35
36 void
37 sched_init_dummy();
38
39 void
40 sched_init()
41 {
42     proc_pile = cake_new_pile("proc", sizeof(struct proc_info), 1, 0);
43     cake_set_constructor(proc_pile, cake_ctor_zeroing);
44
45     sched_ctx = (struct scheduler){ ._procs = vzalloc(PROC_TABLE_SIZE),
46                                     .ptable_len = 0,
47                                     .procs_index = 0 };
48
49     // TODO initialize dummy_proc
50     sched_init_dummy();
51 }
52
53 #define DUMMY_STACK_SIZE 2048
54
55 void
56 sched_init_dummy()
57 {
58     // This surely need to be simplified or encapsulated!
59     // It is a living nightmare!
60
61     extern void my_dummy();
62     static char dummy_stack[DUMMY_STACK_SIZE] __attribute__((aligned(16)));
63
64     ptr_t stktop = (ptr_t)dummy_stack + DUMMY_STACK_SIZE;
65
66     dummy_proc = (struct proc_info){};
67
68     proc_init_transfer(&dummy_proc, stktop, (ptr_t)my_dummy, TRANSFER_IE);
69
70     dummy_proc.page_table = cpu_ldvmspace();
71     dummy_proc.state = PS_READY;
72     dummy_proc.parent = &dummy_proc;
73     dummy_proc.pid = KERNEL_PID;
74
75     __current = &dummy_proc;
76 }
77
78 void
79 run(struct proc_info* proc)
80 {
81     proc->state = PS_RUNNING;
82
83     intc_notify_eos(0);
84     switch_context(proc);
85 }
86
87 int
88 can_schedule(struct proc_info* proc)
89 {
90     if (!proc) {
91         return 0;
92     }
93
94     struct sighail* sh = &proc->sigctx;
95
96     if ((proc->state & PS_PAUSED)) {
97         return !!(sh->sig_pending & ~1);
98     }
99
100     if (sigset_test(sh->sig_pending, _SIGCONT)) {
101         sigset_clear(sh->sig_pending, _SIGSTOP);
102     } else if (sigset_test(sh->sig_pending, _SIGSTOP)) {
103         // 如果进程受到SIGSTOP,则该进程不给予调度。
104         return 0;
105     }
106
107     return (proc->state == PS_READY);
108 }
109
110 void
111 check_sleepers()
112 {
113     struct proc_info* leader = sched_ctx._procs[0];
114     struct proc_info *pos, *n;
115     time_t now = clock_systime() / 1000;
116     llist_for_each(pos, n, &leader->sleep.sleepers, sleep.sleepers)
117     {
118         if (proc_terminated(pos)) {
119             goto del;
120         }
121
122         time_t wtime = pos->sleep.wakeup_time;
123         time_t atime = pos->sleep.alarm_time;
124
125         if (wtime && now >= wtime) {
126             pos->sleep.wakeup_time = 0;
127             pos->state = PS_READY;
128         }
129
130         if (atime && now >= atime) {
131             pos->sleep.alarm_time = 0;
132             proc_setsignal(pos, _SIGALRM);
133         }
134
135         if (!wtime && !atime) {
136         del:
137             llist_delete(&pos->sleep.sleepers);
138         }
139     }
140 }
141
142 void
143 schedule()
144 {
145     if (!sched_ctx.ptable_len) {
146         return;
147     }
148
149     // 上下文切换相当的敏感!我们不希望任何的中断打乱栈的顺序……
150     cpu_disable_interrupt();
151     struct proc_info* next;
152     int prev_ptr = sched_ctx.procs_index;
153     int ptr = prev_ptr;
154     int found = 0;
155
156     if (!(__current->state & ~PS_RUNNING)) {
157         __current->state = PS_READY;
158     }
159
160     check_sleepers();
161
162     // round-robin scheduler
163     do {
164         ptr = (ptr + 1) % sched_ctx.ptable_len;
165         next = sched_ctx._procs[ptr];
166
167         if (!(found = can_schedule(next))) {
168             if (ptr == prev_ptr) {
169                 next = &dummy_proc;
170                 goto done;
171             }
172         }
173     } while (!found);
174
175     sched_ctx.procs_index = ptr;
176
177 done:
178     run(next);
179 }
180
181 void
182 sched_yieldk()
183 {
184     cpu_enable_interrupt();
185     cpu_trap_sched();
186 }
187
188 __DEFINE_LXSYSCALL1(unsigned int, sleep, unsigned int, seconds)
189 {
190     if (!seconds) {
191         return 0;
192     }
193
194     time_t systime = clock_systime() / 1000;
195
196     if (__current->sleep.wakeup_time) {
197         return (__current->sleep.wakeup_time - systime);
198     }
199
200     struct proc_info* root_proc = sched_ctx._procs[0];
201     __current->sleep.wakeup_time = systime + seconds;
202
203     if (llist_empty(&__current->sleep.sleepers)) {
204         llist_append(&root_proc->sleep.sleepers, &__current->sleep.sleepers);
205     }
206
207     store_retval(seconds);
208
209     block_current();
210     schedule();
211
212     return 0;
213 }
214
215 __DEFINE_LXSYSCALL1(unsigned int, alarm, unsigned int, seconds)
216 {
217     time_t prev_ddl = __current->sleep.alarm_time;
218     time_t now = clock_systime() / 1000;
219
220     __current->sleep.alarm_time = seconds ? now + seconds : 0;
221
222     struct proc_info* root_proc = sched_ctx._procs[0];
223     if (llist_empty(&__current->sleep.sleepers)) {
224         llist_append(&root_proc->sleep.sleepers, &__current->sleep.sleepers);
225     }
226
227     return prev_ddl ? (prev_ddl - now) : 0;
228 }
229
230 __DEFINE_LXSYSCALL1(void, exit, int, status)
231 {
232     terminate_proc(status);
233     schedule();
234 }
235
236 __DEFINE_LXSYSCALL(void, yield)
237 {
238     schedule();
239 }
240
241 pid_t
242 _wait(pid_t wpid, int* status, int options);
243
244 __DEFINE_LXSYSCALL1(pid_t, wait, int*, status)
245 {
246     return _wait(-1, status, 0);
247 }
248
249 __DEFINE_LXSYSCALL3(pid_t, waitpid, pid_t, pid, int*, status, int, options)
250 {
251     return _wait(pid, status, options);
252 }
253
254 __DEFINE_LXSYSCALL(int, geterrno)
255 {
256     return __current->k_status;
257 }
258
259 pid_t
260 _wait(pid_t wpid, int* status, int options)
261 {
262     pid_t cur = __current->pid;
263     int status_flags = 0;
264     struct proc_info *proc, *n;
265     if (llist_empty(&__current->children)) {
266         return -1;
267     }
268
269     wpid = wpid ? wpid : -__current->pgid;
270 repeat:
271     llist_for_each(proc, n, &__current->children, siblings)
272     {
273         if (!~wpid || proc->pid == wpid || proc->pgid == -wpid) {
274             if (proc->state == PS_TERMNAT && !options) {
275                 status_flags |= PEXITTERM;
276                 goto done;
277             }
278             if (proc->state == PS_READY && (options & WUNTRACED)) {
279                 status_flags |= PEXITSTOP;
280                 goto done;
281             }
282         }
283     }
284     if ((options & WNOHANG)) {
285         return 0;
286     }
287     // 放弃当前的运行机会
288     sched_yieldk();
289     goto repeat;
290
291 done:
292     if (status) {
293         *status = proc->exit_code | status_flags;
294     }
295     return destroy_process(proc->pid);
296 }
297
298 struct proc_info*
299 alloc_process()
300 {
301     pid_t i = 0;
302     for (; i < sched_ctx.ptable_len && sched_ctx._procs[i]; i++)
303         ;
304
305     if (i == MAX_PROCESS) {
306         panick("Panic in Ponyville shimmer!");
307     }
308
309     if (i == sched_ctx.ptable_len) {
310         sched_ctx.ptable_len++;
311     }
312
313     struct proc_info* proc = cake_grab(proc_pile);
314
315     proc->state = PS_CREATED;
316     proc->pid = i;
317     proc->mm.pid = i;
318     proc->created = clock_systime();
319     proc->pgid = proc->pid;
320     proc->fdtable = vzalloc(sizeof(struct v_fdtable));
321
322     llist_init_head(&proc->mm.regions);
323     llist_init_head(&proc->tasks);
324     llist_init_head(&proc->children);
325     llist_init_head(&proc->grp_member);
326     llist_init_head(&proc->sleep.sleepers);
327     waitq_init(&proc->waitqueue);
328
329     sched_ctx._procs[i] = proc;
330
331     return proc;
332 }
333
334 void
335 commit_process(struct proc_info* process)
336 {
337     assert(process == sched_ctx._procs[process->pid]);
338
339     if (process->state != PS_CREATED) {
340         __current->k_status = EINVAL;
341         return;
342     }
343
344     // every process is the child of first process (pid=1)
345     if (!process->parent) {
346         process->parent = sched_ctx._procs[1];
347     }
348
349     llist_append(&process->parent->children, &process->siblings);
350     llist_append(&sched_ctx._procs[0]->tasks, &process->tasks);
351
352     process->state = PS_READY;
353 }
354
355 // from <kernel/process.c>
356 extern void
357 __del_pagetable(pid_t pid, ptr_t mount_point);
358
359 pid_t
360 destroy_process(pid_t pid)
361 {
362     int index = pid;
363     if (index <= 0 || index > sched_ctx.ptable_len) {
364         __current->k_status = EINVAL;
365         return -1;
366     }
367
368     struct proc_info* proc = sched_ctx._procs[index];
369     sched_ctx._procs[index] = 0;
370
371     llist_delete(&proc->siblings);
372     llist_delete(&proc->grp_member);
373     llist_delete(&proc->tasks);
374     llist_delete(&proc->sleep.sleepers);
375
376     taskfs_invalidate(pid);
377
378     if (proc->cwd) {
379         vfs_unref_dnode(proc->cwd);
380     }
381
382     for (size_t i = 0; i < VFS_MAX_FD; i++) {
383         struct v_fd* fd = proc->fdtable->fds[i];
384         if (fd) {
385             vfs_pclose(fd->file, pid);
386             vfs_free_fd(fd);
387         }
388     }
389
390     vfree(proc->fdtable);
391
392     vmm_mount_pd(VMS_MOUNT_1, proc->page_table);
393
394     struct mm_region *pos, *n;
395     llist_for_each(pos, n, &proc->mm.regions, head)
396     {
397         mem_sync_pages(VMS_MOUNT_1, pos, pos->start, pos->end - pos->start, 0);
398         region_release(pos);
399     }
400
401     __del_pagetable(pid, VMS_MOUNT_1);
402
403     vmm_unmount_pd(VMS_MOUNT_1);
404
405     cake_release(proc_pile, proc);
406
407     return pid;
408 }
409
410 void
411 terminate_proc(int exit_code)
412 {
413     __current->state = PS_TERMNAT;
414     __current->exit_code = exit_code;
415
416     proc_setsignal(__current->parent, _SIGCHLD);
417 }
418
419 struct proc_info*
420 get_process(pid_t pid)
421 {
422     int index = pid;
423     if (index < 0 || index > sched_ctx.ptable_len) {
424         return NULL;
425     }
426     return sched_ctx._procs[index];
427 }
428
429 int
430 orphaned_proc(pid_t pid)
431 {
432     if (!pid)
433         return 0;
434     if (pid >= sched_ctx.ptable_len)
435         return 0;
436     struct proc_info* proc = sched_ctx._procs[pid];
437     struct proc_info* parent = proc->parent;
438
439     // 如果其父进程的状态是terminated 或 destroy中的一种
440     // 或者其父进程是在该进程之后创建的,那么该进程为孤儿进程
441     return proc_terminated(parent) || parent->created > proc->created;
442 }