1a7eb62a4Shoumkh use crate::libs::spinlock::{SpinLock, SpinLockGuard}; 240fe15e0SLoGin use crate::mm::kernel_mapper::KernelMapper; 323ef2b33SLoGin use crate::mm::page::{PAGE_1G_SHIFT, PAGE_4K_SHIFT}; 41496ba7bSLoGin use crate::process::ProcessManager; 5c2481452Shoumkh use crate::{ 640fe15e0SLoGin kdebug, 740fe15e0SLoGin mm::{MMArch, MemoryManagementArch}, 8c2481452Shoumkh }; 940fe15e0SLoGin use crate::{kerror, kinfo, kwarn}; 1040fe15e0SLoGin use alloc::{collections::LinkedList, vec::Vec}; 1140fe15e0SLoGin use core::mem; 1240fe15e0SLoGin use core::mem::MaybeUninit; 1323ef2b33SLoGin use core::sync::atomic::{AtomicBool, Ordering}; 1491e9d4abSLoGin use system_error::SystemError; 1540fe15e0SLoGin 16370472f7SLoGin use super::page::{PageFlags, PAGE_4K_SIZE}; 172dd9f0c7SLoGin use super::{PhysAddr, VirtAddr}; 18c2481452Shoumkh 19c2481452Shoumkh // 最大的伙伴块的幂 2023ef2b33SLoGin const MMIO_BUDDY_MAX_EXP: u32 = PAGE_1G_SHIFT as u32; 21c2481452Shoumkh // 最小的伙伴块的幂 2223ef2b33SLoGin const MMIO_BUDDY_MIN_EXP: u32 = PAGE_4K_SHIFT as u32; 23c2481452Shoumkh // 内存池数组的范围 24c2481452Shoumkh const MMIO_BUDDY_REGION_COUNT: u32 = MMIO_BUDDY_MAX_EXP - MMIO_BUDDY_MIN_EXP + 1; 25c2481452Shoumkh 2640fe15e0SLoGin const PAGE_1G_SIZE: usize = 1 << 30; 2740fe15e0SLoGin 2840fe15e0SLoGin static mut __MMIO_POOL: Option<MmioBuddyMemPool> = None; 2940fe15e0SLoGin 307ae679ddSLoGin pub fn mmio_pool() -> &'static MmioBuddyMemPool { 317ae679ddSLoGin unsafe { __MMIO_POOL.as_ref().unwrap() } 32c2481452Shoumkh } 33c2481452Shoumkh 34c2481452Shoumkh pub enum MmioResult { 35c2481452Shoumkh SUCCESS, 36c2481452Shoumkh EINVAL, 37c2481452Shoumkh ENOFOUND, 38c2481452Shoumkh WRONGEXP, 39c2481452Shoumkh ISEMPTY, 40c2481452Shoumkh } 41c2481452Shoumkh 42c2481452Shoumkh /// @brief buddy内存池 4340fe15e0SLoGin #[derive(Debug)] 44c2481452Shoumkh pub struct MmioBuddyMemPool { 4540fe15e0SLoGin pool_start_addr: VirtAddr, 4640fe15e0SLoGin pool_size: usize, 47c2481452Shoumkh free_regions: [SpinLock<MmioFreeRegionList>; MMIO_BUDDY_REGION_COUNT as usize], 48c2481452Shoumkh } 4940fe15e0SLoGin 50c2481452Shoumkh impl MmioBuddyMemPool { 51453452ccSLoGin #[inline(never)] 52c2481452Shoumkh fn new() -> Self { 5340fe15e0SLoGin let mut free_regions: [MaybeUninit<SpinLock<MmioFreeRegionList>>; 5440fe15e0SLoGin MMIO_BUDDY_REGION_COUNT as usize] = unsafe { MaybeUninit::uninit().assume_init() }; 5540fe15e0SLoGin for i in 0..MMIO_BUDDY_REGION_COUNT { 5640fe15e0SLoGin free_regions[i as usize] = MaybeUninit::new(SpinLock::new(MmioFreeRegionList::new())); 5740fe15e0SLoGin } 5840fe15e0SLoGin let free_regions = unsafe { 5940fe15e0SLoGin mem::transmute::<_, [SpinLock<MmioFreeRegionList>; MMIO_BUDDY_REGION_COUNT as usize]>( 6040fe15e0SLoGin free_regions, 6140fe15e0SLoGin ) 62c2481452Shoumkh }; 6340fe15e0SLoGin 6440fe15e0SLoGin let pool = MmioBuddyMemPool { 6523ef2b33SLoGin pool_start_addr: MMArch::MMIO_BASE, 6623ef2b33SLoGin pool_size: MMArch::MMIO_SIZE, 6740fe15e0SLoGin free_regions, 6840fe15e0SLoGin }; 6923ef2b33SLoGin 7023ef2b33SLoGin assert!(pool.pool_start_addr.data() % PAGE_1G_SIZE == 0); 7140fe15e0SLoGin kdebug!("MMIO buddy pool init: created"); 7240fe15e0SLoGin 7323ef2b33SLoGin let mut vaddr_base = MMArch::MMIO_BASE; 7423ef2b33SLoGin let mut remain_size = MMArch::MMIO_SIZE; 7523ef2b33SLoGin kdebug!( 7623ef2b33SLoGin "BASE: {:?}, TOP: {:?}, size: {:?}", 7723ef2b33SLoGin MMArch::MMIO_BASE, 7823ef2b33SLoGin MMArch::MMIO_TOP, 7923ef2b33SLoGin MMArch::MMIO_SIZE 8023ef2b33SLoGin ); 8123ef2b33SLoGin 8223ef2b33SLoGin for shift in (PAGE_4K_SHIFT..=PAGE_1G_SHIFT).rev() { 8323ef2b33SLoGin if remain_size & (1 << shift) != 0 { 8423ef2b33SLoGin let ok = pool.give_back_block(vaddr_base, shift as u32).is_ok(); 8523ef2b33SLoGin if ok { 8623ef2b33SLoGin vaddr_base += 1 << shift; 8723ef2b33SLoGin remain_size -= 1 << shift; 8823ef2b33SLoGin } else { 8940fe15e0SLoGin panic!("MMIO buddy pool init failed"); 9040fe15e0SLoGin } 9140fe15e0SLoGin } 9240fe15e0SLoGin } 9323ef2b33SLoGin 9440fe15e0SLoGin kdebug!("MMIO buddy pool init success"); 9540fe15e0SLoGin return pool; 96c2481452Shoumkh } 97c2481452Shoumkh 98c2481452Shoumkh /// @brief 创建新的地址区域结构体 99c2481452Shoumkh /// 100c2481452Shoumkh /// @param vaddr 虚拟地址 101c2481452Shoumkh /// 102c2481452Shoumkh /// @return 创建好的地址区域结构体 10340fe15e0SLoGin fn create_region(&self, vaddr: VirtAddr) -> MmioBuddyAddrRegion { 10440fe15e0SLoGin // kdebug!("create_region for vaddr: {vaddr:?}"); 10540fe15e0SLoGin 10640fe15e0SLoGin let region: MmioBuddyAddrRegion = MmioBuddyAddrRegion::new(vaddr); 10740fe15e0SLoGin 10840fe15e0SLoGin // kdebug!("create_region for vaddr: {vaddr:?} OK!!!"); 109c2481452Shoumkh return region; 110c2481452Shoumkh } 111c2481452Shoumkh 112c2481452Shoumkh /// @brief 将内存块归还给buddy 113c2481452Shoumkh /// 114c2481452Shoumkh /// @param vaddr 虚拟地址 115c2481452Shoumkh /// 116c2481452Shoumkh /// @param exp 内存空间的大小(2^exp) 117c2481452Shoumkh /// 118c2481452Shoumkh /// @param list_guard 【exp】对应的链表 119c2481452Shoumkh /// 120c2481452Shoumkh /// @return Ok(i32) 返回0 121c2481452Shoumkh /// 122676b8ef6SMork /// @return Err(SystemError) 返回错误码 12340fe15e0SLoGin fn give_back_block(&self, vaddr: VirtAddr, exp: u32) -> Result<i32, SystemError> { 124c2481452Shoumkh // 确保内存对齐,低位都要为0 12540fe15e0SLoGin if (vaddr.data() & ((1 << exp) - 1)) != 0 { 126676b8ef6SMork return Err(SystemError::EINVAL); 127c2481452Shoumkh } 12840fe15e0SLoGin let region: MmioBuddyAddrRegion = self.create_region(vaddr); 129c2481452Shoumkh // 加入buddy 13040fe15e0SLoGin let mut list_guard = self.free_regions[exp2index(exp)].lock(); 13140fe15e0SLoGin 13240fe15e0SLoGin self.push_block(region, &mut list_guard); 133c2481452Shoumkh return Ok(0); 134c2481452Shoumkh } 135c2481452Shoumkh 136c2481452Shoumkh /// @brief 将给定大小为2^{exp}的内存块一分为二,并插入内存块大小为2^{exp-1}的链表中 137c2481452Shoumkh /// 138c2481452Shoumkh /// @param region 要被分割的地址区域结构体(保证其已经从链表中取出) 139c2481452Shoumkh /// 140c2481452Shoumkh /// @param exp 要被分割的地址区域的大小的幂 141c2481452Shoumkh /// 142c2481452Shoumkh /// @param list_guard 【exp-1】对应的链表 143a7eb62a4Shoumkh fn split_block( 144c2481452Shoumkh &self, 14540fe15e0SLoGin region: MmioBuddyAddrRegion, 146c2481452Shoumkh exp: u32, 147c2481452Shoumkh low_list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 148c2481452Shoumkh ) { 14940fe15e0SLoGin let vaddr = self.calculate_block_vaddr(region.vaddr, exp - 1); 15040fe15e0SLoGin let new_region: MmioBuddyAddrRegion = self.create_region(vaddr); 151a7eb62a4Shoumkh self.push_block(region, low_list_guard); 152a7eb62a4Shoumkh self.push_block(new_region, low_list_guard); 153c2481452Shoumkh } 154c2481452Shoumkh 155c2481452Shoumkh /// @brief 从buddy中申请一块指定大小的内存区域 156c2481452Shoumkh /// 157c2481452Shoumkh /// @param exp 要申请的内存块的大小的幂(2^exp) 158c2481452Shoumkh /// 159c2481452Shoumkh /// @param list_guard exp对应的链表 160c2481452Shoumkh /// 16140fe15e0SLoGin /// @return Ok(MmioBuddyAddrRegion) 符合要求的内存区域。 162c2481452Shoumkh /// 163c2481452Shoumkh /// @return Err(MmioResult) 164c2481452Shoumkh /// - 没有满足要求的内存块时,返回ENOFOUND 165c2481452Shoumkh /// - 申请的内存块大小超过合法范围,返回WRONGEXP 166c2481452Shoumkh /// - 调用函数出错时,返回出错函数对应错误码 167a7eb62a4Shoumkh fn query_addr_region( 168c2481452Shoumkh &self, 169c2481452Shoumkh exp: u32, 170c2481452Shoumkh list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 17140fe15e0SLoGin ) -> Result<MmioBuddyAddrRegion, MmioResult> { 172c2481452Shoumkh // 申请范围错误 173b5b571e0SLoGin if !(MMIO_BUDDY_MIN_EXP..=MMIO_BUDDY_MAX_EXP).contains(&exp) { 174a7eb62a4Shoumkh kdebug!("query_addr_region: exp wrong"); 175c2481452Shoumkh return Err(MmioResult::WRONGEXP); 176c2481452Shoumkh } 177c2481452Shoumkh // 没有恰好符合要求的内存块 178c2481452Shoumkh // 注意:exp对应的链表list_guard已上锁【注意避免死锁问题】 179c2481452Shoumkh if list_guard.num_free == 0 { 180c2481452Shoumkh // 找到最小符合申请范围的内存块 181c2481452Shoumkh // 将大的内存块依次分成小块内存,直到能够满足exp大小,即将exp+1分成两块exp 182c2481452Shoumkh for e in exp + 1..MMIO_BUDDY_MAX_EXP + 1 { 183ef9f9732Shoumkh let pop_list: &mut SpinLockGuard<MmioFreeRegionList> = 184b5b571e0SLoGin &mut self.free_regions[exp2index(e)].lock(); 185ef9f9732Shoumkh if pop_list.num_free == 0 { 186c2481452Shoumkh continue; 187c2481452Shoumkh } 188ef9f9732Shoumkh 189c2481452Shoumkh for e2 in (exp + 1..e + 1).rev() { 190ef9f9732Shoumkh if e2 == e { 191ef9f9732Shoumkh match self.pop_block(pop_list) { 192ef9f9732Shoumkh Ok(region) => { 193ef9f9732Shoumkh if e2 != exp + 1 { 194ef9f9732Shoumkh // 要将分裂后的内存块插入到更小的链表中 195ef9f9732Shoumkh let low_list_guard: &mut SpinLockGuard<MmioFreeRegionList> = 196b5b571e0SLoGin &mut self.free_regions[exp2index(e2 - 1)].lock(); 197ef9f9732Shoumkh self.split_block(region, e2, low_list_guard); 198ef9f9732Shoumkh } else { 199ef9f9732Shoumkh // 由于exp对应的链表list_guard已经被锁住了 不能再加锁 200ef9f9732Shoumkh // 所以直接将list_guard传入 201ef9f9732Shoumkh self.split_block(region, e2, list_guard); 202ef9f9732Shoumkh } 203ef9f9732Shoumkh } 204ef9f9732Shoumkh Err(err) => { 205ef9f9732Shoumkh kdebug!("buddy_pop_region get wrong"); 206ef9f9732Shoumkh return Err(err); 207ef9f9732Shoumkh } 208ef9f9732Shoumkh } 209ef9f9732Shoumkh } else { 210b5b571e0SLoGin match self.pop_block(&mut self.free_regions[exp2index(e2)].lock()) { 211c2481452Shoumkh Ok(region) => { 212c2481452Shoumkh if e2 != exp + 1 { 213c2481452Shoumkh // 要将分裂后的内存块插入到更小的链表中 214c2481452Shoumkh let low_list_guard: &mut SpinLockGuard<MmioFreeRegionList> = 215b5b571e0SLoGin &mut self.free_regions[exp2index(e2 - 1)].lock(); 216a7eb62a4Shoumkh self.split_block(region, e2, low_list_guard); 217c2481452Shoumkh } else { 218c2481452Shoumkh // 由于exp对应的链表list_guard已经被锁住了 不能再加锁 219c2481452Shoumkh // 所以直接将list_guard传入 220a7eb62a4Shoumkh self.split_block(region, e2, list_guard); 221c2481452Shoumkh } 222c2481452Shoumkh } 223c2481452Shoumkh Err(err) => { 224c2481452Shoumkh kdebug!("buddy_pop_region get wrong"); 225c2481452Shoumkh return Err(err); 226c2481452Shoumkh } 227c2481452Shoumkh } 228c2481452Shoumkh } 229ef9f9732Shoumkh } 230c2481452Shoumkh break; 231c2481452Shoumkh } 232c2481452Shoumkh // 判断是否获得了exp大小的内存块 233c2481452Shoumkh if list_guard.num_free > 0 { 234ef9f9732Shoumkh match self.pop_block(list_guard) { 235ef9f9732Shoumkh Ok(ret) => return Ok(ret), 236ef9f9732Shoumkh Err(err) => return Err(err), 237ef9f9732Shoumkh } 238c2481452Shoumkh } 239c2481452Shoumkh // 拆分大内存块无法获得exp大小内存块 240c2481452Shoumkh // 尝试用小内存块合成 241c2481452Shoumkh // 即将两块exp合成一块exp+1 242ef9f9732Shoumkh 243ef9f9732Shoumkh // TODO:修改下一个循环的冗余代码,请不要删除此处的注释 244ef9f9732Shoumkh // let merge = |high_list_guard: &mut SpinLockGuard<MmioFreeRegionList>, exp: u32| { 245ef9f9732Shoumkh // if let Err(err) = self.merge_all_exp( 246ef9f9732Shoumkh // exp, 247ef9f9732Shoumkh // &mut self.free_regions[exp2index(exp) as usize].lock(), 248ef9f9732Shoumkh // high_list_guard, 249ef9f9732Shoumkh // ) { 250ef9f9732Shoumkh // return err; 251ef9f9732Shoumkh // } else { 252ef9f9732Shoumkh // return MmioResult::SUCCESS; 253ef9f9732Shoumkh // } 254ef9f9732Shoumkh // }; 255c2481452Shoumkh for e in MMIO_BUDDY_MIN_EXP..exp { 256c2481452Shoumkh if e != exp - 1 { 257a7eb62a4Shoumkh match self.merge_all_exp( 258ef9f9732Shoumkh exp, 259b5b571e0SLoGin &mut self.free_regions[exp2index(exp)].lock(), 260ef9f9732Shoumkh &mut self.free_regions[exp2index(exp + 1)].lock(), 261c2481452Shoumkh ) { 262c2481452Shoumkh Ok(_) => continue, 263c2481452Shoumkh Err(err) => { 264ef9f9732Shoumkh kdebug!("merge_all_exp get wrong"); 265c2481452Shoumkh return Err(err); 266c2481452Shoumkh } 267c2481452Shoumkh } 268c2481452Shoumkh } else { 269a7eb62a4Shoumkh match self.merge_all_exp( 270ef9f9732Shoumkh exp, 271b5b571e0SLoGin &mut self.free_regions[exp2index(exp)].lock(), 272c2481452Shoumkh list_guard, 273c2481452Shoumkh ) { 274c2481452Shoumkh Ok(_) => continue, 275c2481452Shoumkh Err(err) => { 276ef9f9732Shoumkh kdebug!("merge_all_exp get wrong"); 277c2481452Shoumkh return Err(err); 278c2481452Shoumkh } 279c2481452Shoumkh } 280c2481452Shoumkh } 281c2481452Shoumkh } 282c2481452Shoumkh 283c2481452Shoumkh //判断是否获得了exp大小的内存块 284c2481452Shoumkh if list_guard.num_free > 0 { 285ef9f9732Shoumkh match self.pop_block(list_guard) { 286ef9f9732Shoumkh Ok(ret) => return Ok(ret), 287ef9f9732Shoumkh Err(err) => return Err(err), 288ef9f9732Shoumkh } 289c2481452Shoumkh } 290c2481452Shoumkh return Err(MmioResult::ENOFOUND); 291c2481452Shoumkh } else { 292ef9f9732Shoumkh match self.pop_block(list_guard) { 293ef9f9732Shoumkh Ok(ret) => return Ok(ret), 294ef9f9732Shoumkh Err(err) => return Err(err), 295ef9f9732Shoumkh } 296c2481452Shoumkh } 297c2481452Shoumkh } 298c2481452Shoumkh 299c2481452Shoumkh /// @brief 对query_addr_region进行封装 300c2481452Shoumkh /// 301c2481452Shoumkh /// @param exp 内存区域的大小(2^exp) 302c2481452Shoumkh /// 30340fe15e0SLoGin /// @return Ok(MmioBuddyAddrRegion)符合要求的内存块信息结构体。 304c2481452Shoumkh /// @return Err(MmioResult) 没有满足要求的内存块时,返回__query_addr_region的错误码。 30540fe15e0SLoGin fn mmio_buddy_query_addr_region(&self, exp: u32) -> Result<MmioBuddyAddrRegion, MmioResult> { 30623ef2b33SLoGin let mut list_guard: SpinLockGuard<MmioFreeRegionList> = 30723ef2b33SLoGin self.free_regions[exp2index(exp)].lock(); 30823ef2b33SLoGin match self.query_addr_region(exp, &mut list_guard) { 309c2481452Shoumkh Ok(ret) => return Ok(ret), 310c2481452Shoumkh Err(err) => { 311c2481452Shoumkh kdebug!("mmio_buddy_query_addr_region failed"); 312c2481452Shoumkh return Err(err); 313c2481452Shoumkh } 314c2481452Shoumkh } 315c2481452Shoumkh } 316c2481452Shoumkh /// @brief 往指定的地址空间链表中添加一个地址区域 317c2481452Shoumkh /// 318c2481452Shoumkh /// @param region 要被添加的地址结构体 319c2481452Shoumkh /// 320c2481452Shoumkh /// @param list_guard 目标链表 321a7eb62a4Shoumkh fn push_block( 322c2481452Shoumkh &self, 32340fe15e0SLoGin region: MmioBuddyAddrRegion, 324c2481452Shoumkh list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 325c2481452Shoumkh ) { 326c2481452Shoumkh list_guard.list.push_back(region); 327c2481452Shoumkh list_guard.num_free += 1; 328c2481452Shoumkh } 329c2481452Shoumkh 330c2481452Shoumkh /// @brief 根据地址和内存块大小,计算伙伴块虚拟内存的地址 331c2481452Shoumkh #[inline(always)] 33240fe15e0SLoGin fn calculate_block_vaddr(&self, vaddr: VirtAddr, exp: u32) -> VirtAddr { 33340fe15e0SLoGin return VirtAddr::new(vaddr.data() ^ (1 << exp as usize)); 334c2481452Shoumkh } 335c2481452Shoumkh 336c2481452Shoumkh /// @brief 寻找并弹出指定内存块的伙伴块 337c2481452Shoumkh /// 338c2481452Shoumkh /// @param region 对应内存块的信息 339c2481452Shoumkh /// 340c2481452Shoumkh /// @param exp 内存块大小 341c2481452Shoumkh /// 342c2481452Shoumkh /// @param list_guard 【exp】对应的链表 343c2481452Shoumkh /// 344c2481452Shoumkh /// @return Ok(Box<MmioBuddyAddrRegion) 返回伙伴块的引用 345c2481452Shoumkh /// @return Err(MmioResult) 346c2481452Shoumkh /// - 当链表为空,返回ISEMPTY 347c2481452Shoumkh /// - 没有找到伙伴块,返回ENOFOUND 348a7eb62a4Shoumkh fn pop_buddy_block( 349c2481452Shoumkh &self, 35040fe15e0SLoGin vaddr: VirtAddr, 351c2481452Shoumkh exp: u32, 352c2481452Shoumkh list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 35340fe15e0SLoGin ) -> Result<MmioBuddyAddrRegion, MmioResult> { 354b5b571e0SLoGin if list_guard.list.is_empty() { 355c2481452Shoumkh return Err(MmioResult::ISEMPTY); 356c2481452Shoumkh } else { 357c2481452Shoumkh //计算伙伴块的地址 358a7eb62a4Shoumkh let buddy_vaddr = self.calculate_block_vaddr(vaddr, exp); 359c2481452Shoumkh 360c2481452Shoumkh // element 只会有一个元素 36140fe15e0SLoGin let mut element: Vec<MmioBuddyAddrRegion> = list_guard 362c2481452Shoumkh .list 3631a72a751SLoGin .extract_if(|x| x.vaddr == buddy_vaddr) 364c2481452Shoumkh .collect(); 365c2481452Shoumkh if element.len() == 1 { 366c2481452Shoumkh list_guard.num_free -= 1; 367c2481452Shoumkh return Ok(element.pop().unwrap()); 368c2481452Shoumkh } 369c2481452Shoumkh 370c2481452Shoumkh //没有找到对应的伙伴块 371c2481452Shoumkh return Err(MmioResult::ENOFOUND); 372c2481452Shoumkh } 373c2481452Shoumkh } 374c2481452Shoumkh 375c2481452Shoumkh /// @brief 从指定空闲链表中取出内存区域 376c2481452Shoumkh /// 377c2481452Shoumkh /// @param list_guard 【exp】对应的链表 378c2481452Shoumkh /// 37940fe15e0SLoGin /// @return Ok(MmioBuddyAddrRegion) 内存块信息结构体的引用。 380c2481452Shoumkh /// 381c2481452Shoumkh /// @return Err(MmioResult) 当链表为空,无法删除时,返回ISEMPTY 382a7eb62a4Shoumkh fn pop_block( 383c2481452Shoumkh &self, 384c2481452Shoumkh list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 38540fe15e0SLoGin ) -> Result<MmioBuddyAddrRegion, MmioResult> { 386c2481452Shoumkh if !list_guard.list.is_empty() { 387c2481452Shoumkh list_guard.num_free -= 1; 388c2481452Shoumkh return Ok(list_guard.list.pop_back().unwrap()); 389c2481452Shoumkh } 390c2481452Shoumkh return Err(MmioResult::ISEMPTY); 391c2481452Shoumkh } 392c2481452Shoumkh 393c2481452Shoumkh /// @brief 合并所有2^{exp}大小的内存块 394c2481452Shoumkh /// 395c2481452Shoumkh /// @param exp 内存块大小的幂(2^exp) 396c2481452Shoumkh /// 397c2481452Shoumkh /// @param list_guard exp对应的链表 398c2481452Shoumkh /// 399c2481452Shoumkh /// @param high_list_guard exp+1对应的链表 400c2481452Shoumkh /// 401c2481452Shoumkh /// @return Ok(MmioResult) 合并成功返回SUCCESS 402c2481452Shoumkh /// @return Err(MmioResult) 403c2481452Shoumkh /// - 内存块过少,无法合并,返回EINVAL 404a7eb62a4Shoumkh /// - pop_buddy_block调用出错,返回其错误码 405a7eb62a4Shoumkh /// - merge_blocks调用出错,返回其错误码 406a7eb62a4Shoumkh fn merge_all_exp( 407c2481452Shoumkh &self, 408c2481452Shoumkh exp: u32, 409c2481452Shoumkh list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 410c2481452Shoumkh high_list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 411c2481452Shoumkh ) -> Result<MmioResult, MmioResult> { 412c2481452Shoumkh // 至少要两个内存块才能合并 413c2481452Shoumkh if list_guard.num_free <= 1 { 414c2481452Shoumkh return Err(MmioResult::EINVAL); 415c2481452Shoumkh } 416c2481452Shoumkh loop { 417c2481452Shoumkh if list_guard.num_free <= 1 { 418c2481452Shoumkh break; 419c2481452Shoumkh } 420c2481452Shoumkh // 获取内存块 42140fe15e0SLoGin let vaddr: VirtAddr = list_guard.list.back().unwrap().vaddr; 422c2481452Shoumkh // 获取伙伴内存块 423a7eb62a4Shoumkh match self.pop_buddy_block(vaddr, exp, list_guard) { 424c2481452Shoumkh Err(err) => { 425c2481452Shoumkh return Err(err); 426c2481452Shoumkh } 427c2481452Shoumkh Ok(buddy_region) => { 42840fe15e0SLoGin let region: MmioBuddyAddrRegion = list_guard.list.pop_back().unwrap(); 42940fe15e0SLoGin let copy_region = region.clone(); 430c2481452Shoumkh // 在两块内存都被取出之后才进行合并 431a7eb62a4Shoumkh match self.merge_blocks(region, buddy_region, exp, high_list_guard) { 432c2481452Shoumkh Err(err) => { 433c2481452Shoumkh // 如果合并失败了要将取出来的元素放回去 434a7eb62a4Shoumkh self.push_block(copy_region, list_guard); 435a7eb62a4Shoumkh kdebug!("merge_all_exp: merge_blocks failed"); 436c2481452Shoumkh return Err(err); 437c2481452Shoumkh } 438c2481452Shoumkh Ok(_) => continue, 439c2481452Shoumkh } 440c2481452Shoumkh } 441c2481452Shoumkh } 442c2481452Shoumkh } 443c2481452Shoumkh return Ok(MmioResult::SUCCESS); 444c2481452Shoumkh } 445c2481452Shoumkh 446c2481452Shoumkh /// @brief 合并两个【已经从链表中取出】的内存块 447c2481452Shoumkh /// 448c2481452Shoumkh /// @param region_1 第一个内存块 449c2481452Shoumkh /// 450c2481452Shoumkh /// @param region_2 第二个内存 451c2481452Shoumkh /// 452c2481452Shoumkh /// @return Ok(MmioResult) 成功返回SUCCESS 453c2481452Shoumkh /// 454c2481452Shoumkh /// @return Err(MmioResult) 两个内存块不是伙伴块,返回EINVAL 455a7eb62a4Shoumkh fn merge_blocks( 456c2481452Shoumkh &self, 45740fe15e0SLoGin region_1: MmioBuddyAddrRegion, 45840fe15e0SLoGin region_2: MmioBuddyAddrRegion, 459c2481452Shoumkh exp: u32, 460c2481452Shoumkh high_list_guard: &mut SpinLockGuard<MmioFreeRegionList>, 461c2481452Shoumkh ) -> Result<MmioResult, MmioResult> { 462c2481452Shoumkh // 判断是否为伙伴块 463a7eb62a4Shoumkh if region_1.vaddr != self.calculate_block_vaddr(region_2.vaddr, exp) { 464c2481452Shoumkh return Err(MmioResult::EINVAL); 465c2481452Shoumkh } 466c2481452Shoumkh // 将大的块放进下一级链表 467a7eb62a4Shoumkh self.push_block(region_1, high_list_guard); 468c2481452Shoumkh return Ok(MmioResult::SUCCESS); 469c2481452Shoumkh } 470c2481452Shoumkh 471c2481452Shoumkh /// @brief 创建一块mmio区域,并将vma绑定到initial_mm 472c2481452Shoumkh /// 473c2481452Shoumkh /// @param size mmio区域的大小(字节) 474c2481452Shoumkh /// 475c2481452Shoumkh /// @param vm_flags 要把vma设置成的标志 476c2481452Shoumkh /// 477c2481452Shoumkh /// @param res_vaddr 返回值-分配得到的虚拟地址 478c2481452Shoumkh /// 479c2481452Shoumkh /// @param res_length 返回值-分配的虚拟地址空间长度 480c2481452Shoumkh /// 481a7eb62a4Shoumkh /// @return Ok(i32) 成功返回0 482a7eb62a4Shoumkh /// 483676b8ef6SMork /// @return Err(SystemError) 失败返回错误码 4842dd9f0c7SLoGin pub fn create_mmio(&self, size: usize) -> Result<MMIOSpaceGuard, SystemError> { 485c2481452Shoumkh if size > PAGE_1G_SIZE || size == 0 { 486676b8ef6SMork return Err(SystemError::EPERM); 487c2481452Shoumkh } 488c2481452Shoumkh // 计算前导0 4894fda81ceSLoGin #[cfg(any(target_arch = "x86_64", target_arch = "riscv64"))] 49040fe15e0SLoGin let mut size_exp: u32 = 63 - size.leading_zeros(); 4917ae679ddSLoGin // kdebug!("create_mmio: size_exp: {}", size_exp); 492c2481452Shoumkh // 记录最终申请的空间大小 49340fe15e0SLoGin let mut new_size = size; 494c2481452Shoumkh // 对齐要申请的空间大小 495c2481452Shoumkh // 如果要申请的空间大小小于4k,则分配4k 49623ef2b33SLoGin if size_exp < PAGE_4K_SHIFT as u32 { 497370472f7SLoGin new_size = PAGE_4K_SIZE; 49823ef2b33SLoGin size_exp = PAGE_4K_SHIFT as u32; 499c2481452Shoumkh } else if (new_size & (!(1 << size_exp))) != 0 { 500c2481452Shoumkh // 向左对齐空间大小 501c2481452Shoumkh size_exp += 1; 502c2481452Shoumkh new_size = 1 << size_exp; 503c2481452Shoumkh } 50440fe15e0SLoGin match self.mmio_buddy_query_addr_region(size_exp) { 505c2481452Shoumkh Ok(region) => { 5062dd9f0c7SLoGin let space_guard = 5072dd9f0c7SLoGin unsafe { MMIOSpaceGuard::from_raw(region.vaddr, new_size, false) }; 5082dd9f0c7SLoGin return Ok(space_guard); 509c2481452Shoumkh } 510c2481452Shoumkh Err(_) => { 5111496ba7bSLoGin kerror!( 5121496ba7bSLoGin "failed to create mmio. pid = {:?}", 5131496ba7bSLoGin ProcessManager::current_pcb().pid() 5141496ba7bSLoGin ); 515676b8ef6SMork return Err(SystemError::ENOMEM); 516c2481452Shoumkh } 517c2481452Shoumkh } 518c2481452Shoumkh } 519c2481452Shoumkh 520c2481452Shoumkh /// @brief 取消mmio的映射并将地址空间归还到buddy中 521c2481452Shoumkh /// 522c2481452Shoumkh /// @param vaddr 起始的虚拟地址 523c2481452Shoumkh /// 524c2481452Shoumkh /// @param length 要归还的地址空间的长度 525c2481452Shoumkh /// 526c2481452Shoumkh /// @return Ok(i32) 成功返回0 527c2481452Shoumkh /// 528676b8ef6SMork /// @return Err(SystemError) 失败返回错误码 5297eda31b2SLoGin pub fn release_mmio(&self, vaddr: VirtAddr, length: usize) -> Result<i32, SystemError> { 53040fe15e0SLoGin assert!(vaddr.check_aligned(MMArch::PAGE_SIZE)); 53140fe15e0SLoGin assert!(length & (MMArch::PAGE_SIZE - 1) == 0); 53240fe15e0SLoGin if vaddr < self.pool_start_addr 53340fe15e0SLoGin || vaddr.data() >= self.pool_start_addr.data() + self.pool_size 53440fe15e0SLoGin { 535676b8ef6SMork return Err(SystemError::EINVAL); 536c2481452Shoumkh } 53740fe15e0SLoGin // todo: 重构MMIO管理机制,创建类似全局的manager之类的,管理MMIO的空间? 53840fe15e0SLoGin 53940fe15e0SLoGin // 暂时认为传入的vaddr都是正确的 54040fe15e0SLoGin let page_count = length / MMArch::PAGE_SIZE; 54140fe15e0SLoGin // 取消映射 54240fe15e0SLoGin let mut bindings = KernelMapper::lock(); 54340fe15e0SLoGin let mut kernel_mapper = bindings.as_mut(); 54440fe15e0SLoGin if kernel_mapper.is_none() { 54540fe15e0SLoGin kwarn!("release_mmio: kernel_mapper is read only"); 54640fe15e0SLoGin return Err(SystemError::EAGAIN_OR_EWOULDBLOCK); 547c2481452Shoumkh } 54840fe15e0SLoGin 54940fe15e0SLoGin for i in 0..page_count { 550c2481452Shoumkh unsafe { 5517ae679ddSLoGin let x: Option<( 5527ae679ddSLoGin PhysAddr, 5537ae679ddSLoGin PageFlags<MMArch>, 5547ae679ddSLoGin crate::mm::page::PageFlush<MMArch>, 5557ae679ddSLoGin )> = kernel_mapper 55640fe15e0SLoGin .as_mut() 55740fe15e0SLoGin .unwrap() 5587ae679ddSLoGin .unmap_phys(vaddr + i * MMArch::PAGE_SIZE, false); 5597ae679ddSLoGin if let Some((_, _, flush)) = x { 5607ae679ddSLoGin flush.flush(); 5617ae679ddSLoGin } 56240fe15e0SLoGin }; 563c2481452Shoumkh } 56440fe15e0SLoGin 5657ae679ddSLoGin // 归还到buddy 5667ae679ddSLoGin mmio_pool() 567b5b571e0SLoGin .give_back_block(vaddr, length.trailing_zeros()) 5687ae679ddSLoGin .unwrap_or_else(|err| { 5697ae679ddSLoGin panic!("MMIO release failed: self: {self:?}, err msg: {:?}", err); 5707ae679ddSLoGin }); 57140fe15e0SLoGin 572a7eb62a4Shoumkh return Ok(0); 573a7eb62a4Shoumkh } 574a7eb62a4Shoumkh } 575a7eb62a4Shoumkh 576a7eb62a4Shoumkh /// @brief mmio伙伴系统内部的地址区域结构体 57740fe15e0SLoGin #[derive(Debug, Clone)] 57840fe15e0SLoGin struct MmioBuddyAddrRegion { 57940fe15e0SLoGin vaddr: VirtAddr, 580a7eb62a4Shoumkh } 581a7eb62a4Shoumkh impl MmioBuddyAddrRegion { 58240fe15e0SLoGin pub fn new(vaddr: VirtAddr) -> Self { 58340fe15e0SLoGin return MmioBuddyAddrRegion { vaddr }; 584a7eb62a4Shoumkh } 58540fe15e0SLoGin 58640fe15e0SLoGin #[allow(dead_code)] 58740fe15e0SLoGin pub fn vaddr(&self) -> VirtAddr { 58840fe15e0SLoGin return self.vaddr; 589a7eb62a4Shoumkh } 590a7eb62a4Shoumkh } 591a7eb62a4Shoumkh 592a7eb62a4Shoumkh /// @brief 空闲页数组结构体 593b5b571e0SLoGin #[derive(Debug, Default)] 594a7eb62a4Shoumkh pub struct MmioFreeRegionList { 595a7eb62a4Shoumkh /// 存储mmio_buddy的地址链表 59640fe15e0SLoGin list: LinkedList<MmioBuddyAddrRegion>, 597a7eb62a4Shoumkh /// 空闲块的数量 598a7eb62a4Shoumkh num_free: i64, 599a7eb62a4Shoumkh } 600a7eb62a4Shoumkh impl MmioFreeRegionList { 60164aea4b3SGou Ngai #[allow(dead_code)] 602a7eb62a4Shoumkh fn new() -> Self { 603a7eb62a4Shoumkh return MmioFreeRegionList { 604a7eb62a4Shoumkh ..Default::default() 605a7eb62a4Shoumkh }; 606a7eb62a4Shoumkh } 607a7eb62a4Shoumkh } 608a7eb62a4Shoumkh 609a7eb62a4Shoumkh /// @brief 将内存对象大小的幂转换成内存池中的数组的下标 610a7eb62a4Shoumkh /// 611a7eb62a4Shoumkh /// @param exp内存大小 612a7eb62a4Shoumkh /// 613a7eb62a4Shoumkh /// @return 内存池数组下标 614a7eb62a4Shoumkh #[inline(always)] 615a7eb62a4Shoumkh fn exp2index(exp: u32) -> usize { 616a7eb62a4Shoumkh return (exp - 12) as usize; 617a7eb62a4Shoumkh } 618a7eb62a4Shoumkh 6192dd9f0c7SLoGin #[derive(Debug)] 6202dd9f0c7SLoGin pub struct MMIOSpaceGuard { 6212dd9f0c7SLoGin vaddr: VirtAddr, 6222dd9f0c7SLoGin size: usize, 6232dd9f0c7SLoGin mapped: AtomicBool, 6242dd9f0c7SLoGin } 6252dd9f0c7SLoGin 6262dd9f0c7SLoGin impl MMIOSpaceGuard { 6272dd9f0c7SLoGin pub unsafe fn from_raw(vaddr: VirtAddr, size: usize, mapped: bool) -> Self { 6282dd9f0c7SLoGin // check size 6292dd9f0c7SLoGin assert!( 6302dd9f0c7SLoGin size & (MMArch::PAGE_SIZE - 1) == 0, 6312dd9f0c7SLoGin "MMIO space size must be page aligned" 6322dd9f0c7SLoGin ); 6332dd9f0c7SLoGin assert!(size.is_power_of_two(), "MMIO space size must be power of 2"); 6342dd9f0c7SLoGin assert!( 6352dd9f0c7SLoGin vaddr.check_aligned(size), 6362dd9f0c7SLoGin "MMIO space vaddr must be aligned with size" 6372dd9f0c7SLoGin ); 6382dd9f0c7SLoGin assert!( 63923ef2b33SLoGin vaddr.data() >= MMArch::MMIO_BASE.data() 64023ef2b33SLoGin && vaddr.data() + size <= MMArch::MMIO_TOP.data(), 6412dd9f0c7SLoGin "MMIO space must be in MMIO region" 6422dd9f0c7SLoGin ); 6432dd9f0c7SLoGin 6442dd9f0c7SLoGin // 人工创建的MMIO空间,认为已经映射 6452dd9f0c7SLoGin MMIOSpaceGuard { 6462dd9f0c7SLoGin vaddr, 6472dd9f0c7SLoGin size, 6482dd9f0c7SLoGin mapped: AtomicBool::new(mapped), 6492dd9f0c7SLoGin } 6502dd9f0c7SLoGin } 6512dd9f0c7SLoGin 6522dd9f0c7SLoGin pub fn vaddr(&self) -> VirtAddr { 6532dd9f0c7SLoGin self.vaddr 6542dd9f0c7SLoGin } 6552dd9f0c7SLoGin 6562dd9f0c7SLoGin pub fn size(&self) -> usize { 6572dd9f0c7SLoGin self.size 6582dd9f0c7SLoGin } 6592dd9f0c7SLoGin 6602dd9f0c7SLoGin /// 将物理地址填写到虚拟地址空间中 6612dd9f0c7SLoGin /// 6622dd9f0c7SLoGin /// ## Safety 6632dd9f0c7SLoGin /// 6642dd9f0c7SLoGin /// 传入的物理地址【一定要是设备的物理地址】。 6652dd9f0c7SLoGin /// 如果物理地址是从内存分配器中分配的,那么会造成内存泄露。因为mmio_release的时候,只取消映射,不会释放内存。 6667ae679ddSLoGin pub unsafe fn map_phys(&self, paddr: PhysAddr, length: usize) -> Result<(), SystemError> { 6672dd9f0c7SLoGin if length > self.size { 6687ae679ddSLoGin return Err(SystemError::EINVAL); 6692dd9f0c7SLoGin } 6702dd9f0c7SLoGin 6712dd9f0c7SLoGin let check = self 6722dd9f0c7SLoGin .mapped 6732dd9f0c7SLoGin .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst); 6742dd9f0c7SLoGin if check.is_err() { 6757ae679ddSLoGin return Err(SystemError::EINVAL); 6762dd9f0c7SLoGin } 6772dd9f0c7SLoGin 6782dd9f0c7SLoGin let flags = PageFlags::mmio_flags(); 679*731bc2b3SLoGin 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