blob: 173c0ec305dc22b690803e2e3fe48a8647d0761b [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;
Pierre-Clément Tosi8937cb82023-07-06 15:07:38 +000030use core::mem::size_of;
Alice Wang93ee98a2023-06-08 08:20:39 +000031use core::num::NonZeroUsize;
32use core::ops::Range;
Alice Wangf47b2342023-06-02 11:51:57 +000033use core::ptr::NonNull;
Alice Wangb73a81b2023-06-07 13:05:09 +000034use core::result;
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +000035use hyp::{get_mem_sharer, get_mmio_guard, MMIO_GUARD_GRANULE_SIZE};
Alice Wang93ee98a2023-06-08 08:20:39 +000036use log::{debug, error, trace};
37use once_cell::race::OnceBox;
38use spin::mutex::SpinMutex;
39use tinyvec::ArrayVec;
40
41/// A global static variable representing the system memory tracker, protected by a spin mutex.
42pub static MEMORY: SpinMutex<Option<MemoryTracker>> = SpinMutex::new(None);
43
44static SHARED_POOL: OnceBox<LockedFrameAllocator<32>> = OnceBox::new();
45static SHARED_MEMORY: SpinMutex<Option<MemorySharer>> = SpinMutex::new(None);
46
47/// Memory range.
48pub type MemoryRange = Range<usize>;
Alice Wanga3931aa2023-07-05 12:52:09 +000049
50fn get_va_range(range: &MemoryRange) -> VaRange {
51 VaRange::new(range.start, range.end)
52}
53
Alice Wang93ee98a2023-06-08 08:20:39 +000054type Result<T> = result::Result<T, MemoryTrackerError>;
55
56#[derive(Clone, Copy, Debug, Default, PartialEq)]
57enum MemoryType {
58 #[default]
59 ReadOnly,
60 ReadWrite,
61}
62
63#[derive(Clone, Debug, Default)]
64struct MemoryRegion {
65 range: MemoryRange,
66 mem_type: MemoryType,
67}
68
69/// Tracks non-overlapping slices of main memory.
70pub 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 Wang5bb79502023-06-12 09:25:07 +000076 payload_range: Option<MemoryRange>,
Alice Wang93ee98a2023-06-08 08:20:39 +000077}
78
Andrew Walbranc06e7342023-07-05 14:00:51 +000079// TODO: Remove this once aarch64-paging crate is updated.
80// SAFETY: Only `PageTable` doesn't implement Send, but it should.
Alice Wang93ee98a2023-06-08 08:20:39 +000081unsafe impl Send for MemoryTracker {}
82
83impl 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 Wanga3931aa2023-07-05 12:52:09 +000092 payload_range: Option<Range<VirtualAddress>>,
Alice Wang93ee98a2023-06-08 08:20:39 +000093 ) -> 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 Walbranc06e7342023-07-05 14:00:51 +0000105 // SAFETY: page_table duplicates the static mappings for everything that the Rust code is
Alice Wang93ee98a2023-06-08 08:20:39 +0000106 // 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 Wanga3931aa2023-07-05 12:52:09 +0000116 payload_range: payload_range.map(|r| r.start.0..r.end.0),
Alice Wang93ee98a2023-06-08 08:20:39 +0000117 }
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(&region)?;
Alice Wanga3931aa2023-07-05 12:52:09 +0000142 self.page_table.map_rodata(&get_va_range(range)).map_err(|e| {
Alice Wang93ee98a2023-06-08 08:20:39 +0000143 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(&region)?;
Alice Wanga3931aa2023-07-05 12:52:09 +0000153 self.page_table.map_data_dbm(&get_va_range(range)).map_err(|e| {
Alice Wang93ee98a2023-06-08 08:20:39 +0000154 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 Tosid643cfe2023-06-29 09:30:51 +0000183 if get_mmio_guard().is_some() {
Pierre-Clément Tosi32279ef2023-06-29 10:46:59 +0000184 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 Wang93ee98a2023-06-08 08:20:39 +0000194
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 Tosid643cfe2023-06-29 09:30:51 +0000230 if get_mmio_guard().is_some() {
Pierre-Clément Tosi32279ef2023-06-29 10:46:59 +0000231 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 Wang93ee98a2023-06-08 08:20:39 +0000236 }
237 Ok(())
238 }
239
240 /// Initialize the shared heap to dynamically share memory from the global allocator.
Alice Wangb6d2c642023-06-13 13:07:06 +0000241 pub fn init_dynamic_shared_pool(&mut self, granule: usize) -> Result<()> {
Alice Wang93ee98a2023-06-08 08:20:39 +0000242 const INIT_CAP: usize = 10;
243
Alice Wang93ee98a2023-06-08 08:20:39 +0000244 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 Tosi8937cb82023-07-06 15:07:38 +0000277 /// 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 Wang93ee98a2023-06-08 08:20:39 +0000290 /// 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 Wanga9fe1fb2023-07-04 09:10:35 +0000297 fn handle_mmio_fault(&mut self, addr: VirtualAddress) -> Result<()> {
Alice Wang88736462023-07-05 12:14:15 +0000298 let page_start = VirtualAddress(page_4kb_of(addr.0));
Alice Wanga3931aa2023-07-05 12:52:09 +0000299 let page_range: VaRange = (page_start..page_start + MMIO_GUARD_GRANULE_SIZE).into();
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000300 let mmio_guard = get_mmio_guard().unwrap();
Alice Wang93ee98a2023-06-08 08:20:39 +0000301 self.page_table
302 .modify_range(&page_range, &verify_lazy_mapped_block)
303 .map_err(|_| MemoryTrackerError::InvalidPte)?;
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000304 mmio_guard.map(page_start.0)?;
Alice Wang93ee98a2023-06-08 08:20:39 +0000305 // 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 Wang5bb79502023-06-12 09:25:07 +0000318 for range in writable_regions.chain(self.payload_range.as_ref().into_iter()) {
Alice Wang93ee98a2023-06-08 08:20:39 +0000319 self.page_table
Alice Wanga3931aa2023-07-05 12:52:09 +0000320 .modify_range(&get_va_range(range), &flush_dirty_range)
Alice Wang93ee98a2023-06-08 08:20:39 +0000321 .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 Wanga9fe1fb2023-07-04 09:10:35 +0000329 fn handle_permission_fault(&mut self, addr: VirtualAddress) -> Result<()> {
Alice Wang93ee98a2023-06-08 08:20:39 +0000330 self.page_table
Alice Wanga3931aa2023-07-05 12:52:09 +0000331 .modify_range(&(addr..addr + 1).into(), &mark_dirty_block)
Alice Wang93ee98a2023-06-08 08:20:39 +0000332 .map_err(|_| MemoryTrackerError::SetPteDirtyFailed)
333 }
334}
335
336impl 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.
346pub 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
356fn 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.
377pub 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 Wangf47b2342023-06-02 11:51:57 +0000383
384/// Allocates memory on the heap and shares it with the host.
385///
386/// Unshares all pages when dropped.
Alice Wang93ee98a2023-06-08 08:20:39 +0000387struct MemorySharer {
Alice Wangf47b2342023-06-02 11:51:57 +0000388 granule: usize,
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000389 frames: Vec<(usize, Layout)>,
Alice Wangf47b2342023-06-02 11:51:57 +0000390}
391
392impl MemorySharer {
393 /// Constructs a new `MemorySharer` instance with the specified granule size and capacity.
394 /// `granule` must be a power of 2.
Alice Wang93ee98a2023-06-08 08:20:39 +0000395 fn new(granule: usize, capacity: usize) -> Self {
Alice Wangf47b2342023-06-02 11:51:57 +0000396 assert!(granule.is_power_of_two());
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000397 Self { granule, frames: Vec::with_capacity(capacity) }
Alice Wangf47b2342023-06-02 11:51:57 +0000398 }
399
Alice Wang93ee98a2023-06-08 08:20:39 +0000400 /// 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 Wangf47b2342023-06-02 11:51:57 +0000402 let layout = hint.align_to(self.granule).unwrap().pad_to_align();
403 assert_ne!(layout.size(), 0);
Andrew Walbranc06e7342023-07-05 14:00:51 +0000404 // SAFETY: layout has non-zero size.
Alice Wangf47b2342023-06-02 11:51:57 +0000405 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 Wangf47b2342023-06-02 11:51:57 +0000411
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000412 if let Some(mem_sharer) = get_mem_sharer() {
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000413 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 Tosid643cfe2023-06-29 09:30:51 +0000416 mem_sharer.share(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000417 }
418 }
419
420 self.frames.push((base, layout));
Alice Wangf47b2342023-06-02 11:51:57 +0000421 pool.add_frame(base, end);
422 }
423}
424
425impl Drop for MemorySharer {
426 fn drop(&mut self) {
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000427 while let Some((base, layout)) = self.frames.pop() {
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000428 if let Some(mem_sharer) = get_mem_sharer() {
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000429 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 Tosid643cfe2023-06-29 09:30:51 +0000433 mem_sharer.unshare(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000434 }
Alice Wangf47b2342023-06-02 11:51:57 +0000435 }
436
Andrew Walbranc06e7342023-07-05 14:00:51 +0000437 // SAFETY: The region was obtained from alloc_zeroed() with the recorded layout.
Alice Wangf47b2342023-06-02 11:51:57 +0000438 unsafe { dealloc(base as *mut _, layout) };
439 }
440 }
441}
Alice Wangb73a81b2023-06-07 13:05:09 +0000442
443/// Checks whether block flags indicate it should be MMIO guard mapped.
Alice Wang93ee98a2023-06-08 08:20:39 +0000444fn verify_lazy_mapped_block(
Alice Wangb73a81b2023-06-07 13:05:09 +0000445 _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 Wang93ee98a2023-06-08 08:20:39 +0000461fn mmio_guard_unmap_page(
Alice Wangb73a81b2023-06-07 13:05:09 +0000462 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 Tosi92154762023-06-07 15:32:15 +0000481 MMIO_GUARD_GRANULE_SIZE,
Alice Wangb73a81b2023-06-07 13:05:09 +0000482 "Failed to break down block mapping before MMIO guard mapping"
483 );
484 let page_base = va_range.start().0;
Pierre-Clément Tosi92154762023-06-07 15:32:15 +0000485 assert_eq!(page_base % MMIO_GUARD_GRANULE_SIZE, 0);
Alice Wangb73a81b2023-06-07 13:05:09 +0000486 // 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 Tosid643cfe2023-06-29 09:30:51 +0000489 get_mmio_guard().unwrap().unmap(page_base).map_err(|e| {
Alice Wangb73a81b2023-06-07 13:05:09 +0000490 error!("Error MMIO guard unmapping: {e}");
491 })?;
492 }
493 Ok(())
494}
Alice Wanga9fe1fb2023-07-04 09:10:35 +0000495
496/// Handles a translation fault with the given fault address register (FAR).
497#[inline]
498pub 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]
506pub 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}