fork: properly set up child process

Signed-off-by: Michael Shaw <m@michaelsshaw.com>
This commit is contained in:
Michael Shaw 2026-07-22 00:06:57 -04:00
commit b926d50365
6 changed files with 73 additions and 25 deletions

View file

@ -52,7 +52,7 @@ void enter_userspace_init(struct thread *thread, uaddr_t entry)
_enter_userspace_init(entry, 0x202, thread->ustack_top);
}
void _enter_userspace_init(uaddr_t entry, u64 flags, uaddr_t stack_top);
void fork_trampoline();
pid_t sys_fork()
{
@ -69,18 +69,17 @@ pid_t sys_fork()
vaddr_t ktop = (vaddr_t)kstack + KSTACK_SIZE;
child->kstack_top = ktop;
/* switch_to's pop_all restores rax..r15, then ret returns.
* Set up so child resumes via _enter_userspace_init(entry, flags, stack_top)
* with rax=0 (fork return value).
/* Copy parent's register state, then:
* rax = 0 (child fork return value)
* rdx = parent_r->rsp (user stack for fork_trampoline's mov rsp, rdx)
* ret_addr = fork_trampoline (does mov rsp, rdx; swapgs; sysretq)
*/
struct pt_regs *parent_r = current_pt_regs();
struct pt_regs *child_r = (struct pt_regs *)(ktop - sizeof(struct pt_regs));
memset(child_r, 0, 15 * sizeof(u64));
child_r->rdx = parent_r->rsp; /* rdx = user stack */
child_r->rdi = parent_r->rcx; /* rdi = return addr */
child_r->rsi = 0x202; /* rsi = flags */
/* last address on the stack, *(ktop) is not actually mapped */
*(u64 *)(ktop - 8) = (u64)_enter_userspace_init;
memcpy(child_r, parent_r, sizeof(struct pt_regs) - sizeof(u64));
child_r->rax = 0;
child_r->rdx = parent_r->rsp;
*(u64 *)(ktop - 8) = (u64)fork_trampoline;
child->kstack_ptr = (uaddr_t)child_r;
child->state = PROC_STATE_RUNNING;

View file

@ -21,6 +21,12 @@ struct timespec get_realtime()
return ret;
}
time_t unix_time()
{
u64 sec = (rdtsc() - timekeeper.boot_tsc) / timekeeper.tsc_hz;
return timekeeper.boot_unix_seconds + sec;
}
void time_init()
{
timekeeper.tsc_hz = tsc_calibrate();