x86_64: cleanup linear fb code a bit

This commit is contained in:
Mark Poliakov 2023-07-29 21:11:15 +03:00
parent 48d12c9e77
commit 47f920addf
11 changed files with 462 additions and 254 deletions

View File

@ -17,6 +17,7 @@ bitflags = "2.3.3"
# static_assertions = "1.1.0"
# tock-registers = "0.8.1"
cfg-if = "1.0.0"
bitmap-font = { version = "0.3.0" }
embedded-graphics = "0.8.0"
[dependencies.elf]
@ -30,5 +31,4 @@ fdt-rs = { version = "0.4.3", default-features = false }
aarch64-cpu = "9.3.1"
[target.'cfg(target_arch = "x86_64")'.dependencies]
bitmap-font = { version = "0.3.0" }
yboot-proto = { git = "https://git.alnyan.me/yggdrasil/yboot-proto.git" }

View File

@ -15,7 +15,12 @@ cfg_if! {
} else if #[cfg(target_arch = "x86_64")] {
pub mod x86_64;
pub use x86_64::{X86_64 as ArchitectureImpl, ARCHITECTURE};
pub use x86_64::{
X86_64 as ArchitectureImpl,
X86_64 as PlatformImpl,
ARCHITECTURE,
ARCHITECTURE as PLATFORM
};
} else {
compile_error!("Architecture is not supported");
}

View File

