Merge remote-tracking branch 'origin' into editor

merging into dev
This commit is contained in:
2025-02-27 23:58:01 +00:00
19 changed files with 451 additions and 402 deletions
+115
View File
@@ -0,0 +1,115 @@
use core::arch::x86_64::__cpuid;
use libk::drivers::memory::FoundryOSFrameAllocator;
use spin::Lazy;
use x86_64::{
PhysAddr, VirtAddr,
instructions::port::Port,
registers::model_specific::Msr,
structures::paging::{
FrameAllocator, Mapper, Page, PageTableFlags, PhysFrame, Size4KiB, Translate,
},
};
use crate::serial_print;
use super::{cpu::model_specific_registers::*, memmap::PHYSICAL_MEMORY_OFFSET};
const IA32_APIC_BASE_MSR: u32 = 0x1b;
const IA32_APIC_BASE_MSR_BSP: u64 = 0x100;
const IA32_APIC_BASE_MSR_ENABLE: u64 = 0x800;
const IA32_APIC_BASE_MSR_DISABLE: u64 = !IA32_APIC_BASE_MSR_ENABLE;
const CPUID_FEAT_EDX_APIC: u64 = 1 << 9; // the cpuid instruction will return this flag if it supports APIC
// const APIC_VIRTUAL_ADDRESS: Lazy<VirtAddr> = Lazy::new(|| {
// let apic_base = get_apic_base();
// let virt_addr = unsafe { phys_to_virt(apic_base) };
// virt_addr
// });
fn set_apic_base_enable(apic: PhysAddr) {
let rax = (apic.as_u64() & 0xfffff0000) | IA32_APIC_BASE_MSR_ENABLE;
cpu_set_msr(IA32_APIC_BASE_MSR, rax);
}
fn set_apic_base_disable(apic: PhysAddr) {
let rax = (apic.as_u64() & 0xfffff0000) & IA32_APIC_BASE_MSR_DISABLE;
cpu_set_msr(IA32_APIC_BASE_MSR, rax);
}
fn get_apic_base() -> PhysAddr {
let mut value: u64 = 0;
cpu_get_msr(IA32_APIC_BASE_MSR, &mut value);
PhysAddr::new(value & 0xfffff0000)
}
fn write_apic_register(apic_base: &VirtAddr, reg: u8, value: u32) {
let apic_base = apic_base.as_u64();
let reg_addr = (apic_base & 0xFFFFF0000) + reg as u64;
unsafe { *(reg_addr as *mut u32) = value };
}
fn read_apic_register(apic_base: &VirtAddr, reg: u8) -> u32 {
let apic_base = apic_base.as_u64();
serial_print!("got apic base");
let reg_addr = (apic_base & 0xFFFFF0000) + reg as u64;
unsafe { *(reg_addr as *const u32) }
}
pub fn check_apic() -> bool {
let res = unsafe { __cpuid(1) };
res.edx as u64 & CPUID_FEAT_EDX_APIC != 0
}
#[inline(always)]
unsafe fn phys_to_virt(phys: PhysAddr) -> VirtAddr {
let phys = phys.as_u64();
match phys.checked_add(*PHYSICAL_MEMORY_OFFSET) {
Some(virt) => {
serial_print!("map worked!");
VirtAddr::new(virt)
}
None => {
serial_print!("THIS IS A PROBLEM");
panic!("overflow")
}
}
}
pub fn enable_apic(
mapper: &mut impl Mapper<Size4KiB>,
frame_allocator: &mut FoundryOSFrameAllocator,
) {
let apic_phys_addr = get_apic_base();
set_apic_base_enable(apic_phys_addr);
// map virt address of apic
let apic_virt = unsafe { phys_to_virt(apic_phys_addr) };
// let page: Page<Size4KiB> = Page::containing_address(apic_virt);
// let frame: PhysFrame<Size4KiB> = PhysFrame::containing_address(apic_phys_addr);
// let flags: PageTableFlags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE;
// unsafe {
// match mapper.map_to(page, frame, flags, frame_allocator) {
// Ok(_) => {}
// Err(why) => panic!("failed to map apic: {:?}", why),
// }
// }
// // FIXME: this causes a page fault
// // TODO: map to virtual memor
let reg = read_apic_register(&apic_virt, 0xF0);
serial_print!("ok2");
write_apic_register(&apic_virt, 0xF0, reg | 0x100);
}
pub struct Apic {}
pub enum ApicVector {}
+26
View File
@@ -0,0 +1,26 @@
pub mod model_specific_registers {
use core::arch::x86_64::__cpuid;
use spin::Lazy;
use x86_64::registers::model_specific::Msr;
const CPUID_FLAG_MSR: u32 = 1 << 5;
static EDX: Lazy<u32> = Lazy::new(|| unsafe { __cpuid(1).edx });
pub fn cpu_has_msr() -> bool {
*EDX & CPUID_FLAG_MSR != 0
}
pub fn cpu_get_msr(msr: u32, value: &mut u64) {
let msr = Msr::new(msr);
unsafe {
*value = msr.read();
}
}
pub fn cpu_set_msr(msr: u32, value: u64) {
let mut msr = Msr::new(msr);
unsafe {
msr.write(value);
}
}
}
+36 -8
View File
@@ -1,11 +1,14 @@
use libk::drivers::apic::enable_apic;
use libk::drivers::memory::{FRAME_ALLOCATOR, OFFSET_PAGE_TABLE};
use libk::prelude::*;
use pic8259::ChainedPics;
use x86_64::registers::control::Cr2;
use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame, PageFaultErrorCode};
use x86_64::structures::paging::mapper::MapperFlushAll;
use x86_64::structures::paging::{FrameAllocator, Mapper, Page, PageTableFlags, Size4KiB};
use spin::{Lazy, Mutex};
use super::apic::enable_apic;
use super::gdt;
static IDT: Lazy<InterruptDescriptorTable> = Lazy::new(|| {
@@ -52,14 +55,21 @@ impl InterruptIndex {
pub fn init_idt() {
IDT.load();
// enable_apic();
// TODO: fix apic
}
pub fn enable_pic() {
unsafe {
PICS.lock().initialize();
PICS.lock().write_masks(0xfc, 0xff);
}
}
pub fn disable_pic() {
unsafe {
PICS.lock().disable();
}
}
extern "x86-interrupt" fn breakpoint_handler(stack_frame: InterruptStackFrame) {
serial_println!("Exception: Breakpoint\n{:#?}", stack_frame);
println_log!("Exception: Breakpoint\n{:#?}", stack_frame);
@@ -118,10 +128,28 @@ extern "x86-interrupt" fn page_fault_handler(
stack_frame: InterruptStackFrame,
error_code: PageFaultErrorCode,
) {
serial_println!("Exception: Page Fault");
serial_println!("Accessed Address: {:?}", Cr2::read());
serial_println!("Error Code: {:?}", error_code);
serial_println!("{:#?}", stack_frame);
// serial_println!("Exception: Page Fault");
// serial_println!("Accessed Address: {:?}", Cr2::read());
// serial_println!("Error Code: {:?}", error_code);
// serial_println!("{:#?}", stack_frame);
crate::hcf();
if let Some(frame_allocator) = FRAME_ALLOCATOR.get() {
let mut f = frame_allocator.lock();
let frame = f.allocate_frame().unwrap();
let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE;
let page: Page<Size4KiB> = Page::containing_address(Cr2::read().unwrap());
unsafe {
let mut mapper = OFFSET_PAGE_TABLE.get().unwrap().lock();
match mapper.map_to(page, frame, flags, &mut *f) {
Ok(_) => {}
Err(why) => panic!("failed to map page: {:?}", why),
}
}
MapperFlushAll::new().flush_all();
} else {
panic!("failed to get frame allocator");
}
}
+4 -4
View File
@@ -14,6 +14,10 @@ static MEMORY_MAP_REQUEST: MemoryMapRequest = MemoryMapRequest::new();
#[unsafe(link_section = ".requests")]
static HIGHER_HALF_DIRECT_MAP_REQUEST: HhdmRequest = HhdmRequest::new();
#[used]
#[unsafe(link_section = ".requests")]
static KERNEL_ADDRESS_REQUEST: KernelAddressRequest = KernelAddressRequest::new();
/// ```rs
/// let virt_addr = phys_addr + offset;
/// let phys_addr = virt_addr - offset; // (given VA is in the HHDM). Do not use for executable code.
@@ -25,10 +29,6 @@ pub static PHYSICAL_MEMORY_OFFSET: Lazy<u64> = Lazy::new(|| {
.offset()
});
#[used]
#[unsafe(link_section = ".requests")]
static KERNEL_ADDRESS_REQUEST: KernelAddressRequest = KernelAddressRequest::new();
/// Converts virtual addresses in the kernel to a physical address like this:
/// ```rs
/// let phys_addr = virt_addr - virtual_base + physical_base;
-141
View File
@@ -1,141 +0,0 @@
// use lib_alloc::allocator::FoundryAllocator;
use limine::{memory_map::EntryType, response::MemoryMapResponse};
use x86_64::{
PhysAddr,
VirtAddr,
// addr,
registers::control::Cr3,
structures::paging::{
// page_table::FrameError,
FrameAllocator,
OffsetPageTable,
PageTable,
PhysFrame,
Size4KiB,
},
};
/// Returns a mutable reference to the current level 4 page table.
///
/// # Safety
///
/// The caller must ensure that the level 4 page table is not modified
/// simultaneously. The caller must also ensure that the physical memory offset
/// is correct, to ensure that the correct virtual address is constructed.
unsafe fn active_l4_table(physical_memory_offset: VirtAddr) -> &'static mut PageTable {
let (level_4_frame, _) = Cr3::read();
let phys_addr = level_4_frame.start_address();
let virt = phys_addr.as_u64() + physical_memory_offset.as_u64();
unsafe { &mut *(virt as *mut PageTable) }
}
/// Initializes the `OffsetPageTable` for the current CPU architecture.
///
/// # Safety
///
/// This function must be called only once and should be called before any
/// memory operations are performed that rely on virtual memory management.
/// The provided `physical_memory_offset` must be accurate to ensure correct
/// translation of physical addresses.
///
/// # Parameters
///
/// - `physical_memory_offset`: The offset to convert physical addresses to
/// virtual addresses in the higher-half direct map.
///
/// # Returns
///
/// Returns an `OffsetPageTable` that allows for manipulation of the page
/// tables for the current CPU architecture.
pub unsafe fn init(physical_memory_offset: VirtAddr) -> OffsetPageTable<'static> {
unsafe {
let l4_table = active_l4_table(physical_memory_offset);
OffsetPageTable::new(l4_table, physical_memory_offset)
}
}
pub struct FoundryOSFrameAllocator {
memory_map: &'static MemoryMapResponse,
next: usize,
}
impl FoundryOSFrameAllocator {
/// Creates a new `FoundryOSFrameAllocator` from a memory map.
///
/// This function takes a reference to a `MemoryMapResponse` and initializes a
/// `FoundryOSFrameAllocator` with it. The `next` field is set to 0, indicating that
/// the first frame to be allocated is the first frame in the memory map.
pub const unsafe fn init(memory_map: &'static MemoryMapResponse) -> Self {
Self {
memory_map,
next: 0,
}
}
/// An iterator over all usable frames in the memory map.
///
/// Yields one `PhysFrame` for each available 4KiB frame in the memory map.
///
/// This function is used to allocate frames for the pagemap.
fn usable_frames(&self) -> impl Iterator<Item = PhysFrame> + use<> {
let regions = self.memory_map.entries().iter();
let usable_regions = regions.filter(|region| region.entry_type == EntryType::USABLE);
let addr_ranges = usable_regions.map(|region| region.base..region.base + region.length);
let frame_addresses = addr_ranges.flat_map(|r| r.step_by(4096));
frame_addresses.map(|addr| PhysFrame::from_start_address(PhysAddr::new(addr)).unwrap())
}
}
unsafe impl FrameAllocator<Size4KiB> for FoundryOSFrameAllocator {
/// Allocates a frame from the list of usable frames.
///
/// This function returns the next available `PhysFrame` from the memory map,
/// if one exists. Once a frame is allocated, the internal counter is incremented
/// to point to the next frame for future allocations.
///
/// # Returns
///
/// - `Some(PhysFrame)`: If a usable frame is available.
/// - `None`: If there are no more usable frames to allocate.
fn allocate_frame(&mut self) -> Option<PhysFrame> {
let frame = self.usable_frames().nth(self.next);
self.next += 1;
frame
}
}
// pub unsafe fn translate_addr(addr: VirtAddr, physical_memory_offset: VirtAddr) -> Option<PhysAddr> {
// translate_addr_inner(addr, physical_memory_offset)
// }
// fn translate_addr_inner(addr: VirtAddr, physical_memory_offset: VirtAddr) -> Option<PhysAddr> {
// let (l4_table_frame, _) = Cr3::read();
// let table_indexes = [
// addr.p4_index(),
// addr.p3_index(),
// addr.p2_index(),
// addr.p1_index(),
// ];
// let mut frame = l4_table_frame;
// for &i in &table_indexes {
// let virt = physical_memory_offset + frame.start_address().as_u64();
// let table_ptr: *const PageTable = virt.as_ptr();
// let table = unsafe { &*table_ptr };
// let entry = &table[i];
// frame = match entry.frame() {
// Ok(frame) => frame,
// Err(FrameError::FrameNotPresent) => return None,
// Err(FrameError::HugeFrame) => panic!("huge frames are not supported!"),
// };
// }
// Some(frame.start_address() + u64::from(addr.page_offset()))
// }
+4 -2
View File
@@ -2,6 +2,8 @@ pub mod gdt;
pub mod interrupts;
pub mod memory;
pub mod memmap;
pub mod apic;
pub mod cpu;
+21 -7
View File
@@ -13,7 +13,9 @@
extern crate alloc;
use arch::x86_64::apic::enable_apic;
use core::arch::asm;
use libk::drivers::memory;
use limine::BaseRevision;
use libk::drivers::kalloc::allocator::init_heap;
@@ -56,7 +58,7 @@ pub fn boot() -> Result<(), &'static str> {
return Err("base revision not supported");
}
use arch::x86_64::{gdt, interrupts, memmap, memory};
use arch::x86_64::{gdt, interrupts, memmap};
let memory_map = memmap::get_memory_map();
@@ -75,21 +77,33 @@ pub fn boot() -> Result<(), &'static str> {
interrupts::init_idt();
println_log!("[Success]");
print_log!(" Setting Up Page Table... ");
let mut frame_allocator = unsafe { memory::FoundryOSFrameAllocator::init(memory_map) };
println_log!("[Success]");
print_log!(" Initialising Memory Subsystem... ");
let physical_memory_offset = VirtAddr::new(*memmap::PHYSICAL_MEMORY_OFFSET);
let mut l4_table = unsafe { memory::init(physical_memory_offset) };
let mut l4_table = memory::init_page_table(physical_memory_offset);
println_log!("[Success]");
print_log!(" Setting Up Page Table... ");
memory::init_frame_allocator(memory_map);
println_log!("[Success]");
print_log!(" Initialising Heap... ");
if init_heap(&mut l4_table, &mut frame_allocator).is_err() {
if init_heap().is_err() {
return Err("Failed to initialise heap: error");
}
println_log!("[Success]");
print_log!(" Enabling PICs... ");
interrupts::enable_pic();
println_log!("[Success]");
// print_log!(" Disabling PICs... ");
// interrupts::disable_pic();
// println_log!("[Success]");
//
// print_log!(" Initialising APIC");
// enable_apic(&mut l4_table, &mut frame_allocator);
// println_log!("[Success]");
print_log!(" Enabling Interrupts... ");
x86_64::instructions::interrupts::enable();
println_log!("[Success]");
+7
View File
@@ -38,6 +38,13 @@ extern "C" fn kmain() -> ! {
println!("vec 100000 works");
let mut executor = Executor::new();
let mut v = Vec::with_capacity(1000 * 1000);
for i in 0..1000 * 1000 {
v.push(i);
}
println!("v.len(): {}", v.len());
executor.spawn(Task::new(shell()));
executor.run();
}