1a7eb62a4Shoumkh use crate::libs::spinlock::{SpinLock, SpinLockGuard}; 240fe15e0SLoGin use crate::mm::kernel_mapper::KernelMapper; 3*23ef2b33SLoGin use crate::mm::page::{PAGE_1G_SHIFT, PAGE_4K_SHIFT}; 41496ba7bSLoGin use crate::process::ProcessManager; 5c2481452Shoumkh use crate::{ 6*23ef2b33SLoGin include::bindings::bindings::PAGE_4K_SIZE, 740fe15e0SLoGin kdebug, 840fe15e0SLoGin mm::{MMArch, MemoryManagementArch}, 9c2481452Shoumkh }; 1040fe15e0SLoGin use crate::{kerror, kinfo, kwarn}; 1140fe15e0SLoGin use alloc::{collections::LinkedList, vec::Vec}; 1240fe15e0SLoGin use core::mem; 1340fe15e0SLoGin use core::mem::MaybeUninit; 14*23ef2b33SLoGin use core::sync::atomic::{AtomicBool, Ordering}; 1591e9d4abSLoGin use system_error::SystemError; 1640fe15e0SLoGin 172dd9f0c7SLoGin use super::page::PageFlags; 182dd9f0c7SLoGin use super::{PhysAddr, VirtAddr}; 19c2481452Shoumkh 20c2481452Shoumkh // 最大的伙伴块的幂 21*23ef2b33SLoGin const MMIO_BUDDY_MAX_EXP: u32 = PAGE_1G_SHIFT as u32; 22c2481452Shoumkh // 最小的伙伴块的幂 23*23ef2b33SLoGin const MMIO_BUDDY_MIN_EXP: u32 = PAGE_4K_SHIFT as u32; 24c2481452Shoumkh // 内存池数组的范围 25c2481452Shoumkh const MMIO_BUDDY_REGION_COUNT: u32 = MMIO_BUDDY_MAX_EXP - MMIO_BUDDY_MIN_EXP + 1; 26c2481452Shoumkh 2740fe15e0SLoGin const PAGE_1G_SIZE: usize = 1 << 30; 2840fe15e0SLoGin 2940fe15e0SLoGin static mut __MMIO_POOL: Option<MmioBuddyMemPool> = None; 3040fe15e0SLoGin 317ae679ddSLoGin pub fn mmio_pool() -> &'static MmioBuddyMemPool { 327ae679ddSLoGin unsafe { __MMIO_POOL.as_ref().unwrap() } 33c2481452Shoumkh } 34c2481452Shoumkh 35c2481452Shoumkh pub enum MmioResult { 36c2481452Shoumkh SUCCESS, 37c2481452Shoumkh EINVAL, 38c2481452Shoumkh ENOFOUND, 39c2481452Shoumkh WRONGEXP, 40c2481452Shoumkh ISEMPTY, 41c2481452Shoumkh } 42c2481452Shoumkh 43c2481452Shoumkh /// @brief buddy内存池 4440fe15e0SLoGin #[derive(Debug)] 45c2481452Shoumkh pub struct MmioBuddyMemPool { 4640fe15e0SLoGin pool_start_addr: VirtAddr, 4740fe15e0SLoGin pool_size: usize, 48c2481452Shoumkh free_regions: [SpinLock<MmioFreeRegionList>; MMIO_BUDDY_REGION_COUNT as usize], 49c2481452Shoumkh } 5040fe15e0SLoGin 51c2481452Shoumkh impl MmioBuddyMemPool { 52453452ccSLoGin #[inline(never)] 53c2481452Shoumkh fn new() -> Self { 5440fe15e0SLoGin let mut free_regions: [MaybeUninit<SpinLock<MmioFreeRegionList>>; 5540fe15e0SLoGin MMIO_BUDDY_REGION_COUNT as usize] = unsafe { MaybeUninit::uninit().assume_init() }; 5640fe15e0SLoGin for i in 0..MMIO_BUDDY_REGION_COUNT { 5740fe15e0SLoGin free_regions[i as usize] = MaybeUninit::new(SpinLock::new(MmioFreeRegionList::new())); 5840fe15e0SLoGin } 5940fe15e0SLoGin let free_regions = unsafe { 6040fe15e0SLoGin mem::transmute::<_, [SpinLock<MmioFreeRegionList>; MMIO_BUDDY_REGION_COUNT as usize]>( 6140fe15e0SLoGin free_regions, 6240fe15e0SLoGin ) 63c2481452Shoumkh }; 6440fe15e0SLoGin 6540fe15e0SLoGin let pool = MmioBuddyMemPool { 66*23ef2b33SLoGin pool_start_addr: MMArch::MMIO_BASE, 67*23ef2b33SLoGin pool_size: MMArch::MMIO_SIZE, 6840fe15e0SLoGin free_regions, 6940fe15e0SLoGin }; 70*23ef2b33SLoGin 71*23ef2b33SLoGin assert!(pool.pool_start_addr.data() % PAGE_1G_SIZE == 0); 7240fe15e0SLoGin kdebug!("MMIO buddy pool init: created"); 7340fe15e0SLoGin 74*23ef2b33SLoGin let mut vaddr_base = MMArch::MMIO_BASE; 75*23ef2b33SLoGin let mut remain_size = MMArch::MMIO_SIZE; 76*23ef2b33SLoGin kdebug!( 77*23ef2b33SLoGin "BASE: {:?}, TOP: {:?}, size: {:?}", 78*23ef2b33SLoGin MMArch::MMIO_BASE, 79*23ef2b33SLoGin MMArch::MMIO_TOP, 80*23ef2b33SLoGin MMArch::MMIO_SIZE 81*23ef2b33SLoGin ); 82*23ef2b33SLoGin 83*23ef2b33SLoGin for shift in (PAGE_4K_SHIFT..=PAGE_1G_SHIFT).rev() { 84*23ef2b33SLoGin if remain_size & (1 << shift) != 0 { 85*23ef2b33SLoGin let ok = pool.give_back_block(vaddr_base, shift as u32).is_ok(); 86*23ef2b33SLoGin if ok { 87*23ef2b33SLoGin vaddr_base += 1 << shift; 88*23ef2b33SLoGin remain_size -= 1 << shift; 89*23ef2b33SLoGin } else { 9040fe15e0SLoGin panic!("MMIO buddy pool init failed"); 9140fe15e0SLoGin } 9240fe15e0SLoGin } 9340fe15e0SLoGin } 94*23ef2b33SLoGin 9540fe15e0SLoGin kdebug!("MMIO buddy pool init success"); 9640fe15e0SLoGin return pool; 97c2481452Shoumkh } 98c2481452Shoumkh 99c2481452Shoumkh /// @brief 创建新的地址区域结构体 100c2481452Shoumkh /// 101c2481452Shoumkh /// @param vaddr 虚拟地址 102c2481452Shoumkh /// 103c2481452Shoumkh /// @return 创建好的地址区域结构体 10440fe15e0SLoGin fn create_region(&self, vaddr: VirtAddr) -> MmioBuddyAddrRegion { 10540fe15e0SLoGin // kdebug!("create_region for vaddr: {vaddr:?}"); 10640fe15e0SLoGin 10740fe15e0SLoGin let region: MmioBuddyAddrRegion = MmioBuddyAddrRegion::new(vaddr); 10840fe15e0SLoGin 10940fe15e0SLoGin // kdebug!("create_region for vaddr: {vaddr:?} OK!!!"); 110c2481452Shoumkh return region; 111c2481452Shoumkh } 112c2481452Shoumkh 113c2481452Shoumkh /// @brief 将内存块归还给buddy 114c2481452Shoumkh /// 115c2481452Shoumkh /// @param vaddr 虚拟地址 116c2481452Shoumkh /// 117c2481452Shoumkh /// @param exp 内存空间的大小(2^exp) 118c2481452Shoumkh /// 119c2481452Shoumkh /// @param list_guard 【exp】对应的链表 120c2481452Shoumkh /// 121c2481452Shoumkh /// @return Ok(i32) 返回0 122c2481452Shoumkh /// 123676b8ef6SMork /// @return Err(SystemError) 返回错误码 12440fe15e0SLoGin fn give_back_block(&self, vaddr: VirtAddr, exp: u32) -> Result<i32, SystemError> { 125c2481452Shoumkh // 确保内存对齐,低位都要为0 12640fe15e0SLoGin if (vaddr.data() & ((1 << exp) - 1)) != 0 { 127676b8ef6SMork return Err(SystemError::EINVAL); 128c2481452Shoumkh } 12940fe15e0SLoGin let region: MmioBuddyAddrRegion = self.create_region(vaddr); 130c2481452Shoumkh // 加入buddy 13140fe15e0SLoGin let mut list_guard = self.free_regions[exp2index(exp)].lock(); 13240fe15e0SLoGin 13340fe15e0SLoGin self.push_block(region, &mut list_guard); 134c2481452Shoumkh return Ok(0); 135c2481452Shoumkh } 136c2481452Shoumkh 137c2481452Shoumkh /// @brief 将给定大小为2^{exp}的内存块一分为二,并插入内存块大小为2^{exp-1}的链表中 138c2481452Shoumkh /// 139c2481452Shoumkh /// @param region 要被分割的地址区域结构体(保证其已经从链表中取出) 140c2481452Shoumkh /// 141c2481452Shoumkh /// @param exp 要被分割的地址区域的大小的幂 142c2481452Shoumkh /// 143c2481452Shoumkh /// @param list_guard 【exp-1】对应的链表 144a7eb62a4Shoumkh fn split_block( 145c2481452Shoumkh &self, 14640fe15e0SLoGin region: MmioBuddyAddrRegion, 147c2481452Shoumkh exp: u32, 148c2481452Shoumkh low_list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 149c2481452Shoumkh ) { 15040fe15e0SLoGin let vaddr = self.calculate_block_vaddr(region.vaddr, exp - 1); 15140fe15e0SLoGin let new_region: MmioBuddyAddrRegion = self.create_region(vaddr); 152a7eb62a4Shoumkh self.push_block(region, low_list_guard); 153a7eb62a4Shoumkh self.push_block(new_region, low_list_guard); 154c2481452Shoumkh } 155c2481452Shoumkh 156c2481452Shoumkh /// @brief 从buddy中申请一块指定大小的内存区域 157c2481452Shoumkh /// 158c2481452Shoumkh /// @param exp 要申请的内存块的大小的幂(2^exp) 159c2481452Shoumkh /// 160c2481452Shoumkh /// @param list_guard exp对应的链表 161c2481452Shoumkh /// 16240fe15e0SLoGin /// @return Ok(MmioBuddyAddrRegion) 符合要求的内存区域。 163c2481452Shoumkh /// 164c2481452Shoumkh /// @return Err(MmioResult) 165c2481452Shoumkh /// - 没有满足要求的内存块时,返回ENOFOUND 166c2481452Shoumkh /// - 申请的内存块大小超过合法范围,返回WRONGEXP 167c2481452Shoumkh /// - 调用函数出错时,返回出错函数对应错误码 168a7eb62a4Shoumkh fn query_addr_region( 169c2481452Shoumkh &self, 170c2481452Shoumkh exp: u32, 171c2481452Shoumkh list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 17240fe15e0SLoGin ) -> Result<MmioBuddyAddrRegion, MmioResult> { 173c2481452Shoumkh // 申请范围错误 174b5b571e0SLoGin if !(MMIO_BUDDY_MIN_EXP..=MMIO_BUDDY_MAX_EXP).contains(&exp) { 175a7eb62a4Shoumkh kdebug!("query_addr_region: exp wrong"); 176c2481452Shoumkh return Err(MmioResult::WRONGEXP); 177c2481452Shoumkh } 178c2481452Shoumkh // 没有恰好符合要求的内存块 179c2481452Shoumkh // 注意:exp对应的链表list_guard已上锁【注意避免死锁问题】 180c2481452Shoumkh if list_guard.num_free == 0 { 181c2481452Shoumkh // 找到最小符合申请范围的内存块 182c2481452Shoumkh // 将大的内存块依次分成小块内存,直到能够满足exp大小,即将exp+1分成两块exp 183c2481452Shoumkh for e in exp + 1..MMIO_BUDDY_MAX_EXP + 1 { 184ef9f9732Shoumkh let pop_list: &mut SpinLockGuard<MmioFreeRegionList> = 185b5b571e0SLoGin &mut self.free_regions[exp2index(e)].lock(); 186ef9f9732Shoumkh if pop_list.num_free == 0 { 187c2481452Shoumkh continue; 188c2481452Shoumkh } 189ef9f9732Shoumkh 190c2481452Shoumkh for e2 in (exp + 1..e + 1).rev() { 191ef9f9732Shoumkh if e2 == e { 192ef9f9732Shoumkh match self.pop_block(pop_list) { 193ef9f9732Shoumkh Ok(region) => { 194ef9f9732Shoumkh if e2 != exp + 1 { 195ef9f9732Shoumkh // 要将分裂后的内存块插入到更小的链表中 196ef9f9732Shoumkh let low_list_guard: &mut SpinLockGuard<MmioFreeRegionList> = 197b5b571e0SLoGin &mut self.free_regions[exp2index(e2 - 1)].lock(); 198ef9f9732Shoumkh self.split_block(region, e2, low_list_guard); 199ef9f9732Shoumkh } else { 200ef9f9732Shoumkh // 由于exp对应的链表list_guard已经被锁住了 不能再加锁 201ef9f9732Shoumkh // 所以直接将list_guard传入 202ef9f9732Shoumkh self.split_block(region, e2, list_guard); 203ef9f9732Shoumkh } 204ef9f9732Shoumkh } 205ef9f9732Shoumkh Err(err) => { 206ef9f9732Shoumkh kdebug!("buddy_pop_region get wrong"); 207ef9f9732Shoumkh return Err(err); 208ef9f9732Shoumkh } 209ef9f9732Shoumkh } 210ef9f9732Shoumkh } else { 211b5b571e0SLoGin match self.pop_block(&mut self.free_regions[exp2index(e2)].lock()) { 212c2481452Shoumkh Ok(region) => { 213c2481452Shoumkh if e2 != exp + 1 { 214c2481452Shoumkh // 要将分裂后的内存块插入到更小的链表中 215c2481452Shoumkh let low_list_guard: &mut SpinLockGuard<MmioFreeRegionList> = 216b5b571e0SLoGin &mut self.free_regions[exp2index(e2 - 1)].lock(); 217a7eb62a4Shoumkh self.split_block(region, e2, low_list_guard); 218c2481452Shoumkh } else { 219c2481452Shoumkh // 由于exp对应的链表list_guard已经被锁住了 不能再加锁 220c2481452Shoumkh // 所以直接将list_guard传入 221a7eb62a4Shoumkh self.split_block(region, e2, list_guard); 222c2481452Shoumkh } 223c2481452Shoumkh } 224c2481452Shoumkh Err(err) => { 225c2481452Shoumkh kdebug!("buddy_pop_region get wrong"); 226c2481452Shoumkh return Err(err); 227c2481452Shoumkh } 228c2481452Shoumkh } 229c2481452Shoumkh } 230ef9f9732Shoumkh } 231c2481452Shoumkh break; 232c2481452Shoumkh } 233c2481452Shoumkh // 判断是否获得了exp大小的内存块 234c2481452Shoumkh if list_guard.num_free > 0 { 235ef9f9732Shoumkh match self.pop_block(list_guard) { 236ef9f9732Shoumkh Ok(ret) => return Ok(ret), 237ef9f9732Shoumkh Err(err) => return Err(err), 238ef9f9732Shoumkh } 239c2481452Shoumkh } 240c2481452Shoumkh // 拆分大内存块无法获得exp大小内存块 241c2481452Shoumkh // 尝试用小内存块合成 242c2481452Shoumkh // 即将两块exp合成一块exp+1 243ef9f9732Shoumkh 244ef9f9732Shoumkh // TODO:修改下一个循环的冗余代码,请不要删除此处的注释 245ef9f9732Shoumkh // let merge = |high_list_guard: &mut SpinLockGuard<MmioFreeRegionList>, exp: u32| { 246ef9f9732Shoumkh // if let Err(err) = self.merge_all_exp( 247ef9f9732Shoumkh // exp, 248ef9f9732Shoumkh // &mut self.free_regions[exp2index(exp) as usize].lock(), 249ef9f9732Shoumkh // high_list_guard, 250ef9f9732Shoumkh // ) { 251ef9f9732Shoumkh // return err; 252ef9f9732Shoumkh // } else { 253ef9f9732Shoumkh // return MmioResult::SUCCESS; 254ef9f9732Shoumkh // } 255ef9f9732Shoumkh // }; 256c2481452Shoumkh for e in MMIO_BUDDY_MIN_EXP..exp { 257c2481452Shoumkh if e != exp - 1 { 258a7eb62a4Shoumkh match self.merge_all_exp( 259ef9f9732Shoumkh exp, 260b5b571e0SLoGin &mut self.free_regions[exp2index(exp)].lock(), 261ef9f9732Shoumkh &mut self.free_regions[exp2index(exp + 1)].lock(), 262c2481452Shoumkh ) { 263c2481452Shoumkh Ok(_) => continue, 264c2481452Shoumkh Err(err) => { 265ef9f9732Shoumkh kdebug!("merge_all_exp get wrong"); 266c2481452Shoumkh return Err(err); 267c2481452Shoumkh } 268c2481452Shoumkh } 269c2481452Shoumkh } else { 270a7eb62a4Shoumkh match self.merge_all_exp( 271ef9f9732Shoumkh exp, 272b5b571e0SLoGin &mut self.free_regions[exp2index(exp)].lock(), 273c2481452Shoumkh list_guard, 274c2481452Shoumkh ) { 275c2481452Shoumkh Ok(_) => continue, 276c2481452Shoumkh Err(err) => { 277ef9f9732Shoumkh kdebug!("merge_all_exp get wrong"); 278c2481452Shoumkh return Err(err); 279c2481452Shoumkh } 280c2481452Shoumkh } 281c2481452Shoumkh } 282c2481452Shoumkh } 283c2481452Shoumkh 284c2481452Shoumkh //判断是否获得了exp大小的内存块 285c2481452Shoumkh if list_guard.num_free > 0 { 286ef9f9732Shoumkh match self.pop_block(list_guard) { 287ef9f9732Shoumkh Ok(ret) => return Ok(ret), 288ef9f9732Shoumkh Err(err) => return Err(err), 289ef9f9732Shoumkh } 290c2481452Shoumkh } 291c2481452Shoumkh return Err(MmioResult::ENOFOUND); 292c2481452Shoumkh } else { 293ef9f9732Shoumkh match self.pop_block(list_guard) { 294ef9f9732Shoumkh Ok(ret) => return Ok(ret), 295ef9f9732Shoumkh Err(err) => return Err(err), 296ef9f9732Shoumkh } 297c2481452Shoumkh } 298c2481452Shoumkh } 299c2481452Shoumkh 300c2481452Shoumkh /// @brief 对query_addr_region进行封装 301c2481452Shoumkh /// 302c2481452Shoumkh /// @param exp 内存区域的大小(2^exp) 303c2481452Shoumkh /// 30440fe15e0SLoGin /// @return Ok(MmioBuddyAddrRegion)符合要求的内存块信息结构体。 305c2481452Shoumkh /// @return Err(MmioResult) 没有满足要求的内存块时,返回__query_addr_region的错误码。 30640fe15e0SLoGin fn mmio_buddy_query_addr_region(&self, exp: u32) -> Result<MmioBuddyAddrRegion, MmioResult> { 307*23ef2b33SLoGin let mut list_guard: SpinLockGuard<MmioFreeRegionList> = 308*23ef2b33SLoGin self.free_regions[exp2index(exp)].lock(); 309*23ef2b33SLoGin match self.query_addr_region(exp, &mut list_guard) { 310c2481452Shoumkh Ok(ret) => return Ok(ret), 311c2481452Shoumkh Err(err) => { 312c2481452Shoumkh kdebug!("mmio_buddy_query_addr_region failed"); 313c2481452Shoumkh return Err(err); 314c2481452Shoumkh } 315c2481452Shoumkh } 316c2481452Shoumkh } 317c2481452Shoumkh /// @brief 往指定的地址空间链表中添加一个地址区域 318c2481452Shoumkh /// 319c2481452Shoumkh /// @param region 要被添加的地址结构体 320c2481452Shoumkh /// 321c2481452Shoumkh /// @param list_guard 目标链表 322a7eb62a4Shoumkh fn push_block( 323c2481452Shoumkh &self, 32440fe15e0SLoGin region: MmioBuddyAddrRegion, 325c2481452Shoumkh list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 326c2481452Shoumkh ) { 327c2481452Shoumkh list_guard.list.push_back(region); 328c2481452Shoumkh list_guard.num_free += 1; 329c2481452Shoumkh } 330c2481452Shoumkh 331c2481452Shoumkh /// @brief 根据地址和内存块大小,计算伙伴块虚拟内存的地址 332c2481452Shoumkh #[inline(always)] 33340fe15e0SLoGin fn calculate_block_vaddr(&self, vaddr: VirtAddr, exp: u32) -> VirtAddr { 33440fe15e0SLoGin return VirtAddr::new(vaddr.data() ^ (1 << exp as usize)); 335c2481452Shoumkh } 336c2481452Shoumkh 337c2481452Shoumkh /// @brief 寻找并弹出指定内存块的伙伴块 338c2481452Shoumkh /// 339c2481452Shoumkh /// @param region 对应内存块的信息 340c2481452Shoumkh /// 341c2481452Shoumkh /// @param exp 内存块大小 342c2481452Shoumkh /// 343c2481452Shoumkh /// @param list_guard 【exp】对应的链表 344c2481452Shoumkh /// 345c2481452Shoumkh /// @return Ok(Box<MmioBuddyAddrRegion) 返回伙伴块的引用 346c2481452Shoumkh /// @return Err(MmioResult) 347c2481452Shoumkh /// - 当链表为空,返回ISEMPTY 348c2481452Shoumkh /// - 没有找到伙伴块,返回ENOFOUND 349a7eb62a4Shoumkh fn pop_buddy_block( 350c2481452Shoumkh &self, 35140fe15e0SLoGin vaddr: VirtAddr, 352c2481452Shoumkh exp: u32, 353c2481452Shoumkh list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 35440fe15e0SLoGin ) -> Result<MmioBuddyAddrRegion, MmioResult> { 355b5b571e0SLoGin if list_guard.list.is_empty() { 356c2481452Shoumkh return Err(MmioResult::ISEMPTY); 357c2481452Shoumkh } else { 358c2481452Shoumkh //计算伙伴块的地址 359a7eb62a4Shoumkh let buddy_vaddr = self.calculate_block_vaddr(vaddr, exp); 360c2481452Shoumkh 361c2481452Shoumkh // element 只会有一个元素 36240fe15e0SLoGin let mut element: Vec<MmioBuddyAddrRegion> = list_guard 363c2481452Shoumkh .list 3641a72a751SLoGin .extract_if(|x| x.vaddr == buddy_vaddr) 365c2481452Shoumkh .collect(); 366c2481452Shoumkh if element.len() == 1 { 367c2481452Shoumkh list_guard.num_free -= 1; 368c2481452Shoumkh return Ok(element.pop().unwrap()); 369c2481452Shoumkh } 370c2481452Shoumkh 371c2481452Shoumkh //没有找到对应的伙伴块 372c2481452Shoumkh return Err(MmioResult::ENOFOUND); 373c2481452Shoumkh } 374c2481452Shoumkh } 375c2481452Shoumkh 376c2481452Shoumkh /// @brief 从指定空闲链表中取出内存区域 377c2481452Shoumkh /// 378c2481452Shoumkh /// @param list_guard 【exp】对应的链表 379c2481452Shoumkh /// 38040fe15e0SLoGin /// @return Ok(MmioBuddyAddrRegion) 内存块信息结构体的引用。 381c2481452Shoumkh /// 382c2481452Shoumkh /// @return Err(MmioResult) 当链表为空,无法删除时,返回ISEMPTY 383a7eb62a4Shoumkh fn pop_block( 384c2481452Shoumkh &self, 385c2481452Shoumkh list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 38640fe15e0SLoGin ) -> Result<MmioBuddyAddrRegion, MmioResult> { 387c2481452Shoumkh if !list_guard.list.is_empty() { 388c2481452Shoumkh list_guard.num_free -= 1; 389c2481452Shoumkh return Ok(list_guard.list.pop_back().unwrap()); 390c2481452Shoumkh } 391c2481452Shoumkh return Err(MmioResult::ISEMPTY); 392c2481452Shoumkh } 393c2481452Shoumkh 394c2481452Shoumkh /// @brief 合并所有2^{exp}大小的内存块 395c2481452Shoumkh /// 396c2481452Shoumkh /// @param exp 内存块大小的幂(2^exp) 397c2481452Shoumkh /// 398c2481452Shoumkh /// @param list_guard exp对应的链表 399c2481452Shoumkh /// 400c2481452Shoumkh /// @param high_list_guard exp+1对应的链表 401c2481452Shoumkh /// 402c2481452Shoumkh /// @return Ok(MmioResult) 合并成功返回SUCCESS 403c2481452Shoumkh /// @return Err(MmioResult) 404c2481452Shoumkh /// - 内存块过少,无法合并,返回EINVAL 405a7eb62a4Shoumkh /// - pop_buddy_block调用出错,返回其错误码 406a7eb62a4Shoumkh /// - merge_blocks调用出错,返回其错误码 407a7eb62a4Shoumkh fn merge_all_exp( 408c2481452Shoumkh &self, 409c2481452Shoumkh exp: u32, 410c2481452Shoumkh list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 411c2481452Shoumkh high_list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 412c2481452Shoumkh ) -> Result<MmioResult, MmioResult> { 413c2481452Shoumkh // 至少要两个内存块才能合并 414c2481452Shoumkh if list_guard.num_free <= 1 { 415c2481452Shoumkh return Err(MmioResult::EINVAL); 416c2481452Shoumkh } 417c2481452Shoumkh loop { 418c2481452Shoumkh if list_guard.num_free <= 1 { 419c2481452Shoumkh break; 420c2481452Shoumkh } 421c2481452Shoumkh // 获取内存块 42240fe15e0SLoGin let vaddr: VirtAddr = list_guard.list.back().unwrap().vaddr; 423c2481452Shoumkh // 获取伙伴内存块 424a7eb62a4Shoumkh match self.pop_buddy_block(vaddr, exp, list_guard) { 425c2481452Shoumkh Err(err) => { 426c2481452Shoumkh return Err(err); 427c2481452Shoumkh } 428c2481452Shoumkh Ok(buddy_region) => { 42940fe15e0SLoGin let region: MmioBuddyAddrRegion = list_guard.list.pop_back().unwrap(); 43040fe15e0SLoGin let copy_region = region.clone(); 431c2481452Shoumkh // 在两块内存都被取出之后才进行合并 432a7eb62a4Shoumkh match self.merge_blocks(region, buddy_region, exp, high_list_guard) { 433c2481452Shoumkh Err(err) => { 434c2481452Shoumkh // 如果合并失败了要将取出来的元素放回去 435a7eb62a4Shoumkh self.push_block(copy_region, list_guard); 436a7eb62a4Shoumkh kdebug!("merge_all_exp: merge_blocks failed"); 437c2481452Shoumkh return Err(err); 438c2481452Shoumkh } 439c2481452Shoumkh Ok(_) => continue, 440c2481452Shoumkh } 441c2481452Shoumkh } 442c2481452Shoumkh } 443c2481452Shoumkh } 444c2481452Shoumkh return Ok(MmioResult::SUCCESS); 445c2481452Shoumkh } 446c2481452Shoumkh 447c2481452Shoumkh /// @brief 合并两个【已经从链表中取出】的内存块 448c2481452Shoumkh /// 449c2481452Shoumkh /// @param region_1 第一个内存块 450c2481452Shoumkh /// 451c2481452Shoumkh /// @param region_2 第二个内存 452c2481452Shoumkh /// 453c2481452Shoumkh /// @return Ok(MmioResult) 成功返回SUCCESS 454c2481452Shoumkh /// 455c2481452Shoumkh /// @return Err(MmioResult) 两个内存块不是伙伴块,返回EINVAL 456a7eb62a4Shoumkh fn merge_blocks( 457c2481452Shoumkh &self, 45840fe15e0SLoGin region_1: MmioBuddyAddrRegion, 45940fe15e0SLoGin region_2: MmioBuddyAddrRegion, 460c2481452Shoumkh exp: u32, 461c2481452Shoumkh high_list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 462c2481452Shoumkh ) -> Result<MmioResult, MmioResult> { 463c2481452Shoumkh // 判断是否为伙伴块 464a7eb62a4Shoumkh if region_1.vaddr != self.calculate_block_vaddr(region_2.vaddr, exp) { 465c2481452Shoumkh return Err(MmioResult::EINVAL); 466c2481452Shoumkh } 467c2481452Shoumkh // 将大的块放进下一级链表 468a7eb62a4Shoumkh self.push_block(region_1, high_list_guard); 469c2481452Shoumkh return Ok(MmioResult::SUCCESS); 470c2481452Shoumkh } 471c2481452Shoumkh 472c2481452Shoumkh /// @brief 创建一块mmio区域,并将vma绑定到initial_mm 473c2481452Shoumkh /// 474c2481452Shoumkh /// @param size mmio区域的大小(字节) 475c2481452Shoumkh /// 476c2481452Shoumkh /// @param vm_flags 要把vma设置成的标志 477c2481452Shoumkh /// 478c2481452Shoumkh /// @param res_vaddr 返回值-分配得到的虚拟地址 479c2481452Shoumkh /// 480c2481452Shoumkh /// @param res_length 返回值-分配的虚拟地址空间长度 481c2481452Shoumkh /// 482a7eb62a4Shoumkh /// @return Ok(i32) 成功返回0 483a7eb62a4Shoumkh /// 484676b8ef6SMork /// @return Err(SystemError) 失败返回错误码 4852dd9f0c7SLoGin pub fn create_mmio(&self, size: usize) -> Result<MMIOSpaceGuard, SystemError> { 486c2481452Shoumkh if size > PAGE_1G_SIZE || size == 0 { 487676b8ef6SMork return Err(SystemError::EPERM); 488c2481452Shoumkh } 489c2481452Shoumkh // 计算前导0 4904fda81ceSLoGin #[cfg(any(target_arch = "x86_64", target_arch = "riscv64"))] 49140fe15e0SLoGin let mut size_exp: u32 = 63 - size.leading_zeros(); 4927ae679ddSLoGin // kdebug!("create_mmio: size_exp: {}", size_exp); 493c2481452Shoumkh // 记录最终申请的空间大小 49440fe15e0SLoGin let mut new_size = size; 495c2481452Shoumkh // 对齐要申请的空间大小 496c2481452Shoumkh // 如果要申请的空间大小小于4k,则分配4k 497*23ef2b33SLoGin if size_exp < PAGE_4K_SHIFT as u32 { 49840fe15e0SLoGin new_size = PAGE_4K_SIZE as usize; 499*23ef2b33SLoGin size_exp = PAGE_4K_SHIFT as u32; 500c2481452Shoumkh } else if (new_size & (!(1 << size_exp))) != 0 { 501c2481452Shoumkh // 向左对齐空间大小 502c2481452Shoumkh size_exp += 1; 503c2481452Shoumkh new_size = 1 << size_exp; 504c2481452Shoumkh } 50540fe15e0SLoGin match self.mmio_buddy_query_addr_region(size_exp) { 506c2481452Shoumkh Ok(region) => { 5072dd9f0c7SLoGin let space_guard = 5082dd9f0c7SLoGin unsafe { MMIOSpaceGuard::from_raw(region.vaddr, new_size, false) }; 5092dd9f0c7SLoGin return Ok(space_guard); 510c2481452Shoumkh } 511c2481452Shoumkh Err(_) => { 5121496ba7bSLoGin kerror!( 5131496ba7bSLoGin "failed to create mmio. pid = {:?}", 5141496ba7bSLoGin ProcessManager::current_pcb().pid() 5151496ba7bSLoGin ); 516676b8ef6SMork return Err(SystemError::ENOMEM); 517c2481452Shoumkh } 518c2481452Shoumkh } 519c2481452Shoumkh } 520c2481452Shoumkh 521c2481452Shoumkh /// @brief 取消mmio的映射并将地址空间归还到buddy中 522c2481452Shoumkh /// 523c2481452Shoumkh /// @param vaddr 起始的虚拟地址 524c2481452Shoumkh /// 525c2481452Shoumkh /// @param length 要归还的地址空间的长度 526c2481452Shoumkh /// 527c2481452Shoumkh /// @return Ok(i32) 成功返回0 528c2481452Shoumkh /// 529676b8ef6SMork /// @return Err(SystemError) 失败返回错误码 5307eda31b2SLoGin pub fn release_mmio(&self, vaddr: VirtAddr, length: usize) -> Result<i32, SystemError> { 53140fe15e0SLoGin assert!(vaddr.check_aligned(MMArch::PAGE_SIZE)); 53240fe15e0SLoGin assert!(length & (MMArch::PAGE_SIZE - 1) == 0); 53340fe15e0SLoGin if vaddr < self.pool_start_addr 53440fe15e0SLoGin || vaddr.data() >= self.pool_start_addr.data() + self.pool_size 53540fe15e0SLoGin { 536676b8ef6SMork return Err(SystemError::EINVAL); 537c2481452Shoumkh } 53840fe15e0SLoGin // todo: 重构MMIO管理机制,创建类似全局的manager之类的,管理MMIO的空间? 53940fe15e0SLoGin 54040fe15e0SLoGin // 暂时认为传入的vaddr都是正确的 54140fe15e0SLoGin let page_count = length / MMArch::PAGE_SIZE; 54240fe15e0SLoGin // 取消映射 54340fe15e0SLoGin let mut bindings = KernelMapper::lock(); 54440fe15e0SLoGin let mut kernel_mapper = bindings.as_mut(); 54540fe15e0SLoGin if kernel_mapper.is_none() { 54640fe15e0SLoGin kwarn!("release_mmio: kernel_mapper is read only"); 54740fe15e0SLoGin return Err(SystemError::EAGAIN_OR_EWOULDBLOCK); 548c2481452Shoumkh } 54940fe15e0SLoGin 55040fe15e0SLoGin for i in 0..page_count { 551c2481452Shoumkh unsafe { 5527ae679ddSLoGin let x: Option<( 5537ae679ddSLoGin PhysAddr, 5547ae679ddSLoGin PageFlags<MMArch>, 5557ae679ddSLoGin crate::mm::page::PageFlush<MMArch>, 5567ae679ddSLoGin )> = kernel_mapper 55740fe15e0SLoGin .as_mut() 55840fe15e0SLoGin .unwrap() 5597ae679ddSLoGin .unmap_phys(vaddr + i * MMArch::PAGE_SIZE, false); 5607ae679ddSLoGin if let Some((_, _, flush)) = x { 5617ae679ddSLoGin flush.flush(); 5627ae679ddSLoGin } 56340fe15e0SLoGin }; 564c2481452Shoumkh } 56540fe15e0SLoGin 5667ae679ddSLoGin // 归还到buddy 5677ae679ddSLoGin mmio_pool() 568b5b571e0SLoGin .give_back_block(vaddr, length.trailing_zeros()) 5697ae679ddSLoGin .unwrap_or_else(|err| { 5707ae679ddSLoGin panic!("MMIO release failed: self: {self:?}, err msg: {:?}", err); 5717ae679ddSLoGin }); 57240fe15e0SLoGin 573a7eb62a4Shoumkh return Ok(0); 574a7eb62a4Shoumkh } 575a7eb62a4Shoumkh } 576a7eb62a4Shoumkh 577a7eb62a4Shoumkh /// @brief mmio伙伴系统内部的地址区域结构体 57840fe15e0SLoGin #[derive(Debug, Clone)] 57940fe15e0SLoGin struct MmioBuddyAddrRegion { 58040fe15e0SLoGin vaddr: VirtAddr, 581a7eb62a4Shoumkh } 582a7eb62a4Shoumkh impl MmioBuddyAddrRegion { 58340fe15e0SLoGin pub fn new(vaddr: VirtAddr) -> Self { 58440fe15e0SLoGin return MmioBuddyAddrRegion { vaddr }; 585a7eb62a4Shoumkh } 58640fe15e0SLoGin 58740fe15e0SLoGin #[allow(dead_code)] 58840fe15e0SLoGin pub fn vaddr(&self) -> VirtAddr { 58940fe15e0SLoGin return self.vaddr; 590a7eb62a4Shoumkh } 591a7eb62a4Shoumkh } 592a7eb62a4Shoumkh 593a7eb62a4Shoumkh /// @brief 空闲页数组结构体 594b5b571e0SLoGin #[derive(Debug, Default)] 595a7eb62a4Shoumkh pub struct MmioFreeRegionList { 596a7eb62a4Shoumkh /// 存储mmio_buddy的地址链表 59740fe15e0SLoGin list: LinkedList<MmioBuddyAddrRegion>, 598a7eb62a4Shoumkh /// 空闲块的数量 599a7eb62a4Shoumkh num_free: i64, 600a7eb62a4Shoumkh } 601a7eb62a4Shoumkh impl MmioFreeRegionList { 60264aea4b3SGou Ngai #[allow(dead_code)] 603a7eb62a4Shoumkh fn new() -> Self { 604a7eb62a4Shoumkh return MmioFreeRegionList { 605a7eb62a4Shoumkh ..Default::default() 606a7eb62a4Shoumkh }; 607a7eb62a4Shoumkh } 608a7eb62a4Shoumkh } 609a7eb62a4Shoumkh 610a7eb62a4Shoumkh /// @brief 将内存对象大小的幂转换成内存池中的数组的下标 611a7eb62a4Shoumkh /// 612a7eb62a4Shoumkh /// @param exp内存大小 613a7eb62a4Shoumkh /// 614a7eb62a4Shoumkh /// @return 内存池数组下标 615a7eb62a4Shoumkh #[inline(always)] 616a7eb62a4Shoumkh fn exp2index(exp: u32) -> usize { 617a7eb62a4Shoumkh return (exp - 12) as usize; 618a7eb62a4Shoumkh } 619a7eb62a4Shoumkh 6202dd9f0c7SLoGin #[derive(Debug)] 6212dd9f0c7SLoGin pub struct MMIOSpaceGuard { 6222dd9f0c7SLoGin vaddr: VirtAddr, 6232dd9f0c7SLoGin size: usize, 6242dd9f0c7SLoGin mapped: AtomicBool, 6252dd9f0c7SLoGin } 6262dd9f0c7SLoGin 6272dd9f0c7SLoGin impl MMIOSpaceGuard { 6282dd9f0c7SLoGin pub unsafe fn from_raw(vaddr: VirtAddr, size: usize, mapped: bool) -> Self { 6292dd9f0c7SLoGin // check size 6302dd9f0c7SLoGin assert!( 6312dd9f0c7SLoGin size & (MMArch::PAGE_SIZE - 1) == 0, 6322dd9f0c7SLoGin "MMIO space size must be page aligned" 6332dd9f0c7SLoGin ); 6342dd9f0c7SLoGin assert!(size.is_power_of_two(), "MMIO space size must be power of 2"); 6352dd9f0c7SLoGin assert!( 6362dd9f0c7SLoGin vaddr.check_aligned(size), 6372dd9f0c7SLoGin "MMIO space vaddr must be aligned with size" 6382dd9f0c7SLoGin ); 6392dd9f0c7SLoGin assert!( 640*23ef2b33SLoGin vaddr.data() >= MMArch::MMIO_BASE.data() 641*23ef2b33SLoGin && vaddr.data() + size <= MMArch::MMIO_TOP.data(), 6422dd9f0c7SLoGin "MMIO space must be in MMIO region" 6432dd9f0c7SLoGin ); 6442dd9f0c7SLoGin 6452dd9f0c7SLoGin // 人工创建的MMIO空间,认为已经映射 6462dd9f0c7SLoGin MMIOSpaceGuard { 6472dd9f0c7SLoGin vaddr, 6482dd9f0c7SLoGin size, 6492dd9f0c7SLoGin mapped: AtomicBool::new(mapped), 6502dd9f0c7SLoGin } 6512dd9f0c7SLoGin } 6522dd9f0c7SLoGin 6532dd9f0c7SLoGin pub fn vaddr(&self) -> VirtAddr { 6542dd9f0c7SLoGin self.vaddr 6552dd9f0c7SLoGin } 6562dd9f0c7SLoGin 6572dd9f0c7SLoGin pub fn size(&self) -> usize { 6582dd9f0c7SLoGin self.size 6592dd9f0c7SLoGin } 6602dd9f0c7SLoGin 6612dd9f0c7SLoGin /// 将物理地址填写到虚拟地址空间中 6622dd9f0c7SLoGin /// 6632dd9f0c7SLoGin /// ## Safety 6642dd9f0c7SLoGin /// 6652dd9f0c7SLoGin /// 传入的物理地址【一定要是设备的物理地址】。 6662dd9f0c7SLoGin /// 如果物理地址是从内存分配器中分配的,那么会造成内存泄露。因为mmio_release的时候,只取消映射,不会释放内存。 6677ae679ddSLoGin pub unsafe fn map_phys(&self, paddr: PhysAddr, length: usize) -> Result<(), SystemError> { 6682dd9f0c7SLoGin if length > self.size { 6697ae679ddSLoGin return Err(SystemError::EINVAL); 6702dd9f0c7SLoGin } 6712dd9f0c7SLoGin 6722dd9f0c7SLoGin let check = self 6732dd9f0c7SLoGin .mapped 6742dd9f0c7SLoGin .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst); 6752dd9f0c7SLoGin if check.is_err() { 6767ae679ddSLoGin return Err(SystemError::EINVAL); 6772dd9f0c7SLoGin } 6782dd9f0c7SLoGin 6792dd9f0c7SLoGin let flags = PageFlags::mmio_flags(); 6802dd9f0c7SLoGin let mut kernel_mapper = KernelMapper::lock(); 6812dd9f0c7SLoGin let r = kernel_mapper.map_phys_with_size(self.vaddr, paddr, length, flags, true); 6827ae679ddSLoGin return r; 6832dd9f0c7SLoGin } 6847ae679ddSLoGin 6857ae679ddSLoGin /// 泄露一个MMIO space guard,不会释放映射的空间 6867ae679ddSLoGin pub unsafe fn leak(self) { 6877ae679ddSLoGin core::mem::forget(self); 6882dd9f0c7SLoGin } 6892dd9f0c7SLoGin } 6902dd9f0c7SLoGin 6912dd9f0c7SLoGin impl Drop for MMIOSpaceGuard { 6922dd9f0c7SLoGin fn drop(&mut self) { 6932dd9f0c7SLoGin let _ = mmio_pool() 6942dd9f0c7SLoGin .release_mmio(self.vaddr, self.size) 6952dd9f0c7SLoGin .unwrap_or_else(|err| { 6962dd9f0c7SLoGin panic!("MMIO release failed: self: {self:?}, err msg: {:?}", err); 6972dd9f0c7SLoGin }); 6982dd9f0c7SLoGin } 6992dd9f0c7SLoGin } 7002dd9f0c7SLoGin 70140fe15e0SLoGin pub fn mmio_init() { 70240fe15e0SLoGin kdebug!("Initializing MMIO buddy memory pool..."); 70340fe15e0SLoGin // 初始化mmio内存池 70440fe15e0SLoGin unsafe { 70540fe15e0SLoGin __MMIO_POOL = Some(MmioBuddyMemPool::new()); 70640fe15e0SLoGin } 70740fe15e0SLoGin 70840fe15e0SLoGin kinfo!("MMIO buddy memory pool init done"); 70940fe15e0SLoGin } 710