1 #include "process.h"
2
3 #include <DragonOS/signal.h>
4 #include <common/compiler.h>
5 #include <common/completion.h>
6 #include <common/elf.h>
7 #include <common/kprint.h>
8 #include <common/kthread.h>
9 #include <common/printk.h>
10 #include <common/spinlock.h>
11 #include <common/stdio.h>
12 #include <common/string.h>
13 #include <common/sys/wait.h>
14 #include <common/time.h>
15 #include <common/unistd.h>
16 #include <debug/bug.h>
17 #include <debug/traceback/traceback.h>
18 #include <driver/disk/ahci/ahci.h>
19 #include <driver/usb/usb.h>
20 #include <driver/video/video.h>
21 #include <exception/gate.h>
22 #include <filesystem/devfs/devfs.h>
23 #include <filesystem/fat32/fat32.h>
24 #include <filesystem/rootfs/rootfs.h>
25 #include <filesystem/procfs/procfs.h>
26 #include <ktest/ktest.h>
27 #include <mm/slab.h>
28 #include <sched/sched.h>
29 #include <syscall/syscall.h>
30 #include <syscall/syscall_num.h>
31
32 #include <mm/mmio.h>
33
34 #include <common/lz4.h>
35 extern int __rust_demo_func();
36 // #pragma GCC push_options
37 // #pragma GCC optimize("O0")
38
39 spinlock_t process_global_pid_write_lock; // 增加pid的写锁
40 long process_global_pid = 1; // 系统中最大的pid
41
42 extern void system_call(void);
43 extern void kernel_thread_func(void);
44
45 ul _stack_start; // initial proc的栈基地址(虚拟地址)
46 extern struct mm_struct initial_mm;
47 extern struct signal_struct INITIAL_SIGNALS;
48 extern struct sighand_struct INITIAL_SIGHAND;
49
50 extern void process_exit_sighand(struct process_control_block *pcb);
51 extern void process_exit_signal(struct process_control_block *pcb);
52 extern void initial_proc_init_signal(struct process_control_block *pcb);
53
54 // 设置初始进程的PCB
55 #define INITIAL_PROC(proc) \
56 { \
57 .state = PROC_UNINTERRUPTIBLE, .flags = PF_KTHREAD, .preempt_count = 0, .signal = 0, .cpu_id = 0, \
58 .mm = &initial_mm, .thread = &initial_thread, .addr_limit = 0xffffffffffffffff, .pid = 0, .priority = 2, \
59 .virtual_runtime = 0, .fds = {0}, .next_pcb = &proc, .prev_pcb = &proc, .parent_pcb = &proc, .exit_code = 0, \
60 .wait_child_proc_exit = 0, .worker_private = NULL, .policy = SCHED_NORMAL, .sig_blocked = 0, \
61 .signal = &INITIAL_SIGNALS, .sighand = &INITIAL_SIGHAND, \
62 }
63
64 struct thread_struct initial_thread = {
65 .rbp = (ul)(initial_proc_union.stack + STACK_SIZE / sizeof(ul)),
66 .rsp = (ul)(initial_proc_union.stack + STACK_SIZE / sizeof(ul)),
67 .fs = KERNEL_DS,
68 .gs = KERNEL_DS,
69 .cr2 = 0,
70 .trap_num = 0,
71 .err_code = 0,
72 };
73
74 // 初始化 初始进程的union ,并将其链接到.data.init_proc段内
75 union proc_union initial_proc_union
76 __attribute__((__section__(".data.init_proc_union"))) = {INITIAL_PROC(initial_proc_union.pcb)};
77
78 struct process_control_block *initial_proc[MAX_CPU_NUM] = {&initial_proc_union.pcb, 0};
79
80 // 为每个核心初始化初始进程的tss
81 struct tss_struct initial_tss[MAX_CPU_NUM] = {[0 ... MAX_CPU_NUM - 1] = INITIAL_TSS};
82
83 /**
84 * @brief 回收进程的所有文件描述符
85 *
86 * @param pcb 要被回收的进程的pcb
87 * @return uint64_t
88 */
89 uint64_t process_exit_files(struct process_control_block *pcb);
90
91 /**
92 * @brief 释放进程的页表
93 *
94 * @param pcb 要被释放页表的进程
95 * @return uint64_t
96 */
97 uint64_t process_exit_mm(struct process_control_block *pcb);
98
99 /**
100 * @brief 切换进程
101 *
102 * @param prev 上一个进程的pcb
103 * @param next 将要切换到的进程的pcb
104 * 由于程序在进入内核的时候已经保存了寄存器,因此这里不需要保存寄存器。
105 * 这里切换fs和gs寄存器
106 */
107 #pragma GCC push_options
108 #pragma GCC optimize("O0")
__switch_to(struct process_control_block * prev,struct process_control_block * next)109 void __switch_to(struct process_control_block *prev, struct process_control_block *next)
110 {
111 initial_tss[proc_current_cpu_id].rsp0 = next->thread->rbp;
112 // kdebug("next_rsp = %#018lx ", next->thread->rsp);
113 // set_tss64((uint *)phys_2_virt(TSS64_Table), initial_tss[0].rsp0, initial_tss[0].rsp1, initial_tss[0].rsp2,
114 // initial_tss[0].ist1,
115 // initial_tss[0].ist2, initial_tss[0].ist3, initial_tss[0].ist4, initial_tss[0].ist5,
116 // initial_tss[0].ist6, initial_tss[0].ist7);
117
118 __asm__ __volatile__("movq %%fs, %0 \n\t" : "=a"(prev->thread->fs));
119 __asm__ __volatile__("movq %%gs, %0 \n\t" : "=a"(prev->thread->gs));
120
121 __asm__ __volatile__("movq %0, %%fs \n\t" ::"a"(next->thread->fs));
122 __asm__ __volatile__("movq %0, %%gs \n\t" ::"a"(next->thread->gs));
123 }
124 #pragma GCC pop_options
125
126 /**
127 * @brief 打开要执行的程序文件
128 *
129 * @param path
130 * @return struct vfs_file_t*
131 */
process_open_exec_file(char * path)132 struct vfs_file_t *process_open_exec_file(char *path)
133 {
134 struct vfs_dir_entry_t *dentry = NULL;
135 struct vfs_file_t *filp = NULL;
136 // kdebug("path=%s", path);
137 dentry = vfs_path_walk(path, 0);
138
139 if (dentry == NULL)
140 return (void *)-ENOENT;
141
142 if (dentry->dir_inode->attribute == VFS_IF_DIR)
143 return (void *)-ENOTDIR;
144
145 filp = (struct vfs_file_t *)kmalloc(sizeof(struct vfs_file_t), 0);
146 if (filp == NULL)
147 return (void *)-ENOMEM;
148
149 filp->position = 0;
150 filp->mode = 0;
151 filp->dEntry = dentry;
152 filp->mode = ATTR_READ_ONLY;
153 filp->file_ops = dentry->dir_inode->file_ops;
154
155 return filp;
156 }
157
158 /**
159 * @brief 加载elf格式的程序文件到内存中,并设置regs
160 *
161 * @param regs 寄存器
162 * @param path 文件路径
163 * @return int
164 */
process_load_elf_file(struct pt_regs * regs,char * path)165 static int process_load_elf_file(struct pt_regs *regs, char *path)
166 {
167 int retval = 0;
168 struct vfs_file_t *filp = process_open_exec_file(path);
169
170 if ((long)filp <= 0 && (long)filp >= -255)
171 {
172 kdebug("(long)filp=%ld", (long)filp);
173 return (unsigned long)filp;
174 }
175
176 void *buf = kmalloc(PAGE_4K_SIZE, 0);
177 memset(buf, 0, PAGE_4K_SIZE);
178 uint64_t pos = 0;
179 pos = filp->file_ops->lseek(filp, 0, SEEK_SET);
180 retval = filp->file_ops->read(filp, (char *)buf, sizeof(Elf64_Ehdr), &pos);
181 retval = 0;
182 if (!elf_check(buf))
183 {
184 kerror("Not an ELF file: %s", path);
185 retval = -ENOTSUP;
186 goto load_elf_failed;
187 }
188
189 #if ARCH(X86_64)
190 // 暂时只支持64位的文件
191 if (((Elf32_Ehdr *)buf)->e_ident[EI_CLASS] != ELFCLASS64)
192 {
193 kdebug("((Elf32_Ehdr *)buf)->e_ident[EI_CLASS]=%d", ((Elf32_Ehdr *)buf)->e_ident[EI_CLASS]);
194 retval = -EUNSUPPORTED;
195 goto load_elf_failed;
196 }
197 Elf64_Ehdr ehdr = *(Elf64_Ehdr *)buf;
198 // 暂时只支持AMD64架构
199 if (ehdr.e_machine != EM_AMD64)
200 {
201 kerror("e_machine=%d", ehdr.e_machine);
202 retval = -EUNSUPPORTED;
203 goto load_elf_failed;
204 }
205 #else
206 #error Unsupported architecture!
207 #endif
208 if (ehdr.e_type != ET_EXEC)
209 {
210 kerror("Not executable file! filename=%s\tehdr->e_type=%d", path, ehdr.e_type);
211 retval = -EUNSUPPORTED;
212 goto load_elf_failed;
213 }
214 // kdebug("filename=%s:\te_entry=%#018lx", path, ehdr.e_entry);
215 regs->rip = ehdr.e_entry;
216 current_pcb->mm->code_addr_start = ehdr.e_entry;
217
218 // kdebug("ehdr.e_phoff=%#018lx\t ehdr.e_phentsize=%d, ehdr.e_phnum=%d", ehdr.e_phoff, ehdr.e_phentsize,
219 // ehdr.e_phnum); 将指针移动到program header处
220 pos = ehdr.e_phoff;
221 // 读取所有的phdr
222 pos = filp->file_ops->lseek(filp, pos, SEEK_SET);
223 filp->file_ops->read(filp, (char *)buf, (uint64_t)ehdr.e_phentsize * (uint64_t)ehdr.e_phnum, &pos);
224 if ((unsigned long)filp <= 0)
225 {
226 kdebug("(unsigned long)filp=%d", (long)filp);
227 retval = -ENOEXEC;
228 goto load_elf_failed;
229 }
230 Elf64_Phdr *phdr = buf;
231
232 // 将程序加载到内存中
233 for (int i = 0; i < ehdr.e_phnum; ++i, ++phdr)
234 {
235 // kdebug("phdr[%d] phdr->p_offset=%#018lx phdr->p_vaddr=%#018lx phdr->p_memsz=%ld phdr->p_filesz=%ld
236 // phdr->p_type=%d", i, phdr->p_offset, phdr->p_vaddr, phdr->p_memsz, phdr->p_filesz, phdr->p_type);
237
238 // 不是可加载的段
239 if (phdr->p_type != PT_LOAD)
240 continue;
241
242 int64_t remain_mem_size = phdr->p_memsz;
243 int64_t remain_file_size = phdr->p_filesz;
244 pos = phdr->p_offset;
245
246 uint64_t virt_base = 0;
247 uint64_t beginning_offset = 0; // 由于页表映射导致的virtbase与实际的p_vaddr之间的偏移量
248
249 if (remain_mem_size >= PAGE_2M_SIZE) // 接下来存在映射2M页的情况,因此将vaddr按2M向下对齐
250 virt_base = phdr->p_vaddr & PAGE_2M_MASK;
251 else // 接下来只有4K页的映射
252 virt_base = phdr->p_vaddr & PAGE_4K_MASK;
253
254 beginning_offset = phdr->p_vaddr - virt_base;
255 remain_mem_size += beginning_offset;
256
257 while (remain_mem_size > 0)
258 {
259 // kdebug("loading...");
260 int64_t map_size = 0;
261 if (remain_mem_size >= PAGE_2M_SIZE)
262 {
263 uint64_t pa = alloc_pages(ZONE_NORMAL, 1, PAGE_PGT_MAPPED)->addr_phys;
264 struct vm_area_struct *vma = NULL;
265 int ret =
266 mm_create_vma(current_pcb->mm, virt_base, PAGE_2M_SIZE, VM_USER | VM_ACCESS_FLAGS, NULL, &vma);
267
268 // 防止内存泄露
269 if (ret == -EEXIST)
270 free_pages(Phy_to_2M_Page(pa), 1);
271 else
272 mm_map(current_pcb->mm, virt_base, PAGE_2M_SIZE, pa);
273 // mm_map_vma(vma, pa, 0, PAGE_2M_SIZE);
274 io_mfence();
275 memset((void *)virt_base, 0, PAGE_2M_SIZE);
276 map_size = PAGE_2M_SIZE;
277 }
278 else
279 {
280 // todo: 使用4K、8K、32K大小内存块混合进行分配,提高空间利用率(减少了bmp的大小)
281 map_size = ALIGN(remain_mem_size, PAGE_4K_SIZE);
282 // 循环分配4K大小内存块
283 for (uint64_t off = 0; off < map_size; off += PAGE_4K_SIZE)
284 {
285 uint64_t paddr = virt_2_phys((uint64_t)kmalloc(PAGE_4K_SIZE, 0));
286
287 struct vm_area_struct *vma = NULL;
288 int val = mm_create_vma(current_pcb->mm, virt_base + off, PAGE_4K_SIZE, VM_USER | VM_ACCESS_FLAGS,
289 NULL, &vma);
290 // kdebug("virt_base=%#018lx", virt_base + off);
291 if (val == -EEXIST)
292 kfree(phys_2_virt(paddr));
293 else
294 mm_map(current_pcb->mm, virt_base + off, PAGE_4K_SIZE, paddr);
295 // mm_map_vma(vma, paddr, 0, PAGE_4K_SIZE);
296 io_mfence();
297 memset((void *)(virt_base + off), 0, PAGE_4K_SIZE);
298 }
299 }
300
301 pos = filp->file_ops->lseek(filp, pos, SEEK_SET);
302 int64_t val = 0;
303 if (remain_file_size > 0)
304 {
305 int64_t to_trans = (remain_file_size > PAGE_2M_SIZE) ? PAGE_2M_SIZE : remain_file_size;
306 val = filp->file_ops->read(filp, (char *)(virt_base + beginning_offset), to_trans, &pos);
307 }
308
309 if (val < 0)
310 goto load_elf_failed;
311
312 remain_mem_size -= map_size;
313 remain_file_size -= val;
314 virt_base += map_size;
315 }
316 }
317
318 // 分配2MB的栈内存空间
319 regs->rsp = current_pcb->mm->stack_start;
320 regs->rbp = current_pcb->mm->stack_start;
321
322 {
323 struct vm_area_struct *vma = NULL;
324 uint64_t pa = alloc_pages(ZONE_NORMAL, 1, PAGE_PGT_MAPPED)->addr_phys;
325 int val = mm_create_vma(current_pcb->mm, current_pcb->mm->stack_start - PAGE_2M_SIZE, PAGE_2M_SIZE,
326 VM_USER | VM_ACCESS_FLAGS, NULL, &vma);
327 if (val == -EEXIST)
328 free_pages(Phy_to_2M_Page(pa), 1);
329 else
330 mm_map_vma(vma, pa, 0, PAGE_2M_SIZE);
331 }
332
333 // 清空栈空间
334 memset((void *)(current_pcb->mm->stack_start - PAGE_2M_SIZE), 0, PAGE_2M_SIZE);
335
336 load_elf_failed:;
337 if (buf != NULL)
338 kfree(buf);
339 return retval;
340 }
341 /**
342 * @brief 使当前进程去执行新的代码
343 *
344 * @param regs 当前进程的寄存器
345 * @param path 可执行程序的路径
346 * @param argv 参数列表
347 * @param envp 环境变量
348 * @return ul 错误码
349 */
350 #pragma GCC push_options
351 #pragma GCC optimize("O0")
do_execve(struct pt_regs * regs,char * path,char * argv[],char * envp[])352 ul do_execve(struct pt_regs *regs, char *path, char *argv[], char *envp[])
353 {
354
355 // kdebug("do_execve is running...");
356
357 // 当前进程正在与父进程共享地址空间,需要创建
358 // 独立的地址空间才能使新程序正常运行
359 if (current_pcb->flags & PF_VFORK)
360 {
361 // kdebug("proc:%d creating new mem space", current_pcb->pid);
362 // 分配新的内存空间分布结构体
363 struct mm_struct *new_mms = (struct mm_struct *)kmalloc(sizeof(struct mm_struct), 0);
364 memset(new_mms, 0, sizeof(struct mm_struct));
365 current_pcb->mm = new_mms;
366
367 // 分配顶层页表, 并设置顶层页表的物理地址
368 new_mms->pgd = (pml4t_t *)virt_2_phys(kmalloc(PAGE_4K_SIZE, 0));
369
370 // 由于高2K部分为内核空间,在接下来需要覆盖其数据,因此不用清零
371 memset(phys_2_virt(new_mms->pgd), 0, PAGE_4K_SIZE / 2);
372
373 // 拷贝内核空间的页表指针
374 memcpy(phys_2_virt(new_mms->pgd) + 256, phys_2_virt(initial_proc[proc_current_cpu_id]) + 256, PAGE_4K_SIZE / 2);
375 }
376
377 // 设置用户栈和用户堆的基地址
378 unsigned long stack_start_addr = 0x6ffff0a00000UL;
379 const uint64_t brk_start_addr = 0x700000000000UL;
380
381 process_switch_mm(current_pcb);
382
383 // 为用户态程序设置地址边界
384 if (!(current_pcb->flags & PF_KTHREAD))
385 current_pcb->addr_limit = USER_MAX_LINEAR_ADDR;
386
387 current_pcb->mm->code_addr_end = 0;
388 current_pcb->mm->data_addr_start = 0;
389 current_pcb->mm->data_addr_end = 0;
390 current_pcb->mm->rodata_addr_start = 0;
391 current_pcb->mm->rodata_addr_end = 0;
392 current_pcb->mm->bss_start = 0;
393 current_pcb->mm->bss_end = 0;
394 current_pcb->mm->brk_start = brk_start_addr;
395 current_pcb->mm->brk_end = brk_start_addr;
396 current_pcb->mm->stack_start = stack_start_addr;
397
398 // 关闭之前的文件描述符
399 process_exit_files(current_pcb);
400
401 // 清除进程的vfork标志位
402 current_pcb->flags &= ~PF_VFORK;
403
404 // 加载elf格式的可执行文件
405 int tmp = process_load_elf_file(regs, path);
406 if (tmp < 0)
407 goto exec_failed;
408
409 // 拷贝参数列表
410 if (argv != NULL)
411 {
412 int argc = 0;
413
414 // 目标程序的argv基地址指针,最大8个参数
415 char **dst_argv = (char **)(stack_start_addr - (sizeof(char **) << 3));
416 uint64_t str_addr = (uint64_t)dst_argv;
417
418 for (argc = 0; argc < 8 && argv[argc] != NULL; ++argc)
419 {
420
421 if (*argv[argc] == NULL)
422 break;
423
424 // 测量参数的长度(最大1023)
425 int argv_len = strnlen_user(argv[argc], 1023) + 1;
426 strncpy((char *)(str_addr - argv_len), argv[argc], argv_len - 1);
427 str_addr -= argv_len;
428 dst_argv[argc] = (char *)str_addr;
429 // 字符串加上结尾字符
430 ((char *)str_addr)[argv_len] = '\0';
431 }
432
433 // 重新设定栈基址,并预留空间防止越界
434 stack_start_addr = str_addr - 8;
435 current_pcb->mm->stack_start = stack_start_addr;
436 regs->rsp = regs->rbp = stack_start_addr;
437
438 // 传递参数
439 regs->rdi = argc;
440 regs->rsi = (uint64_t)dst_argv;
441 }
442 // kdebug("execve ok");
443 // 设置进程的段选择子为用户态可访问
444 regs->cs = USER_CS | 3;
445 regs->ds = USER_DS | 3;
446 regs->ss = USER_DS | 0x3;
447 regs->rflags = 0x200246;
448 regs->rax = 1;
449 regs->es = 0;
450
451 return 0;
452
453 exec_failed:;
454 process_do_exit(tmp);
455 }
456 #pragma GCC pop_options
457
458 /**
459 * @brief 内核init进程
460 *
461 * @param arg
462 * @return ul 参数
463 */
464 #pragma GCC push_options
465 #pragma GCC optimize("O0")
initial_kernel_thread(ul arg)466 ul initial_kernel_thread(ul arg)
467 {
468 kinfo("initial proc running...\targ:%#018lx, vruntime=%d", arg, current_pcb->virtual_runtime);
469
470 scm_enable_double_buffer();
471
472 ahci_init();
473 fat32_init();
474 rootfs_umount();
475
476 // 使用单独的内核线程来初始化usb驱动程序
477 // 注释:由于目前usb驱动程序不完善,因此先将其注释掉
478 // int usb_pid = kernel_thread(usb_init, 0, 0);
479
480 kinfo("LZ4 lib Version=%s", LZ4_versionString());
481 __rust_demo_func();
482 // 对completion完成量进行测试
483 // __test_completion();
484
485 // // 对一些组件进行单元测试
486 // uint64_t tpid[] = {
487 // ktest_start(ktest_test_bitree, 0), ktest_start(ktest_test_kfifo, 0), ktest_start(ktest_test_mutex, 0),
488 // ktest_start(ktest_test_idr, 0),
489 // // usb_pid,
490 // };
491 // kinfo("Waiting test thread exit...");
492 // // 等待测试进程退出
493 // for (int i = 0; i < sizeof(tpid) / sizeof(uint64_t); ++i)
494 // waitpid(tpid[i], NULL, NULL);
495 // kinfo("All test done.");
496
497 // 准备切换到用户态
498 struct pt_regs *regs;
499
500 // 若在后面这段代码中触发中断,return时会导致段选择子错误,从而触发#GP,因此这里需要cli
501 cli();
502 current_pcb->thread->rip = (ul)ret_from_system_call;
503 current_pcb->thread->rsp = (ul)current_pcb + STACK_SIZE - sizeof(struct pt_regs);
504 current_pcb->thread->fs = USER_DS | 0x3;
505 barrier();
506 current_pcb->thread->gs = USER_DS | 0x3;
507
508 // 主动放弃内核线程身份
509 current_pcb->flags &= (~PF_KTHREAD);
510 kdebug("in initial_kernel_thread: flags=%ld", current_pcb->flags);
511
512 regs = (struct pt_regs *)current_pcb->thread->rsp;
513 // kdebug("current_pcb->thread->rsp=%#018lx", current_pcb->thread->rsp);
514 current_pcb->flags = 0;
515 // 将返回用户层的代码压入堆栈,向rdx传入regs的地址,然后jmp到do_execve这个系统调用api的处理函数
516 // 这里的设计思路和switch_proc类似 加载用户态程序:shell.elf
517 __asm__ __volatile__("movq %1, %%rsp \n\t"
518 "pushq %2 \n\t"
519 "jmp do_execve \n\t" ::"D"(current_pcb->thread->rsp),
520 "m"(current_pcb->thread->rsp), "m"(current_pcb->thread->rip), "S"("/bin/shell.elf"), "c"(NULL),
521 "d"(NULL)
522 : "memory");
523
524 return 1;
525 }
526 #pragma GCC pop_options
527 /**
528 * @brief 当子进程退出后向父进程发送通知
529 *
530 */
process_exit_notify()531 void process_exit_notify()
532 {
533
534 wait_queue_wakeup(¤t_pcb->parent_pcb->wait_child_proc_exit, PROC_INTERRUPTIBLE);
535 }
536 /**
537 * @brief 进程退出时执行的函数
538 *
539 * @param code 返回码
540 * @return ul
541 */
process_do_exit(ul code)542 ul process_do_exit(ul code)
543 {
544 // kinfo("process exiting..., code is %ld.", (long)code);
545 cli();
546 struct process_control_block *pcb = current_pcb;
547
548 // 进程退出时释放资源
549 process_exit_files(pcb);
550 process_exit_thread(pcb);
551 // todo: 可否在这里释放内存结构体?(在判断共享页引用问题之后)
552
553 pcb->state = PROC_ZOMBIE;
554 pcb->exit_code = code;
555 sti();
556
557 process_exit_notify();
558 sched();
559
560 while (1)
561 pause();
562 }
563
564 /**
565 * @brief 初始化内核进程
566 *
567 * @param fn 目标程序的地址
568 * @param arg 向目标程序传入的参数
569 * @param flags
570 * @return int
571 */
572
kernel_thread(int (* fn)(void *),void * arg,unsigned long flags)573 pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
574 {
575 struct pt_regs regs;
576 barrier();
577 memset(®s, 0, sizeof(regs));
578 barrier();
579 // 在rbx寄存器中保存进程的入口地址
580 regs.rbx = (ul)fn;
581 // 在rdx寄存器中保存传入的参数
582 regs.rdx = (ul)arg;
583 barrier();
584 regs.ds = KERNEL_DS;
585 barrier();
586 regs.es = KERNEL_DS;
587 barrier();
588 regs.cs = KERNEL_CS;
589 barrier();
590 regs.ss = KERNEL_DS;
591 barrier();
592
593 // 置位中断使能标志位
594 regs.rflags = (1 << 9);
595 barrier();
596 // rip寄存器指向内核线程的引导程序
597 regs.rip = (ul)kernel_thread_func;
598 barrier();
599 // kdebug("kernel_thread_func=%#018lx", kernel_thread_func);
600 // kdebug("&kernel_thread_func=%#018lx", &kernel_thread_func);
601 // kdebug("1111\tregs.rip = %#018lx", regs.rip);
602 return do_fork(®s, flags | CLONE_VM, 0, 0);
603 }
604
605 /**
606 * @brief 初始化进程模块
607 * ☆前置条件:已完成系统调用模块的初始化
608 */
process_init()609 void process_init()
610 {
611 kinfo("Initializing process...");
612
613 initial_tss[proc_current_cpu_id].rsp0 = initial_thread.rbp;
614
615 /*
616 kdebug("initial_thread.rbp=%#018lx", initial_thread.rbp);
617 kdebug("initial_tss[0].rsp1=%#018lx", initial_tss[0].rsp1);
618 kdebug("initial_tss[0].ist1=%#018lx", initial_tss[0].ist1);
619 */
620 // 初始化pid的写锁
621
622 spin_init(&process_global_pid_write_lock);
623
624 // 初始化进程的循环链表
625 list_init(&initial_proc_union.pcb.list);
626 wait_queue_init(&initial_proc_union.pcb.wait_child_proc_exit, NULL);
627
628 // 初始化init进程的signal相关的信息
629 initial_proc_init_signal(current_pcb);
630 // 临时设置IDLE进程的的虚拟运行时间为0,防止下面的这些内核线程的虚拟运行时间出错
631 current_pcb->virtual_runtime = 0;
632 barrier();
633 kernel_thread(initial_kernel_thread, 10, CLONE_FS | CLONE_SIGNAL); // 初始化内核线程
634 barrier();
635 kthread_mechanism_init(); // 初始化kthread机制
636
637 initial_proc_union.pcb.state = PROC_RUNNING;
638 initial_proc_union.pcb.preempt_count = 0;
639 initial_proc_union.pcb.cpu_id = 0;
640 initial_proc_union.pcb.virtual_runtime = (1UL << 60);
641 // 将IDLE进程的虚拟运行时间设置为一个很大的数值
642 current_pcb->virtual_runtime = (1UL << 60);
643 }
644
645 /**
646 * @brief 根据pid获取进程的pcb。存在对应的pcb时,返回对应的pcb的指针,否则返回NULL
647 * 当进程管理模块拥有pcblist_lock之后,调用本函数之前,应当对其加锁
648 * @param pid
649 * @return struct process_control_block*
650 */
process_find_pcb_by_pid(pid_t pid)651 struct process_control_block *process_find_pcb_by_pid(pid_t pid)
652 {
653 // todo: 当进程管理模块拥有pcblist_lock之后,对其加锁
654 struct process_control_block *pcb = initial_proc_union.pcb.next_pcb;
655
656 // 使用蛮力法搜索指定pid的pcb
657 // todo: 使用哈希表来管理pcb
658 for (; pcb != &initial_proc_union.pcb; pcb = pcb->next_pcb)
659 {
660 if (pcb->pid == pid)
661 return pcb;
662 }
663 return NULL;
664 }
665
666 /**
667 * @brief 将进程加入到调度器的就绪队列中.
668 *
669 * @param pcb 进程的pcb
670 *
671 * @return true 成功加入调度队列
672 * @return false 进程已经在运行
673 */
process_wakeup(struct process_control_block * pcb)674 int process_wakeup(struct process_control_block *pcb)
675 {
676 // kdebug("pcb pid = %#018lx", pcb->pid);
677
678 BUG_ON(pcb == NULL);
679 if (pcb == NULL)
680 return -EINVAL;
681 // 如果pcb正在调度队列中,则不重复加入调度队列
682 if (pcb->state & PROC_RUNNING)
683 return 0;
684
685 pcb->state |= PROC_RUNNING;
686 sched_enqueue(pcb);
687 return 1;
688 }
689
690 /**
691 * @brief 将进程加入到调度器的就绪队列中,并标志当前进程需要被调度
692 *
693 * @param pcb 进程的pcb
694 */
process_wakeup_immediately(struct process_control_block * pcb)695 int process_wakeup_immediately(struct process_control_block *pcb)
696 {
697 if (pcb->state & PROC_RUNNING)
698 return 0;
699 int retval = process_wakeup(pcb);
700 if (retval != 0)
701 return retval;
702 // 将当前进程标志为需要调度,缩短新进程被wakeup的时间
703 current_pcb->flags |= PF_NEED_SCHED;
704 }
705
706 /**
707 * @brief 回收进程的所有文件描述符
708 *
709 * @param pcb 要被回收的进程的pcb
710 * @return uint64_t
711 */
process_exit_files(struct process_control_block * pcb)712 uint64_t process_exit_files(struct process_control_block *pcb)
713 {
714 // 不与父进程共享文件描述符
715 if (!(pcb->flags & PF_VFORK))
716 {
717
718 for (int i = 0; i < PROC_MAX_FD_NUM; ++i)
719 {
720 if (pcb->fds[i] == NULL)
721 continue;
722 kfree(pcb->fds[i]);
723 }
724 }
725 // 清空当前进程的文件描述符列表
726 memset(pcb->fds, 0, sizeof(struct vfs_file_t *) * PROC_MAX_FD_NUM);
727 }
728
729 /**
730 * @brief 释放进程的页表
731 *
732 * @param pcb 要被释放页表的进程
733 * @return uint64_t
734 */
process_exit_mm(struct process_control_block * pcb)735 uint64_t process_exit_mm(struct process_control_block *pcb)
736 {
737 if (pcb->flags & CLONE_VM)
738 return 0;
739 if (pcb->mm == NULL)
740 {
741 kdebug("pcb->mm==NULL");
742 return 0;
743 }
744 if (pcb->mm->pgd == NULL)
745 {
746 kdebug("pcb->mm->pgd==NULL");
747 return 0;
748 }
749
750 // // 获取顶层页表
751 pml4t_t *current_pgd = (pml4t_t *)phys_2_virt(pcb->mm->pgd);
752
753 // 循环释放VMA中的内存
754 struct vm_area_struct *vma = pcb->mm->vmas;
755 while (vma != NULL)
756 {
757
758 struct vm_area_struct *cur_vma = vma;
759 vma = cur_vma->vm_next;
760
761 uint64_t pa;
762 // kdebug("vm start=%#018lx, sem=%d", cur_vma->vm_start, cur_vma->anon_vma->sem.counter);
763 mm_unmap_vma(pcb->mm, cur_vma, &pa);
764
765 uint64_t size = (cur_vma->vm_end - cur_vma->vm_start);
766
767 // 释放内存
768 switch (size)
769 {
770 case PAGE_4K_SIZE:
771 kfree(phys_2_virt(pa));
772 break;
773 default:
774 break;
775 }
776 vm_area_del(cur_vma);
777 vm_area_free(cur_vma);
778 }
779
780 // 释放顶层页表
781 kfree(current_pgd);
782 if (unlikely(pcb->mm->vmas != NULL))
783 {
784 kwarn("pcb.mm.vmas!=NULL");
785 }
786 // 释放内存空间分布结构体
787 kfree(pcb->mm);
788
789 return 0;
790 }
791
792 /**
793 * @brief todo: 回收线程结构体
794 *
795 * @param pcb
796 */
process_exit_thread(struct process_control_block * pcb)797 void process_exit_thread(struct process_control_block *pcb)
798 {
799 }
800
801 /**
802 * @brief 释放pcb
803 *
804 * @param pcb 要被释放的pcb
805 * @return int
806 */
process_release_pcb(struct process_control_block * pcb)807 int process_release_pcb(struct process_control_block *pcb)
808 {
809 // 释放子进程的页表
810 process_exit_mm(pcb);
811 if ((pcb->flags & PF_KTHREAD)) // 释放内核线程的worker private结构体
812 free_kthread_struct(pcb);
813
814 // 将pcb从pcb链表中移除
815 // todo: 对相关的pcb加锁
816 pcb->prev_pcb->next_pcb = pcb->next_pcb;
817 pcb->next_pcb->prev_pcb = pcb->prev_pcb;
818 process_exit_sighand(pcb);
819 process_exit_signal(pcb);
820 // 释放当前pcb
821 kfree(pcb);
822 return 0;
823 }
824
825 /**
826 * @brief 申请可用的文件句柄
827 *
828 * @return int
829 */
process_fd_alloc(struct vfs_file_t * file)830 int process_fd_alloc(struct vfs_file_t *file)
831 {
832 int fd_num = -1;
833 struct vfs_file_t **f = current_pcb->fds;
834
835 for (int i = 0; i < PROC_MAX_FD_NUM; ++i)
836 {
837 /* 找到指针数组中的空位 */
838 if (f[i] == NULL)
839 {
840 fd_num = i;
841 f[i] = file;
842 break;
843 }
844 }
845 return fd_num;
846 }
847
848 /**
849 * @brief 给pcb设置名字
850 *
851 * @param pcb 需要设置名字的pcb
852 * @param pcb_name 保存名字的char数组
853 */
__set_pcb_name(struct process_control_block * pcb,const char * pcb_name)854 static void __set_pcb_name(struct process_control_block *pcb, const char *pcb_name)
855 {
856 // todo:给pcb加锁
857 // spin_lock(&pcb->alloc_lock);
858 strncpy(pcb->name, pcb_name, PCB_NAME_LEN);
859 // spin_unlock(&pcb->alloc_lock);
860 }
861
862 /**
863 * @brief 给pcb设置名字
864 *
865 * @param pcb 需要设置名字的pcb
866 * @param pcb_name 保存名字的char数组
867 */
process_set_pcb_name(struct process_control_block * pcb,const char * pcb_name)868 void process_set_pcb_name(struct process_control_block *pcb, const char *pcb_name)
869 {
870 __set_pcb_name(pcb, pcb_name);
871 }
872