process.c 33 KB

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