#include <amd64/fx.h>
#include <amd64/msr-index.h>
#include <amd64/msr.h>
#include <amd64/sched.h>
#include <aux/compiler.h>
#include <libk/std.h>
#include <libk/string.h>
#include <proc/proc.h>
#include <sync/spin_lock.h>
#include <sys/debug.h>
#include <sys/mm.h>
#include <sys/smp.h>

void do_sched (struct proc* proc, spin_lock_t* cpu_lock) {
  spin_lock (&proc->lock);

  thiscpu->tss.rsp0 = proc->pdata.kernel_stack;
  thiscpu->syscall_kernel_stack = proc->pdata.kernel_stack;
  wrmsr (MSR_FS_BASE, proc->pdata.fs_base);

  void* cr3 = (void*)proc->procgroup->pd.cr3_paddr;

  struct saved_regs regs;
  memcpy (&regs, &proc->pdata.regs, sizeof (regs));

  fx_restore (proc->pdata.fx_env);

  spin_unlock (&proc->lock);
  spin_unlock (cpu_lock);

  do_sched1 ((void*)&regs, cr3);
}
