blob: 4ed3072d0303fc95c5ed59aa12c360f7fe070656 [file] [log] [blame]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +00001// Copyright 2022, 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//! Low-level allocation and tracking of main memory.
16
Andrew Walbran848decf2022-12-15 14:39:38 +000017#![deny(unsafe_op_in_unsafe_fn)]
18
Jakob Vukalovicb99905d2023-04-20 15:46:02 +010019use crate::helpers::{self, page_4kb_of, RangeExt, PVMFW_PAGE_SIZE, SIZE_4MB};
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000020use crate::mmu;
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +010021use crate::{dsb, isb, tlbi};
Jakob Vukalovicb99905d2023-04-20 15:46:02 +010022use aarch64_paging::paging::{Attributes, Descriptor, MemoryRegion as VaRange};
Andrew Walbran848decf2022-12-15 14:39:38 +000023use alloc::alloc::alloc_zeroed;
24use alloc::alloc::dealloc;
25use alloc::alloc::handle_alloc_error;
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -070026use alloc::boxed::Box;
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +000027use alloc::vec::Vec;
Andrew Walbran87933f32023-05-09 15:29:06 +000028use buddy_system_allocator::{FrameAllocator, LockedFrameAllocator};
Andrew Walbran848decf2022-12-15 14:39:38 +000029use core::alloc::Layout;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000030use core::cmp::max;
31use core::cmp::min;
32use core::fmt;
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +010033use core::iter::once;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000034use core::num::NonZeroUsize;
35use core::ops::Range;
Andrew Walbran848decf2022-12-15 14:39:38 +000036use core::ptr::NonNull;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000037use core::result;
Alice Wang90e6f162023-04-17 13:49:45 +000038use hyp::get_hypervisor;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000039use log::error;
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000040use log::trace;
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -070041use once_cell::race::OnceBox;
Jakob Vukalovic85a00d72023-04-20 09:51:10 +010042use spin::mutex::SpinMutex;
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000043use tinyvec::ArrayVec;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000044
Jiyong Park0ee65392023-03-27 20:52:45 +090045/// Base of the system's contiguous "main" memory.
46pub const BASE_ADDR: usize = 0x8000_0000;
47/// First address that can't be translated by a level 1 TTBR0_EL1.
48pub const MAX_ADDR: usize = 1 << 40;
49
Andrew Walbran0d8b54d2022-12-08 16:32:33 +000050pub type MemoryRange = Range<usize>;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000051
Jakob Vukalovic85a00d72023-04-20 09:51:10 +010052pub static MEMORY: SpinMutex<Option<MemoryTracker>> = SpinMutex::new(None);
53unsafe impl Send for MemoryTracker {}
54
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +010055#[derive(Clone, Copy, Debug, Default, PartialEq)]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000056enum MemoryType {
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000057 #[default]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000058 ReadOnly,
59 ReadWrite,
60}
61
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000062#[derive(Clone, Debug, Default)]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000063struct MemoryRegion {
64 range: MemoryRange,
65 mem_type: MemoryType,
66}
67
68impl MemoryRegion {
69 /// True if the instance overlaps with the passed range.
70 pub fn overlaps(&self, range: &MemoryRange) -> bool {
Andrew Walbran19690632022-12-07 16:41:30 +000071 overlaps(&self.range, range)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000072 }
73
74 /// True if the instance is fully contained within the passed range.
75 pub fn is_within(&self, range: &MemoryRange) -> bool {
Srivatsa Vaddagiric25d68e2023-04-19 22:56:33 -070076 self.as_ref().is_within(range)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000077 }
78}
79
80impl AsRef<MemoryRange> for MemoryRegion {
81 fn as_ref(&self) -> &MemoryRange {
82 &self.range
83 }
84}
85
Andrew Walbran19690632022-12-07 16:41:30 +000086/// Returns true if one range overlaps with the other at all.
87fn overlaps<T: Copy + Ord>(a: &Range<T>, b: &Range<T>) -> bool {
88 max(a.start, b.start) < min(a.end, b.end)
89}
90
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000091/// Tracks non-overlapping slices of main memory.
92pub struct MemoryTracker {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000093 total: MemoryRange,
94 page_table: mmu::PageTable,
Andrew Walbran19690632022-12-07 16:41:30 +000095 regions: ArrayVec<[MemoryRegion; MemoryTracker::CAPACITY]>,
96 mmio_regions: ArrayVec<[MemoryRange; MemoryTracker::MMIO_CAPACITY]>,
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000097}
98
99/// Errors for MemoryTracker operations.
100#[derive(Debug, Clone)]
101pub enum MemoryTrackerError {
102 /// Tried to modify the memory base address.
103 DifferentBaseAddress,
104 /// Tried to shrink to a larger memory size.
105 SizeTooLarge,
106 /// Tracked regions would not fit in memory size.
107 SizeTooSmall,
108 /// Reached limit number of tracked regions.
109 Full,
110 /// Region is out of the tracked memory address space.
111 OutOfRange,
112 /// New region overlaps with tracked regions.
113 Overlaps,
114 /// Region couldn't be mapped.
115 FailedToMap,
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100116 /// Region couldn't be unmapped.
117 FailedToUnmap,
Alice Wang90e6f162023-04-17 13:49:45 +0000118 /// Error from the interaction with the hypervisor.
119 Hypervisor(hyp::Error),
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000120 /// Failure to set `SHARED_MEMORY`.
121 SharedMemorySetFailure,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700122 /// Failure to set `SHARED_POOL`.
123 SharedPoolSetFailure,
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100124 /// Invalid page table entry.
125 InvalidPte,
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100126 /// Failed to flush memory region.
127 FlushRegionFailed,
128 /// Failed to set PTE dirty state.
129 SetPteDirtyFailed,
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000130}
131
132impl fmt::Display for MemoryTrackerError {
133 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
134 match self {
135 Self::DifferentBaseAddress => write!(f, "Received different base address"),
136 Self::SizeTooLarge => write!(f, "Tried to shrink to a larger memory size"),
137 Self::SizeTooSmall => write!(f, "Tracked regions would not fit in memory size"),
138 Self::Full => write!(f, "Reached limit number of tracked regions"),
139 Self::OutOfRange => write!(f, "Region is out of the tracked memory address space"),
140 Self::Overlaps => write!(f, "New region overlaps with tracked regions"),
141 Self::FailedToMap => write!(f, "Failed to map the new region"),
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100142 Self::FailedToUnmap => write!(f, "Failed to unmap the new region"),
Alice Wang90e6f162023-04-17 13:49:45 +0000143 Self::Hypervisor(e) => e.fmt(f),
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000144 Self::SharedMemorySetFailure => write!(f, "Failed to set SHARED_MEMORY"),
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700145 Self::SharedPoolSetFailure => write!(f, "Failed to set SHARED_POOL"),
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100146 Self::InvalidPte => write!(f, "Page table entry is not valid"),
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100147 Self::FlushRegionFailed => write!(f, "Failed to flush memory region"),
148 Self::SetPteDirtyFailed => write!(f, "Failed to set PTE dirty state"),
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000149 }
150 }
151}
152
Alice Wang90e6f162023-04-17 13:49:45 +0000153impl From<hyp::Error> for MemoryTrackerError {
154 fn from(e: hyp::Error) -> Self {
155 Self::Hypervisor(e)
Andrew Walbran19690632022-12-07 16:41:30 +0000156 }
157}
158
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000159type Result<T> = result::Result<T, MemoryTrackerError>;
160
Andrew Walbran87933f32023-05-09 15:29:06 +0000161static SHARED_POOL: OnceBox<LockedFrameAllocator<32>> = OnceBox::new();
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000162static SHARED_MEMORY: SpinMutex<Option<MemorySharer>> = SpinMutex::new(None);
163
164/// Allocates memory on the heap and shares it with the host.
165///
166/// Unshares all pages when dropped.
167pub struct MemorySharer {
168 granule: usize,
169 shared_regions: Vec<(usize, Layout)>,
170}
171
172impl MemorySharer {
173 const INIT_CAP: usize = 10;
174
175 pub fn new(granule: usize) -> Self {
176 assert!(granule.is_power_of_two());
177 Self { granule, shared_regions: Vec::with_capacity(Self::INIT_CAP) }
178 }
179
180 /// Get from the global allocator a granule-aligned region that suits `hint` and share it.
Andrew Walbran87933f32023-05-09 15:29:06 +0000181 pub fn refill(&mut self, pool: &mut FrameAllocator<32>, hint: Layout) {
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000182 let layout = hint.align_to(self.granule).unwrap().pad_to_align();
183 assert_ne!(layout.size(), 0);
184 // SAFETY - layout has non-zero size.
185 let Some(shared) = NonNull::new(unsafe { alloc_zeroed(layout) }) else {
186 handle_alloc_error(layout);
187 };
188
189 let base = shared.as_ptr() as usize;
190 let end = base.checked_add(layout.size()).unwrap();
191 trace!("Sharing memory region {:#x?}", base..end);
192 for vaddr in (base..end).step_by(self.granule) {
193 let vaddr = NonNull::new(vaddr as *mut _).unwrap();
194 get_hypervisor().mem_share(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
195 }
196 self.shared_regions.push((base, layout));
197
Andrew Walbran87933f32023-05-09 15:29:06 +0000198 pool.add_frame(base, end);
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000199 }
200}
201
202impl Drop for MemorySharer {
203 fn drop(&mut self) {
204 while let Some((base, layout)) = self.shared_regions.pop() {
205 let end = base.checked_add(layout.size()).unwrap();
206 trace!("Unsharing memory region {:#x?}", base..end);
207 for vaddr in (base..end).step_by(self.granule) {
208 let vaddr = NonNull::new(vaddr as *mut _).unwrap();
209 get_hypervisor().mem_unshare(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
210 }
211
212 // SAFETY - The region was obtained from alloc_zeroed() with the recorded layout.
213 unsafe { dealloc(base as *mut _, layout) };
214 }
215 }
216}
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700217
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000218impl MemoryTracker {
219 const CAPACITY: usize = 5;
Andrew Walbran19690632022-12-07 16:41:30 +0000220 const MMIO_CAPACITY: usize = 5;
Pierre-Clément Tosi164a6f52023-04-18 19:29:11 +0100221 const PVMFW_RANGE: MemoryRange = (BASE_ADDR - SIZE_4MB)..BASE_ADDR;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000222
223 /// Create a new instance from an active page table, covering the maximum RAM size.
224 pub fn new(page_table: mmu::PageTable) -> Self {
Andrew Walbran19690632022-12-07 16:41:30 +0000225 Self {
Jiyong Park0ee65392023-03-27 20:52:45 +0900226 total: BASE_ADDR..MAX_ADDR,
Andrew Walbran19690632022-12-07 16:41:30 +0000227 page_table,
228 regions: ArrayVec::new(),
229 mmio_regions: ArrayVec::new(),
230 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000231 }
232
233 /// Resize the total RAM size.
234 ///
235 /// This function fails if it contains regions that are not included within the new size.
236 pub fn shrink(&mut self, range: &MemoryRange) -> Result<()> {
237 if range.start != self.total.start {
238 return Err(MemoryTrackerError::DifferentBaseAddress);
239 }
240 if self.total.end < range.end {
241 return Err(MemoryTrackerError::SizeTooLarge);
242 }
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000243 if !self.regions.iter().all(|r| r.is_within(range)) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000244 return Err(MemoryTrackerError::SizeTooSmall);
245 }
246
247 self.total = range.clone();
248 Ok(())
249 }
250
251 /// Allocate the address range for a const slice; returns None if failed.
252 pub fn alloc_range(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
Andrew Walbranda65ab12022-12-07 15:10:13 +0000253 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadOnly };
254 self.check(&region)?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000255 self.page_table.map_rodata(range).map_err(|e| {
256 error!("Error during range allocation: {e}");
257 MemoryTrackerError::FailedToMap
258 })?;
Andrew Walbranda65ab12022-12-07 15:10:13 +0000259 self.add(region)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000260 }
261
262 /// Allocate the address range for a mutable slice; returns None if failed.
263 pub fn alloc_range_mut(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
Andrew Walbranda65ab12022-12-07 15:10:13 +0000264 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadWrite };
265 self.check(&region)?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000266 self.page_table.map_data(range).map_err(|e| {
267 error!("Error during mutable range allocation: {e}");
268 MemoryTrackerError::FailedToMap
269 })?;
Andrew Walbranda65ab12022-12-07 15:10:13 +0000270 self.add(region)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000271 }
272
273 /// Allocate the address range for a const slice; returns None if failed.
274 pub fn alloc(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
275 self.alloc_range(&(base..(base + size.get())))
276 }
277
278 /// Allocate the address range for a mutable slice; returns None if failed.
279 pub fn alloc_mut(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
280 self.alloc_range_mut(&(base..(base + size.get())))
281 }
282
Andrew Walbran19690632022-12-07 16:41:30 +0000283 /// Checks that the given range of addresses is within the MMIO region, and then maps it
284 /// appropriately.
285 pub fn map_mmio_range(&mut self, range: MemoryRange) -> Result<()> {
286 // MMIO space is below the main memory region.
Pierre-Clément Tosi164a6f52023-04-18 19:29:11 +0100287 if range.end > self.total.start || overlaps(&Self::PVMFW_RANGE, &range) {
Andrew Walbran19690632022-12-07 16:41:30 +0000288 return Err(MemoryTrackerError::OutOfRange);
289 }
290 if self.mmio_regions.iter().any(|r| overlaps(r, &range)) {
291 return Err(MemoryTrackerError::Overlaps);
292 }
293 if self.mmio_regions.len() == self.mmio_regions.capacity() {
294 return Err(MemoryTrackerError::Full);
295 }
296
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100297 self.page_table.map_device_lazy(&range).map_err(|e| {
Andrew Walbran19690632022-12-07 16:41:30 +0000298 error!("Error during MMIO device mapping: {e}");
299 MemoryTrackerError::FailedToMap
300 })?;
301
Andrew Walbran19690632022-12-07 16:41:30 +0000302 if self.mmio_regions.try_push(range).is_some() {
303 return Err(MemoryTrackerError::Full);
304 }
305
306 Ok(())
307 }
308
Andrew Walbranda65ab12022-12-07 15:10:13 +0000309 /// Checks that the given region is within the range of the `MemoryTracker` and doesn't overlap
310 /// with any other previously allocated regions, and that the regions ArrayVec has capacity to
311 /// add it.
312 fn check(&self, region: &MemoryRegion) -> Result<()> {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000313 if !region.is_within(&self.total) {
314 return Err(MemoryTrackerError::OutOfRange);
315 }
Andrew Walbranda65ab12022-12-07 15:10:13 +0000316 if self.regions.iter().any(|r| r.overlaps(&region.range)) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000317 return Err(MemoryTrackerError::Overlaps);
318 }
Andrew Walbranda65ab12022-12-07 15:10:13 +0000319 if self.regions.len() == self.regions.capacity() {
320 return Err(MemoryTrackerError::Full);
321 }
322 Ok(())
323 }
324
325 fn add(&mut self, region: MemoryRegion) -> Result<MemoryRange> {
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000326 if self.regions.try_push(region).is_some() {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000327 return Err(MemoryTrackerError::Full);
328 }
329
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000330 Ok(self.regions.last().unwrap().as_ref().clone())
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000331 }
Andrew Walbran19690632022-12-07 16:41:30 +0000332
333 /// Unmaps all tracked MMIO regions from the MMIO guard.
334 ///
335 /// Note that they are not unmapped from the page table.
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100336 pub fn mmio_unmap_all(&mut self) -> Result<()> {
337 for range in &self.mmio_regions {
338 self.page_table
339 .modify_range(range, &mmio_guard_unmap_page)
340 .map_err(|_| MemoryTrackerError::FailedToUnmap)?;
Andrew Walbran19690632022-12-07 16:41:30 +0000341 }
Andrew Walbran19690632022-12-07 16:41:30 +0000342 Ok(())
343 }
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700344
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000345 /// Initialize the shared heap to dynamically share memory from the global allocator.
346 pub fn init_dynamic_shared_pool(&mut self) -> Result<()> {
347 let granule = get_hypervisor().memory_protection_granule()?;
348 let previous = SHARED_MEMORY.lock().replace(MemorySharer::new(granule));
349 if previous.is_some() {
350 return Err(MemoryTrackerError::SharedMemorySetFailure);
351 }
352
353 SHARED_POOL
Andrew Walbran87933f32023-05-09 15:29:06 +0000354 .set(Box::new(LockedFrameAllocator::new()))
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000355 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
356
357 Ok(())
358 }
359
360 /// Initialize the shared heap from a static region of memory.
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700361 ///
362 /// Some hypervisors such as Gunyah do not support a MemShare API for guest
363 /// to share its memory with host. Instead they allow host to designate part
364 /// of guest memory as "shared" ahead of guest starting its execution. The
365 /// shared memory region is indicated in swiotlb node. On such platforms use
366 /// a separate heap to allocate buffers that can be shared with host.
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000367 pub fn init_static_shared_pool(&mut self, range: Range<usize>) -> Result<()> {
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700368 let size = NonZeroUsize::new(range.len()).unwrap();
369 let range = self.alloc_mut(range.start, size)?;
Andrew Walbran87933f32023-05-09 15:29:06 +0000370 let shared_pool = LockedFrameAllocator::<32>::new();
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700371
Andrew Walbran87933f32023-05-09 15:29:06 +0000372 shared_pool.lock().insert(range);
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700373
374 SHARED_POOL
375 .set(Box::new(shared_pool))
376 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
377
378 Ok(())
379 }
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000380
381 /// Unshares any memory that may have been shared.
382 pub fn unshare_all_memory(&mut self) {
383 drop(SHARED_MEMORY.lock().take());
384 }
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100385
386 /// Handles translation fault for blocks flagged for lazy MMIO mapping by enabling the page
387 /// table entry and MMIO guard mapping the block. Breaks apart a block entry if required.
388 pub fn handle_mmio_fault(&mut self, addr: usize) -> Result<()> {
389 let page_range = page_4kb_of(addr)..page_4kb_of(addr) + PVMFW_PAGE_SIZE;
390 self.page_table
391 .modify_range(&page_range, &verify_lazy_mapped_block)
392 .map_err(|_| MemoryTrackerError::InvalidPte)?;
393 get_hypervisor().mmio_guard_map(page_range.start)?;
394 // Maps a single device page, breaking up block mappings if necessary.
395 self.page_table.map_device(&page_range).map_err(|_| MemoryTrackerError::FailedToMap)
396 }
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100397
398 /// Flush all memory regions marked as writable-dirty.
399 fn flush_dirty_pages(&mut self) -> Result<()> {
400 // Collect memory ranges for which dirty state is tracked.
401 let writable_regions =
402 self.regions.iter().filter(|r| r.mem_type == MemoryType::ReadWrite).map(|r| &r.range);
403 let payload_range = mmu::PageTable::appended_payload_range();
404 // Execute a barrier instruction to ensure all hardware updates to the page table have been
405 // observed before reading PTE flags to determine dirty state.
406 dsb!("ish");
407 // Now flush writable-dirty pages in those regions.
408 for range in writable_regions.chain(once(&payload_range)) {
409 self.page_table
410 .modify_range(range, &flush_dirty_range)
411 .map_err(|_| MemoryTrackerError::FlushRegionFailed)?;
412 }
413 Ok(())
414 }
415
416 /// Handles permission fault for read-only blocks by setting writable-dirty state.
417 /// In general, this should be called from the exception handler when hardware dirty
418 /// state management is disabled or unavailable.
419 pub fn handle_permission_fault(&mut self, addr: usize) -> Result<()> {
420 self.page_table
421 .modify_range(&(addr..addr + 1), &mark_dirty_block)
422 .map_err(|_| MemoryTrackerError::SetPteDirtyFailed)
423 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000424}
425
426impl Drop for MemoryTracker {
427 fn drop(&mut self) {
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100428 self.flush_dirty_pages().unwrap();
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000429 self.unshare_all_memory()
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000430 }
431}
Andrew Walbran19690632022-12-07 16:41:30 +0000432
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +0000433/// Allocates a memory range of at least the given size and alignment that is shared with the host.
434/// Returns a pointer to the buffer.
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000435pub fn alloc_shared(layout: Layout) -> hyp::Result<NonNull<u8>> {
436 assert_ne!(layout.size(), 0);
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000437 let Some(buffer) = try_shared_alloc(layout) else {
Andrew Walbran848decf2022-12-15 14:39:38 +0000438 handle_alloc_error(layout);
439 };
440
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000441 trace!("Allocated shared buffer at {buffer:?} with {layout:?}");
Andrew Walbran848decf2022-12-15 14:39:38 +0000442 Ok(buffer)
443}
444
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000445fn try_shared_alloc(layout: Layout) -> Option<NonNull<u8>> {
446 let mut shared_pool = SHARED_POOL.get().unwrap().lock();
447
Andrew Walbran87933f32023-05-09 15:29:06 +0000448 if let Some(buffer) = shared_pool.alloc_aligned(layout) {
449 Some(NonNull::new(buffer as _).unwrap())
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000450 } else if let Some(shared_memory) = SHARED_MEMORY.lock().as_mut() {
451 shared_memory.refill(&mut shared_pool, layout);
Andrew Walbran87933f32023-05-09 15:29:06 +0000452 shared_pool.alloc_aligned(layout).map(|buffer| NonNull::new(buffer as _).unwrap())
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000453 } else {
454 None
455 }
456}
457
Andrew Walbran848decf2022-12-15 14:39:38 +0000458/// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`.
459///
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +0000460/// The layout passed in must be the same layout passed to the original `alloc_shared` call.
Andrew Walbran848decf2022-12-15 14:39:38 +0000461///
462/// # Safety
463///
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +0000464/// The memory must have been allocated by `alloc_shared` with the same layout, and not yet
Andrew Walbran848decf2022-12-15 14:39:38 +0000465/// deallocated.
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000466pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, layout: Layout) -> hyp::Result<()> {
Andrew Walbran87933f32023-05-09 15:29:06 +0000467 SHARED_POOL.get().unwrap().lock().dealloc_aligned(vaddr.as_ptr() as usize, layout);
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700468
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000469 trace!("Deallocated shared buffer at {vaddr:?} with {layout:?}");
Andrew Walbran848decf2022-12-15 14:39:38 +0000470 Ok(())
471}
472
Andrew Walbran848decf2022-12-15 14:39:38 +0000473/// Returns the intermediate physical address corresponding to the given virtual address.
474///
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000475/// As we use identity mapping for everything, this is just a cast, but it's useful to use it to be
476/// explicit about where we are converting from virtual to physical address.
477pub fn virt_to_phys(vaddr: NonNull<u8>) -> usize {
478 vaddr.as_ptr() as _
479}
480
481/// Returns a pointer for the virtual address corresponding to the given non-zero intermediate
482/// physical address.
483///
484/// Panics if `paddr` is 0.
485pub fn phys_to_virt(paddr: usize) -> NonNull<u8> {
486 NonNull::new(paddr as _).unwrap()
Andrew Walbran848decf2022-12-15 14:39:38 +0000487}
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100488
489/// Checks whether a PTE at given level is a page or block descriptor.
490#[inline]
491fn is_leaf_pte(flags: &Attributes, level: usize) -> bool {
492 const LEAF_PTE_LEVEL: usize = 3;
493 if flags.contains(Attributes::TABLE_OR_PAGE) {
494 level == LEAF_PTE_LEVEL
495 } else {
496 level < LEAF_PTE_LEVEL
497 }
498}
499
500/// Checks whether block flags indicate it should be MMIO guard mapped.
501fn verify_lazy_mapped_block(
502 _range: &VaRange,
503 desc: &mut Descriptor,
504 level: usize,
505) -> result::Result<(), ()> {
506 let flags = desc.flags().expect("Unsupported PTE flags set");
507 if !is_leaf_pte(&flags, level) {
508 return Ok(()); // Skip table PTEs as they aren't tagged with MMIO_LAZY_MAP_FLAG.
509 }
510 if flags.contains(mmu::MMIO_LAZY_MAP_FLAG) && !flags.contains(Attributes::VALID) {
511 Ok(())
512 } else {
513 Err(())
514 }
515}
516
517/// MMIO guard unmaps page
518fn mmio_guard_unmap_page(
519 va_range: &VaRange,
520 desc: &mut Descriptor,
521 level: usize,
522) -> result::Result<(), ()> {
523 let flags = desc.flags().expect("Unsupported PTE flags set");
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100524 if !is_leaf_pte(&flags, level) {
525 return Ok(());
526 }
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100527 // This function will be called on an address range that corresponds to a device. Only if a
528 // page has been accessed (written to or read from), will it contain the VALID flag and be MMIO
529 // guard mapped. Therefore, we can skip unmapping invalid pages, they were never MMIO guard
530 // mapped anyway.
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100531 if flags.contains(Attributes::VALID) {
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100532 assert!(
533 flags.contains(mmu::MMIO_LAZY_MAP_FLAG),
534 "Attempting MMIO guard unmap for non-device pages"
535 );
536 assert_eq!(
537 va_range.len(),
538 PVMFW_PAGE_SIZE,
539 "Failed to break down block mapping before MMIO guard mapping"
540 );
541 let page_base = va_range.start().0;
542 assert_eq!(page_base % PVMFW_PAGE_SIZE, 0);
543 // Since mmio_guard_map takes IPAs, if pvmfw moves non-ID address mapping, page_base
544 // should be converted to IPA. However, since 0x0 is a valid MMIO address, we don't use
545 // virt_to_phys here, and just pass page_base instead.
546 get_hypervisor().mmio_guard_unmap(page_base).map_err(|e| {
547 error!("Error MMIO guard unmapping: {e}");
548 })?;
549 }
550 Ok(())
551}
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100552
553/// Flushes a memory range the descriptor refers to, if the descriptor is in writable-dirty state.
554fn flush_dirty_range(
555 va_range: &VaRange,
556 desc: &mut Descriptor,
557 level: usize,
558) -> result::Result<(), ()> {
559 // Only flush ranges corresponding to dirty leaf PTEs.
560 let flags = desc.flags().ok_or(())?;
561 if !is_leaf_pte(&flags, level) {
562 return Ok(());
563 }
564 if !flags.contains(Attributes::READ_ONLY) {
565 helpers::flush_region(va_range.start().0, va_range.len());
566 }
567 Ok(())
568}
569
570/// Clears read-only flag on a PTE, making it writable-dirty. Used when dirty state is managed
571/// in software to handle permission faults on read-only descriptors.
572fn mark_dirty_block(
573 va_range: &VaRange,
574 desc: &mut Descriptor,
575 level: usize,
576) -> result::Result<(), ()> {
577 let flags = desc.flags().ok_or(())?;
578 if !is_leaf_pte(&flags, level) {
579 return Ok(());
580 }
581 if flags.contains(Attributes::DBM) {
582 assert!(flags.contains(Attributes::READ_ONLY), "unexpected PTE writable state");
583 desc.modify_flags(Attributes::empty(), Attributes::READ_ONLY);
584 // Updating the read-only bit of a PTE requires TLB invalidation.
585 // A TLB maintenance instruction is only guaranteed to be complete after a DSB instruction.
586 // An ISB instruction is required to ensure the effects of completed TLB maintenance
587 // instructions are visible to instructions fetched afterwards.
588 // See ARM ARM E2.3.10, and G5.9.
589 tlbi!("vale1", mmu::PageTable::ASID, va_range.start().0);
590 dsb!("ish");
591 isb!();
592 Ok(())
593 } else {
594 Err(())
595 }
596}