process.c 26 KB

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