Compare commits

...

5 Commits

25 changed files with 279 additions and 27 deletions

26
.github/workflows/rust.yml vendored Normal file
View File

@ -0,0 +1,26 @@
name: Rust
on:
push:
branches: [ "dev" ]
pull_request:
branches: [ "dev" ]
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@master
with:
toolchain: nightly
targets: riscv64imac-unknown-none-elf
components: clippy
- name: Build
run: cargo build --verbose
- name: Clippy
run: cargo clippy

34
Cargo.lock generated
View File

@ -2,6 +2,12 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3 version = 3
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]] [[package]]
name = "bit_field" name = "bit_field"
version = "0.10.2" version = "0.10.2"
@ -26,7 +32,17 @@ version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
dependencies = [ dependencies = [
"spin", "spin 0.5.2",
]
[[package]]
name = "lock_api"
version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45"
dependencies = [
"autocfg",
"scopeguard",
] ]
[[package]] [[package]]
@ -68,12 +84,27 @@ dependencies = [
"static_assertions", "static_assertions",
] ]
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]] [[package]]
name = "spin" name = "spin"
version = "0.5.2" version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
dependencies = [
"lock_api",
]
[[package]] [[package]]
name = "static_assertions" name = "static_assertions"
version = "1.1.0" version = "1.1.0"
@ -88,6 +119,7 @@ dependencies = [
"lazy_static", "lazy_static",
"log", "log",
"sbi-rt", "sbi-rt",
"spin 0.9.8",
"static_assertions", "static_assertions",
"uart_16550", "uart_16550",
] ]

View File

@ -27,5 +27,6 @@ bitflags = "2.4.1"
lazy_static = { version = "1.4.0", features = ["spin_no_std"] } lazy_static = { version = "1.4.0", features = ["spin_no_std"] }
log = "0.4" log = "0.4"
sbi-rt = { version = "0.0.2", features = ["legacy"] } sbi-rt = { version = "0.0.2", features = ["legacy"] }
spin = "0.9.8"
static_assertions = "1.1.0" static_assertions = "1.1.0"
uart_16550 = "0.3" uart_16550 = "0.3"

View File

@ -1,10 +1,6 @@
// Basic IO pub use arch::*;
pub mod io;
// Low Level
pub mod lowlevel;
// Arch Level // Arch Level
#[cfg(any(feature = "arch_riscv64", feature = "arch_riscv32"))] #[cfg(any(feature = "arch_riscv64", feature = "arch_riscv32"))]
#[path = "riscv/mod.rs"] #[path = "riscv/mod.rs"]
mod riscv; mod arch;

View File

@ -1,5 +1,6 @@
pub const UART0_BASE: usize = 0x1000_0000; pub const UART0_BASE: usize = 0x1000_0000;
pub const UART0_LSR: usize = 0x1000_0005; pub const UART0_LSR: usize = 0x1000_0005;
pub const TEST_DEVICE: *mut u32 = 0x10_0000 as *mut u32;
pub mod printer; pub mod printer;
pub mod reader; pub mod reader;

View File

