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