Merge branch 'signal-dev'
[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     if (!(__current->state & ~PROC_RUNNING)) {
48         __current->state = PROC_STOPPED;
49     }
50     proc->state = PROC_RUNNING;
51
52     /*
53         将tss.esp0设置为上次调度前的esp值。
54         当处理信号时,上下文信息是不会恢复的,而是保存在用户栈中,然后直接跳转进位于用户空间的sig_wrapper进行
55           信号的处理。当用户自定义的信号处理函数返回时,sigreturn的系统调用才开始进行上下文的恢复(或者说是进行
56           另一次调度。
57         由于这中间没有进行地址空间的交换,所以第二次跳转使用的是同一个内核栈,而之前默认tss.esp0的值是永远指向最顶部
58         这样一来就有可能会覆盖更早的上下文信息(比如嵌套的信号捕获函数)
59     */
60     tss_update_esp(proc->intr_ctx.registers.esp);
61
62     apic_done_servicing();
63
64     asm volatile("pushl %0\n"
65                  "jmp switch_to\n" ::"r"(proc)); // kernel/asm/x86/interrupt.S
66 }
67
68 void
69 schedule()
70 {
71     if (!sched_ctx.ptable_len) {
72         return;
73     }
74
75     // 上下文切换相当的敏感!我们不希望任何的中断打乱栈的顺序……
76     cpu_disable_interrupt();
77     struct proc_info* next;
78     int prev_ptr = sched_ctx.procs_index;
79     int ptr = prev_ptr;
80     // round-robin scheduler
81     do {
82         ptr = (ptr + 1) % sched_ctx.ptable_len;
83         next = &sched_ctx._procs[ptr];
84     } while (next->state != PROC_STOPPED && ptr != prev_ptr);
85
86     sched_ctx.procs_index = ptr;
87
88     run(next);
89 }
90
91 static void
92 proc_timer_callback(struct proc_info* proc)
93 {
94     proc->timer = NULL;
95     proc->state = PROC_STOPPED;
96 }
97
98 __DEFINE_LXSYSCALL1(unsigned int, sleep, unsigned int, seconds)
99 {
100     // FIXME: sleep的实现或许需要改一下。专门绑一个计时器好像没有必要……
101     if (!seconds) {
102         return 0;
103     }
104
105     if (__current->timer) {
106         return __current->timer->counter / timer_context()->running_frequency;
107     }
108
109     struct lx_timer* timer =
110       timer_run_second(seconds, proc_timer_callback, __current, 0);
111     __current->timer = timer;
112     __current->intr_ctx.registers.eax = seconds;
113     __current->state = PROC_BLOCKED;
114     schedule();
115 }
116
117 __DEFINE_LXSYSCALL1(void, exit, int, status)
118 {
119     terminate_proc(status);
120 }
121
122 __DEFINE_LXSYSCALL(void, yield)
123 {
124     schedule();
125 }
126
127 pid_t
128 _wait(pid_t wpid, int* status, int options);
129
130 __DEFINE_LXSYSCALL1(pid_t, wait, int*, status)
131 {
132     return _wait(-1, status, 0);
133 }
134
135 __DEFINE_LXSYSCALL3(pid_t, waitpid, pid_t, pid, int*, status, int, options)
136 {
137     return _wait(pid, status, options);
138 }
139
140 pid_t
141 _wait(pid_t wpid, int* status, int options)
142 {
143     pid_t cur = __current->pid;
144     int status_flags = 0;
145     struct proc_info *proc, *n;
146     if (llist_empty(&__current->children)) {
147         return -1;
148     }
149
150     wpid = wpid ? wpid : -__current->pgid;
151     cpu_enable_interrupt();
152 repeat:
153     llist_for_each(proc, n, &__current->children, siblings)
154     {
155         if (!~wpid || proc->pid == wpid || proc->pgid == -wpid) {
156             if (proc->state == PROC_TERMNAT && !options) {
157                 status_flags |= PROCTERM;
158                 goto done;
159             }
160             if (proc->state == PROC_STOPPED && (options & WUNTRACED)) {
161                 status_flags |= PROCSTOP;
162                 goto done;
163             }
164         }
165     }
166     if ((options & WNOHANG)) {
167         return 0;
168     }
169     // 放弃当前的运行机会
170     sched_yield();
171     goto repeat;
172
173 done:
174     cpu_disable_interrupt();
175     *status = (proc->exit_code & 0xffff) | status_flags;
176     return destroy_process(proc->pid);
177 }
178
179 struct proc_info*
180 alloc_process()
181 {
182     pid_t i = 0;
183     for (;
184          i < sched_ctx.ptable_len && sched_ctx._procs[i].state != PROC_DESTROY;
185          i++)
186         ;
187
188     if (i == MAX_PROCESS) {
189         panick("Panic in Ponyville shimmer!");
190     }
191
192     if (i == sched_ctx.ptable_len) {
193         sched_ctx.ptable_len++;
194     }
195
196     struct proc_info* proc = &sched_ctx._procs[i];
197     memset(proc, 0, sizeof(*proc));
198
199     proc->state = PROC_CREATED;
200     proc->pid = i;
201     proc->created = clock_systime();
202     proc->pgid = proc->pid;
203
204     llist_init_head(&proc->mm.regions);
205     llist_init_head(&proc->children);
206     llist_init_head(&proc->grp_member);
207
208     return proc;
209 }
210
211 void
212 commit_process(struct proc_info* process)
213 {
214     assert(process == &sched_ctx._procs[process->pid]);
215
216     if (process->state != PROC_CREATED) {
217         __current->k_status = LXINVL;
218         return;
219     }
220
221     // every process is the child of first process (pid=1)
222     if (process->parent) {
223         llist_append(&process->parent->children, &process->siblings);
224     } else {
225         process->parent = &sched_ctx._procs[0];
226     }
227
228     process->state = PROC_STOPPED;
229 }
230
231 // from <kernel/process.c>
232 extern void
233 __del_pagetable(pid_t pid, uintptr_t mount_point);
234
235 pid_t
236 destroy_process(pid_t pid)
237 {
238     int index = pid;
239     if (index <= 0 || index > sched_ctx.ptable_len) {
240         __current->k_status = LXINVLDPID;
241         return;
242     }
243     struct proc_info* proc = &sched_ctx._procs[index];
244     proc->state = PROC_DESTROY;
245     llist_delete(&proc->siblings);
246
247     struct mm_region *pos, *n;
248     llist_for_each(pos, n, &proc->mm.regions.head, head)
249     {
250         lxfree(pos);
251     }
252
253     vmm_mount_pd(PD_MOUNT_1, proc->page_table);
254
255     __del_pagetable(pid, PD_MOUNT_1);
256
257     vmm_unmount_pd(PD_MOUNT_1);
258
259     return pid;
260 }
261
262 void
263 terminate_proc(int exit_code)
264 {
265     __current->state = PROC_TERMNAT;
266     __current->exit_code = exit_code;
267
268     __SET_SIGNAL(__current->parent->sig_pending, _SIGCHLD);
269
270     schedule();
271 }
272
273 struct proc_info*
274 get_process(pid_t pid)
275 {
276     int index = pid;
277     if (index < 0 || index > sched_ctx.ptable_len) {
278         return NULL;
279     }
280     return &sched_ctx._procs[index];
281 }
282
283 int
284 orphaned_proc(pid_t pid)
285 {
286     if (!pid)
287         return 0;
288     if (pid >= sched_ctx.ptable_len)
289         return 0;
290     struct proc_info* proc = &sched_ctx._procs[pid];
291     struct proc_info* parent = proc->parent;
292
293     // 如果其父进程的状态是terminated 或 destroy中的一种
294     // 或者其父进程是在该进程之后创建的,那么该进程为孤儿进程
295     return (parent->state & PROC_TERMMASK) || parent->created > proc->created;
296 }