metal-cos/sys/amd64/machine.c
2014-07-16 17:21:18 -07:00

129 lines
2.4 KiB
C

#include <stdbool.h>
#include <stdint.h>
#include <kconfig.h>
#include <kassert.h>
#include <kmem.h>
#include <irq.h>
#include <spinlock.h>
#include "amd64.h"
#include "ioapic.h"
#include "lapic.h"
#include "trap.h"
#include "pmap.h"
#include "../dev/console.h"
extern void PCI_Init();
extern void IDE_Init();
extern void MachineBoot_AddMem();
#define GDT_MAX 7
static SegmentDescriptor GDT[MAX_CPUS][GDT_MAX];
static PseudoDescriptor GDTDescriptor[MAX_CPUS];
static TaskStateSegment64 TSS[MAX_CPUS];
static char df_stack[4096];
void Machine_GDTInit()
{
uint64_t offset;
uint64_t tmp;
kprintf("Initializing GDT... "); // Caused pagefault??
GDT[0][0] = 0x0;
GDT[0][1] = 0x00AF9A000000FFFFULL; /* Kernel CS */
GDT[0][2] = 0x00CF92000000FFFFULL; /* Kernel DS */
GDT[5][1] = 0x00AFFA000000FFFFULL; /* User CS */
GDT[6][2] = 0x00CFF2000000FFFFULL; /* User DS */
// TSS
GDT[0][3] = 0x0; /* TSS */
GDT[0][4] = sizeof(TaskStateSegment64);
offset = (uint64_t)&TSS[0];
tmp = offset & 0x00FFFFFF;
GDT[0][4] |= (tmp << 16);
tmp = offset & 0xFF000000;
GDT[0][4] |= (tmp << 56);
GDT[0][4] |= 0x89ULL << 40;
GDTDescriptor[0].off = (uint64_t)&GDT[0];
GDTDescriptor[0].lim = 8*GDT_MAX - 1;
lgdt(&GDTDescriptor[0]);
kprintf("Done!\n");
}
void Machine_TSSInit()
{
kprintf("Initializing TSS... ");
TSS[0]._unused0 = 0;
TSS[0]._unused1 = 0;
TSS[0]._unused2 = 0;
TSS[0]._unused3 = 0;
TSS[0]._unused4 = 0;
TSS[0].ist1 = (uint64_t)&df_stack;
TSS[0].ist2 = 0x0;
TSS[0].ist3 = 0x0;
TSS[0].ist4 = 0x0;
TSS[0].ist5 = 0x0;
TSS[0].ist6 = 0x0;
TSS[0].ist7 = 0x0;
TSS[0].rsp0 = 0;
TSS[0].rsp1 = 0;
TSS[0].rsp2 = 0;
ltr(SEL_TSS);
kprintf("Done!\n");
}
void Machine_SyscallInit()
{
kprintf("Initializing Syscall... ");
wrmsr(MSR_STAR, (uint64_t)SEL_KCS << 32 | (uint64_t)SEL_UCS << 48);
wrmsr(MSR_LSTAR, 0);
wrmsr(MSR_CSTAR, 0);
wrmsr(MSR_SFMASK, 0);
kprintf("Done!\n");
}
void Machine_EarlyInit()
{
Critical_Init();
Critical_Enter();
Console_Init();
PAlloc_Init();
}
void Machine_Init()
{
Machine_GDTInit();
Machine_TSSInit();
Trap_Init();
//Machine_SyscallInit();
PAlloc_AddRegion(16*1024*1024, 16*1024*1024);
PMap_Init();
MachineBoot_AddMem();
XMem_Init();
IRQ_Init();
LAPIC_Init();
IOAPIC_Init();
PCI_Init();
IDE_Init();
Critical_Exit();
breakpoint();
}