1 use alloc::sync::Arc; 2 use system_error::SystemError; 3 4 use crate::arch::MMArch; 5 6 use core::{ 7 cmp, 8 fmt::Debug, 9 intrinsics::unlikely, 10 ops::{Add, AddAssign, Sub, SubAssign}, 11 ptr, 12 sync::atomic::{AtomicBool, Ordering}, 13 }; 14 15 use self::{ 16 allocator::page_frame::{VirtPageFrame, VirtPageFrameIter}, 17 memblock::MemoryAreaAttr, 18 page::round_up_to_page_size, 19 ucontext::{AddressSpace, LockedVMA, UserMapper}, 20 }; 21 22 pub mod allocator; 23 pub mod c_adapter; 24 pub mod early_ioremap; 25 pub mod fault; 26 pub mod init; 27 pub mod kernel_mapper; 28 pub mod madvise; 29 pub mod memblock; 30 pub mod mmio_buddy; 31 pub mod no_init; 32 pub mod page; 33 pub mod percpu; 34 pub mod syscall; 35 pub mod ucontext; 36 37 /// 内核INIT进程的用户地址空间结构体(仅在process_init中初始化) 38 static mut __IDLE_PROCESS_ADDRESS_SPACE: Option<Arc<AddressSpace>> = None; 39 40 bitflags! { 41 /// Virtual memory flags 42 #[allow(clippy::bad_bit_mask)] 43 pub struct VmFlags:u64{ 44 const VM_NONE = 0x00000000; 45 46 const VM_READ = 0x00000001; 47 const VM_WRITE = 0x00000002; 48 const VM_EXEC = 0x00000004; 49 const VM_SHARED = 0x00000008; 50 51 const VM_MAYREAD = 0x00000010; 52 const VM_MAYWRITE = 0x00000020; 53 const VM_MAYEXEC = 0x00000040; 54 const VM_MAYSHARE = 0x00000080; 55 56 const VM_GROWSDOWN = 0x00000100; 57 const VM_UFFD_MISSING = 0x00000200; 58 const VM_PFNMAP = 0x00000400; 59 const VM_UFFD_WP = 0x00001000; 60 61 const VM_LOCKED = 0x00002000; 62 const VM_IO = 0x00004000; 63 64 const VM_SEQ_READ = 0x00008000; 65 const VM_RAND_READ = 0x00010000; 66 67 const VM_DONTCOPY = 0x00020000; 68 const VM_DONTEXPAND = 0x00040000; 69 const VM_LOCKONFAULT = 0x00080000; 70 const VM_ACCOUNT = 0x00100000; 71 const VM_NORESERVE = 0x00200000; 72 const VM_HUGETLB = 0x00400000; 73 const VM_SYNC = 0x00800000; 74 const VM_ARCH_1 = 0x01000000; 75 const VM_WIPEONFORK = 0x02000000; 76 const VM_DONTDUMP = 0x04000000; 77 } 78 79 /// 描述页面错误处理过程中发生的不同情况或结果 80 pub struct VmFaultReason:u32 { 81 const VM_FAULT_OOM = 0x000001; 82 const VM_FAULT_SIGBUS = 0x000002; 83 const VM_FAULT_MAJOR = 0x000004; 84 const VM_FAULT_WRITE = 0x000008; 85 const VM_FAULT_HWPOISON = 0x000010; 86 const VM_FAULT_HWPOISON_LARGE = 0x000020; 87 const VM_FAULT_SIGSEGV = 0x000040; 88 const VM_FAULT_NOPAGE = 0x000100; 89 const VM_FAULT_LOCKED = 0x000200; 90 const VM_FAULT_RETRY = 0x000400; 91 const VM_FAULT_FALLBACK = 0x000800; 92 const VM_FAULT_DONE_COW = 0x001000; 93 const VM_FAULT_NEEDDSYNC = 0x002000; 94 const VM_FAULT_COMPLETED = 0x004000; 95 const VM_FAULT_HINDEX_MASK = 0x0f0000; 96 } 97 } 98 99 /// 获取内核IDLE进程的用户地址空间结构体 100 #[allow(non_snake_case)] 101 #[inline(always)] 102 pub fn IDLE_PROCESS_ADDRESS_SPACE() -> Arc<AddressSpace> { 103 unsafe { 104 return __IDLE_PROCESS_ADDRESS_SPACE 105 .as_ref() 106 .expect("IDLE_PROCESS_ADDRESS_SPACE is null") 107 .clone(); 108 } 109 } 110 111 /// 设置内核IDLE进程的用户地址空间结构体全局变量 112 #[allow(non_snake_case)] 113 pub unsafe fn set_IDLE_PROCESS_ADDRESS_SPACE(address_space: Arc<AddressSpace>) { 114 static INITIALIZED: AtomicBool = AtomicBool::new(false); 115 if INITIALIZED 116 .compare_exchange(false, true, Ordering::SeqCst, Ordering::Acquire) 117 .is_err() 118 { 119 panic!("IDLE_PROCESS_ADDRESS_SPACE is already initialized"); 120 } 121 __IDLE_PROCESS_ADDRESS_SPACE = Some(address_space); 122 } 123 124 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)] 125 pub enum PageTableKind { 126 /// 用户可访问的页表 127 User, 128 /// 内核页表 129 Kernel, 130 /// x86内存虚拟化中使用的EPT 131 #[cfg(target_arch = "x86_64")] 132 EPT, 133 } 134 135 /// 物理内存地址 136 #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd, Hash)] 137 #[repr(transparent)] 138 pub struct PhysAddr(usize); 139 140 impl PhysAddr { 141 /// 最大物理地址 142 pub const MAX: Self = PhysAddr(usize::MAX); 143 144 #[inline(always)] 145 pub const fn new(address: usize) -> Self { 146 Self(address) 147 } 148 149 /// @brief 获取物理地址的值 150 #[inline(always)] 151 pub const fn data(&self) -> usize { 152 self.0 153 } 154 155 /// @brief 将物理地址加上一个偏移量 156 #[inline(always)] 157 pub fn add(self, offset: usize) -> Self { 158 Self(self.0 + offset) 159 } 160 161 /// @brief 判断物理地址是否按照指定要求对齐 162 #[inline(always)] 163 pub fn check_aligned(&self, align: usize) -> bool { 164 return self.0 & (align - 1) == 0; 165 } 166 167 #[inline(always)] 168 pub fn is_null(&self) -> bool { 169 return self.0 == 0; 170 } 171 } 172 173 impl Debug for PhysAddr { 174 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 175 write!(f, "PhysAddr({:#x})", self.0) 176 } 177 } 178 179 impl core::ops::Add<usize> for PhysAddr { 180 type Output = Self; 181 182 #[inline(always)] 183 fn add(self, rhs: usize) -> Self::Output { 184 return Self(self.0 + rhs); 185 } 186 } 187 188 impl core::ops::AddAssign<usize> for PhysAddr { 189 #[inline(always)] 190 fn add_assign(&mut self, rhs: usize) { 191 self.0 += rhs; 192 } 193 } 194 195 impl core::ops::Add<PhysAddr> for PhysAddr { 196 type Output = Self; 197 198 #[inline(always)] 199 fn add(self, rhs: PhysAddr) -> Self::Output { 200 return Self(self.0 + rhs.0); 201 } 202 } 203 204 impl core::ops::AddAssign<PhysAddr> for PhysAddr { 205 #[inline(always)] 206 fn add_assign(&mut self, rhs: PhysAddr) { 207 self.0 += rhs.0; 208 } 209 } 210 211 impl core::ops::BitOrAssign<usize> for PhysAddr { 212 #[inline(always)] 213 fn bitor_assign(&mut self, rhs: usize) { 214 self.0 |= rhs; 215 } 216 } 217 218 impl core::ops::BitOrAssign<PhysAddr> for PhysAddr { 219 #[inline(always)] 220 fn bitor_assign(&mut self, rhs: PhysAddr) { 221 self.0 |= rhs.0; 222 } 223 } 224 225 impl core::ops::Sub<usize> for PhysAddr { 226 type Output = Self; 227 228 #[inline(always)] 229 fn sub(self, rhs: usize) -> Self::Output { 230 return Self(self.0 - rhs); 231 } 232 } 233 234 impl core::ops::SubAssign<usize> for PhysAddr { 235 #[inline(always)] 236 fn sub_assign(&mut self, rhs: usize) { 237 self.0 -= rhs; 238 } 239 } 240 241 impl core::ops::Sub<PhysAddr> for PhysAddr { 242 type Output = usize; 243 244 #[inline(always)] 245 fn sub(self, rhs: PhysAddr) -> Self::Output { 246 return self.0 - rhs.0; 247 } 248 } 249 250 impl core::ops::SubAssign<PhysAddr> for PhysAddr { 251 #[inline(always)] 252 fn sub_assign(&mut self, rhs: PhysAddr) { 253 self.0 -= rhs.0; 254 } 255 } 256 257 /// 虚拟内存地址 258 #[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd, Hash)] 259 #[repr(transparent)] 260 pub struct VirtAddr(usize); 261 262 impl VirtAddr { 263 #[inline(always)] 264 pub const fn new(address: usize) -> Self { 265 return Self(address); 266 } 267 268 /// @brief 获取虚拟地址的值 269 #[inline(always)] 270 pub const fn data(&self) -> usize { 271 return self.0; 272 } 273 274 /// @brief 判断虚拟地址的类型 275 #[inline(always)] 276 pub fn kind(&self) -> PageTableKind { 277 if self.check_user() { 278 return PageTableKind::User; 279 } else { 280 return PageTableKind::Kernel; 281 } 282 } 283 284 /// @brief 判断虚拟地址是否按照指定要求对齐 285 #[inline(always)] 286 pub fn check_aligned(&self, align: usize) -> bool { 287 return self.0 & (align - 1) == 0; 288 } 289 290 /// @brief 判断虚拟地址是否在用户空间 291 #[inline(always)] 292 pub fn check_user(&self) -> bool { 293 return self < &MMArch::USER_END_VADDR; 294 } 295 296 #[inline(always)] 297 pub fn as_ptr<T>(self) -> *mut T { 298 return self.0 as *mut T; 299 } 300 301 #[inline(always)] 302 pub fn is_null(&self) -> bool { 303 return self.0 == 0; 304 } 305 } 306 307 impl Add<VirtAddr> for VirtAddr { 308 type Output = Self; 309 310 #[inline(always)] 311 fn add(self, rhs: VirtAddr) -> Self::Output { 312 return Self(self.0 + rhs.0); 313 } 314 } 315 316 impl Add<usize> for VirtAddr { 317 type Output = Self; 318 319 #[inline(always)] 320 fn add(self, rhs: usize) -> Self::Output { 321 return Self(self.0 + rhs); 322 } 323 } 324 325 impl Sub<VirtAddr> for VirtAddr { 326 type Output = usize; 327 328 #[inline(always)] 329 fn sub(self, rhs: VirtAddr) -> Self::Output { 330 return self.0 - rhs.0; 331 } 332 } 333 334 impl Sub<usize> for VirtAddr { 335 type Output = Self; 336 337 #[inline(always)] 338 fn sub(self, rhs: usize) -> Self::Output { 339 return Self(self.0 - rhs); 340 } 341 } 342 343 impl AddAssign<usize> for VirtAddr { 344 #[inline(always)] 345 fn add_assign(&mut self, rhs: usize) { 346 self.0 += rhs; 347 } 348 } 349 350 impl AddAssign<VirtAddr> for VirtAddr { 351 #[inline(always)] 352 fn add_assign(&mut self, rhs: VirtAddr) { 353 self.0 += rhs.0; 354 } 355 } 356 357 impl SubAssign<usize> for VirtAddr { 358 #[inline(always)] 359 fn sub_assign(&mut self, rhs: usize) { 360 self.0 -= rhs; 361 } 362 } 363 364 impl SubAssign<VirtAddr> for VirtAddr { 365 #[inline(always)] 366 fn sub_assign(&mut self, rhs: VirtAddr) { 367 self.0 -= rhs.0; 368 } 369 } 370 371 impl Debug for VirtAddr { 372 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 373 write!(f, "VirtAddr({:#x})", self.0) 374 } 375 } 376 377 /// @brief 物理内存区域 378 #[derive(Clone, Copy, Debug)] 379 pub struct PhysMemoryArea { 380 /// 物理基地址 381 pub base: PhysAddr, 382 /// 该区域的物理内存大小 383 pub size: usize, 384 385 pub flags: MemoryAreaAttr, 386 } 387 388 impl PhysMemoryArea { 389 pub const DEFAULT: Self = Self { 390 base: PhysAddr::new(0), 391 size: 0, 392 flags: MemoryAreaAttr::empty(), 393 }; 394 395 pub fn new(base: PhysAddr, size: usize, flags: MemoryAreaAttr) -> Self { 396 Self { base, size, flags } 397 } 398 399 /// 返回向上页面对齐的区域起始物理地址 400 pub fn area_base_aligned(&self) -> PhysAddr { 401 return PhysAddr::new( 402 (self.base.data() + (MMArch::PAGE_SIZE - 1)) & !(MMArch::PAGE_SIZE - 1), 403 ); 404 } 405 406 /// 返回向下页面对齐的区域截止物理地址 407 pub fn area_end_aligned(&self) -> PhysAddr { 408 return PhysAddr::new((self.base.data() + self.size) & !(MMArch::PAGE_SIZE - 1)); 409 } 410 } 411 412 impl Default for PhysMemoryArea { 413 fn default() -> Self { 414 return Self::DEFAULT; 415 } 416 } 417 418 #[allow(dead_code)] 419 pub trait MemoryManagementArch: Clone + Copy + Debug { 420 /// 是否支持缺页中断 421 const PAGE_FAULT_ENABLED: bool; 422 /// 页面大小的shift(假如页面4K,那么这个值就是12,因为2^12=4096) 423 const PAGE_SHIFT: usize; 424 /// 每个页表的页表项数目。(以2^n次幂来表示)假如有512个页表项,那么这个值就是9 425 const PAGE_ENTRY_SHIFT: usize; 426 /// 页表层级数量 427 const PAGE_LEVELS: usize; 428 429 /// 页表项的有效位的index(假如页表项的第0-51位有效,那么这个值就是52) 430 const ENTRY_ADDRESS_SHIFT: usize; 431 /// 页面的页表项的默认值 432 const ENTRY_FLAG_DEFAULT_PAGE: usize; 433 /// 页表的页表项的默认值 434 const ENTRY_FLAG_DEFAULT_TABLE: usize; 435 /// 页表项的present位被置位之后的值 436 const ENTRY_FLAG_PRESENT: usize; 437 /// 页表项为read only时的值 438 const ENTRY_FLAG_READONLY: usize; 439 /// 页表项的write bit 440 const ENTRY_FLAG_WRITEABLE: usize; 441 /// 页表项为可读写状态的值 442 const ENTRY_FLAG_READWRITE: usize; 443 /// 页面项标记页面为user page的值 444 const ENTRY_FLAG_USER: usize; 445 /// 页面项标记页面为write through的值 446 const ENTRY_FLAG_WRITE_THROUGH: usize; 447 /// 页面项标记页面为cache disable的值 448 const ENTRY_FLAG_CACHE_DISABLE: usize; 449 /// 标记当前页面不可执行的标志位(Execute disable)(也就是说,不能从这段内存里面获取处理器指令) 450 const ENTRY_FLAG_NO_EXEC: usize; 451 /// 标记当前页面可执行的标志位(Execute enable) 452 const ENTRY_FLAG_EXEC: usize; 453 /// 当该位为1时,标明这是一个脏页 454 const ENTRY_FLAG_DIRTY: usize; 455 /// 当该位为1时,代表这个页面被处理器访问过 456 const ENTRY_FLAG_ACCESSED: usize; 457 /// 标记该页表项指向的页是否为大页 458 const ENTRY_FLAG_HUGE_PAGE: usize; 459 /// 当该位为1时,代表该页表项是全局的 460 const ENTRY_FLAG_GLOBAL: usize; 461 462 /// 虚拟地址与物理地址的偏移量 463 const PHYS_OFFSET: usize; 464 465 /// 内核在链接时被链接到的偏移量 466 const KERNEL_LINK_OFFSET: usize; 467 468 const KERNEL_VIRT_START: usize = Self::PHYS_OFFSET + Self::KERNEL_LINK_OFFSET; 469 470 /// 每个页面的大小 471 const PAGE_SIZE: usize = 1 << Self::PAGE_SHIFT; 472 /// 通过这个mask,获取地址的页内偏移量 473 const PAGE_OFFSET_MASK: usize = Self::PAGE_SIZE - 1; 474 /// 通过这个mask,获取页的首地址 475 const PAGE_MASK: usize = !(Self::PAGE_OFFSET_MASK); 476 /// 页表项的地址、数据部分的shift。 477 /// 打个比方,如果这个值为52,那么意味着页表项的[0, 52)位,用于表示地址以及其他的标志位 478 const PAGE_ADDRESS_SHIFT: usize = Self::PAGE_LEVELS * Self::PAGE_ENTRY_SHIFT + Self::PAGE_SHIFT; 479 /// 最大的虚拟地址(对于不同的架构,由于上述PAGE_ADDRESS_SHIFT可能包括了reserved bits, 事实上能表示的虚拟地址应该比这个值要小) 480 const PAGE_ADDRESS_SIZE: usize = 1 << Self::PAGE_ADDRESS_SHIFT; 481 /// 页表项的值与这个常量进行与运算,得到的结果是所填写的物理地址 482 const PAGE_ADDRESS_MASK: usize = Self::PAGE_ADDRESS_SIZE - Self::PAGE_SIZE; 483 /// 每个页表项的大小 484 const PAGE_ENTRY_SIZE: usize = 1 << (Self::PAGE_SHIFT - Self::PAGE_ENTRY_SHIFT); 485 /// 每个页表的页表项数目 486 const PAGE_ENTRY_NUM: usize = 1 << Self::PAGE_ENTRY_SHIFT; 487 /// 该字段用于根据虚拟地址,获取该虚拟地址在对应的页表中是第几个页表项 488 const PAGE_ENTRY_MASK: usize = Self::PAGE_ENTRY_NUM - 1; 489 /// 内核页表在顶级页表的第一个页表项的索引 490 const PAGE_KERNEL_INDEX: usize = (Self::PHYS_OFFSET & Self::PAGE_ADDRESS_MASK) 491 >> (Self::PAGE_ADDRESS_SHIFT - Self::PAGE_ENTRY_SHIFT); 492 493 const PAGE_NEGATIVE_MASK: usize = !((Self::PAGE_ADDRESS_SIZE) - 1); 494 495 const ENTRY_ADDRESS_SIZE: usize = 1 << Self::ENTRY_ADDRESS_SHIFT; 496 /// 该mask用于获取页表项中地址字段 497 const ENTRY_ADDRESS_MASK: usize = Self::ENTRY_ADDRESS_SIZE - Self::PAGE_SIZE; 498 /// 这个mask用于获取页表项中的flags 499 const ENTRY_FLAGS_MASK: usize = !Self::ENTRY_ADDRESS_MASK; 500 501 /// 用户空间的最高地址 502 const USER_END_VADDR: VirtAddr; 503 /// 用户堆的起始地址 504 const USER_BRK_START: VirtAddr; 505 /// 用户栈起始地址(向下生长,不包含该值) 506 const USER_STACK_START: VirtAddr; 507 508 /// 内核的固定映射区的起始地址 509 const FIXMAP_START_VADDR: VirtAddr; 510 /// 内核的固定映射区的大小 511 const FIXMAP_SIZE: usize; 512 /// 内核的固定映射区的结束地址 513 const FIXMAP_END_VADDR: VirtAddr = 514 VirtAddr::new(Self::FIXMAP_START_VADDR.data() + Self::FIXMAP_SIZE); 515 516 /// MMIO虚拟空间的基地址 517 const MMIO_BASE: VirtAddr; 518 /// MMIO虚拟空间的大小 519 const MMIO_SIZE: usize; 520 /// MMIO虚拟空间的顶端地址(不包含) 521 const MMIO_TOP: VirtAddr = VirtAddr::new(Self::MMIO_BASE.data() + Self::MMIO_SIZE); 522 523 /// @brief 用于初始化内存管理模块与架构相关的信息。 524 /// 该函数应调用其他模块的接口,把可用内存区域添加到memblock,提供给BumpAllocator使用 525 unsafe fn init(); 526 527 /// 内存管理初始化完成后,调用该函数 528 unsafe fn arch_post_init() {} 529 530 /// @brief 读取指定虚拟地址的值,并假设它是类型T的指针 531 #[inline(always)] 532 unsafe fn read<T>(address: VirtAddr) -> T { 533 return ptr::read(address.data() as *const T); 534 } 535 536 /// @brief 将value写入到指定的虚拟地址 537 #[inline(always)] 538 unsafe fn write<T>(address: VirtAddr, value: T) { 539 ptr::write(address.data() as *mut T, value); 540 } 541 542 #[inline(always)] 543 unsafe fn write_bytes(address: VirtAddr, value: u8, count: usize) { 544 ptr::write_bytes(address.data() as *mut u8, value, count); 545 } 546 547 /// @brief 刷新TLB中,关于指定虚拟地址的条目 548 unsafe fn invalidate_page(address: VirtAddr); 549 550 /// @brief 刷新TLB中,所有的条目 551 unsafe fn invalidate_all(); 552 553 /// @brief 获取顶级页表的物理地址 554 unsafe fn table(table_kind: PageTableKind) -> PhysAddr; 555 556 /// @brief 设置顶级页表的物理地址到处理器中 557 unsafe fn set_table(table_kind: PageTableKind, table: PhysAddr); 558 559 /// @brief 将物理地址转换为虚拟地址. 560 /// 561 /// @param phys 物理地址 562 /// 563 /// @return 转换后的虚拟地址。如果转换失败,返回None 564 #[inline(always)] 565 unsafe fn phys_2_virt(phys: PhysAddr) -> Option<VirtAddr> { 566 if let Some(vaddr) = phys.data().checked_add(Self::PHYS_OFFSET) { 567 return Some(VirtAddr::new(vaddr)); 568 } else { 569 return None; 570 } 571 } 572 573 /// 将虚拟地址转换为物理地址 574 /// 575 /// ## 参数 576 /// 577 /// - `virt` 虚拟地址 578 /// 579 /// ## 返回值 580 /// 581 /// 转换后的物理地址。如果转换失败,返回None 582 #[inline(always)] 583 unsafe fn virt_2_phys(virt: VirtAddr) -> Option<PhysAddr> { 584 if let Some(paddr) = virt.data().checked_sub(Self::PHYS_OFFSET) { 585 return Some(PhysAddr::new(paddr)); 586 } else { 587 return None; 588 } 589 } 590 591 /// @brief 判断指定的虚拟地址是否正确(符合规范) 592 fn virt_is_valid(virt: VirtAddr) -> bool; 593 594 /// 获取内存管理初始化时,创建的第一个内核页表的地址 595 fn initial_page_table() -> PhysAddr; 596 597 /// 初始化新的usermapper,为用户进程创建页表 598 fn setup_new_usermapper() -> Result<UserMapper, SystemError>; 599 600 /// 创建页表项 601 /// 602 /// 这是一个低阶api,用于根据物理地址以及指定好的pageflags,创建页表项 603 /// 604 /// ## 参数 605 /// 606 /// - `paddr` 物理地址 607 /// - `page_flags` 页表项的flags 608 /// 609 /// ## 返回值 610 /// 611 /// 页表项的值 612 fn make_entry(paddr: PhysAddr, page_flags: usize) -> usize; 613 614 /// 判断一个VMA是否允许访问 615 /// 616 /// ## 参数 617 /// 618 /// - `vma`: 进行判断的VMA 619 /// - `write`: 是否需要写入权限(true 表示需要写权限) 620 /// - `execute`: 是否需要执行权限(true 表示需要执行权限) 621 /// - `foreign`: 是否是外部的(即非当前进程的)VMA 622 /// 623 /// ## 返回值 624 /// - `true`: VMA允许访问 625 /// - `false`: 错误的说明 626 fn vma_access_permitted( 627 _vma: Arc<LockedVMA>, 628 _write: bool, 629 _execute: bool, 630 _foreign: bool, 631 ) -> bool { 632 true 633 } 634 } 635 636 /// @brief 虚拟地址范围 637 /// 该结构体用于表示一个虚拟地址范围,包括起始地址与大小 638 /// 639 /// 请注意与VMA进行区分,该结构体被VMA所包含 640 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 641 pub struct VirtRegion { 642 start: VirtAddr, 643 size: usize, 644 } 645 646 #[allow(dead_code)] 647 impl VirtRegion { 648 /// # 创建一个新的虚拟地址范围 649 pub fn new(start: VirtAddr, size: usize) -> Self { 650 VirtRegion { start, size } 651 } 652 653 /// 获取虚拟地址范围的起始地址 654 #[inline(always)] 655 pub fn start(&self) -> VirtAddr { 656 self.start 657 } 658 659 /// 获取虚拟地址范围的截止地址(不包括返回的地址) 660 #[inline(always)] 661 pub fn end(&self) -> VirtAddr { 662 return self.start().add(self.size); 663 } 664 665 /// # Create a new VirtRegion from a range [start, end) 666 /// 667 /// If end <= start, return None 668 pub fn between(start: VirtAddr, end: VirtAddr) -> Option<Self> { 669 if unlikely(end.data() <= start.data()) { 670 return None; 671 } 672 let size = end.data() - start.data(); 673 return Some(VirtRegion::new(start, size)); 674 } 675 676 /// # 取两个虚拟地址范围的交集 677 /// 678 /// 如果两个虚拟地址范围没有交集,返回None 679 pub fn intersect(&self, other: &VirtRegion) -> Option<VirtRegion> { 680 let start = self.start.max(other.start); 681 let end = self.end().min(other.end()); 682 return VirtRegion::between(start, end); 683 } 684 685 /// 设置虚拟地址范围的起始地址 686 #[inline(always)] 687 pub fn set_start(&mut self, start: VirtAddr) { 688 self.start = start; 689 } 690 691 #[inline(always)] 692 pub fn size(&self) -> usize { 693 self.size 694 } 695 696 /// 设置虚拟地址范围的大小 697 #[inline(always)] 698 pub fn set_size(&mut self, size: usize) { 699 self.size = size; 700 } 701 702 /// 判断虚拟地址范围是否为空 703 #[inline(always)] 704 pub fn is_empty(&self) -> bool { 705 self.size == 0 706 } 707 708 /// 将虚拟地址区域的大小向上对齐到页大小 709 #[inline(always)] 710 pub fn round_up_size_to_page(self) -> Self { 711 return VirtRegion::new(self.start, round_up_to_page_size(self.size)); 712 } 713 714 /// 判断两个虚拟地址范围是否由于具有交集而导致冲突 715 #[inline(always)] 716 pub fn collide(&self, other: &VirtRegion) -> bool { 717 return self.intersect(other).is_some(); 718 } 719 720 pub fn iter_pages(&self) -> VirtPageFrameIter { 721 return VirtPageFrame::iter_range( 722 VirtPageFrame::new(self.start), 723 VirtPageFrame::new(self.end()), 724 ); 725 } 726 727 /// 获取[self.start(), region.start())的虚拟地址范围 728 /// 729 /// 如果self.start() >= region.start(),返回None 730 pub fn before(self, region: &VirtRegion) -> Option<Self> { 731 return Self::between(self.start(), region.start()); 732 } 733 734 /// 获取[region.end(),self.end())的虚拟地址范围 735 /// 736 /// 如果 self.end() >= region.end() ,返回None 737 pub fn after(self, region: &VirtRegion) -> Option<Self> { 738 // if self.end() > region.end() none 739 return Self::between(region.end(), self.end()); 740 } 741 742 /// 把当前虚拟地址范围内的某个虚拟地址,转换为另一个虚拟地址范围内的虚拟地址 743 /// 744 /// 如果vaddr不在当前虚拟地址范围内,返回None 745 /// 746 /// 如果vaddr在当前虚拟地址范围内,返回vaddr在new_base中的虚拟地址 747 pub fn rebase(self, vaddr: VirtAddr, new_base: &VirtRegion) -> Option<VirtAddr> { 748 if !self.contains(vaddr) { 749 return None; 750 } 751 let offset = vaddr.data() - self.start().data(); 752 let new_start = new_base.start().data() + offset; 753 return Some(VirtAddr::new(new_start)); 754 } 755 756 /// 判断虚拟地址范围是否包含指定的虚拟地址 757 pub fn contains(&self, addr: VirtAddr) -> bool { 758 return self.start() <= addr && addr < self.end(); 759 } 760 761 /// 创建当前虚拟地址范围的页面迭代器 762 pub fn pages(&self) -> VirtPageFrameIter { 763 return VirtPageFrame::iter_range( 764 VirtPageFrame::new(self.start()), 765 VirtPageFrame::new(self.end()), 766 ); 767 } 768 } 769 770 impl PartialOrd for VirtRegion { 771 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { 772 Some(self.cmp(other)) 773 } 774 } 775 776 impl Ord for VirtRegion { 777 fn cmp(&self, other: &Self) -> cmp::Ordering { 778 return self.start.cmp(&other.start); 779 } 780 } 781 782 /// ## 判断虚拟地址是否超出了用户空间 783 /// 784 /// 如果虚拟地址超出了用户空间,返回Err(SystemError::EFAULT). 785 /// 如果end < start,返回Err(SystemError::EOVERFLOW) 786 /// 787 /// 否则返回Ok(()) 788 pub fn verify_area(addr: VirtAddr, size: usize) -> Result<(), SystemError> { 789 let end = addr.add(size); 790 if unlikely(end.data() < addr.data()) { 791 return Err(SystemError::EOVERFLOW); 792 } 793 794 if !addr.check_user() || !end.check_user() { 795 return Err(SystemError::EFAULT); 796 } 797 798 return Ok(()); 799 } 800