page_table_generic/
lib.rs

1#![cfg_attr(not(test), no_std)]
2
3mod addr;
4mod iter;
5mod table;
6use core::{alloc::Layout, fmt::Debug};
7
8pub use addr::*;
9pub use table::{MapConfig, PageTableRef};
10
11pub const KB: usize = 1024;
12pub const MB: usize = 1024 * KB;
13pub const GB: usize = 1024 * MB;
14
15#[derive(Debug, Clone, Copy)]
16pub struct PTEInfo<P: PTEGeneric> {
17    pub level: usize,
18    pub vaddr: VirtAddr,
19    pub pte: P,
20}
21
22pub trait TableGeneric: Sync + Send + Clone + Copy + 'static {
23    type PTE: PTEGeneric;
24
25    const PAGE_SIZE: usize = 0x1000;
26    const LEVEL: usize = 4;
27    const VALID_BITS: usize = 12 + Self::LEVEL * 9;
28    // 大页最高支持的级别
29    const MAX_BLOCK_LEVEL: usize = 3;
30    const TABLE_LEN: usize = Self::PAGE_SIZE / core::mem::size_of::<Self::PTE>();
31    fn flush(vaddr: Option<VirtAddr>);
32}
33
34pub trait PTEGeneric: Debug + Sync + Send + Clone + Copy + Sized + 'static {
35    fn valid(&self) -> bool;
36    fn paddr(&self) -> PhysAddr;
37    fn set_paddr(&mut self, paddr: PhysAddr);
38    fn set_valid(&mut self, valid: bool);
39    fn is_huge(&self) -> bool;
40    fn set_is_huge(&mut self, b: bool);
41}
42
43pub trait Access {
44    /// Alloc memory for a page table entry.
45    ///
46    /// # Safety
47    ///
48    /// should be deallocated by [`dealloc`].
49    unsafe fn alloc(&mut self, layout: Layout) -> Option<PhysAddr>;
50    /// dealloc memory for a page table entry.
51    ///
52    /// # Safety
53    ///
54    /// ptr must be allocated by [`alloc`].
55    unsafe fn dealloc(&mut self, ptr: PhysAddr, layout: Layout);
56
57    fn phys_to_mut(&self, phys: PhysAddr) -> *mut u8;
58}
59
60use thiserror::Error;
61
62/// The error type for page table operation failures.
63#[derive(Error, Debug, PartialEq, Eq)]
64pub enum PagingError {
65    #[error("can't allocate memory")]
66    NoMemory,
67    #[error("{0} is not aligned")]
68    NotAligned(&'static str),
69    #[error("not mapped")]
70    NotMapped,
71    #[error("already mapped")]
72    AlreadyMapped,
73}
74
75/// The specialized `Result` type for page table operations.
76pub type PagingResult<T = ()> = Result<T, PagingError>;