//! Page table manipulation.

use ax_alloc::{UsageKind, global_allocator};
use ax_memory_addr::{PAGE_SIZE_4K, PhysAddr, VirtAddr};
use ax_page_table_multiarch::PagingHandler;
#[doc(no_inline)]
pub use ax_page_table_multiarch::{MappingFlags, PageSize, PagingError, PagingResult};

use crate::mem::{phys_to_virt, virt_to_phys};

/// Implementation of [`PagingHandler`], to provide physical memory manipulation to
/// the `ax-page-table-multiarch` crate.
pub struct PagingHandlerImpl;

impl PagingHandler for PagingHandlerImpl {
    fn alloc_frame() -> Option<PhysAddr> {
        Self::alloc_frames(1, PAGE_SIZE_4K)
    }

    fn alloc_frames(num: usize, align: usize) -> Option<PhysAddr> {
        global_allocator()
            .alloc_pages(num, align, UsageKind::PageTable)
            .map(|vaddr| virt_to_phys(vaddr.into()))
            .ok()
    }

    fn dealloc_frame(paddr: PhysAddr) {
        Self::dealloc_frames(paddr, 1)
    }

    fn dealloc_frames(paddr: PhysAddr, num: usize) {
        global_allocator().dealloc_pages(phys_to_virt(paddr).as_usize(), num, UsageKind::PageTable);
    }

    #[inline]
    fn phys_to_virt(paddr: PhysAddr) -> VirtAddr {
        phys_to_virt(paddr)
    }
}

cfg_if::cfg_if! {
    if #[cfg(target_arch = "x86_64")] {
        /// The architecture-specific page table.
        pub type PageTable = ax_page_table_multiarch::x86_64::X64PageTable<PagingHandlerImpl>;
        /// The architecture-specific page table cursor.
        pub type PageTableCursor<'a> = ax_page_table_multiarch::x86_64::X64PageTableCursor<'a, PagingHandlerImpl>;
    } else if #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] {
        /// The architecture-specific page table.
        pub type PageTable = ax_page_table_multiarch::riscv::Sv39PageTable<PagingHandlerImpl>;
        /// The architecture-specific page table cursor.
        pub type PageTableCursor<'a> = ax_page_table_multiarch::riscv::Sv39PageTableCursor<'a, PagingHandlerImpl>;
    } else if #[cfg(target_arch = "aarch64")]{
        /// The architecture-specific page table.
        pub type PageTable = ax_page_table_multiarch::aarch64::A64PageTable<PagingHandlerImpl>;
        /// The architecture-specific page table cursor.
        pub type PageTableCursor<'a> = ax_page_table_multiarch::aarch64::A64PageTableCursor<'a, PagingHandlerImpl>;
    } else if #[cfg(target_arch = "loongarch64")] {
        /// The architecture-specific page table.
        pub type PageTable = ax_page_table_multiarch::loongarch64::LA64PageTable<PagingHandlerImpl>;
        /// The architecture-specific page table cursor.
        pub type PageTableCursor<'a> = ax_page_table_multiarch::loongarch64::LA64PageTableCursor<'a, PagingHandlerImpl>;
    }
}
