blob: 1a2b4b74cedc06703c633d2c6fabe7fa5254006c [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 Vukalovicb99905d2023-04-20 15:46:02 +010021use aarch64_paging::paging::{Attributes, Descriptor, MemoryRegion as VaRange};
Andrew Walbran848decf2022-12-15 14:39:38 +000022use alloc::alloc::alloc_zeroed;
23use alloc::alloc::dealloc;
24use alloc::alloc::handle_alloc_error;
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -070025use alloc::boxed::Box;
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +000026use alloc::vec::Vec;
Andrew Walbran87933f32023-05-09 15:29:06 +000027use buddy_system_allocator::{FrameAllocator, LockedFrameAllocator};
Andrew Walbran848decf2022-12-15 14:39:38 +000028use core::alloc::Layout;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000029use core::cmp::max;
30use core::cmp::min;
31use core::fmt;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000032use core::num::NonZeroUsize;
33use core::ops::Range;
Andrew Walbran848decf2022-12-15 14:39:38 +000034use core::ptr::NonNull;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000035use core::result;
Alice Wang90e6f162023-04-17 13:49:45 +000036use hyp::get_hypervisor;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000037use log::error;
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000038use log::trace;
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -070039use once_cell::race::OnceBox;
Jakob Vukalovic85a00d72023-04-20 09:51:10 +010040use spin::mutex::SpinMutex;
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000041use tinyvec::ArrayVec;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000042
Jiyong Park0ee65392023-03-27 20:52:45 +090043/// Base of the system's contiguous "main" memory.
44pub const BASE_ADDR: usize = 0x8000_0000;
45/// First address that can't be translated by a level 1 TTBR0_EL1.
46pub const MAX_ADDR: usize = 1 << 40;
47
Andrew Walbran0d8b54d2022-12-08 16:32:33 +000048pub type MemoryRange = Range<usize>;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000049
Jakob Vukalovic85a00d72023-04-20 09:51:10 +010050pub static MEMORY: SpinMutex<Option<MemoryTracker>> = SpinMutex::new(None);
51unsafe impl Send for MemoryTracker {}
52
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000053#[derive(Clone, Copy, Debug, Default)]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000054enum MemoryType {
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000055 #[default]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000056 ReadOnly,
57 ReadWrite,
58}
59
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000060#[derive(Clone, Debug, Default)]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000061struct MemoryRegion {
62 range: MemoryRange,
63 mem_type: MemoryType,
64}
65
66impl MemoryRegion {
67 /// True if the instance overlaps with the passed range.
68 pub fn overlaps(&self, range: &MemoryRange) -> bool {
Andrew Walbran19690632022-12-07 16:41:30 +000069 overlaps(&self.range, range)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000070 }
71
72 /// True if the instance is fully contained within the passed range.
73 pub fn is_within(&self, range: &MemoryRange) -> bool {
Srivatsa Vaddagiric25d68e2023-04-19 22:56:33 -070074 self.as_ref().is_within(range)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000075 }
76}
77
78impl AsRef<MemoryRange> for MemoryRegion {
79 fn as_ref(&self) -> &MemoryRange {
80 &self.range
81 }
82}
83
Andrew Walbran19690632022-12-07 16:41:30 +000084/// Returns true if one range overlaps with the other at all.
85fn overlaps<T: Copy + Ord>(a: &Range<T>, b: &Range<T>) -> bool {
86 max(a.start, b.start) < min(a.end, b.end)
87}
88
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000089/// Tracks non-overlapping slices of main memory.
90pub struct MemoryTracker {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000091 total: MemoryRange,
92 page_table: mmu::PageTable,
Andrew Walbran19690632022-12-07 16:41:30 +000093 regions: ArrayVec<[MemoryRegion; MemoryTracker::CAPACITY]>,
94 mmio_regions: ArrayVec<[MemoryRange; MemoryTracker::MMIO_CAPACITY]>,
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000095}
96
97/// Errors for MemoryTracker operations.
98#[derive(Debug, Clone)]
99pub enum MemoryTrackerError {
100 /// Tried to modify the memory base address.
101 DifferentBaseAddress,
102 /// Tried to shrink to a larger memory size.
103 SizeTooLarge,
104 /// Tracked regions would not fit in memory size.
105 SizeTooSmall,
106 /// Reached limit number of tracked regions.
107 Full,
108 /// Region is out of the tracked memory address space.
109 OutOfRange,
110 /// New region overlaps with tracked regions.
111 Overlaps,
112 /// Region couldn't be mapped.
113 FailedToMap,
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100114 /// Region couldn't be unmapped.
115 FailedToUnmap,
Alice Wang90e6f162023-04-17 13:49:45 +0000116 /// Error from the interaction with the hypervisor.
117 Hypervisor(hyp::Error),
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000118 /// Failure to set `SHARED_MEMORY`.
119 SharedMemorySetFailure,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700120 /// Failure to set `SHARED_POOL`.
121 SharedPoolSetFailure,
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100122 /// Invalid page table entry.
123 InvalidPte,
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000124}
125
126impl fmt::Display for MemoryTrackerError {
127 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
128 match self {
129 Self::DifferentBaseAddress => write!(f, "Received different base address"),
130 Self::SizeTooLarge => write!(f, "Tried to shrink to a larger memory size"),
131 Self::SizeTooSmall => write!(f, "Tracked regions would not fit in memory size"),
132 Self::Full => write!(f, "Reached limit number of tracked regions"),
133 Self::OutOfRange => write!(f, "Region is out of the tracked memory address space"),
134 Self::Overlaps => write!(f, "New region overlaps with tracked regions"),
135 Self::FailedToMap => write!(f, "Failed to map the new region"),
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100136 Self::FailedToUnmap => write!(f, "Failed to unmap the new region"),
Alice Wang90e6f162023-04-17 13:49:45 +0000137 Self::Hypervisor(e) => e.fmt(f),
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000138 Self::SharedMemorySetFailure => write!(f, "Failed to set SHARED_MEMORY"),
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700139 Self::SharedPoolSetFailure => write!(f, "Failed to set SHARED_POOL"),
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100140 Self::InvalidPte => write!(f, "Page table entry is not valid"),
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000141 }
142 }
143}
144
Alice Wang90e6f162023-04-17 13:49:45 +0000145impl From<hyp::Error> for MemoryTrackerError {
146 fn from(e: hyp::Error) -> Self {
147 Self::Hypervisor(e)
Andrew Walbran19690632022-12-07 16:41:30 +0000148 }
149}
150
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000151type Result<T> = result::Result<T, MemoryTrackerError>;
152
Andrew Walbran87933f32023-05-09 15:29:06 +0000153static SHARED_POOL: OnceBox<LockedFrameAllocator<32>> = OnceBox::new();
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000154static SHARED_MEMORY: SpinMutex<Option<MemorySharer>> = SpinMutex::new(None);
155
156/// Allocates memory on the heap and shares it with the host.
157///
158/// Unshares all pages when dropped.
159pub struct MemorySharer {
160 granule: usize,
161 shared_regions: Vec<(usize, Layout)>,
162}
163
164impl MemorySharer {
165 const INIT_CAP: usize = 10;
166
167 pub fn new(granule: usize) -> Self {
168 assert!(granule.is_power_of_two());
169 Self { granule, shared_regions: Vec::with_capacity(Self::INIT_CAP) }
170 }
171
172 /// Get from the global allocator a granule-aligned region that suits `hint` and share it.
Andrew Walbran87933f32023-05-09 15:29:06 +0000173 pub fn refill(&mut self, pool: &mut FrameAllocator<32>, hint: Layout) {
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000174 let layout = hint.align_to(self.granule).unwrap().pad_to_align();
175 assert_ne!(layout.size(), 0);
176 // SAFETY - layout has non-zero size.
177 let Some(shared) = NonNull::new(unsafe { alloc_zeroed(layout) }) else {
178 handle_alloc_error(layout);
179 };
180
181 let base = shared.as_ptr() as usize;
182 let end = base.checked_add(layout.size()).unwrap();
183 trace!("Sharing memory region {:#x?}", base..end);
184 for vaddr in (base..end).step_by(self.granule) {
185 let vaddr = NonNull::new(vaddr as *mut _).unwrap();
186 get_hypervisor().mem_share(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
187 }
188 self.shared_regions.push((base, layout));
189
Andrew Walbran87933f32023-05-09 15:29:06 +0000190 pool.add_frame(base, end);
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000191 }
192}
193
194impl Drop for MemorySharer {
195 fn drop(&mut self) {
196 while let Some((base, layout)) = self.shared_regions.pop() {
197 let end = base.checked_add(layout.size()).unwrap();
198 trace!("Unsharing memory region {:#x?}", base..end);
199 for vaddr in (base..end).step_by(self.granule) {
200 let vaddr = NonNull::new(vaddr as *mut _).unwrap();
201 get_hypervisor().mem_unshare(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
202 }
203
204 // SAFETY - The region was obtained from alloc_zeroed() with the recorded layout.
205 unsafe { dealloc(base as *mut _, layout) };
206 }
207 }
208}
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700209
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000210impl MemoryTracker {
211 const CAPACITY: usize = 5;
Andrew Walbran19690632022-12-07 16:41:30 +0000212 const MMIO_CAPACITY: usize = 5;
Pierre-Clément Tosi164a6f52023-04-18 19:29:11 +0100213 const PVMFW_RANGE: MemoryRange = (BASE_ADDR - SIZE_4MB)..BASE_ADDR;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000214
215 /// Create a new instance from an active page table, covering the maximum RAM size.
216 pub fn new(page_table: mmu::PageTable) -> Self {
Andrew Walbran19690632022-12-07 16:41:30 +0000217 Self {
Jiyong Park0ee65392023-03-27 20:52:45 +0900218 total: BASE_ADDR..MAX_ADDR,
Andrew Walbran19690632022-12-07 16:41:30 +0000219 page_table,
220 regions: ArrayVec::new(),
221 mmio_regions: ArrayVec::new(),
222 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000223 }
224
225 /// Resize the total RAM size.
226 ///
227 /// This function fails if it contains regions that are not included within the new size.
228 pub fn shrink(&mut self, range: &MemoryRange) -> Result<()> {
229 if range.start != self.total.start {
230 return Err(MemoryTrackerError::DifferentBaseAddress);
231 }
232 if self.total.end < range.end {
233 return Err(MemoryTrackerError::SizeTooLarge);
234 }
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000235 if !self.regions.iter().all(|r| r.is_within(range)) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000236 return Err(MemoryTrackerError::SizeTooSmall);
237 }
238
239 self.total = range.clone();
240 Ok(())
241 }
242
243 /// Allocate the address range for a const slice; returns None if failed.
244 pub fn alloc_range(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
Andrew Walbranda65ab12022-12-07 15:10:13 +0000245 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadOnly };
246 self.check(&region)?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000247 self.page_table.map_rodata(range).map_err(|e| {
248 error!("Error during range allocation: {e}");
249 MemoryTrackerError::FailedToMap
250 })?;
Andrew Walbranda65ab12022-12-07 15:10:13 +0000251 self.add(region)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000252 }
253
254 /// Allocate the address range for a mutable slice; returns None if failed.
255 pub fn alloc_range_mut(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
Andrew Walbranda65ab12022-12-07 15:10:13 +0000256 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadWrite };
257 self.check(&region)?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000258 self.page_table.map_data(range).map_err(|e| {
259 error!("Error during mutable range allocation: {e}");
260 MemoryTrackerError::FailedToMap
261 })?;
Andrew Walbranda65ab12022-12-07 15:10:13 +0000262 self.add(region)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000263 }
264
265 /// Allocate the address range for a const slice; returns None if failed.
266 pub fn alloc(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
267 self.alloc_range(&(base..(base + size.get())))
268 }
269
270 /// Allocate the address range for a mutable slice; returns None if failed.
271 pub fn alloc_mut(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
272 self.alloc_range_mut(&(base..(base + size.get())))
273 }
274
Andrew Walbran19690632022-12-07 16:41:30 +0000275 /// Checks that the given range of addresses is within the MMIO region, and then maps it
276 /// appropriately.
277 pub fn map_mmio_range(&mut self, range: MemoryRange) -> Result<()> {
278 // MMIO space is below the main memory region.
Pierre-Clément Tosi164a6f52023-04-18 19:29:11 +0100279 if range.end > self.total.start || overlaps(&Self::PVMFW_RANGE, &range) {
Andrew Walbran19690632022-12-07 16:41:30 +0000280 return Err(MemoryTrackerError::OutOfRange);
281 }
282 if self.mmio_regions.iter().any(|r| overlaps(r, &range)) {
283 return Err(MemoryTrackerError::Overlaps);
284 }
285 if self.mmio_regions.len() == self.mmio_regions.capacity() {
286 return Err(MemoryTrackerError::Full);
287 }
288
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100289 self.page_table.map_device_lazy(&range).map_err(|e| {
Andrew Walbran19690632022-12-07 16:41:30 +0000290 error!("Error during MMIO device mapping: {e}");
291 MemoryTrackerError::FailedToMap
292 })?;
293
Andrew Walbran19690632022-12-07 16:41:30 +0000294 if self.mmio_regions.try_push(range).is_some() {
295 return Err(MemoryTrackerError::Full);
296 }
297
298 Ok(())
299 }
300
Andrew Walbranda65ab12022-12-07 15:10:13 +0000301 /// Checks that the given region is within the range of the `MemoryTracker` and doesn't overlap
302 /// with any other previously allocated regions, and that the regions ArrayVec has capacity to
303 /// add it.
304 fn check(&self, region: &MemoryRegion) -> Result<()> {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000305 if !region.is_within(&self.total) {
306 return Err(MemoryTrackerError::OutOfRange);
307 }
Andrew Walbranda65ab12022-12-07 15:10:13 +0000308 if self.regions.iter().any(|r| r.overlaps(&region.range)) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000309 return Err(MemoryTrackerError::Overlaps);
310 }
Andrew Walbranda65ab12022-12-07 15:10:13 +0000311 if self.regions.len() == self.regions.capacity() {
312 return Err(MemoryTrackerError::Full);
313 }
314 Ok(())
315 }
316
317 fn add(&mut self, region: MemoryRegion) -> Result<MemoryRange> {
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000318 if self.regions.try_push(region).is_some() {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000319 return Err(MemoryTrackerError::Full);
320 }
321
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000322 Ok(self.regions.last().unwrap().as_ref().clone())
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000323 }
Andrew Walbran19690632022-12-07 16:41:30 +0000324
325 /// Unmaps all tracked MMIO regions from the MMIO guard.
326 ///
327 /// Note that they are not unmapped from the page table.
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100328 pub fn mmio_unmap_all(&mut self) -> Result<()> {
329 for range in &self.mmio_regions {
330 self.page_table
331 .modify_range(range, &mmio_guard_unmap_page)
332 .map_err(|_| MemoryTrackerError::FailedToUnmap)?;
Andrew Walbran19690632022-12-07 16:41:30 +0000333 }
Andrew Walbran19690632022-12-07 16:41:30 +0000334 Ok(())
335 }
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700336
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000337 /// Initialize the shared heap to dynamically share memory from the global allocator.
338 pub fn init_dynamic_shared_pool(&mut self) -> Result<()> {
339 let granule = get_hypervisor().memory_protection_granule()?;
340 let previous = SHARED_MEMORY.lock().replace(MemorySharer::new(granule));
341 if previous.is_some() {
342 return Err(MemoryTrackerError::SharedMemorySetFailure);
343 }
344
345 SHARED_POOL
Andrew Walbran87933f32023-05-09 15:29:06 +0000346 .set(Box::new(LockedFrameAllocator::new()))
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000347 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
348
349 Ok(())
350 }
351
352 /// Initialize the shared heap from a static region of memory.
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700353 ///
354 /// Some hypervisors such as Gunyah do not support a MemShare API for guest
355 /// to share its memory with host. Instead they allow host to designate part
356 /// of guest memory as "shared" ahead of guest starting its execution. The
357 /// shared memory region is indicated in swiotlb node. On such platforms use
358 /// a separate heap to allocate buffers that can be shared with host.
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000359 pub fn init_static_shared_pool(&mut self, range: Range<usize>) -> Result<()> {
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700360 let size = NonZeroUsize::new(range.len()).unwrap();
361 let range = self.alloc_mut(range.start, size)?;
Andrew Walbran87933f32023-05-09 15:29:06 +0000362 let shared_pool = LockedFrameAllocator::<32>::new();
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700363
Andrew Walbran87933f32023-05-09 15:29:06 +0000364 shared_pool.lock().insert(range);
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700365
366 SHARED_POOL
367 .set(Box::new(shared_pool))
368 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
369
370 Ok(())
371 }
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000372
373 /// Unshares any memory that may have been shared.
374 pub fn unshare_all_memory(&mut self) {
375 drop(SHARED_MEMORY.lock().take());
376 }
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100377
378 /// Handles translation fault for blocks flagged for lazy MMIO mapping by enabling the page
379 /// table entry and MMIO guard mapping the block. Breaks apart a block entry if required.
380 pub fn handle_mmio_fault(&mut self, addr: usize) -> Result<()> {
381 let page_range = page_4kb_of(addr)..page_4kb_of(addr) + PVMFW_PAGE_SIZE;
382 self.page_table
383 .modify_range(&page_range, &verify_lazy_mapped_block)
384 .map_err(|_| MemoryTrackerError::InvalidPte)?;
385 get_hypervisor().mmio_guard_map(page_range.start)?;
386 // Maps a single device page, breaking up block mappings if necessary.
387 self.page_table.map_device(&page_range).map_err(|_| MemoryTrackerError::FailedToMap)
388 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000389}
390
391impl Drop for MemoryTracker {
392 fn drop(&mut self) {
Andrew Walbran19690632022-12-07 16:41:30 +0000393 for region in &self.regions {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000394 match region.mem_type {
395 MemoryType::ReadWrite => {
Pierre-Clément Tosi73c2d642023-02-17 14:56:48 +0000396 // TODO(b/269738062): Use PT's dirty bit to only flush pages that were touched.
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000397 helpers::flush_region(region.range.start, region.range.len())
398 }
399 MemoryType::ReadOnly => {}
400 }
401 }
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000402 self.unshare_all_memory()
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000403 }
404}
Andrew Walbran19690632022-12-07 16:41:30 +0000405
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +0000406/// Allocates a memory range of at least the given size and alignment that is shared with the host.
407/// Returns a pointer to the buffer.
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000408pub fn alloc_shared(layout: Layout) -> hyp::Result<NonNull<u8>> {
409 assert_ne!(layout.size(), 0);
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000410 let Some(buffer) = try_shared_alloc(layout) else {
Andrew Walbran848decf2022-12-15 14:39:38 +0000411 handle_alloc_error(layout);
412 };
413
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000414 trace!("Allocated shared buffer at {buffer:?} with {layout:?}");
Andrew Walbran848decf2022-12-15 14:39:38 +0000415 Ok(buffer)
416}
417
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000418fn try_shared_alloc(layout: Layout) -> Option<NonNull<u8>> {
419 let mut shared_pool = SHARED_POOL.get().unwrap().lock();
420
Andrew Walbran87933f32023-05-09 15:29:06 +0000421 if let Some(buffer) = shared_pool.alloc_aligned(layout) {
422 Some(NonNull::new(buffer as _).unwrap())
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000423 } else if let Some(shared_memory) = SHARED_MEMORY.lock().as_mut() {
424 shared_memory.refill(&mut shared_pool, layout);
Andrew Walbran87933f32023-05-09 15:29:06 +0000425 shared_pool.alloc_aligned(layout).map(|buffer| NonNull::new(buffer as _).unwrap())
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000426 } else {
427 None
428 }
429}
430
Andrew Walbran848decf2022-12-15 14:39:38 +0000431/// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`.
432///
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +0000433/// The layout passed in must be the same layout passed to the original `alloc_shared` call.
Andrew Walbran848decf2022-12-15 14:39:38 +0000434///
435/// # Safety
436///
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +0000437/// The memory must have been allocated by `alloc_shared` with the same layout, and not yet
Andrew Walbran848decf2022-12-15 14:39:38 +0000438/// deallocated.
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000439pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, layout: Layout) -> hyp::Result<()> {
Andrew Walbran87933f32023-05-09 15:29:06 +0000440 SHARED_POOL.get().unwrap().lock().dealloc_aligned(vaddr.as_ptr() as usize, layout);
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700441
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000442 trace!("Deallocated shared buffer at {vaddr:?} with {layout:?}");
Andrew Walbran848decf2022-12-15 14:39:38 +0000443 Ok(())
444}
445
Andrew Walbran848decf2022-12-15 14:39:38 +0000446/// Returns the intermediate physical address corresponding to the given virtual address.
447///
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000448/// As we use identity mapping for everything, this is just a cast, but it's useful to use it to be
449/// explicit about where we are converting from virtual to physical address.
450pub fn virt_to_phys(vaddr: NonNull<u8>) -> usize {
451 vaddr.as_ptr() as _
452}
453
454/// Returns a pointer for the virtual address corresponding to the given non-zero intermediate
455/// physical address.
456///
457/// Panics if `paddr` is 0.
458pub fn phys_to_virt(paddr: usize) -> NonNull<u8> {
459 NonNull::new(paddr as _).unwrap()
Andrew Walbran848decf2022-12-15 14:39:38 +0000460}
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100461
462/// Checks whether a PTE at given level is a page or block descriptor.
463#[inline]
464fn is_leaf_pte(flags: &Attributes, level: usize) -> bool {
465 const LEAF_PTE_LEVEL: usize = 3;
466 if flags.contains(Attributes::TABLE_OR_PAGE) {
467 level == LEAF_PTE_LEVEL
468 } else {
469 level < LEAF_PTE_LEVEL
470 }
471}
472
473/// Checks whether block flags indicate it should be MMIO guard mapped.
474fn verify_lazy_mapped_block(
475 _range: &VaRange,
476 desc: &mut Descriptor,
477 level: usize,
478) -> result::Result<(), ()> {
479 let flags = desc.flags().expect("Unsupported PTE flags set");
480 if !is_leaf_pte(&flags, level) {
481 return Ok(()); // Skip table PTEs as they aren't tagged with MMIO_LAZY_MAP_FLAG.
482 }
483 if flags.contains(mmu::MMIO_LAZY_MAP_FLAG) && !flags.contains(Attributes::VALID) {
484 Ok(())
485 } else {
486 Err(())
487 }
488}
489
490/// MMIO guard unmaps page
491fn mmio_guard_unmap_page(
492 va_range: &VaRange,
493 desc: &mut Descriptor,
494 level: usize,
495) -> result::Result<(), ()> {
496 let flags = desc.flags().expect("Unsupported PTE flags set");
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 is_leaf_pte(&flags, level) && flags.contains(Attributes::VALID) {
502 assert!(
503 flags.contains(mmu::MMIO_LAZY_MAP_FLAG),
504 "Attempting MMIO guard unmap for non-device pages"
505 );
506 assert_eq!(
507 va_range.len(),
508 PVMFW_PAGE_SIZE,
509 "Failed to break down block mapping before MMIO guard mapping"
510 );
511 let page_base = va_range.start().0;
512 assert_eq!(page_base % PVMFW_PAGE_SIZE, 0);
513 // Since mmio_guard_map takes IPAs, if pvmfw moves non-ID address mapping, page_base
514 // should be converted to IPA. However, since 0x0 is a valid MMIO address, we don't use
515 // virt_to_phys here, and just pass page_base instead.
516 get_hypervisor().mmio_guard_unmap(page_base).map_err(|e| {
517 error!("Error MMIO guard unmapping: {e}");
518 })?;
519 }
520 Ok(())
521}