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