blob: 6c8a84403b4ef281203dc8bace02745e667a8e25 [file] [log] [blame]
Alice Wangf47b2342023-06-02 11:51:57 +00001// 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 Wang93ee98a2023-06-08 08:20:39 +000017use super::dbm::{flush_dirty_range, mark_dirty_block, set_dbm_enabled};
18use super::error::MemoryTrackerError;
19use super::page_table::{is_leaf_pte, PageTable, MMIO_LAZY_MAP_FLAG};
20use super::util::{page_4kb_of, virt_to_phys};
21use crate::dsb;
Alice Wanga9fe1fb2023-07-04 09:10:35 +000022use crate::exceptions::HandleExceptionError;
Alice Wang93ee98a2023-06-08 08:20:39 +000023use crate::util::RangeExt as _;
Alice Wanga3931aa2023-07-05 12:52:09 +000024use aarch64_paging::paging::{Attributes, Descriptor, MemoryRegion as VaRange, VirtualAddress};
Alice Wangf47b2342023-06-02 11:51:57 +000025use alloc::alloc::{alloc_zeroed, dealloc, handle_alloc_error};
Alice Wang93ee98a2023-06-08 08:20:39 +000026use alloc::boxed::Box;
Alice Wangf47b2342023-06-02 11:51:57 +000027use alloc::vec::Vec;
Alice Wang93ee98a2023-06-08 08:20:39 +000028use buddy_system_allocator::{FrameAllocator, LockedFrameAllocator};
Alice Wangf47b2342023-06-02 11:51:57 +000029use core::alloc::Layout;
Alice Wangdf6bacc2023-07-17 14:30:57 +000030use core::cmp::max;
Pierre-Clément Tosi8937cb82023-07-06 15:07:38 +000031use core::mem::size_of;
Alice Wang93ee98a2023-06-08 08:20:39 +000032use core::num::NonZeroUsize;
33use core::ops::Range;
Alice Wangf47b2342023-06-02 11:51:57 +000034use core::ptr::NonNull;
Alice Wangb73a81b2023-06-07 13:05:09 +000035use core::result;
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +000036use hyp::{get_mem_sharer, get_mmio_guard, MMIO_GUARD_GRANULE_SIZE};
Alice Wang93ee98a2023-06-08 08:20:39 +000037use log::{debug, error, trace};
38use once_cell::race::OnceBox;
39use spin::mutex::SpinMutex;
40use tinyvec::ArrayVec;
41
42/// A global static variable representing the system memory tracker, protected by a spin mutex.
43pub static MEMORY: SpinMutex<Option<MemoryTracker>> = SpinMutex::new(None);
44
45static SHARED_POOL: OnceBox<LockedFrameAllocator<32>> = OnceBox::new();
46static SHARED_MEMORY: SpinMutex<Option<MemorySharer>> = SpinMutex::new(None);
47
48/// Memory range.
49pub type MemoryRange = Range<usize>;
Alice Wanga3931aa2023-07-05 12:52:09 +000050
51fn get_va_range(range: &MemoryRange) -> VaRange {
52 VaRange::new(range.start, range.end)
53}
54
Alice Wang93ee98a2023-06-08 08:20:39 +000055type Result<T> = result::Result<T, MemoryTrackerError>;
56
57#[derive(Clone, Copy, Debug, Default, PartialEq)]
58enum MemoryType {
59 #[default]
60 ReadOnly,
61 ReadWrite,
62}
63
64#[derive(Clone, Debug, Default)]
65struct MemoryRegion {
66 range: MemoryRange,
67 mem_type: MemoryType,
68}
69
70/// Tracks non-overlapping slices of main memory.
71pub 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 Wang5bb79502023-06-12 09:25:07 +000077 payload_range: Option<MemoryRange>,
Alice Wang93ee98a2023-06-08 08:20:39 +000078}
79
Alice Wang93ee98a2023-06-08 08:20:39 +000080impl 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 Wanga3931aa2023-07-05 12:52:09 +000089 payload_range: Option<Range<VirtualAddress>>,
Alice Wang93ee98a2023-06-08 08:20:39 +000090 ) -> 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 Walbranc06e7342023-07-05 14:00:51 +0000102 // SAFETY: page_table duplicates the static mappings for everything that the Rust code is
Alice Wang93ee98a2023-06-08 08:20:39 +0000103 // 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 Wanga3931aa2023-07-05 12:52:09 +0000113 payload_range: payload_range.map(|r| r.start.0..r.end.0),
Alice Wang93ee98a2023-06-08 08:20:39 +0000114 }
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 Wang9f3ca832023-09-20 09:33:14 +0000138 self.check_allocatable(&region)?;
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(&region)?;
Alice Wanga3931aa2023-07-05 12:52:09 +0000158 self.page_table.map_rodata(&get_va_range(range)).map_err(|e| {
Alice Wang93ee98a2023-06-08 08:20:39 +0000159 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 Wang9f3ca832023-09-20 09:33:14 +0000168 self.check_allocatable(&region)?;
Alice Wanga3931aa2023-07-05 12:52:09 +0000169 self.page_table.map_data_dbm(&get_va_range(range)).map_err(|e| {
Alice Wang93ee98a2023-06-08 08:20:39 +0000170 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 Tosid643cfe2023-06-29 09:30:51 +0000199 if get_mmio_guard().is_some() {
Pierre-Clément Tosi32279ef2023-06-29 10:46:59 +0000200 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 Wang93ee98a2023-06-08 08:20:39 +0000210
211 if self.mmio_regions.try_push(range).is_some() {
212 return Err(MemoryTrackerError::Full);
213 }
214
215 Ok(())
216 }
217
Alice Wang9f3ca832023-09-20 09:33:14 +0000218 /// 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 Wang93ee98a2023-06-08 08:20:39 +0000223 if !region.range.is_within(&self.total) {
224 return Err(MemoryTrackerError::OutOfRange);
225 }
Alice Wang9f3ca832023-09-20 09:33:14 +0000226 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 Wang93ee98a2023-06-08 08:20:39 +0000232 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 Tosid643cfe2023-06-29 09:30:51 +0000253 if get_mmio_guard().is_some() {
Pierre-Clément Tosi32279ef2023-06-29 10:46:59 +0000254 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 Wang93ee98a2023-06-08 08:20:39 +0000259 }
260 Ok(())
261 }
262
263 /// Initialize the shared heap to dynamically share memory from the global allocator.
Alice Wangb6d2c642023-06-13 13:07:06 +0000264 pub fn init_dynamic_shared_pool(&mut self, granule: usize) -> Result<()> {
Alice Wang93ee98a2023-06-08 08:20:39 +0000265 const INIT_CAP: usize = 10;
266
Alice Wang93ee98a2023-06-08 08:20:39 +0000267 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 Tosi8937cb82023-07-06 15:07:38 +0000300 /// 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 Wang93ee98a2023-06-08 08:20:39 +0000313 /// 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 Wanga9fe1fb2023-07-04 09:10:35 +0000320 fn handle_mmio_fault(&mut self, addr: VirtualAddress) -> Result<()> {
Alice Wang88736462023-07-05 12:14:15 +0000321 let page_start = VirtualAddress(page_4kb_of(addr.0));
Alice Wanga3931aa2023-07-05 12:52:09 +0000322 let page_range: VaRange = (page_start..page_start + MMIO_GUARD_GRANULE_SIZE).into();
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000323 let mmio_guard = get_mmio_guard().unwrap();
Alice Wang93ee98a2023-06-08 08:20:39 +0000324 self.page_table
325 .modify_range(&page_range, &verify_lazy_mapped_block)
326 .map_err(|_| MemoryTrackerError::InvalidPte)?;
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000327 mmio_guard.map(page_start.0)?;
Alice Wang93ee98a2023-06-08 08:20:39 +0000328 // 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 Wang5bb79502023-06-12 09:25:07 +0000341 for range in writable_regions.chain(self.payload_range.as_ref().into_iter()) {
Alice Wang93ee98a2023-06-08 08:20:39 +0000342 self.page_table
Alice Wanga3931aa2023-07-05 12:52:09 +0000343 .modify_range(&get_va_range(range), &flush_dirty_range)
Alice Wang93ee98a2023-06-08 08:20:39 +0000344 .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 Wanga9fe1fb2023-07-04 09:10:35 +0000352 fn handle_permission_fault(&mut self, addr: VirtualAddress) -> Result<()> {
Alice Wang93ee98a2023-06-08 08:20:39 +0000353 self.page_table
Alice Wanga3931aa2023-07-05 12:52:09 +0000354 .modify_range(&(addr..addr + 1).into(), &mark_dirty_block)
Alice Wang93ee98a2023-06-08 08:20:39 +0000355 .map_err(|_| MemoryTrackerError::SetPteDirtyFailed)
356 }
357}
358
359impl 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 Wang6c4cda02023-07-18 08:18:07 +0000369pub(crate) fn alloc_shared(layout: Layout) -> hyp::Result<NonNull<u8>> {
Alice Wang7cbe29a2023-07-27 11:45:58 +0000370 assert_ne!(layout.size(), 0);
Alice Wang93ee98a2023-06-08 08:20:39 +0000371 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
379fn 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 Wang2a6b2172023-07-18 10:38:16 +0000385 // 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 Wang93ee98a2023-06-08 08:20:39 +0000390 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 Wang6c4cda02023-07-18 08:18:07 +0000404pub(crate) unsafe fn dealloc_shared(vaddr: NonNull<u8>, layout: Layout) -> hyp::Result<()> {
Alice Wang93ee98a2023-06-08 08:20:39 +0000405 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 Wangf47b2342023-06-02 11:51:57 +0000410
411/// Allocates memory on the heap and shares it with the host.
412///
413/// Unshares all pages when dropped.
Alice Wang93ee98a2023-06-08 08:20:39 +0000414struct MemorySharer {
Alice Wangf47b2342023-06-02 11:51:57 +0000415 granule: usize,
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000416 frames: Vec<(usize, Layout)>,
Alice Wangf47b2342023-06-02 11:51:57 +0000417}
418
419impl MemorySharer {
420 /// Constructs a new `MemorySharer` instance with the specified granule size and capacity.
421 /// `granule` must be a power of 2.
Alice Wang93ee98a2023-06-08 08:20:39 +0000422 fn new(granule: usize, capacity: usize) -> Self {
Alice Wangf47b2342023-06-02 11:51:57 +0000423 assert!(granule.is_power_of_two());
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000424 Self { granule, frames: Vec::with_capacity(capacity) }
Alice Wangf47b2342023-06-02 11:51:57 +0000425 }
426
Alice Wang93ee98a2023-06-08 08:20:39 +0000427 /// 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 Wangf47b2342023-06-02 11:51:57 +0000429 let layout = hint.align_to(self.granule).unwrap().pad_to_align();
430 assert_ne!(layout.size(), 0);
Andrew Walbranc06e7342023-07-05 14:00:51 +0000431 // SAFETY: layout has non-zero size.
Alice Wangf47b2342023-06-02 11:51:57 +0000432 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 Wangf47b2342023-06-02 11:51:57 +0000438
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000439 if let Some(mem_sharer) = get_mem_sharer() {
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000440 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 Tosid643cfe2023-06-29 09:30:51 +0000443 mem_sharer.share(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000444 }
445 }
446
447 self.frames.push((base, layout));
Alice Wangf47b2342023-06-02 11:51:57 +0000448 pool.add_frame(base, end);
449 }
450}
451
452impl Drop for MemorySharer {
453 fn drop(&mut self) {
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000454 while let Some((base, layout)) = self.frames.pop() {
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000455 if let Some(mem_sharer) = get_mem_sharer() {
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000456 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 Tosid643cfe2023-06-29 09:30:51 +0000460 mem_sharer.unshare(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000461 }
Alice Wangf47b2342023-06-02 11:51:57 +0000462 }
463
Andrew Walbranc06e7342023-07-05 14:00:51 +0000464 // SAFETY: The region was obtained from alloc_zeroed() with the recorded layout.
Alice Wangf47b2342023-06-02 11:51:57 +0000465 unsafe { dealloc(base as *mut _, layout) };
466 }
467 }
468}
Alice Wangb73a81b2023-06-07 13:05:09 +0000469
470/// Checks whether block flags indicate it should be MMIO guard mapped.
Alice Wang93ee98a2023-06-08 08:20:39 +0000471fn verify_lazy_mapped_block(
Alice Wangb73a81b2023-06-07 13:05:09 +0000472 _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 Wang93ee98a2023-06-08 08:20:39 +0000488fn mmio_guard_unmap_page(
Alice Wangb73a81b2023-06-07 13:05:09 +0000489 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 Tosi92154762023-06-07 15:32:15 +0000508 MMIO_GUARD_GRANULE_SIZE,
Alice Wangb73a81b2023-06-07 13:05:09 +0000509 "Failed to break down block mapping before MMIO guard mapping"
510 );
511 let page_base = va_range.start().0;
Pierre-Clément Tosi92154762023-06-07 15:32:15 +0000512 assert_eq!(page_base % MMIO_GUARD_GRANULE_SIZE, 0);
Alice Wangb73a81b2023-06-07 13:05:09 +0000513 // 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 Tosid643cfe2023-06-29 09:30:51 +0000516 get_mmio_guard().unwrap().unmap(page_base).map_err(|e| {
Alice Wangb73a81b2023-06-07 13:05:09 +0000517 error!("Error MMIO guard unmapping: {e}");
518 })?;
519 }
520 Ok(())
521}
Alice Wanga9fe1fb2023-07-04 09:10:35 +0000522
523/// Handles a translation fault with the given fault address register (FAR).
524#[inline]
525pub 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]
533pub 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}