89 lines
2 KiB
C
89 lines
2 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(PAGE_SIZE, ALLOC_KERN);
|
|
tls->kernel_rsp = (vaddr_t)kstack + PAGE_SIZE;
|
|
tls->tss.rsp0 = tls->kernel_rsp;
|
|
|
|
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->stack_addr);
|
|
}
|
|
|
|
extern void sched_start(void);
|
|
|
|
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;
|
|
|
|
struct pt_regs *parent_r = current_pt_regs();
|
|
u64 *sp = (u64 *)(ktop - 128);
|
|
sp[0] = 0;
|
|
memcpy(&sp[1], &parent_r->rbx, 14 * sizeof(u64));
|
|
*(u64 *)(ktop - 8) = (u64)sched_start;
|
|
*(u64 *)(ktop) = parent_r->rsp;
|
|
child->stack_addr = (uaddr_t)sp;
|
|
|
|
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);
|