Files
mango/arch/x86_64/acpi/apic.cpp
2023-03-20 20:41:39 +00:00

135 lines
2.6 KiB
C++

#include <socks/printk.h>
#include <socks/vm.h>
#include <socks/cpu.h>
#include <arch/acpi.h>
#include <arch/msr.h>
#include <arch/ports.h>
#include <arch/pit.h>
#define PIC1_DATA 0x21
#define PIC2_DATA 0xA1
#define IA32_APIC_BASE_MSR 0x1B
#define IA32_APIC_BASE_MSR_BSP 0x100
#define IA32_APIC_BASE_MSR_ENABLE 0x800
static uint32_t *lapic_base;
extern "C" {
/* defined in apic_ctrl.S */
extern int check_apic(void);
}
static uintptr_t apic_get_base(void)
{
return rdmsr(IA32_APIC_BASE_MSR);
}
static void apic_set_base(uintptr_t addr)
{
wrmsr(IA32_APIC_BASE_MSR, addr);
}
static void disable_8259(void)
{
/* mask all interrupts on PICs 1 and 2 */
outportb(PIC1_DATA, 0xFF);
outportb(PIC2_DATA, 0xFF);
}
static uint32_t local_apic_read(uint32_t reg)
{
return READ_ONCE(lapic_base[reg >> 4]);
}
static void local_apic_write(uint32_t reg, uint32_t val)
{
}
static void *find_lapic(struct acpi_madt *madt)
{
phys_addr_t local_apic = madt->m_lapic_ptr;
unsigned char *p = (unsigned char *)madt + sizeof *madt;
unsigned char *madt_end = (unsigned char *)madt + madt->m_base.s_length;
while (p < madt_end) {
struct acpi_madt_record *rec = (struct acpi_madt_record *)p;
struct lapic_override_record *lapic;
switch (rec->r_type) {
case ACPI_MADT_LAPIC_OVERRIDE:
lapic = (struct lapic_override_record *)(rec + 1);
return vm_phys_to_virt(lapic->l_lapic_ptr);
default:
break;
}
p += rec->r_length;
}
return vm_phys_to_virt(local_apic);
}
kern_status_t local_apic_enable(void)
{
struct acpi_madt *madt = (struct acpi_madt *)acpi_find_sdt(ACPI_SIG_MADT);
if (!madt) {
return KERN_UNSUPPORTED;
}
apic_set_base(apic_get_base());
lapic_base = (uint32_t *)find_lapic(madt);
local_apic_write(0xF0, local_apic_read(0xF0) | 0x100);
printk("acpi: enabled local APIC on core %u", this_cpu());
return KERN_OK;
}
static void configure_legacy_pic(void)
{
printk("acpi: APIC unavailable, using 8259 PIC");
pit_start(1000);
}
static void ioapic_init(void)
{
}
static void init_all_ioapic(void)
{
ioapic_init();
}
kern_status_t apic_init(void)
{
static unsigned int bsp_id = (unsigned int)-1;
/* the bootstrap processor will be the first one ro call apic_init().
it is responsible for initialising the I/O APICs */
if (bsp_id == (unsigned int)-1) {
bsp_id = this_cpu();
}
struct acpi_madt *madt = (struct acpi_madt *)acpi_find_sdt(ACPI_SIG_MADT);
if (check_apic() == 0 || !madt) {
configure_legacy_pic();
return KERN_UNSUPPORTED;
}
if (this_cpu() == bsp_id) {
init_all_ioapic();
}
local_apic_enable();
disable_8259();
pit_start(10);
return KERN_OK;
}