process.c 33 KB

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