#include <amd64/gdt.h>
#include <amd64/smp.h>
#include <aux/compiler.h>
#include <libk/std.h>
#include <libk/string.h>

#define TSS         0x80
#define TSS_PRESENT 0x89

/* Set a GDT entry */
static void gdt_set (volatile struct gdt_entry* ent, uint32_t base, uint32_t limit, uint8_t acc,
                     uint8_t gran) {
  ent->baselow = (base & 0xFFFF);
  ent->basemid = (base >> 16) & 0xFF;
  ent->basehigh = (base >> 24) & 0xFF;
  ent->limitlow = (limit & 0xFFFF);
  ent->gran = ((limit >> 16) & 0x0F) | (gran & 0xF0);
  ent->access = acc;
}

/* Initialize GDT and TSS structures for a given CPU */
void gdt_init (struct cpu* cpu) {
  volatile struct tss* tss = &cpu->tss;
  volatile struct gdt_extended* gdt = &cpu->gdt;

  memset ((void*)gdt, 0, sizeof (*gdt));
  memset ((void*)tss, 0, sizeof (*tss));

  tss->iopb_off = sizeof (*tss);
  tss->rsp0 = (uint64_t)((uintptr_t)cpu->kernel_stack + sizeof (cpu->kernel_stack));
  tss->ist[0] = (uint64_t)((uintptr_t)cpu->except_stack + sizeof (cpu->except_stack));
  tss->ist[1] = (uint64_t)((uintptr_t)cpu->irq_stack + sizeof (cpu->irq_stack));

  uint64_t tssbase = (uint64_t)tss;
  uint64_t tsslimit = sizeof (*tss) - 1;

  gdt_set (&gdt->old[0], 0, 0, 0, 0);
  gdt_set (&gdt->old[1], 0, 0xFFFFF, 0x9A, 0xA0);
  gdt_set (&gdt->old[2], 0, 0xFFFFF, 0x92, 0xC0);
  gdt_set (&gdt->old[3], 0, 0xFFFFF, 0xF2, 0xC0);
  gdt_set (&gdt->old[4], 0, 0xFFFFF, 0xFA, 0xA0);
  gdt_set (&gdt->tsslow, (tssbase & 0xFFFFFFFF), tsslimit, TSS_PRESENT | TSS, 0);

  uint32_t tssbasehigh = (tssbase >> 32);
  gdt->tsshigh.limitlow = (tssbasehigh & 0xFFFF);
  gdt->tsshigh.baselow = (tssbasehigh >> 16) & 0xFFFF;
  gdt->tsshigh.basemid = 0;
  gdt->tsshigh.basehigh = 0;
  gdt->tsshigh.access = 0;
  gdt->tsshigh.gran = 0;

  /* Load GDTR */
  struct gdt_ptr gdtr;
  gdtr.limit = sizeof (*gdt) - 1;
  gdtr.base = (uint64_t)gdt;
  __asm__ volatile ("lgdt %0" ::"m"(gdtr) : "memory");

  /* Reload CS */
  __asm__ volatile ("pushq %[kcode]\n"
                    "lea 1f(%%rip), %%rax\n"
                    "pushq %%rax\n"
                    "lretq\n"
                    "1:\n"
                    "movw %[kdata], %%ax\n"
                    "movw %%ax, %%ds\n"
                    "movw %%ax, %%es\n"
                    "movw %%ax, %%ss\n"
                    :
                    : [kcode] "i"(GDT_KCODE), [kdata] "i"(GDT_KDATA)
                    : "rax", "memory");

  __asm__ volatile ("ltr %0" ::"r"((uint16_t)GDT_TSS));
}
