strat9_kernel/ipc/v2/memobj.rs
1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Memory objects (IPC ABI v2, ยง9.1).
24//!
25//! A MemObject owns zeroed frames registered in the frame ownership table
26//! (the `SharedRing` machinery). Lifetime is reference-counted per frame:
27//!
28//! - the object holds one owner reference per frame, dropped with the last
29//! handle;
30//! - every `SYS_MEMOBJ_MAP` mapping registers a **fresh** mapping identity per
31//! page, dropped by `munmap` or address-space teardown.
32//!
33//! A frame returns to the allocator only when both kinds of reference are
34//! gone, so closing every handle while a mapping exists (or the reverse) can
35//! never expose a freed frame.
36//!
37//! Accounting: the backing is charged to the creator's silo at creation
38//! (released with the object). Each mapping is additionally charged as a
39//! virtual region to the mapping silo, like every other mapping, because
40//! `munmap` and address-space teardown always refund the mapping length:
41//! an uncharged (`AlreadyCharged`) mapping would make that refund credit
42//! bytes that were never charged.
43
44use super::quota::MemCharge;
45use crate::{
46 ipc::shared_ring::{self, SharedRing},
47 memory::address_space::{AddressSpace, SiloCharge, VmaFlags, VmaPageSize, VmaType},
48 syscall::error::SyscallError,
49};
50use alloc::vec::Vec;
51use strat9_abi::ipc_v2::{
52 MEMOBJ_MAX_SIZE, MEMOBJ_PROT_EXEC, MEMOBJ_PROT_READ, MEMOBJ_PROT_WRITE, MEM_EXEC, MEM_READ,
53 MEM_WRITE,
54};
55
56const PAGE: u64 = 4096;
57
58/// A shareable, mappable memory object.
59pub struct MemObject {
60 frames: SharedRing,
61 /// Page-rounded size in bytes.
62 size: u64,
63 _charge: Option<MemCharge>,
64}
65
66impl MemObject {
67 /// Allocate a zeroed object of `size` bytes (rounded up to pages).
68 ///
69 /// `charge` pays for the backing; it is taken by the caller so a quota
70 /// failure happens before any frame is allocated.
71 pub fn create(size: u64, charge: Option<MemCharge>) -> Result<MemObject, SyscallError> {
72 let size = page_round(size)?;
73 let frames = shared_ring::allocate_ring(size as usize).map_err(|e| match e {
74 shared_ring::RingError::InvalidSize => SyscallError::InvalidArgument,
75 _ => SyscallError::OutOfMemory,
76 })?;
77 Ok(MemObject {
78 frames,
79 size,
80 _charge: charge,
81 })
82 }
83
84 /// Page-rounded size in bytes.
85 pub fn size(&self) -> u64 {
86 self.size
87 }
88
89 /// Map `[offset, offset + len)` of the object into `aspace`.
90 ///
91 /// `prot` (`MEMOBJ_PROT_*`) must be covered by `rights` (`MEM_*`);
92 /// `addr_hint == 0` lets the kernel choose. Returns the mapped address.
93 pub fn map(
94 &self,
95 aspace: &AddressSpace,
96 rights: u32,
97 addr_hint: u64,
98 offset: u64,
99 len: u64,
100 prot: u32,
101 ) -> Result<u64, SyscallError> {
102 if prot & !(MEMOBJ_PROT_READ | MEMOBJ_PROT_WRITE | MEMOBJ_PROT_EXEC) != 0 {
103 return Err(SyscallError::InvalidArgument);
104 }
105 let needs = |p: u32, r: u32| prot & p == 0 || rights & r != 0;
106 if !(needs(MEMOBJ_PROT_READ, MEM_READ)
107 && needs(MEMOBJ_PROT_WRITE, MEM_WRITE)
108 && needs(MEMOBJ_PROT_EXEC, MEM_EXEC))
109 {
110 return Err(SyscallError::PermissionDenied);
111 }
112 if len == 0 || offset % PAGE != 0 || len % PAGE != 0 || addr_hint % PAGE != 0 {
113 return Err(SyscallError::InvalidArgument);
114 }
115 let end = offset
116 .checked_add(len)
117 .ok_or(SyscallError::InvalidArgument)?;
118 if end > self.size {
119 return Err(SyscallError::InvalidArgument);
120 }
121 let first = (offset / PAGE) as usize;
122 let count = (len / PAGE) as usize;
123 let phys: Vec<u64> = self.frames.frame_phys_addrs()[first..first + count].to_vec();
124 let handles: Vec<_> = phys
125 .iter()
126 .map(|p| crate::memory::resolve_handle(crate::arch::xshim::PhysAddr::new(*p)))
127 .collect();
128
129 let base = if addr_hint != 0 {
130 addr_hint
131 } else {
132 aspace
133 .find_free_vma_range(crate::kaslr::mmap_base(), count, VmaPageSize::Small)
134 .ok_or(SyscallError::OutOfMemory)?
135 };
136 // Fresh per-page mapping identities (`None`): each mapping holds its
137 // own frame reference. Charged as a region (refunded by munmap).
138 aspace
139 .map_shared_handles_with_cap_ids_charged(
140 base,
141 &handles,
142 None,
143 VmaFlags {
144 readable: prot & MEMOBJ_PROT_READ != 0,
145 writable: prot & MEMOBJ_PROT_WRITE != 0,
146 executable: prot & MEMOBJ_PROT_EXEC != 0,
147 user_accessible: true,
148 },
149 VmaType::Anonymous,
150 VmaPageSize::Small,
151 SiloCharge::Charge,
152 )
153 .map_err(|_| SyscallError::OutOfMemory)?;
154 Ok(base)
155 }
156}
157
158/// Validate a requested size and round it up to whole pages.
159pub fn page_round(size: u64) -> Result<u64, SyscallError> {
160 if size == 0 || size > MEMOBJ_MAX_SIZE {
161 return Err(SyscallError::InvalidArgument);
162 }
163 Ok(size.div_ceil(PAGE) * PAGE)
164}