95 lines
2.3 KiB
C
95 lines
2.3 KiB
C
/* SPDX-License-Identifier: GPL-2.0-only */
|
|
#include <arch/proc.h>
|
|
#include <arch/page.h>
|
|
#include <kernel/proc.h>
|
|
#include <kernel/sched.h>
|
|
#include <kernel/syscall.h>
|
|
#include <lib/string.h>
|
|
#include "arch/msr.h"
|
|
|
|
struct cpu_local *tls_get()
|
|
{
|
|
return (void *)rdmsr(IA32_GS_BASE);
|
|
}
|
|
|
|
struct thread *get_cur_thread()
|
|
{
|
|
struct cpu_local *l = tls_get();
|
|
if (!l)
|
|
return NULL;
|
|
if (!l->cur_thread)
|
|
return NULL;
|
|
return l->cur_thread;
|
|
}
|
|
|
|
struct proc *get_cur_proc()
|
|
{
|
|
struct thread *t = get_cur_thread();
|
|
if (!t)
|
|
return NULL;
|
|
return t->proc;
|
|
}
|
|
|
|
/* the thread that calls this will be lost, so it should only be called
|
|
* on the initial process, and while doing an exec
|
|
*/
|
|
void enter_userspace_init(struct thread *thread, uaddr_t entry)
|
|
{
|
|
struct cpu_local *tls = tls_get();
|
|
|
|
tls->cur_thread = thread;
|
|
|
|
void *kstack = kalloc(KSTACK_SIZE, ALLOC_KERN);
|
|
thread->kstack_top = (vaddr_t)kstack + KSTACK_SIZE;
|
|
tls->kernel_rsp = thread->kstack_top;
|
|
tls->tss.rsp0 = thread->kstack_top;
|
|
|
|
pgd_load(thread->proc->pgd);
|
|
|
|
thread->state = PROC_STATE_RUNNING;
|
|
|
|
void _enter_userspace_init(uaddr_t entry, u64 flags, uaddr_t stack_top);
|
|
_enter_userspace_init(entry, 0x202, thread->ustack_top);
|
|
}
|
|
|
|
void fork_trampoline();
|
|
|
|
pid_t sys_fork()
|
|
{
|
|
struct thread *parent = get_cur_thread();
|
|
struct proc *child_proc = proc_create(parent);
|
|
if (!child_proc)
|
|
return -ENOMEM;
|
|
|
|
struct thread *child = child_proc->main_thread;
|
|
child_proc->pid = alloc_pid();
|
|
child->tid = child_proc->pid;
|
|
|
|
void *kstack = kalloc(KSTACK_SIZE, ALLOC_KERN);
|
|
vaddr_t ktop = (vaddr_t)kstack + KSTACK_SIZE;
|
|
child->kstack_top = ktop;
|
|
|
|
/* 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));
|
|
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;
|
|
sched_add_thread(child);
|
|
|
|
return child_proc->pid;
|
|
}
|
|
|
|
static void arch_proc_init()
|
|
{
|
|
syscall_insert(sys_fork, SYS_fork);
|
|
}
|
|
DRIVER_ENTRY(arch_proc_init);
|