1 use alloc::sync::Arc; 2 3 use crate::{ 4 arch::MMArch, 5 include::bindings::bindings::{process_control_block, PAGE_OFFSET}, 6 syscall::SystemError, 7 }; 8 9 use core::{ 10 cmp, 11 fmt::Debug, 12 intrinsics::unlikely, 13 ops::{Add, AddAssign, Sub, SubAssign}, 14 ptr, 15 sync::atomic::{AtomicBool, Ordering}, 16 }; 17 18 use self::{ 19 allocator::page_frame::{VirtPageFrame, VirtPageFrameIter}, 20 page::round_up_to_page_size, 21 ucontext::{AddressSpace, UserMapper}, 22 }; 23 24 pub mod allocator; 25 pub mod c_adapter; 26 pub mod kernel_mapper; 27 pub mod mmio_buddy; 28 pub mod no_init; 29 pub mod page; 30 pub mod percpu; 31 pub mod syscall; 32 pub mod ucontext; 33 34 /// 内核INIT进程的用户地址空间结构体(仅在process_init中初始化) 35 static mut __INITIAL_PROCESS_ADDRESS_SPACE: Option<Arc<AddressSpace>> = None; 36 37 /// 获取内核INIT进程的用户地址空间结构体 38 #[allow(non_snake_case)] 39 #[inline(always)] 40 pub fn INITIAL_PROCESS_ADDRESS_SPACE() -> Arc<AddressSpace> { 41 unsafe { 42 return __INITIAL_PROCESS_ADDRESS_SPACE 43 .as_ref() 44 .expect("INITIAL_PROCESS_ADDRESS_SPACE is null") 45 .clone(); 46 } 47 } 48 49 /// 设置内核INIT进程的用户地址空间结构体全局变量 50 #[allow(non_snake_case)] 51 pub unsafe fn set_INITIAL_PROCESS_ADDRESS_SPACE(address_space: Arc<AddressSpace>) { 52 static INITIALIZED: AtomicBool = AtomicBool::new(false); 53 if INITIALIZED 54 .compare_exchange(false, true, Ordering::SeqCst, Ordering::Acquire) 55 .is_err() 56 { 57 panic!("INITIAL_PROCESS_ADDRESS_SPACE is already initialized"); 58 } 59 __INITIAL_PROCESS_ADDRESS_SPACE = Some(address_space); 60 } 61 62 /// @brief 将内核空间的虚拟地址转换为物理地址 63 #[inline(always)] 64 pub fn virt_2_phys(addr: usize) -> usize { 65 addr - PAGE_OFFSET as usize 66 } 67 68 /// @brief 将物理地址转换为内核空间的虚拟地址 69 #[inline(always)] 70 pub fn phys_2_virt(addr: usize) -> usize { 71 addr + PAGE_OFFSET as usize 72 } 73 74 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)] 75 pub enum PageTableKind { 76 /// 用户可访问的页表 77 User, 78 /// 内核页表 79 Kernel, 80 } 81 82 /// 物理内存地址 83 #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd, Hash)] 84 #[repr(transparent)] 85 pub struct PhysAddr(usize); 86 87 impl PhysAddr { 88 #[inline(always)] 89 pub const fn new(address: usize) -> Self { 90 Self(address) 91 } 92 93 /// @brief 获取物理地址的值 94 #[inline(always)] 95 pub fn data(&self) -> usize { 96 self.0 97 } 98 99 /// @brief 将物理地址加上一个偏移量 100 #[inline(always)] 101 pub fn add(self, offset: usize) -> Self { 102 Self(self.0 + offset) 103 } 104 105 /// @brief 判断物理地址是否按照指定要求对齐 106 #[inline(always)] 107 pub fn check_aligned(&self, align: usize) -> bool { 108 return self.0 & (align - 1) == 0; 109 } 110 111 #[inline(always)] 112 pub fn is_null(&self) -> bool { 113 return self.0 == 0; 114 } 115 } 116 117 impl Debug for PhysAddr { 118 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 119 write!(f, "PhysAddr({:#x})", self.0) 120 } 121 } 122 123 impl core::ops::Add<usize> for PhysAddr { 124 type Output = Self; 125 126 #[inline(always)] 127 fn add(self, rhs: usize) -> Self::Output { 128 return Self(self.0 + rhs); 129 } 130 } 131 132 impl core::ops::AddAssign<usize> for PhysAddr { 133 #[inline(always)] 134 fn add_assign(&mut self, rhs: usize) { 135 self.0 += rhs; 136 } 137 } 138 139 impl core::ops::Add<PhysAddr> for PhysAddr { 140 type Output = Self; 141 142 #[inline(always)] 143 fn add(self, rhs: PhysAddr) -> Self::Output { 144 return Self(self.0 + rhs.0); 145 } 146 } 147 148 impl core::ops::AddAssign<PhysAddr> for PhysAddr { 149 #[inline(always)] 150 fn add_assign(&mut self, rhs: PhysAddr) { 151 self.0 += rhs.0; 152 } 153 } 154 155 impl core::ops::BitOrAssign<usize> for PhysAddr { 156 #[inline(always)] 157 fn bitor_assign(&mut self, rhs: usize) { 158 self.0 |= rhs; 159 } 160 } 161 162 impl core::ops::BitOrAssign<PhysAddr> for PhysAddr { 163 #[inline(always)] 164 fn bitor_assign(&mut self, rhs: PhysAddr) { 165 self.0 |= rhs.0; 166 } 167 } 168 169 impl core::ops::Sub<usize> for PhysAddr { 170 type Output = Self; 171 172 #[inline(always)] 173 fn sub(self, rhs: usize) -> Self::Output { 174 return Self(self.0 - rhs); 175 } 176 } 177 178 impl core::ops::SubAssign<usize> for PhysAddr { 179 #[inline(always)] 180 fn sub_assign(&mut self, rhs: usize) { 181 self.0 -= rhs; 182 } 183 } 184 185 impl core::ops::Sub<PhysAddr> for PhysAddr { 186 type Output = usize; 187 188 #[inline(always)] 189 fn sub(self, rhs: PhysAddr) -> Self::Output { 190 return self.0 - rhs.0; 191 } 192 } 193 194 impl core::ops::SubAssign<PhysAddr> for PhysAddr { 195 #[inline(always)] 196 fn sub_assign(&mut self, rhs: PhysAddr) { 197 self.0 -= rhs.0; 198 } 199 } 200 201 /// 虚拟内存地址 202 #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd, Hash)] 203 #[repr(transparent)] 204 pub struct VirtAddr(usize); 205 206 impl VirtAddr { 207 #[inline(always)] 208 pub const fn new(address: usize) -> Self { 209 return Self(address); 210 } 211 212 /// @brief 获取虚拟地址的值 213 #[inline(always)] 214 pub fn data(&self) -> usize { 215 return self.0; 216 } 217 218 /// @brief 判断虚拟地址的类型 219 #[inline(always)] 220 pub fn kind(&self) -> PageTableKind { 221 if self.check_user() { 222 return PageTableKind::User; 223 } else { 224 return PageTableKind::Kernel; 225 } 226 } 227 228 /// @brief 判断虚拟地址是否按照指定要求对齐 229 #[inline(always)] 230 pub fn check_aligned(&self, align: usize) -> bool { 231 return self.0 & (align - 1) == 0; 232 } 233 234 /// @brief 判断虚拟地址是否在用户空间 235 #[inline(always)] 236 pub fn check_user(&self) -> bool { 237 if self < &MMArch::USER_END_VADDR { 238 return true; 239 } else { 240 return false; 241 } 242 } 243 244 #[inline(always)] 245 pub fn as_ptr<T>(self) -> *mut T { 246 return self.0 as *mut T; 247 } 248 249 #[inline(always)] 250 pub fn is_null(&self) -> bool { 251 return self.0 == 0; 252 } 253 } 254 255 impl Add<VirtAddr> for VirtAddr { 256 type Output = Self; 257 258 #[inline(always)] 259 fn add(self, rhs: VirtAddr) -> Self::Output { 260 return Self(self.0 + rhs.0); 261 } 262 } 263 264 impl Add<usize> for VirtAddr { 265 type Output = Self; 266 267 #[inline(always)] 268 fn add(self, rhs: usize) -> Self::Output { 269 return Self(self.0 + rhs); 270 } 271 } 272 273 impl Sub<VirtAddr> for VirtAddr { 274 type Output = usize; 275 276 #[inline(always)] 277 fn sub(self, rhs: VirtAddr) -> Self::Output { 278 return self.0 - rhs.0; 279 } 280 } 281 282 impl Sub<usize> for VirtAddr { 283 type Output = Self; 284 285 #[inline(always)] 286 fn sub(self, rhs: usize) -> Self::Output { 287 return Self(self.0 - rhs); 288 } 289 } 290 291 impl AddAssign<usize> for VirtAddr { 292 #[inline(always)] 293 fn add_assign(&mut self, rhs: usize) { 294 self.0 += rhs; 295 } 296 } 297 298 impl AddAssign<VirtAddr> for VirtAddr { 299 #[inline(always)] 300 fn add_assign(&mut self, rhs: VirtAddr) { 301 self.0 += rhs.0; 302 } 303 } 304 305 impl SubAssign<usize> for VirtAddr { 306 #[inline(always)] 307 fn sub_assign(&mut self, rhs: usize) { 308 self.0 -= rhs; 309 } 310 } 311 312 impl SubAssign<VirtAddr> for VirtAddr { 313 #[inline(always)] 314 fn sub_assign(&mut self, rhs: VirtAddr) { 315 self.0 -= rhs.0; 316 } 317 } 318 319 impl Debug for VirtAddr { 320 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 321 write!(f, "VirtAddr({:#x})", self.0) 322 } 323 } 324 325 /// @brief 物理内存区域 326 #[derive(Clone, Copy, Debug)] 327 pub struct PhysMemoryArea { 328 /// 物理基地址 329 pub base: PhysAddr, 330 /// 该区域的物理内存大小 331 pub size: usize, 332 } 333 334 pub trait MemoryManagementArch: Clone + Copy + Debug { 335 /// 页面大小的shift(假如页面4K,那么这个值就是12,因为2^12=4096) 336 const PAGE_SHIFT: usize; 337 /// 每个页表的页表项数目。(以2^n次幂来表示)假如有512个页表项,那么这个值就是9 338 const PAGE_ENTRY_SHIFT: usize; 339 /// 页表层级数量 340 const PAGE_LEVELS: usize; 341 342 /// 页表项的有效位的index(假如页表项的第0-51位有效,那么这个值就是52) 343 const ENTRY_ADDRESS_SHIFT: usize; 344 /// 页面的页表项的默认值 345 const ENTRY_FLAG_DEFAULT_PAGE: usize; 346 /// 页表的页表项的默认值 347 const ENTRY_FLAG_DEFAULT_TABLE: usize; 348 /// 页表项的present位被置位之后的值 349 const ENTRY_FLAG_PRESENT: usize; 350 /// 页表项为read only时的值 351 const ENTRY_FLAG_READONLY: usize; 352 /// 页表项为可读写状态的值 353 const ENTRY_FLAG_READWRITE: usize; 354 /// 页面项标记页面为user page的值 355 const ENTRY_FLAG_USER: usize; 356 /// 页面项标记页面为write through的值 357 const ENTRY_FLAG_WRITE_THROUGH: usize; 358 /// 页面项标记页面为cache disable的值 359 const ENTRY_FLAG_CACHE_DISABLE: usize; 360 /// 标记当前页面不可执行的标志位(Execute disable)(也就是说,不能从这段内存里面获取处理器指令) 361 const ENTRY_FLAG_NO_EXEC: usize; 362 /// 标记当前页面可执行的标志位(Execute enable) 363 const ENTRY_FLAG_EXEC: usize; 364 365 /// 虚拟地址与物理地址的偏移量 366 const PHYS_OFFSET: usize; 367 368 /// 每个页面的大小 369 const PAGE_SIZE: usize = 1 << Self::PAGE_SHIFT; 370 /// 通过这个mask,获取地址的页内偏移量 371 const PAGE_OFFSET_MASK: usize = Self::PAGE_SIZE - 1; 372 /// 页表项的地址、数据部分的shift。 373 /// 打个比方,如果这个值为52,那么意味着页表项的[0, 52)位,用于表示地址以及其他的标志位 374 const PAGE_ADDRESS_SHIFT: usize = Self::PAGE_LEVELS * Self::PAGE_ENTRY_SHIFT + Self::PAGE_SHIFT; 375 /// 最大的虚拟地址(对于不同的架构,由于上述PAGE_ADDRESS_SHIFT可能包括了reserved bits, 事实上能表示的虚拟地址应该比这个值要小) 376 const PAGE_ADDRESS_SIZE: usize = 1 << Self::PAGE_ADDRESS_SHIFT; 377 /// 页表项的值与这个常量进行与运算,得到的结果是所填写的物理地址 378 const PAGE_ADDRESS_MASK: usize = Self::PAGE_ADDRESS_SIZE - Self::PAGE_SIZE; 379 /// 每个页表项的大小 380 const PAGE_ENTRY_SIZE: usize = 1 << (Self::PAGE_SHIFT - Self::PAGE_ENTRY_SHIFT); 381 /// 每个页表的页表项数目 382 const PAGE_ENTRY_NUM: usize = 1 << Self::PAGE_ENTRY_SHIFT; 383 /// 该字段用于根据虚拟地址,获取该虚拟地址在对应的页表中是第几个页表项 384 const PAGE_ENTRY_MASK: usize = Self::PAGE_ENTRY_NUM - 1; 385 386 const PAGE_NEGATIVE_MASK: usize = !((Self::PAGE_ADDRESS_SIZE) - 1); 387 388 const ENTRY_ADDRESS_SIZE: usize = 1 << Self::ENTRY_ADDRESS_SHIFT; 389 /// 该mask用于获取页表项中地址字段 390 const ENTRY_ADDRESS_MASK: usize = Self::ENTRY_ADDRESS_SIZE - Self::PAGE_SIZE; 391 /// 这个mask用于获取页表项中的flags 392 const ENTRY_FLAGS_MASK: usize = !Self::ENTRY_ADDRESS_MASK; 393 394 /// 用户空间的最高地址 395 const USER_END_VADDR: VirtAddr; 396 /// 用户堆的起始地址 397 const USER_BRK_START: VirtAddr; 398 /// 用户栈起始地址(向下生长,不包含该值) 399 const USER_STACK_START: VirtAddr; 400 401 /// @brief 用于初始化内存管理模块与架构相关的信息。 402 /// 该函数应调用其他模块的接口,生成内存区域结构体,提供给BumpAllocator使用 403 unsafe fn init() -> &'static [PhysMemoryArea]; 404 405 /// @brief 读取指定虚拟地址的值,并假设它是类型T的指针 406 #[inline(always)] 407 unsafe fn read<T>(address: VirtAddr) -> T { 408 return ptr::read(address.data() as *const T); 409 } 410 411 /// @brief 将value写入到指定的虚拟地址 412 #[inline(always)] 413 unsafe fn write<T>(address: VirtAddr, value: T) { 414 ptr::write(address.data() as *mut T, value); 415 } 416 417 #[inline(always)] 418 unsafe fn write_bytes(address: VirtAddr, value: u8, count: usize) { 419 ptr::write_bytes(address.data() as *mut u8, value, count); 420 } 421 422 /// @brief 刷新TLB中,关于指定虚拟地址的条目 423 unsafe fn invalidate_page(address: VirtAddr); 424 425 /// @brief 刷新TLB中,所有的条目 426 unsafe fn invalidate_all(); 427 428 /// @brief 获取顶级页表的物理地址 429 unsafe fn table(table_kind: PageTableKind) -> PhysAddr; 430 431 /// @brief 设置顶级页表的物理地址到处理器中 432 unsafe fn set_table(table_kind: PageTableKind, table: PhysAddr); 433 434 /// @brief 将物理地址转换为虚拟地址. 435 /// 436 /// @param phys 物理地址 437 /// 438 /// @return 转换后的虚拟地址。如果转换失败,返回None 439 #[inline(always)] 440 unsafe fn phys_2_virt(phys: PhysAddr) -> Option<VirtAddr> { 441 if let Some(vaddr) = phys.data().checked_add(Self::PHYS_OFFSET) { 442 return Some(VirtAddr::new(vaddr)); 443 } else { 444 return None; 445 } 446 } 447 448 /// 将虚拟地址转换为物理地址 449 /// 450 /// ## 参数 451 /// 452 /// - `virt` 虚拟地址 453 /// 454 /// ## 返回值 455 /// 456 /// 转换后的物理地址。如果转换失败,返回None 457 #[inline(always)] 458 unsafe fn virt_2_phys(virt: VirtAddr) -> Option<PhysAddr> { 459 if let Some(paddr) = virt.data().checked_sub(Self::PHYS_OFFSET) { 460 return Some(PhysAddr::new(paddr)); 461 } else { 462 return None; 463 } 464 } 465 466 /// @brief 判断指定的虚拟地址是否正确(符合规范) 467 fn virt_is_valid(virt: VirtAddr) -> bool; 468 469 /// 获取内存管理初始化时,创建的第一个内核页表的地址 470 fn initial_page_table() -> PhysAddr; 471 472 /// 初始化新的usermapper,为用户进程创建页表 473 fn setup_new_usermapper() -> Result<UserMapper, SystemError>; 474 } 475 476 /// @brief 虚拟地址范围 477 /// 该结构体用于表示一个虚拟地址范围,包括起始地址与大小 478 /// 479 /// 请注意与VMA进行区分,该结构体被VMA所包含 480 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 481 pub struct VirtRegion { 482 start: VirtAddr, 483 size: usize, 484 } 485 486 #[allow(dead_code)] 487 impl VirtRegion { 488 /// # 创建一个新的虚拟地址范围 489 pub fn new(start: VirtAddr, size: usize) -> Self { 490 VirtRegion { start, size } 491 } 492 493 /// 获取虚拟地址范围的起始地址 494 #[inline(always)] 495 pub fn start(&self) -> VirtAddr { 496 self.start 497 } 498 499 /// 获取虚拟地址范围的截止地址(不包括返回的地址) 500 #[inline(always)] 501 pub fn end(&self) -> VirtAddr { 502 return self.start().add(self.size); 503 } 504 505 /// # Create a new VirtRegion from a range [start, end) 506 /// 507 /// If end <= start, return None 508 pub fn between(start: VirtAddr, end: VirtAddr) -> Option<Self> { 509 if unlikely(end.data() <= start.data()) { 510 return None; 511 } 512 let size = end.data() - start.data(); 513 return Some(VirtRegion::new(start, size)); 514 } 515 516 /// # 取两个虚拟地址范围的交集 517 /// 518 /// 如果两个虚拟地址范围没有交集,返回None 519 pub fn intersect(&self, other: &VirtRegion) -> Option<VirtRegion> { 520 let start = self.start.max(other.start); 521 let end = self.end().min(other.end()); 522 return VirtRegion::between(start, end); 523 } 524 525 /// 设置虚拟地址范围的起始地址 526 #[inline(always)] 527 pub fn set_start(&mut self, start: VirtAddr) { 528 self.start = start; 529 } 530 531 #[inline(always)] 532 pub fn size(&self) -> usize { 533 self.size 534 } 535 536 /// 设置虚拟地址范围的大小 537 #[inline(always)] 538 pub fn set_size(&mut self, size: usize) { 539 self.size = size; 540 } 541 542 /// 判断虚拟地址范围是否为空 543 #[inline(always)] 544 pub fn is_empty(&self) -> bool { 545 self.size == 0 546 } 547 548 /// 将虚拟地址区域的大小向上对齐到页大小 549 #[inline(always)] 550 pub fn round_up_size_to_page(self) -> Self { 551 return VirtRegion::new(self.start, round_up_to_page_size(self.size)); 552 } 553 554 /// 判断两个虚拟地址范围是否由于具有交集而导致冲突 555 #[inline(always)] 556 pub fn collide(&self, other: &VirtRegion) -> bool { 557 return self.intersect(other).is_some(); 558 } 559 560 pub fn iter_pages(&self) -> VirtPageFrameIter { 561 return VirtPageFrame::iter_range( 562 VirtPageFrame::new(self.start), 563 VirtPageFrame::new(self.end()), 564 ); 565 } 566 567 /// 获取[self.start(), region.start())的虚拟地址范围 568 /// 569 /// 如果self.start() >= region.start(),返回None 570 pub fn before(self, region: &VirtRegion) -> Option<Self> { 571 return Self::between(self.start(), region.start()); 572 } 573 574 /// 获取[region.end(),self.end())的虚拟地址范围 575 /// 576 /// 如果 self.end() >= region.end() ,返回None 577 pub fn after(self, region: &VirtRegion) -> Option<Self> { 578 // if self.end() > region.end() none 579 return Self::between(region.end(), self.end()); 580 } 581 582 /// 把当前虚拟地址范围内的某个虚拟地址,转换为另一个虚拟地址范围内的虚拟地址 583 /// 584 /// 如果vaddr不在当前虚拟地址范围内,返回None 585 /// 586 /// 如果vaddr在当前虚拟地址范围内,返回vaddr在new_base中的虚拟地址 587 pub fn rebase(self, vaddr: VirtAddr, new_base: &VirtRegion) -> Option<VirtAddr> { 588 if !self.contains(vaddr) { 589 return None; 590 } 591 let offset = vaddr.data() - self.start().data(); 592 let new_start = new_base.start().data() + offset; 593 return Some(VirtAddr::new(new_start)); 594 } 595 596 /// 判断虚拟地址范围是否包含指定的虚拟地址 597 pub fn contains(&self, addr: VirtAddr) -> bool { 598 return self.start() <= addr && addr < self.end(); 599 } 600 601 /// 创建当前虚拟地址范围的页面迭代器 602 pub fn pages(&self) -> VirtPageFrameIter { 603 return VirtPageFrame::iter_range( 604 VirtPageFrame::new(self.start()), 605 VirtPageFrame::new(self.end()), 606 ); 607 } 608 } 609 610 impl PartialOrd for VirtRegion { 611 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { 612 return self.start.partial_cmp(&other.start); 613 } 614 } 615 616 impl Ord for VirtRegion { 617 fn cmp(&self, other: &Self) -> cmp::Ordering { 618 return self.start.cmp(&other.start); 619 } 620 } 621 622 /// ## 判断虚拟地址是否超出了用户空间 623 /// 624 /// 如果虚拟地址超出了用户空间,返回Err(SystemError::EFAULT). 625 /// 如果end < start,返回Err(SystemError::EOVERFLOW) 626 /// 627 /// 否则返回Ok(()) 628 pub fn verify_area(addr: VirtAddr, size: usize) -> Result<(), SystemError> { 629 let end = addr.add(size); 630 if unlikely(end.data() < addr.data()) { 631 return Err(SystemError::EOVERFLOW); 632 } 633 634 if !addr.check_user() || !end.check_user() { 635 return Err(SystemError::EFAULT); 636 } 637 638 return Ok(()); 639 } 640 // ====== 重构内存管理、进程管理后,请删除这几行 BEGIN ====== 641 //BUG pcb问题 642 unsafe impl Send for process_control_block {} 643 unsafe impl Sync for process_control_block {} 644 645 // ====== 重构内存管理后,请删除这几行 END ======= 646