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