@ -1,4 +1,4 @@
use crate::arch::io::{Printer, RawConsole}; use crate::utils::io::{Printer, RawConsole};
/* /*
Theoretically, we should wait until Theoretically, we should wait until

View File

@ -1,4 +1,4 @@
use crate::arch::io::{RawConsole, Reader}; use crate::utils::io::{RawConsole, Reader};
impl Reader for RawConsole { impl Reader for RawConsole {
#[inline] #[inline]

View File

@ -1,5 +1,5 @@
#[allow(unused_imports)] #[allow(unused_imports)]
use crate::arch::io::{Printer, RawConsole, Reader}; use crate::utils::io::{Printer, RawConsole, Reader};
#[cfg(feature = "board_default")] #[cfg(feature = "board_default")]
impl Printer for RawConsole { impl Printer for RawConsole {

View File

@ -1,2 +1,10 @@
pub use super::mm::page::PAGE_SIZE;
pub const KERNEL_MEM_START: usize = 0x8030_0000;
// TODO: currently a dummy value, figure out our memory layout // TODO: currently a dummy value, figure out our memory layout
pub const TRAPFRAME: usize = 0x8000_0000; pub const TRAPFRAME: usize = 0x8000_0000;
extern "C" {
static __kernel_end: u8;
}

View File

@ -56,4 +56,6 @@ SECTIONS {
/DISCARD/ : { /DISCARD/ : {
*(.eh_frame) *(.eh_frame)
} }
__kernel_end = .;
} }

View File

@ -1,6 +1,10 @@
use crate::arch::lowlevel::{Hardware, LowLevel};
use log::error; use log::error;
use crate::utils::lowlevel::{Hardware, LowLevel};
#[cfg(feature = "board_virt")]
use super::board::TEST_DEVICE;
impl LowLevel for Hardware { impl LowLevel for Hardware {
#[inline] #[inline]
fn halt() { fn halt() {
@ -12,9 +16,21 @@ impl LowLevel for Hardware {
Self::disable_interrupt(); Self::disable_interrupt();
if failure { if failure {
#[cfg(not(feature = "board_virt"))]
sbi_rt::system_reset(sbi_rt::Shutdown, sbi_rt::SystemFailure); sbi_rt::system_reset(sbi_rt::Shutdown, sbi_rt::SystemFailure);
#[cfg(feature = "board_virt")]
unsafe {
TEST_DEVICE.write_volatile(0x0042_3333)
}
} else { } else {
#[cfg(not(feature = "board_virt"))]
sbi_rt::system_reset(sbi_rt::Shutdown, sbi_rt::NoReason); sbi_rt::system_reset(sbi_rt::Shutdown, sbi_rt::NoReason);
#[cfg(feature = "board_virt")]
unsafe {
TEST_DEVICE.write_volatile(0x0042_5555)
}
} }
loop { loop {
@ -24,13 +40,19 @@ impl LowLevel for Hardware {
} }
#[inline] #[inline]
fn reset(failure: bool) -> ! { fn reset(#[allow(unused_variables)] failure: bool) -> ! {
#[cfg(not(feature = "board_virt"))]
if failure { if failure {
sbi_rt::system_reset(sbi_rt::ColdReboot, sbi_rt::SystemFailure); sbi_rt::system_reset(sbi_rt::ColdReboot, sbi_rt::SystemFailure);
} else { } else {
sbi_rt::system_reset(sbi_rt::WarmReboot, sbi_rt::NoReason); sbi_rt::system_reset(sbi_rt::WarmReboot, sbi_rt::NoReason);
} }
#[cfg(feature = "board_virt")]
unsafe {
TEST_DEVICE.write_volatile(0x0042_7777)
}
error!("[riscv/lowlevel] system_reset failed, shutdown instead"); error!("[riscv/lowlevel] system_reset failed, shutdown instead");
Self::shutdown(true); Self::shutdown(true);
} }

View File

@ -1,10 +1,10 @@
use crate::mm::addr::{AddressOps, PhysAddr, VirtAddr};
use crate::mm::page;
use bitflags::bitflags; use bitflags::bitflags;
use static_assertions::assert_eq_size; use static_assertions::assert_eq_size;
const PAGE_SIZE: usize = 4096; use crate::mm::addr::{AddressOps, PhysAddr};
use crate::mm::page;
pub const PAGE_SIZE: usize = 4096;
const PAGE_TABLE_ENTRIES: usize = 512; const PAGE_TABLE_ENTRIES: usize = 512;
const PG_OFFSET: u64 = 12; const PG_OFFSET: u64 = 12;

View File

@ -2,10 +2,9 @@
#[path = "board/virt/mod.rs"] #[path = "board/virt/mod.rs"]
mod board; mod board;
mod layout;
pub mod entry; pub mod entry;
pub mod io; pub mod io;
pub mod layout;
pub mod lowlevel; pub mod lowlevel;
pub mod mm; pub mod mm;
pub mod trap; pub mod trap;

View File

@ -1,5 +0,0 @@
pub struct Trap;
pub trait Trampoline {
fn init();
}

View File

@ -1,6 +1,7 @@
use crate::arch::lowlevel::{Hardware, LowLevel};
use log::{error, info}; use log::{error, info};
use crate::utils::lowlevel::{Hardware, LowLevel};
pub extern "C" fn rust_main(hart_id: usize, device_tree_addr: usize) -> ! { pub extern "C" fn rust_main(hart_id: usize, device_tree_addr: usize) -> ! {
crate::logging::init(); crate::logging::init();

View File

@ -1,7 +1,9 @@
use crate::arch::lowlevel::{Hardware, LowLevel};
use core::panic::PanicInfo; use core::panic::PanicInfo;
use log::error; use log::error;
use crate::utils::lowlevel::{Hardware, LowLevel};
#[panic_handler] #[panic_handler]
fn panic(info: &PanicInfo) -> ! { fn panic(info: &PanicInfo) -> ! {
error!("[lang] Kernel panic!"); error!("[lang] Kernel panic!");

View File

@ -18,5 +18,8 @@ pub mod entry;
// page table // page table
pub mod mm; pub mod mm;
// utils
pub mod utils;
// logging // logging
pub mod logging; pub mod logging;

View File

@ -1,7 +1,9 @@
use crate::arch::io::RawConsole;
use core::fmt::Write; use core::fmt::Write;
use log::{self, LevelFilter, Log, Metadata, Record}; use log::{self, LevelFilter, Log, Metadata, Record};
use crate::utils::io::RawConsole;
struct SimpleLogger; struct SimpleLogger;
impl Log for SimpleLogger { impl Log for SimpleLogger {

View File

@ -1,4 +1,4 @@
use core::fmt::{Debug, Formatter, LowerHex, Result, UpperHex}; use core::fmt::{Debug, Display, Formatter, LowerHex, Result, UpperHex};
use core::hash::Hash; use core::hash::Hash;
use core::ops::{Add, AddAssign, Sub, SubAssign}; use core::ops::{Add, AddAssign, Sub, SubAssign};
@ -180,6 +180,12 @@ impl Debug for PhysAddr {
} }
} }
impl Display for PhysAddr {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{:#x}", self.0)
}
}
impl LowerHex for PhysAddr { impl LowerHex for PhysAddr {
fn fmt(&self, f: &mut Formatter) -> Result { fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{:#x}", self.0) write!(f, "{:#x}", self.0)
@ -198,6 +204,12 @@ impl Debug for VirtAddr {
} }
} }
impl Display for VirtAddr {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{:#x}", self.0)
}
}
impl LowerHex for VirtAddr { impl LowerHex for VirtAddr {
fn fmt(&self, f: &mut Formatter) -> Result { fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{:#x}", self.0) write!(f, "{:#x}", self.0)

115
src/mm/bitmap.rs Normal file
View File

@ -0,0 +1,115 @@
pub trait BitmapOps: Copy + Clone {
const CAPACITY: usize;
const DEFAULT: Self;
// a workaround for const fn new()
fn alloc(&mut self) -> Option<usize>;
fn dealloc(&mut self, index: usize);
}
const BITS_PER_LEVEL: usize = 32;
#[derive(Copy, Clone)]
pub struct Bitmap32(u32);
impl BitmapOps for Bitmap32 {
const CAPACITY: usize = u32::BITS as usize;
const DEFAULT: Self = Self(0);
fn alloc(&mut self) -> Option<usize> {
// fast-path
let i = self.0.trailing_zeros() as usize;
if i > 0 {
self.0 |= 1u32 << (i - 1);
return Some(i - 1);
}
// check full
if self.0 == u32::MAX {
return None;
}
// slow-path
for i in (0..BITS_PER_LEVEL).rev() {
if self.0 & (1 << i) == 0 {
self.0 |= 1 << i;
return Some(i);
}
}
None
}
fn dealloc(&mut self, index: usize) {
if index < BITS_PER_LEVEL {
self.0 &= !(1 << index);
}
}
}
#[derive(Copy, Clone)]
pub struct Bitmap<B: BitmapOps> {
bits: u32,
next: [B; BITS_PER_LEVEL],
}
impl<B: BitmapOps> BitmapOps for Bitmap<B> {
const CAPACITY: usize = BITS_PER_LEVEL * B::CAPACITY;
const DEFAULT: Self = Self {
bits: 0,
next: [B::DEFAULT; BITS_PER_LEVEL],
};
fn alloc(&mut self) -> Option<usize> {
if self.bits == u32::MAX {
return None;
}
// fast-path
loop {
let i = self.bits.leading_zeros() as usize;
if i == 0 {
break;
}
if let Some(index) = self.alloc_index(i - 1) {
return Some(index);
}
}
// slow-path
for i in (0..BITS_PER_LEVEL).rev() {
if self.bits & (1 << i) == 0 {
if let Some(index) = self.alloc_index(i) {
return Some(index);
}
}
}
None
}
fn dealloc(&mut self, index: usize) {
let i = index / B::CAPACITY;
if i < BITS_PER_LEVEL {
self.next[i].dealloc(index % B::CAPACITY);
self.bits &= !(1 << i);
}
}
}
impl<B: BitmapOps> Bitmap<B> {
fn alloc_index(&mut self, i: usize) -> Option<usize> {
if let Some(sub) = self.next[i].alloc() {
return Some(i * B::CAPACITY + sub);
}
self.bits |= 1 << i;
None
}
}
#[allow(unused)]
pub type Bitmap1K = Bitmap<Bitmap32>;
#[allow(unused)]
pub type Bitmap32K = Bitmap<Bitmap1K>;
#[allow(unused)]
pub type Bitmap1M = Bitmap<Bitmap32K>;

31
src/mm/frame.rs Normal file
View File

@ -0,0 +1,31 @@
use spin::mutex::SpinMutex;
use crate::arch::layout::*;
use crate::mm::addr::{AddressOps, PhysAddr};
use crate::mm::bitmap::{Bitmap1K, BitmapOps};
// TODO: allow to switch allocator between `BitmapXX` and `FreeList`
// 1k * 4k = 4MB, currently enough for kernel data
static ALLOCATOR: SpinMutex<Bitmap1K> = SpinMutex::new(Bitmap1K::DEFAULT);
pub trait FrameOps {
fn alloc(&self) -> Option<PhysAddr>;
fn dealloc(&self, addr: PhysAddr);
}
pub struct FrameAllocator;
impl FrameOps for FrameAllocator {
fn alloc(&self) -> Option<PhysAddr> {
ALLOCATOR
.lock()
.alloc()
.map(|i| PhysAddr((i * PAGE_SIZE) + KERNEL_MEM_START))
}
fn dealloc(&self, addr: PhysAddr) {
ALLOCATOR
.lock()
.dealloc((addr.as_usize() - KERNEL_MEM_START) / PAGE_SIZE);
}
}

View File

@ -1,2 +1,4 @@
pub mod addr; pub mod addr;
mod bitmap;
pub mod frame;
pub mod page; pub mod page;

2
src/utils/mod.rs Normal file
View File

@ -0,0 +1,2 @@
pub mod io;
pub mod lowlevel;