@ -1,24 +1,14 @@
use core::arch::global_asm;
use abi::error::Error;
use bitmap_font::TextStyle;
use embedded_graphics::{
pixelcolor::BinaryColor,
prelude::{DrawTarget, OriginDimensions, Point},
text::Text,
Drawable, Pixel,
};
use yboot_proto::{
v1::FramebufferOption, LoadProtocolHeader, LoadProtocolV1, KERNEL_MAGIC, LOADER_MAGIC,
PROTOCOL_VERSION_1,
};
use crate::{
arch::Architecture,
debug::{self, DebugSink},
mem::device::DeviceMemory,
sync::IrqSafeSpinlock,
util::OneTimeInit,
arch::{Architecture, ArchitectureImpl},
debug,
device::platform::Platform,
};
use super::ARCHITECTURE;
@ -57,206 +47,28 @@ static mut YBOOT_DATA: LoadProtocolV1 = LoadProtocolV1 {
},
};
struct LinearFramebufferInner {
mmio: DeviceMemory,
base: usize,
stride: usize,
width: usize,
height: usize,
}
unsafe extern "C" fn __x86_64_upper_entry() -> ! {
ArchitectureImpl::set_interrupt_mask(true);
pub struct LinearFramebuffer {
inner: IrqSafeSpinlock<LinearFramebufferInner>,
}
ARCHITECTURE.init_mmu(true);
core::arch::asm!("wbinvd");
struct Position {
row: u32,
col: u32,
}
ARCHITECTURE
.yboot_framebuffer
.init(YBOOT_DATA.opt_framebuffer);
ARCHITECTURE.init_primary_debug_sink();
pub struct FramebufferConsole {
framebuffer: &'static LinearFramebuffer,
position: IrqSafeSpinlock<Position>,
char_height: usize,
char_width: usize,
width_chars: usize,
height_chars: usize,
}
impl OriginDimensions for LinearFramebufferInner {
fn size(&self) -> embedded_graphics::prelude::Size {
embedded_graphics::prelude::Size::new(self.width as _, self.height as _)
}
}
impl DrawTarget for LinearFramebufferInner {
type Color = BinaryColor;
type Error = ();
fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
where
I: IntoIterator<Item = Pixel<Self::Color>>,
{
for Pixel(coord, color) in pixels {
let x = coord.x as usize;
let y = coord.y as usize;
let addr = self.base + y * self.stride + x * 4;
let ptr = addr as *mut u32;
unsafe {
if color.is_on() {
ptr.write_volatile(0xFFFFFFFF);
} else {
ptr.write_volatile(0);
}
}
}
Ok(())
}
}
impl DebugSink for FramebufferConsole {
fn putc(&self, c: u8) -> Result<(), Error> {
let mut pos = self.position.lock();
self.framebuffer.draw_glyph(
self.char_width * pos.col as usize,
self.char_height * pos.row as usize,
c,
);
if c == b'\n' {
pos.row += 1;
pos.col = 0;
} else {
pos.col += 1;
}
if pos.col == self.width_chars as u32 {
pos.row += 1;
pos.col = 0;
}
if pos.row == self.height_chars as u32 {
pos.row = self.height_chars as u32 - 1;
}
Ok(())
}
}
impl LinearFramebuffer {
pub fn from_yboot(fb: &FramebufferOption) -> Result<Self, Error> {
let mmio =
unsafe { DeviceMemory::map("framebuffer", fb.res_address as _, fb.res_size as _) }?;
let inner = LinearFramebufferInner {
base: mmio.base(),
mmio,
stride: fb.res_stride as _,
width: fb.res_width as _,
height: fb.res_height as _,
};
Ok(Self {
inner: IrqSafeSpinlock::new(inner),
})
}
pub fn draw_glyph(&self, x: usize, y: usize, c: u8) {
let mut inner = self.inner.lock();
let font = &bitmap_font::tamzen::FONT_6x12;
let text_data = [c];
let text_str = unsafe { core::str::from_utf8_unchecked(&text_data) };
let text = Text::new(
text_str,
Point::new(x as _, y as _),
TextStyle::new(font, BinaryColor::On),
);
text.draw(&mut *inner).ok();
}
}
impl FramebufferConsole {
pub fn new(framebuffer: &'static LinearFramebuffer) -> Self {
let char_width = 6;
let char_height = 12;
let (w, h) = {
let inner = framebuffer.inner.lock();
(inner.width, inner.height)
};
Self {
framebuffer,
position: IrqSafeSpinlock::new(Position { row: 0, col: 0 }),
width_chars: w / char_width,
height_chars: h / char_height,
char_width,
char_height,
}
}
}
static DISPLAY: OneTimeInit<LinearFramebuffer> = OneTimeInit::new();
static CONSOLE: OneTimeInit<FramebufferConsole> = OneTimeInit::new();
extern "C" fn __x86_64_upper_entry() -> ! {
unsafe {
ARCHITECTURE.init_mmu(true);
core::arch::asm!("wbinvd");
}
let fb = unsafe { &YBOOT_DATA.opt_framebuffer };
DISPLAY.init(LinearFramebuffer::from_yboot(fb).unwrap());
CONSOLE.init(FramebufferConsole::new(DISPLAY.get()));
debug::init_with_sink(CONSOLE.get());
for i in 0..10 {
debugln!("Test {}", i);
}
debug::init();
let mut i = 0;
loop {
unsafe {
core::arch::asm!("cli; hlt");
}
debugln!("{} {}", env!("PROFILE"), i);
i += 1;
}
// if let Ok(fb_mmio) = unsafe { DeviceMemory::map("framebuffer", fb.res_address as _, 0x1000) } {
// unsafe {
// core::arch::asm!("mov %cr3, %rax; mov %rax, %cr3", options(att_syntax));
// }
// let addr = 0xffffff8140000000usize;
// let slice = unsafe { core::slice::from_raw_parts_mut(addr as *mut u32, 1024) };
// slice.fill(0xFFFF0000);
// loop {}
// // for y in 0..2 {
// // let y_val = (y * 255) / fb.res_height;
// // let addr = fb_mmio.base() + y as usize * fb.res_stride as usize;
// // let row =
// // unsafe { core::slice::from_raw_parts_mut(addr as *mut u32, fb.res_width as _) };
// // let v = 0xFF000000 | (y_val << 16) | (y_val << 8) | y_val;
// // row.fill(v);
// // }
// loop {
// ArchitectureImpl::wait_for_interrupt();
// }
// unsafe {
// core::arch::asm!(
// r#"
// mov $0x3F8, %dx
// mov $'@', %al
// out %al, %dx
// "#,
// options(att_syntax)
// );
// }
loop {}
}
global_asm!(
@ -280,7 +92,7 @@ __x86_64_entry:
movabsq ${stack_bottom} + {stack_size}, %rax
movabsq ${entry}, %rcx
mov %rax, %rsp
jmp *%rcx
callq *%rcx
.section .text
"#,

View File

@ -1,13 +1,24 @@
use abi::error::Error;
use yboot_proto::v1::FramebufferOption;
use crate::arch::x86_64::table::{init_fixed_tables, KERNEL_TABLES};
use crate::{
arch::x86_64::table::{init_fixed_tables, KERNEL_TABLES},
debug::DebugSink,
device::{
display::{fb_console::FramebufferConsole, linear_fb::LinearFramebuffer},
platform::Platform,
},
util::OneTimeInit,
};
use super::Architecture;
pub mod boot;
pub mod table;
pub struct X86_64;
pub struct X86_64 {
yboot_framebuffer: OneTimeInit<FramebufferOption>,
}
impl Architecture for X86_64 {
const KERNEL_VIRT_OFFSET: usize = 0xFFFFFF8000000000;
@ -26,16 +37,72 @@ impl Architecture for X86_64 {
}
fn wait_for_interrupt() {
todo!()
unsafe {
core::arch::asm!("hlt");
}
}
unsafe fn set_interrupt_mask(mask: bool) {
todo!()
if mask {
core::arch::asm!("cli");
} else {
core::arch::asm!("sti");
}
}
fn interrupt_mask() -> bool {
todo!()
let mut flags: u64;
unsafe {
core::arch::asm!("pushfd; pop {0}", out(reg) flags, options(att_syntax));
}
// If IF is zero, interrupts are disabled (masked)
flags & (1 << 9) == 0
}
}
pub static ARCHITECTURE: X86_64 = X86_64;
impl Platform for X86_64 {
unsafe fn init(&'static self, _is_bsp: bool) -> Result<(), Error> {
Ok(())
}
unsafe fn init_primary_debug_sink(&self) {
let Some(fb) = self.yboot_framebuffer.try_get() else {
// TODO fallback to serial as primary
return;
};
LINEAR_FB.init(
LinearFramebuffer::from_physical_bits(
fb.res_address as _,
fb.res_size as _,
fb.res_stride as _,
fb.res_width,
fb.res_height,
)
.unwrap(),
);
FB_CONSOLE.init(FramebufferConsole::from_framebuffer(
LINEAR_FB.get(),
&bitmap_font::tamzen::FONT_6x12,
));
}
fn name(&self) -> &'static str {
"x86-64"
}
fn primary_debug_sink(&self) -> Option<&dyn DebugSink> {
if let Some(console) = FB_CONSOLE.try_get() {
Some(console)
} else {
None
}
}
}
pub static ARCHITECTURE: X86_64 = X86_64 {
yboot_framebuffer: OneTimeInit::new(),
};
static LINEAR_FB: OneTimeInit<LinearFramebuffer> = OneTimeInit::new();
static FB_CONSOLE: OneTimeInit<FramebufferConsole> = OneTimeInit::new();

View File

@ -3,7 +3,7 @@ use core::fmt::{self, Arguments};
use abi::error::Error;
use crate::{sync::IrqSafeSpinlock, util::OneTimeInit};
use crate::{arch::PLATFORM, device::platform::Platform, sync::IrqSafeSpinlock, util::OneTimeInit};
// use crate::{
// arch::PLATFORM,
@ -30,6 +30,13 @@ pub enum LogLevel {
pub trait DebugSink {
fn putc(&self, c: u8) -> Result<(), Error>;
fn puts(&self, s: &str) -> Result<(), Error> {
for &byte in s.as_bytes() {
self.putc(byte)?;
}
Ok(())
}
fn supports_color(&self) -> bool {
return false;
}
@ -103,10 +110,7 @@ impl LogLevel {
impl fmt::Write for DebugPrinter {
fn write_str(&mut self, s: &str) -> fmt::Result {
for c in s.bytes() {
self.sink.putc(c).ok();
}
self.sink.puts(s).ok();
Ok(())
}
}
@ -138,9 +142,9 @@ pub fn hex_dump(level: LogLevel, addr_offset: usize, data: &[u8]) {
///
/// Will panic if called more than once.
pub fn init() {
// DEBUG_PRINTER.init(IrqSafeSpinlock::new(DebugPrinter {
// sink: PLATFORM.primary_serial().unwrap(),
// }));
DEBUG_PRINTER.init(IrqSafeSpinlock::new(DebugPrinter {
sink: PLATFORM.primary_debug_sink().unwrap(),
}));
// unsafe {
// vfs::init_debug_hook(&move |args| {
// debug_internal(args, LogLevel::Debug);

View File

@ -0,0 +1,156 @@
use abi::error::Error;
use bitmap_font::{BitmapFont, TextStyle};
use embedded_graphics::{
pixelcolor::BinaryColor,
prelude::{DrawTarget, OriginDimensions, Point, Size},
text::Text,
Drawable, Pixel,
};
use crate::{debug::DebugSink, sync::IrqSafeSpinlock};
use super::{linear_fb::LinearFramebuffer, DisplayDevice, DisplayDimensions};
struct Inner {
framebuffer: &'static LinearFramebuffer,
font: &'static BitmapFont<'static>,
row: u32,
col: u32,
char_height: u32,
char_width: u32,
width_chars: u32,
height_chars: u32,
}
pub struct FramebufferConsole {
inner: IrqSafeSpinlock<Inner>,
}
impl FramebufferConsole {
pub fn from_framebuffer(
framebuffer: &'static LinearFramebuffer,
font: &'static BitmapFont<'static>,
) -> Self {
let char_width = 6;
let char_height = 12;
let dim = framebuffer.dimensions();
let inner = Inner {
framebuffer,
font,
row: 0,
col: 0,
width_chars: dim.width / char_width,
height_chars: dim.height / char_height,
char_width,
char_height,
};
Self {
inner: IrqSafeSpinlock::new(inner),
}
}
}
impl Inner {
fn putc(&mut self, c: u8) {
self.draw_glyph(
self.font,
self.char_width * self.col,
self.char_height * self.row,
c,
);
if c == b'\n' {
self.col = 0;
self.row += 1;
} else {
self.col += 1;
}
if self.col == self.width_chars {
self.col = 0;
self.row += 1;
}
self.scroll();
// if self.row == self.height_chars {
// self.row = self.height_chars - 1;
// }
}
fn scroll(&mut self) {
// Should only happen once
while self.row >= self.height_chars {
let mut fb = unsafe { self.framebuffer.lock() };
fb.copy_rows(self.char_height, 0, self.char_height * self.height_chars);
fb.fill_rows(
(self.height_chars - 1) * self.char_height,
self.char_height,
0x00000000,
);
self.row -= 1;
}
}
fn draw_glyph(&mut self, font: &BitmapFont, x: u32, y: u32, c: u8) {
let text_data = [c];
let text_str = unsafe { core::str::from_utf8_unchecked(&text_data) };
let text = Text::new(
text_str,
Point::new(x as _, y as _),
TextStyle::new(font, BinaryColor::On),
);
text.draw(self).ok();
}
}
impl DebugSink for FramebufferConsole {
fn putc(&self, c: u8) -> Result<(), Error> {
self.inner.lock().putc(c);
Ok(())
}
fn supports_color(&self) -> bool {
false
}
}
impl OriginDimensions for Inner {
fn size(&self) -> Size {
self.framebuffer.dimensions().into()
}
}
impl DrawTarget for Inner {
type Color = BinaryColor;
type Error = ();
fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
where
I: IntoIterator<Item = Pixel<Self::Color>>,
{
let mut fb = unsafe { self.framebuffer.lock() };
for Pixel(coord, color) in pixels {
let row = &mut fb[coord.y as u32];
let color = if color.is_on() {
0xFFFFFFFF
} else {
0xFF000000
};
row[coord.x as usize] = color;
}
Ok(())
}
}
impl From<DisplayDimensions> for Size {
fn from(value: DisplayDimensions) -> Self {
Self::new(value.width as _, value.height as _)
}
}

View File

@ -0,0 +1,142 @@
use core::ops::{Index, IndexMut};
use abi::error::Error;
use crate::{device::Device, mem::device::DeviceMemory, sync::IrqSafeSpinlock};
use super::{DisplayDevice, DisplayDimensions};
struct Inner {
dimensions: DisplayDimensions,
base: usize,
stride: usize,
}
pub struct FramebufferAccess {
dimensions: DisplayDimensions,
base: usize,
stride: usize,
}
pub struct LinearFramebuffer {
inner: IrqSafeSpinlock<Inner>,
}
impl LinearFramebuffer {
pub unsafe fn from_physical_bits(
base: usize,
size: usize,
stride: usize,
width: u32,
height: u32,
) -> Result<Self, Error> {
// TODO this may get Dropped later
let mmio = unsafe { DeviceMemory::map("framebuffer", base, size) }?;
let inner = Inner {
dimensions: DisplayDimensions { width, height },
base: mmio.base(),
stride,
};
Ok(Self {
inner: IrqSafeSpinlock::new(inner),
})
}
// TODO doesn't actually lock
pub unsafe fn lock(&self) -> FramebufferAccess {
let inner = self.inner.lock();
FramebufferAccess {
dimensions: inner.dimensions,
base: inner.base,
stride: inner.stride,
}
}
}
impl Device for LinearFramebuffer {
fn name(&self) -> &'static str {
"Linear Framebuffer"
}
unsafe fn init(&self) -> Result<(), Error> {
Ok(())
}
}
impl DisplayDevice for LinearFramebuffer {
fn dimensions(&self) -> DisplayDimensions {
self.inner.lock().dimensions
}
}
impl FramebufferAccess {
pub fn copy_rows(&mut self, src_row: u32, dst_row: u32, count: u32) {
use core::ffi::c_void;
extern "C" {
fn memmove(dst: *mut c_void, src: *const c_void, len: usize) -> *mut c_void;
}
if src_row == dst_row {
return;
}
let src_end_row = core::cmp::min(self.dimensions.height, src_row + count);
let dst_end_row = core::cmp::min(self.dimensions.height, dst_row + count);
if dst_end_row <= dst_row || src_end_row <= dst_row {
return;
}
let count = core::cmp::min(src_end_row - src_row, dst_end_row - dst_row) as usize;
let src_base_addr = self.base + self.stride * src_row as usize;
let dst_base_addr = self.base + self.stride * dst_row as usize;
unsafe {
memmove(
dst_base_addr as *mut c_void,
src_base_addr as *mut c_void,
self.stride * count,
);
}
}
pub fn fill_rows(&mut self, start_row: u32, count: u32, value: u32) {
use core::ffi::c_void;
extern "C" {
fn memset(s: *mut c_void, c: u32, len: usize) -> *mut c_void;
}
let end_row = core::cmp::min(self.dimensions.height, start_row + count);
if end_row <= start_row {
return;
}
let count = (end_row - start_row) as usize;
let base_addr = self.base + self.stride * start_row as usize;
unsafe {
memset(base_addr as *mut c_void, value, self.stride * count);
}
}
}
impl Index<u32> for FramebufferAccess {
type Output = [u32];
fn index(&self, index: u32) -> &Self::Output {
assert!(index < self.dimensions.height);
let row_addr = self.base + self.stride * index as usize;
unsafe { core::slice::from_raw_parts(row_addr as *const u32, self.dimensions.width as _) }
}
}
impl IndexMut<u32> for FramebufferAccess {
fn index_mut(&mut self, index: u32) -> &mut Self::Output {
assert!(index < self.dimensions.height);
let row_addr = self.base + self.stride * index as usize;
unsafe { core::slice::from_raw_parts_mut(row_addr as *mut u32, self.dimensions.width as _) }
}
}

14
src/device/display/mod.rs Normal file
View File

@ -0,0 +1,14 @@
use super::Device;
pub mod fb_console;
pub mod linear_fb;
#[derive(Clone, Copy, Debug)]
pub struct DisplayDimensions {
pub width: u32,
pub height: u32,
}
pub trait DisplayDevice: Device {
fn dimensions(&self) -> DisplayDimensions;
}

View File

@ -1,11 +1,12 @@
//! Device management and interfaces
use abi::error::Error;
pub mod interrupt;
// pub mod interrupt;
pub mod display;
pub mod platform;
pub mod serial;
pub mod timer;
pub mod tty;
// pub mod serial;
// pub mod timer;
// pub mod tty;
/// General device interface
pub trait Device {

View File

@ -2,15 +2,17 @@
use abi::error::Error;
use super::{interrupt::InterruptController, serial::SerialDevice, timer::TimestampSource};
use crate::debug::DebugSink;
// use super::{interrupt::InterruptController, serial::SerialDevice, timer::TimestampSource};
/// Platform interface for interacting with a general hardware set
pub trait Platform {
/// Interrupt number type for the platform
type IrqNumber;
// type IrqNumber;
/// Address, to which the kernel is expected to be loaded for this platform
const KERNEL_PHYS_BASE: usize;
// const KERNEL_PHYS_BASE: usize;
/// Initializes the platform devices to their usable state.
///
@ -18,34 +20,39 @@ pub trait Platform {
///
/// Unsafe to call if the platform has already been initialized.
unsafe fn init(&'static self, is_bsp: bool) -> Result<(), Error>;
/// Initializes the primary serial device to provide the debugging output as early as possible.
///
/// # Safety
///
/// Unsafe to call if the device has already been initialized.
unsafe fn init_primary_serial(&self);
unsafe fn init_primary_debug_sink(&self);
// /// Initializes the primary serial device to provide the debugging output as early as possible.
// ///
// /// # Safety
// ///
// /// Unsafe to call if the device has already been initialized.
// unsafe fn init_primary_serial(&self);
/// Returns a display name for the platform
fn name(&self) -> &'static str;
/// Returns a reference to the primary serial device.
///
/// # Note
///
/// May not be initialized at the moment of calling.
fn primary_serial(&self) -> Option<&dyn SerialDevice>;
fn primary_debug_sink(&self) -> Option<&dyn DebugSink>;
/// Returns a reference to the platform's interrupt controller.
///
/// # Note
///
/// May not be initialized at the moment of calling.
fn interrupt_controller(&self) -> &dyn InterruptController<IrqNumber = Self::IrqNumber>;
// /// Returns a reference to the primary serial device.
// ///
// /// # Note
// ///
// /// May not be initialized at the moment of calling.
// fn primary_serial(&self) -> Option<&dyn SerialDevice>;
/// Returns the platform's primary timestamp source.
///
/// # Note
///
/// May not be initialized at the moment of calling.
fn timestamp_source(&self) -> &dyn TimestampSource;
// /// Returns a reference to the platform's interrupt controller.
// ///
// /// # Note
// ///
// /// May not be initialized at the moment of calling.
// fn interrupt_controller(&self) -> &dyn InterruptController<IrqNumber = Self::IrqNumber>;
// /// Returns the platform's primary timestamp source.
// ///
// /// # Note
// ///
// /// May not be initialized at the moment of calling.
// fn timestamp_source(&self) -> &dyn TimestampSource;
}

View File

@ -39,7 +39,7 @@ fn panic_handler(_pi: &core::panic::PanicInfo) -> ! {
loop {}
}
//
// pub mod device;
pub mod device;
// pub mod fs;
pub mod mem;
// pub mod panic;