Skip to main content

os/memory/
address_space.rs

1/*
2 * ============================================
3 * RISC-V 地址空间抽象
4 * ============================================
5 * 功能:管理独立的虚拟地址空间
6 *
7 * 教学说明:
8 * - 每个进程都有独立的地址空间
9 * - 地址空间包含页表和内存区域
10 * - 可以激活(切换到)某个地址空间
11 * ============================================
12 */
13
14use super::paging::{map_page, unmap_page};
15use super::{PageTable, PageTableFlags, PhysAddr, SimpleFrameAllocator, VirtAddr, PAGE_SIZE};
16use alloc::vec::Vec;
17use core::ops::Range;
18
19/// 内存区域类型
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum MemoryAreaType {
22    Code,   // 代码段(R-X)
23    Data,   // 数据段(RW-)
24    Heap,   // 堆(RW-)
25    Stack,  // 栈(RW-)
26    Shared, // 共享内存(RW-)
27    Kernel, // 内核内存(RWX)
28}
29
30impl MemoryAreaType {
31    /// 获取该区域类型的默认标志位
32    pub fn default_flags(&self) -> usize {
33        use PageTableFlags as PTF;
34
35        match self {
36            MemoryAreaType::Code => {
37                // 代码段:可读、可执行
38                PTF::Valid as usize | PTF::Read as usize | PTF::Execute as usize
39            }
40            MemoryAreaType::Data | MemoryAreaType::Heap | MemoryAreaType::Stack => {
41                // 数据段、堆、栈:可读、可写
42                PTF::Valid as usize | PTF::Read as usize | PTF::Write as usize
43            }
44            MemoryAreaType::Shared => {
45                // 共享内存:可读、可写
46                PTF::Valid as usize | PTF::Read as usize | PTF::Write as usize
47            }
48            MemoryAreaType::Kernel => {
49                // 内核内存:可读、可写、可执行
50                PTF::Valid as usize
51                    | PTF::Read as usize
52                    | PTF::Write as usize
53                    | PTF::Execute as usize
54            }
55        }
56    }
57}
58
59/// 内存区域
60///
61/// # 教学说明
62/// 内存区域是地址空间的一部分,具有连续的虚拟地址和相同的权限
63#[derive(Debug, Clone)]
64pub struct MemoryArea {
65    pub range: Range<VirtAddr>,
66    pub area_type: MemoryAreaType,
67    pub flags: usize,
68}
69
70impl MemoryArea {
71    /// 创建新的内存区域
72    pub fn new(start: VirtAddr, end: VirtAddr, area_type: MemoryAreaType) -> Self {
73        MemoryArea {
74            range: start..end,
75            area_type,
76            flags: area_type.default_flags(),
77        }
78    }
79
80    /// 获取区域大小
81    pub fn size(&self) -> usize {
82        self.range.end.as_usize() - self.range.start.as_usize()
83    }
84
85    /// 获取页数
86    pub fn page_count(&self) -> usize {
87        self.size().div_ceil(PAGE_SIZE)
88    }
89}
90
91/// 地址空间
92///
93/// # 教学说明
94/// 地址空间代表一个独立的虚拟内存空间,包含:
95/// - 一个根页表
96/// - 多个内存区域
97/// - 可以激活(切换satp寄存器)
98pub struct AddressSpace {
99    page_table: *mut PageTable,
100    page_table_paddr: PhysAddr,
101    areas: Vec<MemoryArea>,
102}
103
104/// Deep-copy user-space mappings from `src_satp` into a new page table.
105///
106/// Kernel leaf mappings (no U flag) keep pointing at the same physical frames,
107/// but every page-table level is private to the new address space.  User leaf
108/// pages (U flag set) are allocated new physical frames and their data copied.
109/// Returns the new satp value (Sv39 mode).
110pub fn deep_copy_user_address_space(
111    src_satp: usize,
112    allocator: &mut SimpleFrameAllocator,
113) -> Result<usize, &'static str> {
114    let src_root_ppn = src_satp & 0x0000_0FFF_FFFF_FFFF;
115    let src_root_paddr = src_root_ppn << 12;
116
117    let new_root_frame = allocator.allocate().ok_or("OOM for root page table")?;
118    let new_root_paddr = new_root_frame.start_address().as_usize();
119
120    unsafe {
121        let new_root = new_root_paddr as *mut PageTable;
122        (*new_root).zero();
123
124        clone_page_table_level(allocator, src_root_paddr, new_root_paddr, 2, true)?;
125    }
126
127    Ok((8usize << 60) | (new_root_paddr >> 12))
128}
129
130/// Recursively copy a Sv39 page-table subtree without sharing intermediate
131/// page-table pages.
132///
133/// Non-user leaves are kernel/MMIO mappings: they are copied as PTE leaves so
134/// both address spaces reference the same physical kernel device/memory pages,
135/// but the intermediate page tables are newly allocated.  User leaves are
136/// either skipped (`copy_user_pages = false`) or deep-copied into fresh frames.
137unsafe fn clone_page_table_level(
138    allocator: &mut SimpleFrameAllocator,
139    src_table_paddr: usize,
140    dst_table_paddr: usize,
141    level: usize,
142    copy_user_pages: bool,
143) -> Result<(), &'static str> {
144    let src = src_table_paddr as *const PageTable;
145    let dst = dst_table_paddr as *mut PageTable;
146
147    for idx in 0..512 {
148        let entry = (*src).entries[idx];
149        if !entry.is_valid() {
150            continue;
151        }
152
153        let flags = entry.flags();
154        let has_user = (flags & (PageTableFlags::User as usize)) != 0;
155
156        if entry.is_leaf() {
157            if !has_user {
158                // Kernel leaf or MMIO mapping: share the physical mapping but
159                // keep all page-table pages private.
160                (*dst).entries[idx] = entry;
161            } else if copy_user_pages {
162                if level != 0 {
163                    return Err("Unsupported user huge page");
164                }
165                let page_paddr = entry.ppn() << 12;
166                let new_frame = allocator.allocate().ok_or("OOM for user page copy")?;
167                let new_paddr = new_frame.start_address().as_usize();
168                copy_4k_page(page_paddr, new_paddr);
169                (*dst).entries[idx].set(new_paddr >> 12, flags);
170            }
171            // Otherwise this is a stale/user leaf while cloning kernel
172            // mappings for a fresh exec address space: intentionally skip it.
173        } else {
174            if level == 0 {
175                return Err("Malformed page table: non-leaf at level 0");
176            }
177            // Non-leaf: allocate new intermediate page table and recurse
178            let src_child_paddr = entry.ppn() << 12;
179            let new_child_frame = allocator.allocate().ok_or("OOM for intermediate PT")?;
180            let new_child_paddr = new_child_frame.start_address().as_usize();
181            let child = new_child_paddr as *mut PageTable;
182            (*child).zero();
183            (*dst).entries[idx].set(new_child_paddr >> 12, flags);
184            clone_page_table_level(
185                allocator,
186                src_child_paddr,
187                new_child_paddr,
188                level - 1,
189                copy_user_pages,
190            )?;
191        }
192    }
193    Ok(())
194}
195
196unsafe fn copy_4k_page(src_paddr: usize, dst_paddr: usize) {
197    let page_size_words = PAGE_SIZE / core::mem::size_of::<u64>();
198    for off in 0..page_size_words {
199        let src_word = *((src_paddr + off * core::mem::size_of::<u64>()) as *const u64);
200        *((dst_paddr + off * core::mem::size_of::<u64>()) as *mut u64) = src_word;
201    }
202}
203
204impl AddressSpace {
205    /// 创建新的地址空间
206    ///
207    /// # 教学说明
208    /// 1. 分配一个物理帧作为根页表
209    /// 2. 清空页表
210    /// 3. 初始化空的内存区域列表
211    pub fn new(allocator: &mut SimpleFrameAllocator) -> Result<Self, &'static str> {
212        // 分配根页表
213        let frame = allocator.allocate().ok_or("Out of memory")?;
214        let page_table_paddr = frame.start_address();
215        let page_table_ptr = page_table_paddr.as_usize() as *mut PageTable;
216
217        // 清空页表
218        unsafe {
219            (*page_table_ptr).zero();
220        }
221
222        crate::serial_println!(
223            "[ADDRESS_SPACE] Created new address space, page table at {:#x}",
224            page_table_paddr.as_usize()
225        );
226
227        Ok(AddressSpace {
228            page_table: page_table_ptr,
229            page_table_paddr,
230            areas: Vec::new(),
231        })
232    }
233
234    /// Copy kernel/MMIO mappings from an existing kernel root into this address
235    /// space without sharing intermediate page-table pages.
236    ///
237    /// This is intentionally a private page-table clone, not a shallow root-PTE
238    /// copy.  AhRightOS maps UART at a low virtual address that shares VPN[2] with
239    /// early user programs; sharing that subtree lets later user mappings write
240    /// back into the boot kernel root and breaks repeated exec/ELF loads.
241    pub fn copy_kernel_mappings_from(
242        &mut self,
243        kernel_root_paddr: PhysAddr,
244        allocator: &mut SimpleFrameAllocator,
245    ) -> Result<(), &'static str> {
246        unsafe {
247            clone_page_table_level(
248                allocator,
249                kernel_root_paddr.as_usize(),
250                self.page_table_paddr.as_usize(),
251                2,
252                false,
253            )
254        }
255    }
256
257    /// 映射内存区域
258    ///
259    /// # 参数
260    /// - `start`: 起始虚拟地址
261    /// - `size`: 区域大小
262    /// - `area_type`: 区域类型
263    /// - `allocator`: 帧分配器
264    ///
265    /// # 教学说明
266    /// 1. 创建内存区域描述
267    /// 2. 分配物理帧
268    /// 3. 建立虚拟地址到物理地址的映射
269    pub fn map_region(
270        &mut self,
271        start: VirtAddr,
272        size: usize,
273        area_type: MemoryAreaType,
274        allocator: &mut SimpleFrameAllocator,
275    ) -> Result<(), &'static str> {
276        let end = VirtAddr::new(start.as_usize() + size);
277        let area = MemoryArea::new(start, end, area_type);
278
279        crate::serial_println!(
280            "[ADDRESS_SPACE] Mapping region: {:#x} - {:#x} ({:?})",
281            start.as_usize(),
282            end.as_usize(),
283            area_type
284        );
285
286        // 分配并映射每个页面
287        let page_count = area.page_count();
288
289        for i in 0..page_count {
290            let vaddr = VirtAddr::new(start.as_usize() + i * PAGE_SIZE);
291
292            // 分配物理帧
293            let frame = allocator.allocate().ok_or("Out of memory")?;
294            let paddr = frame.start_address();
295
296            // 建立映射
297            unsafe {
298                map_page(&mut *self.page_table, vaddr, paddr, area.flags, allocator)?;
299            }
300        }
301
302        self.areas.push(area);
303        Ok(())
304    }
305
306    /// 映射内存区域(恒等映射)
307    ///
308    /// # 教学说明
309    /// 恒等映射:虚拟地址 == 物理地址
310    /// 主要用于内核代码段,方便直接访问物理内存
311    pub fn map_region_identity(
312        &mut self,
313        start: PhysAddr,
314        size: usize,
315        area_type: MemoryAreaType,
316        allocator: &mut SimpleFrameAllocator,
317    ) -> Result<(), &'static str> {
318        let vstart = VirtAddr::new(start.as_usize());
319        let end = VirtAddr::new(start.as_usize() + size);
320        let area = MemoryArea::new(vstart, end, area_type);
321
322        crate::serial_println!(
323            "[ADDRESS_SPACE] Identity mapping region: {:#x} - {:#x} ({:?})",
324            start.as_usize(),
325            start.as_usize() + size,
326            area_type
327        );
328
329        // 映射每个页面(恒等映射)
330        let page_count = area.page_count();
331
332        for i in 0..page_count {
333            let addr = start.as_usize() + i * PAGE_SIZE;
334            let vaddr = VirtAddr::new(addr);
335            let paddr = PhysAddr::new(addr);
336
337            // 建立恒等映射
338            unsafe {
339                map_page(&mut *self.page_table, vaddr, paddr, area.flags, allocator)?;
340            }
341        }
342
343        self.areas.push(area);
344        Ok(())
345    }
346
347    /// 取消映射内存区域
348    pub fn unmap_region(&mut self, start: VirtAddr, size: usize) -> Result<(), &'static str> {
349        let page_count = size.div_ceil(PAGE_SIZE);
350
351        for i in 0..page_count {
352            let vaddr = VirtAddr::new(start.as_usize() + i * PAGE_SIZE);
353            unsafe {
354                unmap_page(&mut *self.page_table, vaddr)?;
355            }
356        }
357
358        // 从区域列表中移除
359        self.areas
360            .retain(|area| area.range.start.as_usize() != start.as_usize());
361
362        Ok(())
363    }
364
365    /// 激活此地址空间(写入 satp)
366    ///
367    /// # 教学说明
368    /// 1. 计算页表的物理页号(PPN)
369    /// 2. 设置 satp 寄存器(Sv39 模式)
370    /// 3. 刷新 TLB
371    pub fn activate(&self) {
372        use riscv::register::satp;
373
374        let ppn = self.page_table_paddr.as_usize() >> 12;
375
376        crate::serial_println!("[ADDRESS_SPACE] Activating address space, PPN: {:#x}", ppn);
377
378        unsafe {
379            // Sv39 模式,ASID = 0
380            satp::set(satp::Mode::Sv39, 0, ppn);
381
382            // 刷新整个 TLB
383            core::arch::asm!("sfence.vma");
384        }
385
386        crate::serial_println!("[ADDRESS_SPACE] Address space activated");
387    }
388
389    /// 获取页表的物理地址
390    pub fn page_table_paddr(&self) -> PhysAddr {
391        self.page_table_paddr
392    }
393
394    /// Get mutable pointer to the root page table
395    pub fn page_table_ptr(&self) -> *mut PageTable {
396        self.page_table
397    }
398
399    /// 获取内存区域列表
400    pub fn areas(&self) -> &[MemoryArea] {
401        &self.areas
402    }
403
404    /// 可视化显示地址空间布局(教学特色)
405    pub fn print_layout(&self) {
406        crate::serial_println!("\n╔════════════════════════════════════════╗");
407        crate::serial_println!("║      地址空间布局                      ║");
408        crate::serial_println!("╠════════════════════════════════════════╣");
409        crate::serial_println!(
410            "║ 页表物理地址: {:#018x}      ║",
411            self.page_table_paddr.as_usize()
412        );
413        crate::serial_println!("╠════════════════════════════════════════╣");
414        crate::serial_println!("║ 内存区域:                              ║");
415
416        for (i, area) in self.areas.iter().enumerate() {
417            crate::serial_println!(
418                "║ [{:2}] {:8?} {:#010x} - {:#010x} ║",
419                i,
420                area.area_type,
421                area.range.start.as_usize(),
422                area.range.end.as_usize()
423            );
424        }
425
426        crate::serial_println!("╚════════════════════════════════════════╝\n");
427    }
428}
429
430// 由于我们存储的是原始指针,需要手动实现 Send
431unsafe impl Send for AddressSpace {}
432unsafe impl Sync for AddressSpace {}
433
434/// 创建内核地址空间
435///
436/// # 功能
437/// - 映射内核代码和数据段(恒等映射)
438/// - 映射物理内存
439/// - 映射 MMIO 设备
440///
441/// # 教学说明
442/// 内核地址空间使用恒等映射,这样内核代码可以直接访问物理地址
443pub fn create_kernel_address_space(
444    allocator: &mut SimpleFrameAllocator,
445) -> Result<AddressSpace, &'static str> {
446    let mut addr_space = AddressSpace::new(allocator)?;
447
448    crate::serial_println!("\n[KERNEL] Creating kernel address space...");
449
450    // 1. Map a minimal kernel region first for safety, then expand
451    const KERNEL_START: usize = 0x8000_0000;
452    const KERNEL_MAP_SIZE: usize = 8 * 1024 * 1024; // 8 MB — room for kernel + fork allocations
453
454    crate::serial_println!("[KERNEL] step1");
455    addr_space.map_region_identity(
456        PhysAddr::new(KERNEL_START),
457        KERNEL_MAP_SIZE,
458        MemoryAreaType::Kernel,
459        allocator,
460    )?;
461    crate::serial_println!(
462        "[KERNEL] Kernel region mapped OK ({} MB)",
463        KERNEL_MAP_SIZE / 1024 / 1024
464    );
465
466    // 2. 映射 UART(0x10000000)
467    const UART_BASE: usize = 0x1000_0000;
468
469    crate::serial_println!("[KERNEL] Mapping UART: {:#x}", UART_BASE);
470
471    addr_space.map_region_identity(
472        PhysAddr::new(UART_BASE),
473        PAGE_SIZE,
474        MemoryAreaType::Data,
475        allocator,
476    )?;
477
478    crate::serial_println!("[KERNEL] Kernel address space created successfully\n");
479
480    Ok(addr_space)
481}
482
483#[cfg(test)]
484mod tests {
485    use super::*;
486    use crate::memory::paging::{map_page, walk_page_table};
487
488    #[test_case]
489    fn deep_copy_user_address_space_copies_user_pages_independently() {
490        let mut allocator = SimpleFrameAllocator::new(0x8060_0000, 0x8070_0000);
491        let root_frame = allocator.allocate().expect("root frame");
492        let root_paddr = root_frame.start_address();
493        let root = unsafe { &mut *(root_paddr.as_usize() as *mut PageTable) };
494        root.zero();
495
496        let user_vaddr = VirtAddr::new(0x4000);
497        let user_frame = allocator.allocate().expect("user page");
498        unsafe {
499            let page = user_frame.start_address().as_usize() as *mut u8;
500            *page = 0x5a;
501            *page.add(1) = 0xa5;
502        }
503
504        map_page(
505            root,
506            user_vaddr,
507            user_frame.start_address(),
508            PageTableFlags::Read as usize
509                | PageTableFlags::Write as usize
510                | PageTableFlags::User as usize,
511            &mut allocator,
512        )
513        .expect("map user page");
514
515        let kernel_vaddr = VirtAddr::new(0x8000_0000);
516        let kernel_frame = allocator.allocate().expect("kernel page");
517        map_page(
518            root,
519            kernel_vaddr,
520            kernel_frame.start_address(),
521            PageTableFlags::Read as usize | PageTableFlags::Write as usize,
522            &mut allocator,
523        )
524        .expect("map kernel page");
525
526        let src_satp = (8usize << 60) | (root_paddr.as_usize() >> 12);
527        let child_satp =
528            deep_copy_user_address_space(src_satp, &mut allocator).expect("copy address space");
529        let child_root_paddr = PhysAddr::new((child_satp & 0x0000_0FFF_FFFF_FFFF) << 12);
530
531        let parent_user_paddr =
532            walk_page_table(root_paddr, user_vaddr).expect("parent user mapping");
533        let child_user_paddr =
534            walk_page_table(child_root_paddr, user_vaddr).expect("child user mapping");
535        assert_ne!(
536            parent_user_paddr.as_usize() & !(PAGE_SIZE - 1),
537            child_user_paddr.as_usize() & !(PAGE_SIZE - 1)
538        );
539
540        unsafe {
541            let parent_page = parent_user_paddr.as_usize() as *mut u8;
542            let child_page = child_user_paddr.as_usize() as *mut u8;
543            assert_eq!(*child_page, 0x5a);
544            assert_eq!(*child_page.add(1), 0xa5);
545            *child_page = 0x11;
546            assert_eq!(*parent_page, 0x5a);
547        }
548
549        let child_kernel_paddr =
550            walk_page_table(child_root_paddr, kernel_vaddr).expect("child kernel mapping");
551        assert_eq!(child_kernel_paddr, kernel_frame.start_address());
552    }
553}