#include <amd64/gdt.h>
#include <amd64/intr.h>
#include <amd64/mm.h>
#include <amd64/msr-index.h>
#include <amd64/msr.h>
#include <m/syscall_defs.h>
#include <proc/proc.h>
#include <sys/debug.h>
#include <sys/smp.h>
#include <syscall/syscall.h>

extern void amd64_syscall_entry (void);

int amd64_syscall_dispatch (void* stack_ptr) {
  struct saved_regs* regs = stack_ptr;

  int syscall_num = regs->rax;
  syscall_handler_func_t func = syscall_find_handler (syscall_num);

  if (func == NULL)
    return -SR_SYSCALL_NOT_FOUND;

  struct proc* caller = thiscpu->proc_current;

  __asm__ volatile ("sti");

  int result = func (caller, regs->rdi, regs->rsi, regs->rdx, regs->r10, regs->r8, regs->r9);

  __asm__ volatile ("cli");

  return result;
}

void syscall_init (void) {
  amd64_wrmsr (MSR_STAR, ((uint64_t)GDT_KCODE << 32) | ((uint64_t)(GDT_UCODE - 16) << 48));
  amd64_wrmsr (MSR_LSTAR, (uint64_t)&amd64_syscall_entry);
  amd64_wrmsr (MSR_SYSCALL_MASK, (1ULL << 9));
  amd64_wrmsr (MSR_EFER, amd64_rdmsr (MSR_EFER) | EFER_SCE);
}
