dedicated kthread interface and enablement of lrud auto-recycler
[lunaix-os.git] / lunaix-os / kernel / process / sched.c
1 #include <asm/abi.h>
2 #include <asm/mempart.h>
3
4 #include <asm/cpu.h>
5
6 #include <lunaix/fs/taskfs.h>
7 #include <lunaix/mm/cake.h>
8 #include <lunaix/mm/mmap.h>
9 #include <lunaix/mm/pmm.h>
10 #include <lunaix/mm/valloc.h>
11 #include <lunaix/mm/vmm.h>
12 #include <lunaix/mm/procvm.h>
13 #include <lunaix/process.h>
14 #include <lunaix/sched.h>
15 #include <lunaix/signal.h>
16 #include <lunaix/spike.h>
17 #include <lunaix/status.h>
18 #include <lunaix/syscall.h>
19 #include <lunaix/syslog.h>
20 #include <lunaix/hart_state.h>
21 #include <lunaix/kpreempt.h>
22
23 #include <klibc/string.h>
24
25 struct thread empty_thread_obj;
26
27 volatile struct proc_info* __current = NULL;
28 volatile struct thread* current_thread = &empty_thread_obj;
29
30 struct scheduler sched_ctx;
31
32 struct cake_pile *proc_pile ,*thread_pile;
33
34 #define root_process   (sched_ctx.procs[1])
35
36 LOG_MODULE("SCHED")
37
38 void
39 sched_init()
40 {
41     proc_pile = cake_new_pile("proc", sizeof(struct proc_info), 1, 0);
42     thread_pile = cake_new_pile("thread", sizeof(struct thread), 1, 0);
43     cake_set_constructor(proc_pile, cake_ctor_zeroing);
44     cake_set_constructor(thread_pile, cake_ctor_zeroing);
45
46     sched_ctx = (struct scheduler){
47         .procs = vzalloc(PROC_TABLE_SIZE), .ptable_len = 0, .procs_index = 0};
48     
49     llist_init_head(&sched_ctx.sleepers);
50 }
51
52 void
53 run(struct thread* thread)
54 {
55     thread->state = PS_RUNNING;
56     thread->process->state = PS_RUNNING;
57     thread->process->th_active = thread;
58
59     procvm_mount_self(vmspace(thread->process));
60     set_current_executing(thread);
61
62     switch_context();
63
64     fail("unexpected return from switching");
65 }
66
67 /*
68     Currently, we do not allow self-destorying thread, doing
69     so will eliminate current kernel stack which is disaster.
70     A compromise solution is to perform a regular scan and 
71     clean-up on these thread, in the preemptible kernel thread.
72 */
73
74 void
75 cleanup_detached_threads() 
76 {
77     // XXX may be a lock on sched_context will ben the most appropriate?
78     cpu_disable_interrupt();
79
80     int i = 0;
81     struct thread *pos, *n;
82     llist_for_each(pos, n, sched_ctx.threads, sched_sibs) {
83         if (likely(!proc_terminated(pos) || !thread_detached(pos))) {
84             continue;
85         }
86
87         struct proc_mm* mm = vmspace(pos->process);
88
89         procvm_mount(mm);
90         destory_thread(pos);
91         procvm_unmount(mm);
92         
93         i++;
94     }
95
96     if (i) {
97         INFO("cleaned %d terminated detached thread(s)", i);
98     }
99
100     cpu_enable_interrupt();
101 }
102
103 bool
104 can_schedule(struct thread* thread)
105 {
106     if (!thread) {
107         return 0;
108     }
109
110     if (proc_terminated(thread)) {
111         return false;
112     }
113
114     if (preempt_check_stalled(thread)) {
115         thread_flags_set(thread, TH_STALLED);
116         return true;
117     }
118
119     if (unlikely(kernel_process(thread->process))) {
120         // a kernel process is always runnable
121         return thread->state == PS_READY;
122     }
123
124     struct sigctx* sh = &thread->sigctx;
125
126     if ((thread->state & PS_PAUSED)) {
127         return !!(sh->sig_pending & ~1);
128     }
129
130     if ((thread->state & PS_BLOCKED)) {
131         return sigset_test(sh->sig_pending, _SIGINT);
132     }
133
134     if (sigset_test(sh->sig_pending, _SIGSTOP)) {
135         // If one thread is experiencing SIGSTOP, then we know
136         // all other threads are also SIGSTOP (as per POSIX-2008.1)
137         // In which case, the entire process is stopped.
138         thread->state = PS_STOPPED;
139         return false;
140     }
141     
142     if (sigset_test(sh->sig_pending, _SIGCONT)) {
143         thread->state = PS_READY;
144     }
145
146     return (thread->state == PS_READY) \
147             && proc_runnable(thread->process);
148 }
149
150 void
151 check_sleepers()
152 {
153     struct thread *pos, *n;
154     time_t now = clock_systime() / 1000;
155
156     llist_for_each(pos, n, &sched_ctx.sleepers, sleep.sleepers)
157     {
158         if (proc_terminated(pos)) {
159             goto del;
160         }
161
162         time_t wtime = pos->sleep.wakeup_time;
163         time_t atime = pos->sleep.alarm_time;
164
165         if (wtime && now >= wtime) {
166             pos->sleep.wakeup_time = 0;
167             pos->state = PS_READY;
168         }
169
170         if (atime && now >= atime) {
171             pos->sleep.alarm_time = 0;
172             thread_setsignal(pos, _SIGALRM);
173         }
174
175         if (!wtime && !atime) {
176         del:
177             llist_delete(&pos->sleep.sleepers);
178         }
179     }
180 }
181
182 void
183 schedule()
184 {
185     assert(sched_ctx.ptable_len && sched_ctx.ttable_len);
186
187     // 上下文切换相当的敏感!我们不希望任何的中断打乱栈的顺序……
188     no_preemption();
189
190     if (!(current_thread->state & ~PS_RUNNING)) {
191         current_thread->state = PS_READY;
192         __current->state = PS_READY;
193
194     }
195
196     procvm_unmount_self(vmspace(__current));
197     check_sleepers();
198
199     // round-robin scheduler
200     
201     struct thread* current = current_thread;
202     struct thread* to_check = current;
203     
204     do {
205         to_check = list_next(to_check, struct thread, sched_sibs);
206
207         if (can_schedule(to_check)) {
208             break;
209         }
210
211         if (to_check == current) {
212             // FIXME do something less leathal here
213             fail("Ran out of threads!")
214             goto done;  
215         }
216
217     } while (1);
218
219     sched_ctx.procs_index = to_check->process->pid;
220
221 done:
222     run(to_check);
223
224     fail("unexpected return from scheduler");
225 }
226
227 __DEFINE_LXSYSCALL1(unsigned int, alarm, unsigned int, seconds)
228 {
229     struct haybed* bed = &current_thread->sleep;
230     time_t prev_ddl = bed->alarm_time;
231     time_t now = clock_systime() / 1000;
232
233     bed->alarm_time = seconds ? now + seconds : 0;
234
235     if (llist_empty(&bed->sleepers)) {
236         llist_append(&sched_ctx.sleepers, &bed->sleepers);
237     }
238
239     return prev_ddl ? (prev_ddl - now) : 0;
240 }
241
242 __DEFINE_LXSYSCALL1(void, exit, int, status)
243 {
244     terminate_current(status);
245     schedule();
246 }
247
248 __DEFINE_LXSYSCALL(void, yield)
249 {
250     schedule();
251 }
252
253 pid_t
254 _wait(pid_t wpid, int* status, int options);
255
256 __DEFINE_LXSYSCALL1(pid_t, wait, int*, status)
257 {
258     return _wait(-1, status, 0);
259 }
260
261 __DEFINE_LXSYSCALL3(pid_t, waitpid, pid_t, pid, int*, status, int, options)
262 {
263     return _wait(pid, status, options);
264 }
265
266 __DEFINE_LXSYSCALL(int, geterrno)
267 {
268     return current_thread->syscall_ret;
269 }
270
271 pid_t
272 _wait(pid_t wpid, int* status, int options)
273 {
274     pid_t cur = __current->pid;
275     int status_flags = 0;
276     struct proc_info *proc, *n;
277     if (llist_empty(&__current->children)) {
278         return -1;
279     }
280
281     wpid = wpid ? wpid : -__current->pgid;
282
283 repeat:
284     llist_for_each(proc, n, &__current->children, siblings)
285     {
286         if (!~wpid || proc->pid == wpid || proc->pgid == -wpid) {
287             if (proc->state == PS_TERMNAT && !options) {
288                 status_flags |= PEXITTERM;
289                 goto done;
290             }
291             if (proc->state == PS_READY && (options & WUNTRACED)) {
292                 status_flags |= PEXITSTOP;
293                 goto done;
294             }
295         }
296     }
297     if ((options & WNOHANG)) {
298         return 0;
299     }
300     // 放弃当前的运行机会
301     yield_current();
302     goto repeat;
303
304 done:
305     if (status) {
306         *status = PEXITNUM(status_flags, proc->exit_code);
307     }
308     return destroy_process(proc->pid);
309 }
310
311 static inline pid_t
312 get_free_pid() {
313     pid_t i = 0;
314     
315     for (; i < sched_ctx.ptable_len && sched_ctx.procs[i]; i++)
316         ;
317     
318     if (unlikely(i == MAX_PROCESS)) {
319         fail("Panic in Ponyville shimmer!");
320     }
321
322     return i;
323 }
324
325 struct thread*
326 alloc_thread(struct proc_info* process) {
327     if (process->thread_count >= MAX_THREAD_PP) {
328         return NULL;
329     }
330     
331     struct thread* th = cake_grab(thread_pile);
332
333     th->process = process;
334     th->created = clock_systime();
335
336     // FIXME we need a better tid allocation method!
337     th->tid = th->created;
338     th->tid = (th->created ^ ((ptr_t)th)) % MAX_THREAD_PP;
339
340     th->state = PS_CREATED;
341     
342     llist_init_head(&th->sleep.sleepers);
343     llist_init_head(&th->sched_sibs);
344     llist_init_head(&th->proc_sibs);
345     waitq_init(&th->waitqueue);
346
347     return th;
348 }
349
350 struct proc_info*
351 alloc_process()
352 {
353     pid_t i = get_free_pid();
354
355     if (i == sched_ctx.ptable_len) {
356         sched_ctx.ptable_len++;
357     }
358
359     struct proc_info* proc = cake_grab(proc_pile);
360     if (!proc) {
361         return NULL;
362     }
363
364     proc->state = PS_CREATED;
365     proc->pid = i;
366     proc->created = clock_systime();
367     proc->pgid = proc->pid;
368
369     proc->root = vfs_sysroot;
370
371     proc->sigreg = vzalloc(sizeof(struct sigregistry));
372     proc->fdtable = fdtable_create();
373
374     proc->mm = procvm_create(proc);
375     
376     llist_init_head(&proc->tasks);
377     llist_init_head(&proc->children);
378     llist_init_head(&proc->grp_member);
379     llist_init_head(&proc->threads);
380
381     iopoll_init(&proc->pollctx);
382
383     sched_ctx.procs[i] = proc;
384
385     return proc;
386 }
387
388 void
389 commit_thread(struct thread* thread) {
390     struct proc_info* process = thread->process;
391
392     assert(process && !proc_terminated(process));
393
394     llist_append(&process->threads, &thread->proc_sibs);
395     
396     if (sched_ctx.threads) {
397         llist_append(sched_ctx.threads, &thread->sched_sibs);
398     } else {
399         sched_ctx.threads = &thread->sched_sibs;
400     }
401
402     sched_ctx.ttable_len++;
403     process->thread_count++;
404     thread->state = PS_READY;
405 }
406
407 void
408 commit_process(struct proc_info* process)
409 {
410     assert(process == sched_ctx.procs[process->pid]);
411     assert(process->state == PS_CREATED);
412
413     // every process is the child of first process (pid=1)
414     if (!process->parent) {
415         if (likely(!kernel_process(process))) {
416             process->parent = root_process;
417         } else {
418             process->parent = process;
419         }
420     } else {
421         assert(!proc_terminated(process->parent));
422     }
423
424     if (sched_ctx.proc_list) {
425         llist_append(sched_ctx.proc_list, &process->tasks);
426     } else {
427         sched_ctx.proc_list = &process->tasks;
428     }
429
430     llist_append(&process->parent->children, &process->siblings);
431
432     process->state = PS_READY;
433 }
434
435 void
436 destory_thread(struct thread* thread) 
437 {
438     cake_ensure_valid(thread);
439     
440     struct proc_info* proc = thread->process;
441
442     llist_delete(&thread->sched_sibs);
443     llist_delete(&thread->proc_sibs);
444     llist_delete(&thread->sleep.sleepers);
445     waitq_cancel_wait(&thread->waitqueue);
446
447     thread_release_mem(thread);
448
449     proc->thread_count--;
450     sched_ctx.ttable_len--;
451
452     cake_release(thread_pile, thread);
453 }
454
455 static void
456 orphan_children(struct proc_info* proc)
457 {
458     struct proc_info *root;
459     struct proc_info *pos, *n;
460
461     root = root_process;
462
463     llist_for_each(pos, n, &proc->children, siblings) {
464         pos->parent = root;
465         llist_append(&root->children, &pos->siblings);
466     }
467 }
468
469 void 
470 delete_process(struct proc_info* proc)
471 {
472     pid_t pid = proc->pid;
473     struct proc_mm* mm = vmspace(proc);
474
475     assert(pid);    // long live the pid0 !!
476
477     sched_ctx.procs[pid] = NULL;
478
479     llist_delete(&proc->siblings);
480     llist_delete(&proc->grp_member);
481     llist_delete(&proc->tasks);
482
483     iopoll_free(proc);
484
485     taskfs_invalidate(pid);
486
487     if (proc->cwd) {
488         vfs_unref_dnode(proc->cwd);
489     }
490
491     if (proc->cmd) {
492         vfree(proc->cmd);
493     }
494
495     for (size_t i = 0; i < VFS_MAX_FD; i++) {
496         struct v_fd* fd = proc->fdtable->fds[i];
497         if (fd) {
498             vfs_pclose(fd->file, pid);
499             vfs_free_fd(fd);
500         }
501     }
502
503     vfree(proc->fdtable);
504
505     signal_free_registry(proc->sigreg);
506
507     procvm_mount(mm);
508     
509     struct thread *pos, *n;
510     llist_for_each(pos, n, &proc->threads, proc_sibs) {
511         // terminate and destory all thread unconditionally
512         destory_thread(pos);
513     }
514
515     orphan_children(proc);
516
517     procvm_unmount_release(mm);
518
519     cake_release(proc_pile, proc);
520 }
521
522 pid_t
523 destroy_process(pid_t pid)
524 {    
525     int index = pid;
526     if (index <= 0 || index > sched_ctx.ptable_len) {
527         syscall_result(EINVAL);
528         return -1;
529     }
530
531     struct proc_info* proc = sched_ctx.procs[index];
532     delete_process(proc);
533
534     return pid;
535 }
536
537 static void 
538 terminate_proc_only(struct proc_info* proc, int exit_code) {
539     assert(proc->pid != 0);
540
541     proc->state = PS_TERMNAT;
542     proc->exit_code = exit_code;
543
544     proc_setsignal(proc->parent, _SIGCHLD);
545 }
546
547 void
548 terminate_thread(struct thread* thread, ptr_t val) {
549     thread->exit_val = val;
550     thread->state = PS_TERMNAT;
551
552     struct proc_info* proc = thread->process;
553     if (proc->thread_count == 1) {
554         terminate_proc_only(thread->process, 0);
555     }
556 }
557
558 void
559 terminate_current_thread(ptr_t val) {
560     terminate_thread(current_thread, val);
561 }
562
563 void 
564 terminate_proccess(struct proc_info* proc, int exit_code) {
565     assert(!kernel_process(proc));
566
567     if (proc->pid == 1) {
568         fail("Attempt to kill init");
569     }
570
571     terminate_proc_only(proc, exit_code);
572
573     struct thread *pos, *n;
574     llist_for_each(pos, n, &proc->threads, proc_sibs) {
575         pos->state = PS_TERMNAT;
576     }
577 }
578
579 void
580 terminate_current(int exit_code)
581 {
582     terminate_proccess(__current, exit_code);
583 }
584
585 struct proc_info*
586 get_process(pid_t pid)
587 {
588     int index = pid;
589     if (index < 0 || index > sched_ctx.ptable_len) {
590         return NULL;
591     }
592     return sched_ctx.procs[index];
593 }
594
595 int
596 orphaned_proc(pid_t pid)
597 {
598     if (!pid)
599         return 0;
600     if (pid >= sched_ctx.ptable_len)
601         return 0;
602     struct proc_info* proc = sched_ctx.procs[pid];
603     struct proc_info* parent = proc->parent;
604
605     // 如果其父进程的状态是terminated 或 destroy中的一种
606     // 或者其父进程是在该进程之后创建的,那么该进程为孤儿进程
607     return proc_terminated(parent) || parent->created > proc->created;
608 }
609