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