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