96 lines
2.4 KiB
C
96 lines
2.4 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 _enter_userspace_init(uaddr_t entry, u64 flags, uaddr_t stack_top);
|
|
|
|
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;
|
|
|
|
/* 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).
|
|
*/
|
|
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;
|
|
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);
|