blob: dd433d4a2f719b367940358d6b64138edeb9ed13 [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;
Ard Biesheuvela8dc46f2023-10-20 15:10:38 +020019use super::page_table::{PageTable, MMIO_LAZY_MAP_FLAG};
Alice Wang93ee98a2023-06-08 08:20:39 +000020use 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 _;
Ard Biesheuvela8dc46f2023-10-20 15:10:38 +020024use aarch64_paging::paging::{
25 Attributes, Descriptor, MemoryRegion as VaRange, VirtualAddress, BITS_PER_LEVEL, PAGE_SIZE,
26};
Alice Wangf47b2342023-06-02 11:51:57 +000027use alloc::alloc::{alloc_zeroed, dealloc, handle_alloc_error};
Alice Wang93ee98a2023-06-08 08:20:39 +000028use alloc::boxed::Box;
Alice Wangf47b2342023-06-02 11:51:57 +000029use alloc::vec::Vec;
Alice Wang93ee98a2023-06-08 08:20:39 +000030use buddy_system_allocator::{FrameAllocator, LockedFrameAllocator};
Alice Wangf47b2342023-06-02 11:51:57 +000031use core::alloc::Layout;
Alice Wangdf6bacc2023-07-17 14:30:57 +000032use core::cmp::max;
Pierre-Clément Tosi8937cb82023-07-06 15:07:38 +000033use core::mem::size_of;
Alice Wang93ee98a2023-06-08 08:20:39 +000034use core::num::NonZeroUsize;
35use core::ops::Range;
Alice Wangf47b2342023-06-02 11:51:57 +000036use core::ptr::NonNull;
Alice Wangb73a81b2023-06-07 13:05:09 +000037use core::result;
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +000038use hyp::{get_mem_sharer, get_mmio_guard, MMIO_GUARD_GRANULE_SIZE};
Alice Wang93ee98a2023-06-08 08:20:39 +000039use log::{debug, error, trace};
40use once_cell::race::OnceBox;
41use spin::mutex::SpinMutex;
42use tinyvec::ArrayVec;
43
44/// A global static variable representing the system memory tracker, protected by a spin mutex.
45pub static MEMORY: SpinMutex<Option<MemoryTracker>> = SpinMutex::new(None);
46
47static SHARED_POOL: OnceBox<LockedFrameAllocator<32>> = OnceBox::new();
48static SHARED_MEMORY: SpinMutex<Option<MemorySharer>> = SpinMutex::new(None);
49
50/// Memory range.
51pub type MemoryRange = Range<usize>;
Alice Wanga3931aa2023-07-05 12:52:09 +000052
53fn get_va_range(range: &MemoryRange) -> VaRange {
54 VaRange::new(range.start, range.end)
55}
56
Alice Wang93ee98a2023-06-08 08:20:39 +000057type Result<T> = result::Result<T, MemoryTrackerError>;
58
59#[derive(Clone, Copy, Debug, Default, PartialEq)]
60enum MemoryType {
61 #[default]
62 ReadOnly,
63 ReadWrite,
64}
65
66#[derive(Clone, Debug, Default)]
67struct MemoryRegion {
68 range: MemoryRange,
69 mem_type: MemoryType,
70}
71
72/// Tracks non-overlapping slices of main memory.
73pub struct MemoryTracker {
74 total: MemoryRange,
75 page_table: PageTable,
76 regions: ArrayVec<[MemoryRegion; MemoryTracker::CAPACITY]>,
77 mmio_regions: ArrayVec<[MemoryRange; MemoryTracker::MMIO_CAPACITY]>,
78 mmio_range: MemoryRange,
Alice Wang5bb79502023-06-12 09:25:07 +000079 payload_range: Option<MemoryRange>,
Alice Wang93ee98a2023-06-08 08:20:39 +000080}
81
Alice Wang93ee98a2023-06-08 08:20:39 +000082impl 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 Wanga3931aa2023-07-05 12:52:09 +000091 payload_range: Option<Range<VirtualAddress>>,
Alice Wang93ee98a2023-06-08 08:20:39 +000092 ) -> 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 Walbranc06e7342023-07-05 14:00:51 +0000104 // SAFETY: page_table duplicates the static mappings for everything that the Rust code is
Alice Wang93ee98a2023-06-08 08:20:39 +0000105 // 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 Wanga3931aa2023-07-05 12:52:09 +0000115 payload_range: payload_range.map(|r| r.start.0..r.end.0),
Alice Wang93ee98a2023-06-08 08:20:39 +0000116 }
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 };
Alice Wang9f3ca832023-09-20 09:33:14 +0000140 self.check_allocatable(&region)?;
141 self.page_table.map_rodata(&get_va_range(range)).map_err(|e| {
142 error!("Error during range allocation: {e}");
143 MemoryTrackerError::FailedToMap
144 })?;
145 self.add(region)
146 }
147
148 /// Allocates the address range for a const slice.
149 ///
150 /// # Safety
151 ///
152 /// Callers of this method need to ensure that the `range` is valid for mapping as read-only
153 /// data.
154 pub unsafe fn alloc_range_outside_main_memory(
155 &mut self,
156 range: &MemoryRange,
157 ) -> Result<MemoryRange> {
158 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadOnly };
159 self.check_no_overlap(&region)?;
Alice Wanga3931aa2023-07-05 12:52:09 +0000160 self.page_table.map_rodata(&get_va_range(range)).map_err(|e| {
Alice Wang93ee98a2023-06-08 08:20:39 +0000161 error!("Error during range allocation: {e}");
162 MemoryTrackerError::FailedToMap
163 })?;
164 self.add(region)
165 }
166
167 /// Allocate the address range for a mutable slice; returns None if failed.
168 pub fn alloc_range_mut(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
169 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadWrite };
Alice Wang9f3ca832023-09-20 09:33:14 +0000170 self.check_allocatable(&region)?;
Alice Wanga3931aa2023-07-05 12:52:09 +0000171 self.page_table.map_data_dbm(&get_va_range(range)).map_err(|e| {
Alice Wang93ee98a2023-06-08 08:20:39 +0000172 error!("Error during mutable range allocation: {e}");
173 MemoryTrackerError::FailedToMap
174 })?;
175 self.add(region)
176 }
177
178 /// Allocate the address range for a const slice; returns None if failed.
179 pub fn alloc(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
180 self.alloc_range(&(base..(base + size.get())))
181 }
182
183 /// Allocate the address range for a mutable slice; returns None if failed.
184 pub fn alloc_mut(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
185 self.alloc_range_mut(&(base..(base + size.get())))
186 }
187
188 /// Checks that the given range of addresses is within the MMIO region, and then maps it
189 /// appropriately.
190 pub fn map_mmio_range(&mut self, range: MemoryRange) -> Result<()> {
191 if !range.is_within(&self.mmio_range) {
192 return Err(MemoryTrackerError::OutOfRange);
193 }
194 if self.mmio_regions.iter().any(|r| range.overlaps(r)) {
195 return Err(MemoryTrackerError::Overlaps);
196 }
197 if self.mmio_regions.len() == self.mmio_regions.capacity() {
198 return Err(MemoryTrackerError::Full);
199 }
200
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000201 if get_mmio_guard().is_some() {
Pierre-Clément Tosi32279ef2023-06-29 10:46:59 +0000202 self.page_table.map_device_lazy(&get_va_range(&range)).map_err(|e| {
203 error!("Error during lazy MMIO device mapping: {e}");
204 MemoryTrackerError::FailedToMap
205 })?;
206 } else {
207 self.page_table.map_device(&get_va_range(&range)).map_err(|e| {
208 error!("Error during MMIO device mapping: {e}");
209 MemoryTrackerError::FailedToMap
210 })?;
211 }
Alice Wang93ee98a2023-06-08 08:20:39 +0000212
213 if self.mmio_regions.try_push(range).is_some() {
214 return Err(MemoryTrackerError::Full);
215 }
216
217 Ok(())
218 }
219
Alice Wang9f3ca832023-09-20 09:33:14 +0000220 /// Checks that the memory region meets the following criteria:
221 /// - It is within the range of the `MemoryTracker`.
222 /// - It does not overlap with any previously allocated regions.
223 /// - The `regions` ArrayVec has sufficient capacity to add it.
224 fn check_allocatable(&self, region: &MemoryRegion) -> Result<()> {
Alice Wang93ee98a2023-06-08 08:20:39 +0000225 if !region.range.is_within(&self.total) {
226 return Err(MemoryTrackerError::OutOfRange);
227 }
Alice Wang9f3ca832023-09-20 09:33:14 +0000228 self.check_no_overlap(region)
229 }
230
231 /// Checks that the given region doesn't overlap with any other previously allocated regions,
232 /// and that the regions ArrayVec has capacity to add it.
233 fn check_no_overlap(&self, region: &MemoryRegion) -> Result<()> {
Alice Wang93ee98a2023-06-08 08:20:39 +0000234 if self.regions.iter().any(|r| region.range.overlaps(&r.range)) {
235 return Err(MemoryTrackerError::Overlaps);
236 }
237 if self.regions.len() == self.regions.capacity() {
238 return Err(MemoryTrackerError::Full);
239 }
240 Ok(())
241 }
242
243 fn add(&mut self, region: MemoryRegion) -> Result<MemoryRange> {
244 if self.regions.try_push(region).is_some() {
245 return Err(MemoryTrackerError::Full);
246 }
247
248 Ok(self.regions.last().unwrap().range.clone())
249 }
250
251 /// Unmaps all tracked MMIO regions from the MMIO guard.
252 ///
253 /// Note that they are not unmapped from the page table.
254 pub fn mmio_unmap_all(&mut self) -> Result<()> {
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000255 if get_mmio_guard().is_some() {
Pierre-Clément Tosi32279ef2023-06-29 10:46:59 +0000256 for range in &self.mmio_regions {
257 self.page_table
Ard Biesheuvela8dc46f2023-10-20 15:10:38 +0200258 .walk_range(&get_va_range(range), &mmio_guard_unmap_page)
Pierre-Clément Tosi32279ef2023-06-29 10:46:59 +0000259 .map_err(|_| MemoryTrackerError::FailedToUnmap)?;
260 }
Alice Wang93ee98a2023-06-08 08:20:39 +0000261 }
262 Ok(())
263 }
264
265 /// Initialize the shared heap to dynamically share memory from the global allocator.
Alice Wangb6d2c642023-06-13 13:07:06 +0000266 pub fn init_dynamic_shared_pool(&mut self, granule: usize) -> Result<()> {
Alice Wang93ee98a2023-06-08 08:20:39 +0000267 const INIT_CAP: usize = 10;
268
Alice Wang93ee98a2023-06-08 08:20:39 +0000269 let previous = SHARED_MEMORY.lock().replace(MemorySharer::new(granule, INIT_CAP));
270 if previous.is_some() {
271 return Err(MemoryTrackerError::SharedMemorySetFailure);
272 }
273
274 SHARED_POOL
275 .set(Box::new(LockedFrameAllocator::new()))
276 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
277
278 Ok(())
279 }
280
281 /// Initialize the shared heap from a static region of memory.
282 ///
283 /// Some hypervisors such as Gunyah do not support a MemShare API for guest
284 /// to share its memory with host. Instead they allow host to designate part
285 /// of guest memory as "shared" ahead of guest starting its execution. The
286 /// shared memory region is indicated in swiotlb node. On such platforms use
287 /// a separate heap to allocate buffers that can be shared with host.
288 pub fn init_static_shared_pool(&mut self, range: Range<usize>) -> Result<()> {
289 let size = NonZeroUsize::new(range.len()).unwrap();
290 let range = self.alloc_mut(range.start, size)?;
291 let shared_pool = LockedFrameAllocator::<32>::new();
292
293 shared_pool.lock().insert(range);
294
295 SHARED_POOL
296 .set(Box::new(shared_pool))
297 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
298
299 Ok(())
300 }
301
Pierre-Clément Tosi8937cb82023-07-06 15:07:38 +0000302 /// Initialize the shared heap to use heap memory directly.
303 ///
304 /// When running on "non-protected" hypervisors which permit host direct accesses to guest
305 /// memory, there is no need to perform any memory sharing and/or allocate buffers from a
306 /// dedicated region so this function instructs the shared pool to use the global allocator.
307 pub fn init_heap_shared_pool(&mut self) -> Result<()> {
308 // As MemorySharer only calls MEM_SHARE methods if the hypervisor supports them, internally
309 // using init_dynamic_shared_pool() on a non-protected platform will make use of the heap
310 // without any actual "dynamic memory sharing" taking place and, as such, the granule may
311 // be set to the one of the global_allocator i.e. a byte.
312 self.init_dynamic_shared_pool(size_of::<u8>())
313 }
314
Alice Wang93ee98a2023-06-08 08:20:39 +0000315 /// Unshares any memory that may have been shared.
316 pub fn unshare_all_memory(&mut self) {
317 drop(SHARED_MEMORY.lock().take());
318 }
319
320 /// Handles translation fault for blocks flagged for lazy MMIO mapping by enabling the page
321 /// table entry and MMIO guard mapping the block. Breaks apart a block entry if required.
Alice Wanga9fe1fb2023-07-04 09:10:35 +0000322 fn handle_mmio_fault(&mut self, addr: VirtualAddress) -> Result<()> {
Alice Wang88736462023-07-05 12:14:15 +0000323 let page_start = VirtualAddress(page_4kb_of(addr.0));
Ard Biesheuvel5815c8b2023-10-24 00:52:57 +0200324 assert_eq!(page_start.0 % MMIO_GUARD_GRANULE_SIZE, 0);
Alice Wanga3931aa2023-07-05 12:52:09 +0000325 let page_range: VaRange = (page_start..page_start + MMIO_GUARD_GRANULE_SIZE).into();
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000326 let mmio_guard = get_mmio_guard().unwrap();
Ard Biesheuvel5815c8b2023-10-24 00:52:57 +0200327 // This must be safe and free from break-before-make (BBM) violations, given that the
328 // initial lazy mapping has the valid bit cleared, and each newly created valid descriptor
329 // created inside the mapping has the same size and alignment.
Alice Wang93ee98a2023-06-08 08:20:39 +0000330 self.page_table
Ard Biesheuvel5815c8b2023-10-24 00:52:57 +0200331 .modify_range(&page_range, &|_: &VaRange, desc: &mut Descriptor, _: usize| {
332 let flags = desc.flags().expect("Unsupported PTE flags set");
333 if flags.contains(MMIO_LAZY_MAP_FLAG) && !flags.contains(Attributes::VALID) {
334 desc.modify_flags(Attributes::VALID, Attributes::empty());
335 Ok(())
336 } else {
337 Err(())
338 }
339 })
Alice Wang93ee98a2023-06-08 08:20:39 +0000340 .map_err(|_| MemoryTrackerError::InvalidPte)?;
Ard Biesheuvel5815c8b2023-10-24 00:52:57 +0200341 Ok(mmio_guard.map(page_start.0)?)
Alice Wang93ee98a2023-06-08 08:20:39 +0000342 }
343
344 /// Flush all memory regions marked as writable-dirty.
345 fn flush_dirty_pages(&mut self) -> Result<()> {
346 // Collect memory ranges for which dirty state is tracked.
347 let writable_regions =
348 self.regions.iter().filter(|r| r.mem_type == MemoryType::ReadWrite).map(|r| &r.range);
349 // Execute a barrier instruction to ensure all hardware updates to the page table have been
350 // observed before reading PTE flags to determine dirty state.
351 dsb!("ish");
352 // Now flush writable-dirty pages in those regions.
Alice Wang5bb79502023-06-12 09:25:07 +0000353 for range in writable_regions.chain(self.payload_range.as_ref().into_iter()) {
Alice Wang93ee98a2023-06-08 08:20:39 +0000354 self.page_table
Ard Biesheuvela8dc46f2023-10-20 15:10:38 +0200355 .walk_range(&get_va_range(range), &flush_dirty_range)
Alice Wang93ee98a2023-06-08 08:20:39 +0000356 .map_err(|_| MemoryTrackerError::FlushRegionFailed)?;
357 }
358 Ok(())
359 }
360
361 /// Handles permission fault for read-only blocks by setting writable-dirty state.
362 /// In general, this should be called from the exception handler when hardware dirty
363 /// state management is disabled or unavailable.
Alice Wanga9fe1fb2023-07-04 09:10:35 +0000364 fn handle_permission_fault(&mut self, addr: VirtualAddress) -> Result<()> {
Alice Wang93ee98a2023-06-08 08:20:39 +0000365 self.page_table
Alice Wanga3931aa2023-07-05 12:52:09 +0000366 .modify_range(&(addr..addr + 1).into(), &mark_dirty_block)
Alice Wang93ee98a2023-06-08 08:20:39 +0000367 .map_err(|_| MemoryTrackerError::SetPteDirtyFailed)
368 }
369}
370
371impl Drop for MemoryTracker {
372 fn drop(&mut self) {
373 set_dbm_enabled(false);
374 self.flush_dirty_pages().unwrap();
375 self.unshare_all_memory();
376 }
377}
378
379/// Allocates a memory range of at least the given size and alignment that is shared with the host.
380/// Returns a pointer to the buffer.
Alice Wang6c4cda02023-07-18 08:18:07 +0000381pub(crate) fn alloc_shared(layout: Layout) -> hyp::Result<NonNull<u8>> {
Alice Wang7cbe29a2023-07-27 11:45:58 +0000382 assert_ne!(layout.size(), 0);
Alice Wang93ee98a2023-06-08 08:20:39 +0000383 let Some(buffer) = try_shared_alloc(layout) else {
384 handle_alloc_error(layout);
385 };
386
387 trace!("Allocated shared buffer at {buffer:?} with {layout:?}");
388 Ok(buffer)
389}
390
391fn try_shared_alloc(layout: Layout) -> Option<NonNull<u8>> {
392 let mut shared_pool = SHARED_POOL.get().unwrap().lock();
393
394 if let Some(buffer) = shared_pool.alloc_aligned(layout) {
395 Some(NonNull::new(buffer as _).unwrap())
396 } else if let Some(shared_memory) = SHARED_MEMORY.lock().as_mut() {
Alice Wang2a6b2172023-07-18 10:38:16 +0000397 // Adjusts the layout size to the max of the next power of two and the alignment,
398 // as this is the actual size of the memory allocated in `alloc_aligned()`.
399 let size = max(layout.size().next_power_of_two(), layout.align());
400 let refill_layout = Layout::from_size_align(size, layout.align()).unwrap();
401 shared_memory.refill(&mut shared_pool, refill_layout);
Alice Wang93ee98a2023-06-08 08:20:39 +0000402 shared_pool.alloc_aligned(layout).map(|buffer| NonNull::new(buffer as _).unwrap())
403 } else {
404 None
405 }
406}
407
408/// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`.
409///
410/// The layout passed in must be the same layout passed to the original `alloc_shared` call.
411///
412/// # Safety
413///
414/// The memory must have been allocated by `alloc_shared` with the same layout, and not yet
415/// deallocated.
Alice Wang6c4cda02023-07-18 08:18:07 +0000416pub(crate) unsafe fn dealloc_shared(vaddr: NonNull<u8>, layout: Layout) -> hyp::Result<()> {
Alice Wang93ee98a2023-06-08 08:20:39 +0000417 SHARED_POOL.get().unwrap().lock().dealloc_aligned(vaddr.as_ptr() as usize, layout);
418
419 trace!("Deallocated shared buffer at {vaddr:?} with {layout:?}");
420 Ok(())
421}
Alice Wangf47b2342023-06-02 11:51:57 +0000422
423/// Allocates memory on the heap and shares it with the host.
424///
425/// Unshares all pages when dropped.
Alice Wang93ee98a2023-06-08 08:20:39 +0000426struct MemorySharer {
Alice Wangf47b2342023-06-02 11:51:57 +0000427 granule: usize,
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000428 frames: Vec<(usize, Layout)>,
Alice Wangf47b2342023-06-02 11:51:57 +0000429}
430
431impl MemorySharer {
432 /// Constructs a new `MemorySharer` instance with the specified granule size and capacity.
433 /// `granule` must be a power of 2.
Alice Wang93ee98a2023-06-08 08:20:39 +0000434 fn new(granule: usize, capacity: usize) -> Self {
Alice Wangf47b2342023-06-02 11:51:57 +0000435 assert!(granule.is_power_of_two());
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000436 Self { granule, frames: Vec::with_capacity(capacity) }
Alice Wangf47b2342023-06-02 11:51:57 +0000437 }
438
Alice Wang93ee98a2023-06-08 08:20:39 +0000439 /// Gets from the global allocator a granule-aligned region that suits `hint` and share it.
440 fn refill(&mut self, pool: &mut FrameAllocator<32>, hint: Layout) {
Alice Wangf47b2342023-06-02 11:51:57 +0000441 let layout = hint.align_to(self.granule).unwrap().pad_to_align();
442 assert_ne!(layout.size(), 0);
Andrew Walbranc06e7342023-07-05 14:00:51 +0000443 // SAFETY: layout has non-zero size.
Alice Wangf47b2342023-06-02 11:51:57 +0000444 let Some(shared) = NonNull::new(unsafe { alloc_zeroed(layout) }) else {
445 handle_alloc_error(layout);
446 };
447
448 let base = shared.as_ptr() as usize;
449 let end = base.checked_add(layout.size()).unwrap();
Alice Wangf47b2342023-06-02 11:51:57 +0000450
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000451 if let Some(mem_sharer) = get_mem_sharer() {
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000452 trace!("Sharing memory region {:#x?}", base..end);
453 for vaddr in (base..end).step_by(self.granule) {
454 let vaddr = NonNull::new(vaddr as *mut _).unwrap();
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000455 mem_sharer.share(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000456 }
457 }
458
459 self.frames.push((base, layout));
Alice Wangf47b2342023-06-02 11:51:57 +0000460 pool.add_frame(base, end);
461 }
462}
463
464impl Drop for MemorySharer {
465 fn drop(&mut self) {
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000466 while let Some((base, layout)) = self.frames.pop() {
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000467 if let Some(mem_sharer) = get_mem_sharer() {
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000468 let end = base.checked_add(layout.size()).unwrap();
469 trace!("Unsharing memory region {:#x?}", base..end);
470 for vaddr in (base..end).step_by(self.granule) {
471 let vaddr = NonNull::new(vaddr as *mut _).unwrap();
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000472 mem_sharer.unshare(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
Pierre-Clément Tosid2f7ad12023-06-29 11:48:29 +0000473 }
Alice Wangf47b2342023-06-02 11:51:57 +0000474 }
475
Andrew Walbranc06e7342023-07-05 14:00:51 +0000476 // SAFETY: The region was obtained from alloc_zeroed() with the recorded layout.
Alice Wangf47b2342023-06-02 11:51:57 +0000477 unsafe { dealloc(base as *mut _, layout) };
478 }
479 }
480}
Alice Wangb73a81b2023-06-07 13:05:09 +0000481
Alice Wangb73a81b2023-06-07 13:05:09 +0000482/// MMIO guard unmaps page
Alice Wang93ee98a2023-06-08 08:20:39 +0000483fn mmio_guard_unmap_page(
Alice Wangb73a81b2023-06-07 13:05:09 +0000484 va_range: &VaRange,
Ard Biesheuvela8dc46f2023-10-20 15:10:38 +0200485 desc: &Descriptor,
Alice Wangb73a81b2023-06-07 13:05:09 +0000486 level: usize,
487) -> result::Result<(), ()> {
488 let flags = desc.flags().expect("Unsupported PTE flags set");
Alice Wangb73a81b2023-06-07 13:05:09 +0000489 // This function will be called on an address range that corresponds to a device. Only if a
490 // page has been accessed (written to or read from), will it contain the VALID flag and be MMIO
491 // guard mapped. Therefore, we can skip unmapping invalid pages, they were never MMIO guard
492 // mapped anyway.
493 if flags.contains(Attributes::VALID) {
494 assert!(
495 flags.contains(MMIO_LAZY_MAP_FLAG),
496 "Attempting MMIO guard unmap for non-device pages"
497 );
Ard Biesheuvela8dc46f2023-10-20 15:10:38 +0200498 const MMIO_GUARD_GRANULE_SHIFT: u32 = MMIO_GUARD_GRANULE_SIZE.ilog2() - PAGE_SIZE.ilog2();
499 const MMIO_GUARD_GRANULE_LEVEL: usize =
500 3 - (MMIO_GUARD_GRANULE_SHIFT as usize / BITS_PER_LEVEL);
Alice Wangb73a81b2023-06-07 13:05:09 +0000501 assert_eq!(
Ard Biesheuvela8dc46f2023-10-20 15:10:38 +0200502 level, MMIO_GUARD_GRANULE_LEVEL,
Alice Wangb73a81b2023-06-07 13:05:09 +0000503 "Failed to break down block mapping before MMIO guard mapping"
504 );
505 let page_base = va_range.start().0;
Pierre-Clément Tosi92154762023-06-07 15:32:15 +0000506 assert_eq!(page_base % MMIO_GUARD_GRANULE_SIZE, 0);
Alice Wangb73a81b2023-06-07 13:05:09 +0000507 // Since mmio_guard_map takes IPAs, if pvmfw moves non-ID address mapping, page_base
508 // should be converted to IPA. However, since 0x0 is a valid MMIO address, we don't use
509 // virt_to_phys here, and just pass page_base instead.
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000510 get_mmio_guard().unwrap().unmap(page_base).map_err(|e| {
Alice Wangb73a81b2023-06-07 13:05:09 +0000511 error!("Error MMIO guard unmapping: {e}");
512 })?;
513 }
514 Ok(())
515}
Alice Wanga9fe1fb2023-07-04 09:10:35 +0000516
517/// Handles a translation fault with the given fault address register (FAR).
518#[inline]
519pub fn handle_translation_fault(far: VirtualAddress) -> result::Result<(), HandleExceptionError> {
520 let mut guard = MEMORY.try_lock().ok_or(HandleExceptionError::PageTableUnavailable)?;
521 let memory = guard.as_mut().ok_or(HandleExceptionError::PageTableNotInitialized)?;
522 Ok(memory.handle_mmio_fault(far)?)
523}
524
525/// Handles a permission fault with the given fault address register (FAR).
526#[inline]
527pub fn handle_permission_fault(far: VirtualAddress) -> result::Result<(), HandleExceptionError> {
528 let mut guard = MEMORY.try_lock().ok_or(HandleExceptionError::PageTableUnavailable)?;
529 let memory = guard.as_mut().ok_or(HandleExceptionError::PageTableNotInitialized)?;
530 Ok(memory.handle_permission_fault(far)?)
531}