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