Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 1 | // Copyright 2023, The Android Open Source Project |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | //! Shared memory management. |
| 16 | |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 17 | use super::dbm::{flush_dirty_range, mark_dirty_block, set_dbm_enabled}; |
| 18 | use super::error::MemoryTrackerError; |
| 19 | use super::page_table::{is_leaf_pte, PageTable, MMIO_LAZY_MAP_FLAG}; |
| 20 | use super::util::{page_4kb_of, virt_to_phys}; |
| 21 | use crate::dsb; |
Alice Wang | a9fe1fb | 2023-07-04 09:10:35 +0000 | [diff] [blame] | 22 | use crate::exceptions::HandleExceptionError; |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 23 | use crate::util::RangeExt as _; |
Alice Wang | a3931aa | 2023-07-05 12:52:09 +0000 | [diff] [blame] | 24 | use aarch64_paging::paging::{Attributes, Descriptor, MemoryRegion as VaRange, VirtualAddress}; |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 25 | use alloc::alloc::{alloc_zeroed, dealloc, handle_alloc_error}; |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 26 | use alloc::boxed::Box; |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 27 | use alloc::vec::Vec; |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 28 | use buddy_system_allocator::{FrameAllocator, LockedFrameAllocator}; |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 29 | use core::alloc::Layout; |
Pierre-Clément Tosi | 8937cb8 | 2023-07-06 15:07:38 +0000 | [diff] [blame] | 30 | use core::mem::size_of; |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 31 | use core::num::NonZeroUsize; |
| 32 | use core::ops::Range; |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 33 | use core::ptr::NonNull; |
Alice Wang | b73a81b | 2023-06-07 13:05:09 +0000 | [diff] [blame] | 34 | use core::result; |
Pierre-Clément Tosi | d643cfe | 2023-06-29 09:30:51 +0000 | [diff] [blame] | 35 | use hyp::{get_mem_sharer, get_mmio_guard, MMIO_GUARD_GRANULE_SIZE}; |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 36 | use log::{debug, error, trace}; |
| 37 | use once_cell::race::OnceBox; |
| 38 | use spin::mutex::SpinMutex; |
| 39 | use tinyvec::ArrayVec; |
| 40 | |
| 41 | /// A global static variable representing the system memory tracker, protected by a spin mutex. |
| 42 | pub static MEMORY: SpinMutex<Option<MemoryTracker>> = SpinMutex::new(None); |
| 43 | |
| 44 | static SHARED_POOL: OnceBox<LockedFrameAllocator<32>> = OnceBox::new(); |
| 45 | static SHARED_MEMORY: SpinMutex<Option<MemorySharer>> = SpinMutex::new(None); |
| 46 | |
| 47 | /// Memory range. |
| 48 | pub type MemoryRange = Range<usize>; |
Alice Wang | a3931aa | 2023-07-05 12:52:09 +0000 | [diff] [blame] | 49 | |
| 50 | fn get_va_range(range: &MemoryRange) -> VaRange { |
| 51 | VaRange::new(range.start, range.end) |
| 52 | } |
| 53 | |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 54 | type Result<T> = result::Result<T, MemoryTrackerError>; |
| 55 | |
| 56 | #[derive(Clone, Copy, Debug, Default, PartialEq)] |
| 57 | enum MemoryType { |
| 58 | #[default] |
| 59 | ReadOnly, |
| 60 | ReadWrite, |
| 61 | } |
| 62 | |
| 63 | #[derive(Clone, Debug, Default)] |
| 64 | struct MemoryRegion { |
| 65 | range: MemoryRange, |
| 66 | mem_type: MemoryType, |
| 67 | } |
| 68 | |
| 69 | /// Tracks non-overlapping slices of main memory. |
| 70 | pub struct MemoryTracker { |
| 71 | total: MemoryRange, |
| 72 | page_table: PageTable, |
| 73 | regions: ArrayVec<[MemoryRegion; MemoryTracker::CAPACITY]>, |
| 74 | mmio_regions: ArrayVec<[MemoryRange; MemoryTracker::MMIO_CAPACITY]>, |
| 75 | mmio_range: MemoryRange, |
Alice Wang | 5bb7950 | 2023-06-12 09:25:07 +0000 | [diff] [blame] | 76 | payload_range: Option<MemoryRange>, |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 77 | } |
| 78 | |
Andrew Walbran | c06e734 | 2023-07-05 14:00:51 +0000 | [diff] [blame] | 79 | // TODO: Remove this once aarch64-paging crate is updated. |
| 80 | // SAFETY: Only `PageTable` doesn't implement Send, but it should. |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 81 | unsafe impl Send for MemoryTracker {} |
| 82 | |
| 83 | impl MemoryTracker { |
| 84 | const CAPACITY: usize = 5; |
| 85 | const MMIO_CAPACITY: usize = 5; |
| 86 | |
| 87 | /// Creates a new instance from an active page table, covering the maximum RAM size. |
| 88 | pub fn new( |
| 89 | mut page_table: PageTable, |
| 90 | total: MemoryRange, |
| 91 | mmio_range: MemoryRange, |
Alice Wang | a3931aa | 2023-07-05 12:52:09 +0000 | [diff] [blame] | 92 | payload_range: Option<Range<VirtualAddress>>, |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 93 | ) -> Self { |
| 94 | assert!( |
| 95 | !total.overlaps(&mmio_range), |
| 96 | "MMIO space should not overlap with the main memory region." |
| 97 | ); |
| 98 | |
| 99 | // Activate dirty state management first, otherwise we may get permission faults immediately |
| 100 | // after activating the new page table. This has no effect before the new page table is |
| 101 | // activated because none of the entries in the initial idmap have the DBM flag. |
| 102 | set_dbm_enabled(true); |
| 103 | |
| 104 | debug!("Activating dynamic page table..."); |
Andrew Walbran | c06e734 | 2023-07-05 14:00:51 +0000 | [diff] [blame] | 105 | // SAFETY: page_table duplicates the static mappings for everything that the Rust code is |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 106 | // aware of so activating it shouldn't have any visible effect. |
| 107 | unsafe { page_table.activate() } |
| 108 | debug!("... Success!"); |
| 109 | |
| 110 | Self { |
| 111 | total, |
| 112 | page_table, |
| 113 | regions: ArrayVec::new(), |
| 114 | mmio_regions: ArrayVec::new(), |
| 115 | mmio_range, |
Alice Wang | a3931aa | 2023-07-05 12:52:09 +0000 | [diff] [blame] | 116 | payload_range: payload_range.map(|r| r.start.0..r.end.0), |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 117 | } |
| 118 | } |
| 119 | |
| 120 | /// Resize the total RAM size. |
| 121 | /// |
| 122 | /// This function fails if it contains regions that are not included within the new size. |
| 123 | pub fn shrink(&mut self, range: &MemoryRange) -> Result<()> { |
| 124 | if range.start != self.total.start { |
| 125 | return Err(MemoryTrackerError::DifferentBaseAddress); |
| 126 | } |
| 127 | if self.total.end < range.end { |
| 128 | return Err(MemoryTrackerError::SizeTooLarge); |
| 129 | } |
| 130 | if !self.regions.iter().all(|r| r.range.is_within(range)) { |
| 131 | return Err(MemoryTrackerError::SizeTooSmall); |
| 132 | } |
| 133 | |
| 134 | self.total = range.clone(); |
| 135 | Ok(()) |
| 136 | } |
| 137 | |
| 138 | /// Allocate the address range for a const slice; returns None if failed. |
| 139 | pub fn alloc_range(&mut self, range: &MemoryRange) -> Result<MemoryRange> { |
| 140 | let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadOnly }; |
| 141 | self.check(®ion)?; |
Alice Wang | a3931aa | 2023-07-05 12:52:09 +0000 | [diff] [blame] | 142 | self.page_table.map_rodata(&get_va_range(range)).map_err(|e| { |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 143 | error!("Error during range allocation: {e}"); |
| 144 | MemoryTrackerError::FailedToMap |
| 145 | })?; |
| 146 | self.add(region) |
| 147 | } |
| 148 | |
| 149 | /// Allocate the address range for a mutable slice; returns None if failed. |
| 150 | pub fn alloc_range_mut(&mut self, range: &MemoryRange) -> Result<MemoryRange> { |
| 151 | let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadWrite }; |
| 152 | self.check(®ion)?; |
Alice Wang | a3931aa | 2023-07-05 12:52:09 +0000 | [diff] [blame] | 153 | self.page_table.map_data_dbm(&get_va_range(range)).map_err(|e| { |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 154 | error!("Error during mutable range allocation: {e}"); |
| 155 | MemoryTrackerError::FailedToMap |
| 156 | })?; |
| 157 | self.add(region) |
| 158 | } |
| 159 | |
| 160 | /// Allocate the address range for a const slice; returns None if failed. |
| 161 | pub fn alloc(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> { |
| 162 | self.alloc_range(&(base..(base + size.get()))) |
| 163 | } |
| 164 | |
| 165 | /// Allocate the address range for a mutable slice; returns None if failed. |
| 166 | pub fn alloc_mut(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> { |
| 167 | self.alloc_range_mut(&(base..(base + size.get()))) |
| 168 | } |
| 169 | |
| 170 | /// Checks that the given range of addresses is within the MMIO region, and then maps it |
| 171 | /// appropriately. |
| 172 | pub fn map_mmio_range(&mut self, range: MemoryRange) -> Result<()> { |
| 173 | if !range.is_within(&self.mmio_range) { |
| 174 | return Err(MemoryTrackerError::OutOfRange); |
| 175 | } |
| 176 | if self.mmio_regions.iter().any(|r| range.overlaps(r)) { |
| 177 | return Err(MemoryTrackerError::Overlaps); |
| 178 | } |
| 179 | if self.mmio_regions.len() == self.mmio_regions.capacity() { |
| 180 | return Err(MemoryTrackerError::Full); |
| 181 | } |
| 182 | |
Pierre-Clément Tosi | d643cfe | 2023-06-29 09:30:51 +0000 | [diff] [blame] | 183 | if get_mmio_guard().is_some() { |
Pierre-Clément Tosi | 32279ef | 2023-06-29 10:46:59 +0000 | [diff] [blame] | 184 | self.page_table.map_device_lazy(&get_va_range(&range)).map_err(|e| { |
| 185 | error!("Error during lazy MMIO device mapping: {e}"); |
| 186 | MemoryTrackerError::FailedToMap |
| 187 | })?; |
| 188 | } else { |
| 189 | self.page_table.map_device(&get_va_range(&range)).map_err(|e| { |
| 190 | error!("Error during MMIO device mapping: {e}"); |
| 191 | MemoryTrackerError::FailedToMap |
| 192 | })?; |
| 193 | } |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 194 | |
| 195 | if self.mmio_regions.try_push(range).is_some() { |
| 196 | return Err(MemoryTrackerError::Full); |
| 197 | } |
| 198 | |
| 199 | Ok(()) |
| 200 | } |
| 201 | |
| 202 | /// Checks that the given region is within the range of the `MemoryTracker` and doesn't overlap |
| 203 | /// with any other previously allocated regions, and that the regions ArrayVec has capacity to |
| 204 | /// add it. |
| 205 | fn check(&self, region: &MemoryRegion) -> Result<()> { |
| 206 | if !region.range.is_within(&self.total) { |
| 207 | return Err(MemoryTrackerError::OutOfRange); |
| 208 | } |
| 209 | if self.regions.iter().any(|r| region.range.overlaps(&r.range)) { |
| 210 | return Err(MemoryTrackerError::Overlaps); |
| 211 | } |
| 212 | if self.regions.len() == self.regions.capacity() { |
| 213 | return Err(MemoryTrackerError::Full); |
| 214 | } |
| 215 | Ok(()) |
| 216 | } |
| 217 | |
| 218 | fn add(&mut self, region: MemoryRegion) -> Result<MemoryRange> { |
| 219 | if self.regions.try_push(region).is_some() { |
| 220 | return Err(MemoryTrackerError::Full); |
| 221 | } |
| 222 | |
| 223 | Ok(self.regions.last().unwrap().range.clone()) |
| 224 | } |
| 225 | |
| 226 | /// Unmaps all tracked MMIO regions from the MMIO guard. |
| 227 | /// |
| 228 | /// Note that they are not unmapped from the page table. |
| 229 | pub fn mmio_unmap_all(&mut self) -> Result<()> { |
Pierre-Clément Tosi | d643cfe | 2023-06-29 09:30:51 +0000 | [diff] [blame] | 230 | if get_mmio_guard().is_some() { |
Pierre-Clément Tosi | 32279ef | 2023-06-29 10:46:59 +0000 | [diff] [blame] | 231 | for range in &self.mmio_regions { |
| 232 | self.page_table |
| 233 | .modify_range(&get_va_range(range), &mmio_guard_unmap_page) |
| 234 | .map_err(|_| MemoryTrackerError::FailedToUnmap)?; |
| 235 | } |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 236 | } |
| 237 | Ok(()) |
| 238 | } |
| 239 | |
| 240 | /// Initialize the shared heap to dynamically share memory from the global allocator. |
Alice Wang | b6d2c64 | 2023-06-13 13:07:06 +0000 | [diff] [blame] | 241 | pub fn init_dynamic_shared_pool(&mut self, granule: usize) -> Result<()> { |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 242 | const INIT_CAP: usize = 10; |
| 243 | |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 244 | let previous = SHARED_MEMORY.lock().replace(MemorySharer::new(granule, INIT_CAP)); |
| 245 | if previous.is_some() { |
| 246 | return Err(MemoryTrackerError::SharedMemorySetFailure); |
| 247 | } |
| 248 | |
| 249 | SHARED_POOL |
| 250 | .set(Box::new(LockedFrameAllocator::new())) |
| 251 | .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?; |
| 252 | |
| 253 | Ok(()) |
| 254 | } |
| 255 | |
| 256 | /// Initialize the shared heap from a static region of memory. |
| 257 | /// |
| 258 | /// Some hypervisors such as Gunyah do not support a MemShare API for guest |
| 259 | /// to share its memory with host. Instead they allow host to designate part |
| 260 | /// of guest memory as "shared" ahead of guest starting its execution. The |
| 261 | /// shared memory region is indicated in swiotlb node. On such platforms use |
| 262 | /// a separate heap to allocate buffers that can be shared with host. |
| 263 | pub fn init_static_shared_pool(&mut self, range: Range<usize>) -> Result<()> { |
| 264 | let size = NonZeroUsize::new(range.len()).unwrap(); |
| 265 | let range = self.alloc_mut(range.start, size)?; |
| 266 | let shared_pool = LockedFrameAllocator::<32>::new(); |
| 267 | |
| 268 | shared_pool.lock().insert(range); |
| 269 | |
| 270 | SHARED_POOL |
| 271 | .set(Box::new(shared_pool)) |
| 272 | .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?; |
| 273 | |
| 274 | Ok(()) |
| 275 | } |
| 276 | |
Pierre-Clément Tosi | 8937cb8 | 2023-07-06 15:07:38 +0000 | [diff] [blame] | 277 | /// Initialize the shared heap to use heap memory directly. |
| 278 | /// |
| 279 | /// When running on "non-protected" hypervisors which permit host direct accesses to guest |
| 280 | /// memory, there is no need to perform any memory sharing and/or allocate buffers from a |
| 281 | /// dedicated region so this function instructs the shared pool to use the global allocator. |
| 282 | pub fn init_heap_shared_pool(&mut self) -> Result<()> { |
| 283 | // As MemorySharer only calls MEM_SHARE methods if the hypervisor supports them, internally |
| 284 | // using init_dynamic_shared_pool() on a non-protected platform will make use of the heap |
| 285 | // without any actual "dynamic memory sharing" taking place and, as such, the granule may |
| 286 | // be set to the one of the global_allocator i.e. a byte. |
| 287 | self.init_dynamic_shared_pool(size_of::<u8>()) |
| 288 | } |
| 289 | |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 290 | /// Unshares any memory that may have been shared. |
| 291 | pub fn unshare_all_memory(&mut self) { |
| 292 | drop(SHARED_MEMORY.lock().take()); |
| 293 | } |
| 294 | |
| 295 | /// Handles translation fault for blocks flagged for lazy MMIO mapping by enabling the page |
| 296 | /// table entry and MMIO guard mapping the block. Breaks apart a block entry if required. |
Alice Wang | a9fe1fb | 2023-07-04 09:10:35 +0000 | [diff] [blame] | 297 | fn handle_mmio_fault(&mut self, addr: VirtualAddress) -> Result<()> { |
Alice Wang | 8873646 | 2023-07-05 12:14:15 +0000 | [diff] [blame] | 298 | let page_start = VirtualAddress(page_4kb_of(addr.0)); |
Alice Wang | a3931aa | 2023-07-05 12:52:09 +0000 | [diff] [blame] | 299 | let page_range: VaRange = (page_start..page_start + MMIO_GUARD_GRANULE_SIZE).into(); |
Pierre-Clément Tosi | d643cfe | 2023-06-29 09:30:51 +0000 | [diff] [blame] | 300 | let mmio_guard = get_mmio_guard().unwrap(); |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 301 | self.page_table |
| 302 | .modify_range(&page_range, &verify_lazy_mapped_block) |
| 303 | .map_err(|_| MemoryTrackerError::InvalidPte)?; |
Pierre-Clément Tosi | d643cfe | 2023-06-29 09:30:51 +0000 | [diff] [blame] | 304 | mmio_guard.map(page_start.0)?; |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 305 | // Maps a single device page, breaking up block mappings if necessary. |
| 306 | self.page_table.map_device(&page_range).map_err(|_| MemoryTrackerError::FailedToMap) |
| 307 | } |
| 308 | |
| 309 | /// Flush all memory regions marked as writable-dirty. |
| 310 | fn flush_dirty_pages(&mut self) -> Result<()> { |
| 311 | // Collect memory ranges for which dirty state is tracked. |
| 312 | let writable_regions = |
| 313 | self.regions.iter().filter(|r| r.mem_type == MemoryType::ReadWrite).map(|r| &r.range); |
| 314 | // Execute a barrier instruction to ensure all hardware updates to the page table have been |
| 315 | // observed before reading PTE flags to determine dirty state. |
| 316 | dsb!("ish"); |
| 317 | // Now flush writable-dirty pages in those regions. |
Alice Wang | 5bb7950 | 2023-06-12 09:25:07 +0000 | [diff] [blame] | 318 | for range in writable_regions.chain(self.payload_range.as_ref().into_iter()) { |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 319 | self.page_table |
Alice Wang | a3931aa | 2023-07-05 12:52:09 +0000 | [diff] [blame] | 320 | .modify_range(&get_va_range(range), &flush_dirty_range) |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 321 | .map_err(|_| MemoryTrackerError::FlushRegionFailed)?; |
| 322 | } |
| 323 | Ok(()) |
| 324 | } |
| 325 | |
| 326 | /// Handles permission fault for read-only blocks by setting writable-dirty state. |
| 327 | /// In general, this should be called from the exception handler when hardware dirty |
| 328 | /// state management is disabled or unavailable. |
Alice Wang | a9fe1fb | 2023-07-04 09:10:35 +0000 | [diff] [blame] | 329 | fn handle_permission_fault(&mut self, addr: VirtualAddress) -> Result<()> { |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 330 | self.page_table |
Alice Wang | a3931aa | 2023-07-05 12:52:09 +0000 | [diff] [blame] | 331 | .modify_range(&(addr..addr + 1).into(), &mark_dirty_block) |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 332 | .map_err(|_| MemoryTrackerError::SetPteDirtyFailed) |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | impl Drop for MemoryTracker { |
| 337 | fn drop(&mut self) { |
| 338 | set_dbm_enabled(false); |
| 339 | self.flush_dirty_pages().unwrap(); |
| 340 | self.unshare_all_memory(); |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | /// Allocates a memory range of at least the given size and alignment that is shared with the host. |
| 345 | /// Returns a pointer to the buffer. |
| 346 | pub fn alloc_shared(layout: Layout) -> hyp::Result<NonNull<u8>> { |
| 347 | assert_ne!(layout.size(), 0); |
| 348 | let Some(buffer) = try_shared_alloc(layout) else { |
| 349 | handle_alloc_error(layout); |
| 350 | }; |
| 351 | |
| 352 | trace!("Allocated shared buffer at {buffer:?} with {layout:?}"); |
| 353 | Ok(buffer) |
| 354 | } |
| 355 | |
| 356 | fn try_shared_alloc(layout: Layout) -> Option<NonNull<u8>> { |
| 357 | let mut shared_pool = SHARED_POOL.get().unwrap().lock(); |
| 358 | |
| 359 | if let Some(buffer) = shared_pool.alloc_aligned(layout) { |
| 360 | Some(NonNull::new(buffer as _).unwrap()) |
| 361 | } else if let Some(shared_memory) = SHARED_MEMORY.lock().as_mut() { |
| 362 | shared_memory.refill(&mut shared_pool, layout); |
| 363 | shared_pool.alloc_aligned(layout).map(|buffer| NonNull::new(buffer as _).unwrap()) |
| 364 | } else { |
| 365 | None |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | /// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`. |
| 370 | /// |
| 371 | /// The layout passed in must be the same layout passed to the original `alloc_shared` call. |
| 372 | /// |
| 373 | /// # Safety |
| 374 | /// |
| 375 | /// The memory must have been allocated by `alloc_shared` with the same layout, and not yet |
| 376 | /// deallocated. |
| 377 | pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, layout: Layout) -> hyp::Result<()> { |
| 378 | SHARED_POOL.get().unwrap().lock().dealloc_aligned(vaddr.as_ptr() as usize, layout); |
| 379 | |
| 380 | trace!("Deallocated shared buffer at {vaddr:?} with {layout:?}"); |
| 381 | Ok(()) |
| 382 | } |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 383 | |
| 384 | /// Allocates memory on the heap and shares it with the host. |
| 385 | /// |
| 386 | /// Unshares all pages when dropped. |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 387 | struct MemorySharer { |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 388 | granule: usize, |
Pierre-Clément Tosi | d2f7ad1 | 2023-06-29 11:48:29 +0000 | [diff] [blame] | 389 | frames: Vec<(usize, Layout)>, |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 390 | } |
| 391 | |
| 392 | impl MemorySharer { |
| 393 | /// Constructs a new `MemorySharer` instance with the specified granule size and capacity. |
| 394 | /// `granule` must be a power of 2. |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 395 | fn new(granule: usize, capacity: usize) -> Self { |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 396 | assert!(granule.is_power_of_two()); |
Pierre-Clément Tosi | d2f7ad1 | 2023-06-29 11:48:29 +0000 | [diff] [blame] | 397 | Self { granule, frames: Vec::with_capacity(capacity) } |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 398 | } |
| 399 | |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 400 | /// Gets from the global allocator a granule-aligned region that suits `hint` and share it. |
| 401 | fn refill(&mut self, pool: &mut FrameAllocator<32>, hint: Layout) { |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 402 | let layout = hint.align_to(self.granule).unwrap().pad_to_align(); |
| 403 | assert_ne!(layout.size(), 0); |
Andrew Walbran | c06e734 | 2023-07-05 14:00:51 +0000 | [diff] [blame] | 404 | // SAFETY: layout has non-zero size. |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 405 | let Some(shared) = NonNull::new(unsafe { alloc_zeroed(layout) }) else { |
| 406 | handle_alloc_error(layout); |
| 407 | }; |
| 408 | |
| 409 | let base = shared.as_ptr() as usize; |
| 410 | let end = base.checked_add(layout.size()).unwrap(); |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 411 | |
Pierre-Clément Tosi | d643cfe | 2023-06-29 09:30:51 +0000 | [diff] [blame] | 412 | if let Some(mem_sharer) = get_mem_sharer() { |
Pierre-Clément Tosi | d2f7ad1 | 2023-06-29 11:48:29 +0000 | [diff] [blame] | 413 | trace!("Sharing memory region {:#x?}", base..end); |
| 414 | for vaddr in (base..end).step_by(self.granule) { |
| 415 | let vaddr = NonNull::new(vaddr as *mut _).unwrap(); |
Pierre-Clément Tosi | d643cfe | 2023-06-29 09:30:51 +0000 | [diff] [blame] | 416 | mem_sharer.share(virt_to_phys(vaddr).try_into().unwrap()).unwrap(); |
Pierre-Clément Tosi | d2f7ad1 | 2023-06-29 11:48:29 +0000 | [diff] [blame] | 417 | } |
| 418 | } |
| 419 | |
| 420 | self.frames.push((base, layout)); |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 421 | pool.add_frame(base, end); |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | impl Drop for MemorySharer { |
| 426 | fn drop(&mut self) { |
Pierre-Clément Tosi | d2f7ad1 | 2023-06-29 11:48:29 +0000 | [diff] [blame] | 427 | while let Some((base, layout)) = self.frames.pop() { |
Pierre-Clément Tosi | d643cfe | 2023-06-29 09:30:51 +0000 | [diff] [blame] | 428 | if let Some(mem_sharer) = get_mem_sharer() { |
Pierre-Clément Tosi | d2f7ad1 | 2023-06-29 11:48:29 +0000 | [diff] [blame] | 429 | let end = base.checked_add(layout.size()).unwrap(); |
| 430 | trace!("Unsharing memory region {:#x?}", base..end); |
| 431 | for vaddr in (base..end).step_by(self.granule) { |
| 432 | let vaddr = NonNull::new(vaddr as *mut _).unwrap(); |
Pierre-Clément Tosi | d643cfe | 2023-06-29 09:30:51 +0000 | [diff] [blame] | 433 | mem_sharer.unshare(virt_to_phys(vaddr).try_into().unwrap()).unwrap(); |
Pierre-Clément Tosi | d2f7ad1 | 2023-06-29 11:48:29 +0000 | [diff] [blame] | 434 | } |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 435 | } |
| 436 | |
Andrew Walbran | c06e734 | 2023-07-05 14:00:51 +0000 | [diff] [blame] | 437 | // SAFETY: The region was obtained from alloc_zeroed() with the recorded layout. |
Alice Wang | f47b234 | 2023-06-02 11:51:57 +0000 | [diff] [blame] | 438 | unsafe { dealloc(base as *mut _, layout) }; |
| 439 | } |
| 440 | } |
| 441 | } |
Alice Wang | b73a81b | 2023-06-07 13:05:09 +0000 | [diff] [blame] | 442 | |
| 443 | /// Checks whether block flags indicate it should be MMIO guard mapped. |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 444 | fn verify_lazy_mapped_block( |
Alice Wang | b73a81b | 2023-06-07 13:05:09 +0000 | [diff] [blame] | 445 | _range: &VaRange, |
| 446 | desc: &mut Descriptor, |
| 447 | level: usize, |
| 448 | ) -> result::Result<(), ()> { |
| 449 | let flags = desc.flags().expect("Unsupported PTE flags set"); |
| 450 | if !is_leaf_pte(&flags, level) { |
| 451 | return Ok(()); // Skip table PTEs as they aren't tagged with MMIO_LAZY_MAP_FLAG. |
| 452 | } |
| 453 | if flags.contains(MMIO_LAZY_MAP_FLAG) && !flags.contains(Attributes::VALID) { |
| 454 | Ok(()) |
| 455 | } else { |
| 456 | Err(()) |
| 457 | } |
| 458 | } |
| 459 | |
| 460 | /// MMIO guard unmaps page |
Alice Wang | 93ee98a | 2023-06-08 08:20:39 +0000 | [diff] [blame] | 461 | fn mmio_guard_unmap_page( |
Alice Wang | b73a81b | 2023-06-07 13:05:09 +0000 | [diff] [blame] | 462 | va_range: &VaRange, |
| 463 | desc: &mut Descriptor, |
| 464 | level: usize, |
| 465 | ) -> result::Result<(), ()> { |
| 466 | let flags = desc.flags().expect("Unsupported PTE flags set"); |
| 467 | if !is_leaf_pte(&flags, level) { |
| 468 | return Ok(()); |
| 469 | } |
| 470 | // This function will be called on an address range that corresponds to a device. Only if a |
| 471 | // page has been accessed (written to or read from), will it contain the VALID flag and be MMIO |
| 472 | // guard mapped. Therefore, we can skip unmapping invalid pages, they were never MMIO guard |
| 473 | // mapped anyway. |
| 474 | if flags.contains(Attributes::VALID) { |
| 475 | assert!( |
| 476 | flags.contains(MMIO_LAZY_MAP_FLAG), |
| 477 | "Attempting MMIO guard unmap for non-device pages" |
| 478 | ); |
| 479 | assert_eq!( |
| 480 | va_range.len(), |
Pierre-Clément Tosi | 9215476 | 2023-06-07 15:32:15 +0000 | [diff] [blame] | 481 | MMIO_GUARD_GRANULE_SIZE, |
Alice Wang | b73a81b | 2023-06-07 13:05:09 +0000 | [diff] [blame] | 482 | "Failed to break down block mapping before MMIO guard mapping" |
| 483 | ); |
| 484 | let page_base = va_range.start().0; |
Pierre-Clément Tosi | 9215476 | 2023-06-07 15:32:15 +0000 | [diff] [blame] | 485 | assert_eq!(page_base % MMIO_GUARD_GRANULE_SIZE, 0); |
Alice Wang | b73a81b | 2023-06-07 13:05:09 +0000 | [diff] [blame] | 486 | // Since mmio_guard_map takes IPAs, if pvmfw moves non-ID address mapping, page_base |
| 487 | // should be converted to IPA. However, since 0x0 is a valid MMIO address, we don't use |
| 488 | // virt_to_phys here, and just pass page_base instead. |
Pierre-Clément Tosi | d643cfe | 2023-06-29 09:30:51 +0000 | [diff] [blame] | 489 | get_mmio_guard().unwrap().unmap(page_base).map_err(|e| { |
Alice Wang | b73a81b | 2023-06-07 13:05:09 +0000 | [diff] [blame] | 490 | error!("Error MMIO guard unmapping: {e}"); |
| 491 | })?; |
| 492 | } |
| 493 | Ok(()) |
| 494 | } |
Alice Wang | a9fe1fb | 2023-07-04 09:10:35 +0000 | [diff] [blame] | 495 | |
| 496 | /// Handles a translation fault with the given fault address register (FAR). |
| 497 | #[inline] |
| 498 | pub fn handle_translation_fault(far: VirtualAddress) -> result::Result<(), HandleExceptionError> { |
| 499 | let mut guard = MEMORY.try_lock().ok_or(HandleExceptionError::PageTableUnavailable)?; |
| 500 | let memory = guard.as_mut().ok_or(HandleExceptionError::PageTableNotInitialized)?; |
| 501 | Ok(memory.handle_mmio_fault(far)?) |
| 502 | } |
| 503 | |
| 504 | /// Handles a permission fault with the given fault address register (FAR). |
| 505 | #[inline] |
| 506 | pub fn handle_permission_fault(far: VirtualAddress) -> result::Result<(), HandleExceptionError> { |
| 507 | let mut guard = MEMORY.try_lock().ok_or(HandleExceptionError::PageTableUnavailable)?; |
| 508 | let memory = guard.as_mut().ok_or(HandleExceptionError::PageTableNotInitialized)?; |
| 509 | Ok(memory.handle_permission_fault(far)?) |
| 510 | } |