process.c 31 KB

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