mit-pdos / xv6-riscv

Xv6 for RISC-V
Other
6.58k stars 2.38k forks source link

where and when set the uservec into stvec #175

Closed wangzhankun closed 1 year ago

wangzhankun commented 1 year ago

I noticed that the kernel only set stvec to uservec at usertrapret function. I can understand that after user process exec syscall and return, the stvec can also points to uservec. But at the first time when user exec syscall, why colud the code be trapped into uservec? Because only usertrapret sets stvec to uservec.

wangzhankun commented 1 year ago

I know now. Kernel will prepare the first user process by calling userinit() in main. And the cpu will run scheduler, the scheduler will call swtch to change the process. In swtch function, the ra register will be changed into the ra of the first process which is created by userinit(). When try to return from swtch, cpu will jumps to ra. uerinit() set the ra to forkret(), in which usertrapret is called, and all needed trapframe values will be inited. Also stvec will be set to uservec. usertrapret will jump into userret defined in trampoline.S. usertrapret will change page table into user process's page table.