blob: 323ac745433d2e25b007d8a8d7e8386cec6fe77d [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
Alice Wang3fa9b802023-06-06 07:52:31 +000019use crate::helpers::{RangeExt, PVMFW_PAGE_SIZE};
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +000020use aarch64_paging::idmap::IdMap;
Jakob Vukalovicb99905d2023-04-20 15:46:02 +010021use aarch64_paging::paging::{Attributes, Descriptor, MemoryRegion as VaRange};
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +000022use aarch64_paging::MapError;
Andrew Walbran848decf2022-12-15 14:39:38 +000023use alloc::alloc::handle_alloc_error;
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -070024use alloc::boxed::Box;
Alice Wangf47b2342023-06-02 11:51:57 +000025use buddy_system_allocator::LockedFrameAllocator;
Andrew Walbran848decf2022-12-15 14:39:38 +000026use core::alloc::Layout;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000027use core::fmt;
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +010028use core::iter::once;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000029use core::num::NonZeroUsize;
30use core::ops::Range;
Andrew Walbran848decf2022-12-15 14:39:38 +000031use core::ptr::NonNull;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000032use core::result;
Alice Wang90e6f162023-04-17 13:49:45 +000033use hyp::get_hypervisor;
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000034use log::trace;
Jakob Vukalovic4c1edbe2023-04-17 19:10:57 +010035use log::{debug, error};
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -070036use once_cell::race::OnceBox;
Jakob Vukalovic85a00d72023-04-20 09:51:10 +010037use spin::mutex::SpinMutex;
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000038use tinyvec::ArrayVec;
Pierre-Clément Tosi3d4c5c32023-05-31 16:57:06 +000039use vmbase::{
40 dsb, isb, layout,
Alice Wangeacb7382023-06-05 12:53:54 +000041 memory::{
Alice Wang3fa9b802023-06-06 07:52:31 +000042 flush_dirty_range, is_leaf_pte, page_4kb_of, set_dbm_enabled, MemorySharer, PageTable,
43 MMIO_LAZY_MAP_FLAG, SIZE_2MB, SIZE_4KB, SIZE_4MB,
Alice Wangeacb7382023-06-05 12:53:54 +000044 },
Pierre-Clément Tosi3d4c5c32023-05-31 16:57:06 +000045 tlbi,
Alice Wangeacb7382023-06-05 12:53:54 +000046 util::align_up,
Pierre-Clément Tosi3d4c5c32023-05-31 16:57:06 +000047};
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000048
Jiyong Park0ee65392023-03-27 20:52:45 +090049/// Base of the system's contiguous "main" memory.
50pub const BASE_ADDR: usize = 0x8000_0000;
51/// First address that can't be translated by a level 1 TTBR0_EL1.
52pub const MAX_ADDR: usize = 1 << 40;
53
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +000054const PT_ROOT_LEVEL: usize = 1;
55const PT_ASID: usize = 1;
56
Andrew Walbran0d8b54d2022-12-08 16:32:33 +000057pub type MemoryRange = Range<usize>;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000058
Jakob Vukalovic85a00d72023-04-20 09:51:10 +010059pub static MEMORY: SpinMutex<Option<MemoryTracker>> = SpinMutex::new(None);
60unsafe impl Send for MemoryTracker {}
61
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +010062#[derive(Clone, Copy, Debug, Default, PartialEq)]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000063enum MemoryType {
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000064 #[default]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000065 ReadOnly,
66 ReadWrite,
67}
68
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000069#[derive(Clone, Debug, Default)]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000070struct MemoryRegion {
71 range: MemoryRange,
72 mem_type: MemoryType,
73}
74
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000075/// Tracks non-overlapping slices of main memory.
76pub struct MemoryTracker {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000077 total: MemoryRange,
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +000078 page_table: PageTable,
Andrew Walbran19690632022-12-07 16:41:30 +000079 regions: ArrayVec<[MemoryRegion; MemoryTracker::CAPACITY]>,
80 mmio_regions: ArrayVec<[MemoryRange; MemoryTracker::MMIO_CAPACITY]>,
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000081}
82
83/// Errors for MemoryTracker operations.
84#[derive(Debug, Clone)]
85pub enum MemoryTrackerError {
86 /// Tried to modify the memory base address.
87 DifferentBaseAddress,
88 /// Tried to shrink to a larger memory size.
89 SizeTooLarge,
90 /// Tracked regions would not fit in memory size.
91 SizeTooSmall,
92 /// Reached limit number of tracked regions.
93 Full,
94 /// Region is out of the tracked memory address space.
95 OutOfRange,
96 /// New region overlaps with tracked regions.
97 Overlaps,
98 /// Region couldn't be mapped.
99 FailedToMap,
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100100 /// Region couldn't be unmapped.
101 FailedToUnmap,
Alice Wang90e6f162023-04-17 13:49:45 +0000102 /// Error from the interaction with the hypervisor.
103 Hypervisor(hyp::Error),
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000104 /// Failure to set `SHARED_MEMORY`.
105 SharedMemorySetFailure,
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700106 /// Failure to set `SHARED_POOL`.
107 SharedPoolSetFailure,
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100108 /// Invalid page table entry.
109 InvalidPte,
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100110 /// Failed to flush memory region.
111 FlushRegionFailed,
112 /// Failed to set PTE dirty state.
113 SetPteDirtyFailed,
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000114}
115
116impl fmt::Display for MemoryTrackerError {
117 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
118 match self {
119 Self::DifferentBaseAddress => write!(f, "Received different base address"),
120 Self::SizeTooLarge => write!(f, "Tried to shrink to a larger memory size"),
121 Self::SizeTooSmall => write!(f, "Tracked regions would not fit in memory size"),
122 Self::Full => write!(f, "Reached limit number of tracked regions"),
123 Self::OutOfRange => write!(f, "Region is out of the tracked memory address space"),
124 Self::Overlaps => write!(f, "New region overlaps with tracked regions"),
125 Self::FailedToMap => write!(f, "Failed to map the new region"),
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100126 Self::FailedToUnmap => write!(f, "Failed to unmap the new region"),
Alice Wang90e6f162023-04-17 13:49:45 +0000127 Self::Hypervisor(e) => e.fmt(f),
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000128 Self::SharedMemorySetFailure => write!(f, "Failed to set SHARED_MEMORY"),
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700129 Self::SharedPoolSetFailure => write!(f, "Failed to set SHARED_POOL"),
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100130 Self::InvalidPte => write!(f, "Page table entry is not valid"),
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100131 Self::FlushRegionFailed => write!(f, "Failed to flush memory region"),
132 Self::SetPteDirtyFailed => write!(f, "Failed to set PTE dirty state"),
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000133 }
134 }
135}
136
Alice Wang90e6f162023-04-17 13:49:45 +0000137impl From<hyp::Error> for MemoryTrackerError {
138 fn from(e: hyp::Error) -> Self {
139 Self::Hypervisor(e)
Andrew Walbran19690632022-12-07 16:41:30 +0000140 }
141}
142
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000143type Result<T> = result::Result<T, MemoryTrackerError>;
144
Andrew Walbran87933f32023-05-09 15:29:06 +0000145static SHARED_POOL: OnceBox<LockedFrameAllocator<32>> = OnceBox::new();
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000146static SHARED_MEMORY: SpinMutex<Option<MemorySharer>> = SpinMutex::new(None);
147
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000148impl MemoryTracker {
149 const CAPACITY: usize = 5;
Andrew Walbran19690632022-12-07 16:41:30 +0000150 const MMIO_CAPACITY: usize = 5;
Pierre-Clément Tosi164a6f52023-04-18 19:29:11 +0100151 const PVMFW_RANGE: MemoryRange = (BASE_ADDR - SIZE_4MB)..BASE_ADDR;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000152
153 /// Create a new instance from an active page table, covering the maximum RAM size.
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +0000154 pub fn new(mut page_table: PageTable) -> Self {
Jakob Vukalovic4c1edbe2023-04-17 19:10:57 +0100155 // Activate dirty state management first, otherwise we may get permission faults immediately
156 // after activating the new page table. This has no effect before the new page table is
157 // activated because none of the entries in the initial idmap have the DBM flag.
Alice Wang4dd20932023-05-26 13:47:16 +0000158 set_dbm_enabled(true);
Jakob Vukalovic4c1edbe2023-04-17 19:10:57 +0100159
160 debug!("Activating dynamic page table...");
161 // SAFETY - page_table duplicates the static mappings for everything that the Rust code is
162 // aware of so activating it shouldn't have any visible effect.
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +0000163 unsafe { page_table.activate() }
Jakob Vukalovic4c1edbe2023-04-17 19:10:57 +0100164 debug!("... Success!");
165
Andrew Walbran19690632022-12-07 16:41:30 +0000166 Self {
Jiyong Park0ee65392023-03-27 20:52:45 +0900167 total: BASE_ADDR..MAX_ADDR,
Andrew Walbran19690632022-12-07 16:41:30 +0000168 page_table,
169 regions: ArrayVec::new(),
170 mmio_regions: ArrayVec::new(),
171 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000172 }
173
174 /// Resize the total RAM size.
175 ///
176 /// This function fails if it contains regions that are not included within the new size.
177 pub fn shrink(&mut self, range: &MemoryRange) -> Result<()> {
178 if range.start != self.total.start {
179 return Err(MemoryTrackerError::DifferentBaseAddress);
180 }
181 if self.total.end < range.end {
182 return Err(MemoryTrackerError::SizeTooLarge);
183 }
Alice Wang81e8f142023-06-06 12:47:14 +0000184 if !self.regions.iter().all(|r| r.range.is_within(range)) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000185 return Err(MemoryTrackerError::SizeTooSmall);
186 }
187
188 self.total = range.clone();
189 Ok(())
190 }
191
192 /// Allocate the address range for a const slice; returns None if failed.
193 pub fn alloc_range(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
Andrew Walbranda65ab12022-12-07 15:10:13 +0000194 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadOnly };
195 self.check(&region)?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000196 self.page_table.map_rodata(range).map_err(|e| {
197 error!("Error during range allocation: {e}");
198 MemoryTrackerError::FailedToMap
199 })?;
Andrew Walbranda65ab12022-12-07 15:10:13 +0000200 self.add(region)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000201 }
202
203 /// Allocate the address range for a mutable slice; returns None if failed.
204 pub fn alloc_range_mut(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
Andrew Walbranda65ab12022-12-07 15:10:13 +0000205 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadWrite };
206 self.check(&region)?;
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +0000207 self.page_table.map_data_dbm(range).map_err(|e| {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000208 error!("Error during mutable range allocation: {e}");
209 MemoryTrackerError::FailedToMap
210 })?;
Andrew Walbranda65ab12022-12-07 15:10:13 +0000211 self.add(region)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000212 }
213
214 /// Allocate the address range for a const slice; returns None if failed.
215 pub fn alloc(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
216 self.alloc_range(&(base..(base + size.get())))
217 }
218
219 /// Allocate the address range for a mutable slice; returns None if failed.
220 pub fn alloc_mut(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
221 self.alloc_range_mut(&(base..(base + size.get())))
222 }
223
Andrew Walbran19690632022-12-07 16:41:30 +0000224 /// Checks that the given range of addresses is within the MMIO region, and then maps it
225 /// appropriately.
226 pub fn map_mmio_range(&mut self, range: MemoryRange) -> Result<()> {
227 // MMIO space is below the main memory region.
Alice Wang81e8f142023-06-06 12:47:14 +0000228 if range.end > self.total.start || range.overlaps(&Self::PVMFW_RANGE) {
Andrew Walbran19690632022-12-07 16:41:30 +0000229 return Err(MemoryTrackerError::OutOfRange);
230 }
Alice Wang81e8f142023-06-06 12:47:14 +0000231 if self.mmio_regions.iter().any(|r| range.overlaps(r)) {
Andrew Walbran19690632022-12-07 16:41:30 +0000232 return Err(MemoryTrackerError::Overlaps);
233 }
234 if self.mmio_regions.len() == self.mmio_regions.capacity() {
235 return Err(MemoryTrackerError::Full);
236 }
237
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100238 self.page_table.map_device_lazy(&range).map_err(|e| {
Andrew Walbran19690632022-12-07 16:41:30 +0000239 error!("Error during MMIO device mapping: {e}");
240 MemoryTrackerError::FailedToMap
241 })?;
242
Andrew Walbran19690632022-12-07 16:41:30 +0000243 if self.mmio_regions.try_push(range).is_some() {
244 return Err(MemoryTrackerError::Full);
245 }
246
247 Ok(())
248 }
249
Andrew Walbranda65ab12022-12-07 15:10:13 +0000250 /// Checks that the given region is within the range of the `MemoryTracker` and doesn't overlap
251 /// with any other previously allocated regions, and that the regions ArrayVec has capacity to
252 /// add it.
253 fn check(&self, region: &MemoryRegion) -> Result<()> {
Alice Wang81e8f142023-06-06 12:47:14 +0000254 if !region.range.is_within(&self.total) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000255 return Err(MemoryTrackerError::OutOfRange);
256 }
Alice Wang81e8f142023-06-06 12:47:14 +0000257 if self.regions.iter().any(|r| region.range.overlaps(&r.range)) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000258 return Err(MemoryTrackerError::Overlaps);
259 }
Andrew Walbranda65ab12022-12-07 15:10:13 +0000260 if self.regions.len() == self.regions.capacity() {
261 return Err(MemoryTrackerError::Full);
262 }
263 Ok(())
264 }
265
266 fn add(&mut self, region: MemoryRegion) -> Result<MemoryRange> {
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000267 if self.regions.try_push(region).is_some() {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000268 return Err(MemoryTrackerError::Full);
269 }
270
Alice Wang81e8f142023-06-06 12:47:14 +0000271 Ok(self.regions.last().unwrap().range.clone())
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000272 }
Andrew Walbran19690632022-12-07 16:41:30 +0000273
274 /// Unmaps all tracked MMIO regions from the MMIO guard.
275 ///
276 /// Note that they are not unmapped from the page table.
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100277 pub fn mmio_unmap_all(&mut self) -> Result<()> {
278 for range in &self.mmio_regions {
279 self.page_table
280 .modify_range(range, &mmio_guard_unmap_page)
281 .map_err(|_| MemoryTrackerError::FailedToUnmap)?;
Andrew Walbran19690632022-12-07 16:41:30 +0000282 }
Andrew Walbran19690632022-12-07 16:41:30 +0000283 Ok(())
284 }
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700285
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000286 /// Initialize the shared heap to dynamically share memory from the global allocator.
287 pub fn init_dynamic_shared_pool(&mut self) -> Result<()> {
Alice Wangf47b2342023-06-02 11:51:57 +0000288 const INIT_CAP: usize = 10;
289
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000290 let granule = get_hypervisor().memory_protection_granule()?;
Alice Wangf47b2342023-06-02 11:51:57 +0000291 let previous = SHARED_MEMORY.lock().replace(MemorySharer::new(granule, INIT_CAP));
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000292 if previous.is_some() {
293 return Err(MemoryTrackerError::SharedMemorySetFailure);
294 }
295
296 SHARED_POOL
Andrew Walbran87933f32023-05-09 15:29:06 +0000297 .set(Box::new(LockedFrameAllocator::new()))
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000298 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
299
300 Ok(())
301 }
302
303 /// Initialize the shared heap from a static region of memory.
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700304 ///
305 /// Some hypervisors such as Gunyah do not support a MemShare API for guest
306 /// to share its memory with host. Instead they allow host to designate part
307 /// of guest memory as "shared" ahead of guest starting its execution. The
308 /// shared memory region is indicated in swiotlb node. On such platforms use
309 /// a separate heap to allocate buffers that can be shared with host.
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000310 pub fn init_static_shared_pool(&mut self, range: Range<usize>) -> Result<()> {
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700311 let size = NonZeroUsize::new(range.len()).unwrap();
312 let range = self.alloc_mut(range.start, size)?;
Andrew Walbran87933f32023-05-09 15:29:06 +0000313 let shared_pool = LockedFrameAllocator::<32>::new();
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700314
Andrew Walbran87933f32023-05-09 15:29:06 +0000315 shared_pool.lock().insert(range);
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700316
317 SHARED_POOL
318 .set(Box::new(shared_pool))
319 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
320
321 Ok(())
322 }
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000323
324 /// Unshares any memory that may have been shared.
325 pub fn unshare_all_memory(&mut self) {
326 drop(SHARED_MEMORY.lock().take());
327 }
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100328
329 /// Handles translation fault for blocks flagged for lazy MMIO mapping by enabling the page
330 /// table entry and MMIO guard mapping the block. Breaks apart a block entry if required.
331 pub fn handle_mmio_fault(&mut self, addr: usize) -> Result<()> {
332 let page_range = page_4kb_of(addr)..page_4kb_of(addr) + PVMFW_PAGE_SIZE;
333 self.page_table
334 .modify_range(&page_range, &verify_lazy_mapped_block)
335 .map_err(|_| MemoryTrackerError::InvalidPte)?;
336 get_hypervisor().mmio_guard_map(page_range.start)?;
337 // Maps a single device page, breaking up block mappings if necessary.
338 self.page_table.map_device(&page_range).map_err(|_| MemoryTrackerError::FailedToMap)
339 }
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100340
341 /// Flush all memory regions marked as writable-dirty.
342 fn flush_dirty_pages(&mut self) -> Result<()> {
343 // Collect memory ranges for which dirty state is tracked.
344 let writable_regions =
345 self.regions.iter().filter(|r| r.mem_type == MemoryType::ReadWrite).map(|r| &r.range);
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +0000346 let payload_range = appended_payload_range();
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100347 // Execute a barrier instruction to ensure all hardware updates to the page table have been
348 // observed before reading PTE flags to determine dirty state.
349 dsb!("ish");
350 // Now flush writable-dirty pages in those regions.
351 for range in writable_regions.chain(once(&payload_range)) {
352 self.page_table
353 .modify_range(range, &flush_dirty_range)
354 .map_err(|_| MemoryTrackerError::FlushRegionFailed)?;
355 }
356 Ok(())
357 }
358
359 /// Handles permission fault for read-only blocks by setting writable-dirty state.
360 /// In general, this should be called from the exception handler when hardware dirty
361 /// state management is disabled or unavailable.
362 pub fn handle_permission_fault(&mut self, addr: usize) -> Result<()> {
363 self.page_table
364 .modify_range(&(addr..addr + 1), &mark_dirty_block)
365 .map_err(|_| MemoryTrackerError::SetPteDirtyFailed)
366 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000367}
368
369impl Drop for MemoryTracker {
370 fn drop(&mut self) {
Alice Wang4dd20932023-05-26 13:47:16 +0000371 set_dbm_enabled(false);
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100372 self.flush_dirty_pages().unwrap();
Jakob Vukalovic4c1edbe2023-04-17 19:10:57 +0100373 self.unshare_all_memory();
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000374 }
375}
Andrew Walbran19690632022-12-07 16:41:30 +0000376
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +0000377/// Allocates a memory range of at least the given size and alignment that is shared with the host.
378/// Returns a pointer to the buffer.
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000379pub fn alloc_shared(layout: Layout) -> hyp::Result<NonNull<u8>> {
380 assert_ne!(layout.size(), 0);
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000381 let Some(buffer) = try_shared_alloc(layout) else {
Andrew Walbran848decf2022-12-15 14:39:38 +0000382 handle_alloc_error(layout);
383 };
384
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000385 trace!("Allocated shared buffer at {buffer:?} with {layout:?}");
Andrew Walbran848decf2022-12-15 14:39:38 +0000386 Ok(buffer)
387}
388
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000389fn try_shared_alloc(layout: Layout) -> Option<NonNull<u8>> {
390 let mut shared_pool = SHARED_POOL.get().unwrap().lock();
391
Andrew Walbran87933f32023-05-09 15:29:06 +0000392 if let Some(buffer) = shared_pool.alloc_aligned(layout) {
393 Some(NonNull::new(buffer as _).unwrap())
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000394 } else if let Some(shared_memory) = SHARED_MEMORY.lock().as_mut() {
395 shared_memory.refill(&mut shared_pool, layout);
Andrew Walbran87933f32023-05-09 15:29:06 +0000396 shared_pool.alloc_aligned(layout).map(|buffer| NonNull::new(buffer as _).unwrap())
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000397 } else {
398 None
399 }
400}
401
Andrew Walbran848decf2022-12-15 14:39:38 +0000402/// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`.
403///
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +0000404/// The layout passed in must be the same layout passed to the original `alloc_shared` call.
Andrew Walbran848decf2022-12-15 14:39:38 +0000405///
406/// # Safety
407///
Andrew Walbran2b0c7fb2023-05-09 12:16:20 +0000408/// The memory must have been allocated by `alloc_shared` with the same layout, and not yet
Andrew Walbran848decf2022-12-15 14:39:38 +0000409/// deallocated.
Pierre-Clément Tosi2d5bc582023-05-03 11:23:11 +0000410pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, layout: Layout) -> hyp::Result<()> {
Andrew Walbran87933f32023-05-09 15:29:06 +0000411 SHARED_POOL.get().unwrap().lock().dealloc_aligned(vaddr.as_ptr() as usize, layout);
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700412
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000413 trace!("Deallocated shared buffer at {vaddr:?} with {layout:?}");
Andrew Walbran848decf2022-12-15 14:39:38 +0000414 Ok(())
415}
416
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100417/// Checks whether block flags indicate it should be MMIO guard mapped.
418fn verify_lazy_mapped_block(
419 _range: &VaRange,
420 desc: &mut Descriptor,
421 level: usize,
422) -> result::Result<(), ()> {
423 let flags = desc.flags().expect("Unsupported PTE flags set");
424 if !is_leaf_pte(&flags, level) {
425 return Ok(()); // Skip table PTEs as they aren't tagged with MMIO_LAZY_MAP_FLAG.
426 }
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +0000427 if flags.contains(MMIO_LAZY_MAP_FLAG) && !flags.contains(Attributes::VALID) {
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100428 Ok(())
429 } else {
430 Err(())
431 }
432}
433
434/// MMIO guard unmaps page
435fn mmio_guard_unmap_page(
436 va_range: &VaRange,
437 desc: &mut Descriptor,
438 level: usize,
439) -> result::Result<(), ()> {
440 let flags = desc.flags().expect("Unsupported PTE flags set");
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100441 if !is_leaf_pte(&flags, level) {
442 return Ok(());
443 }
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100444 // This function will be called on an address range that corresponds to a device. Only if a
445 // page has been accessed (written to or read from), will it contain the VALID flag and be MMIO
446 // guard mapped. Therefore, we can skip unmapping invalid pages, they were never MMIO guard
447 // mapped anyway.
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100448 if flags.contains(Attributes::VALID) {
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100449 assert!(
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +0000450 flags.contains(MMIO_LAZY_MAP_FLAG),
Jakob Vukalovicb99905d2023-04-20 15:46:02 +0100451 "Attempting MMIO guard unmap for non-device pages"
452 );
453 assert_eq!(
454 va_range.len(),
455 PVMFW_PAGE_SIZE,
456 "Failed to break down block mapping before MMIO guard mapping"
457 );
458 let page_base = va_range.start().0;
459 assert_eq!(page_base % PVMFW_PAGE_SIZE, 0);
460 // Since mmio_guard_map takes IPAs, if pvmfw moves non-ID address mapping, page_base
461 // should be converted to IPA. However, since 0x0 is a valid MMIO address, we don't use
462 // virt_to_phys here, and just pass page_base instead.
463 get_hypervisor().mmio_guard_unmap(page_base).map_err(|e| {
464 error!("Error MMIO guard unmapping: {e}");
465 })?;
466 }
467 Ok(())
468}
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100469
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100470/// Clears read-only flag on a PTE, making it writable-dirty. Used when dirty state is managed
471/// in software to handle permission faults on read-only descriptors.
472fn mark_dirty_block(
473 va_range: &VaRange,
474 desc: &mut Descriptor,
475 level: usize,
476) -> result::Result<(), ()> {
477 let flags = desc.flags().ok_or(())?;
478 if !is_leaf_pte(&flags, level) {
479 return Ok(());
480 }
481 if flags.contains(Attributes::DBM) {
482 assert!(flags.contains(Attributes::READ_ONLY), "unexpected PTE writable state");
483 desc.modify_flags(Attributes::empty(), Attributes::READ_ONLY);
484 // Updating the read-only bit of a PTE requires TLB invalidation.
485 // A TLB maintenance instruction is only guaranteed to be complete after a DSB instruction.
486 // An ISB instruction is required to ensure the effects of completed TLB maintenance
487 // instructions are visible to instructions fetched afterwards.
488 // See ARM ARM E2.3.10, and G5.9.
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +0000489 tlbi!("vale1", PT_ASID, va_range.start().0);
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100490 dsb!("ish");
491 isb!();
492 Ok(())
493 } else {
494 Err(())
495 }
496}
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +0000497
498/// Returns memory range reserved for the appended payload.
499pub fn appended_payload_range() -> Range<usize> {
Alice Wangeacb7382023-06-05 12:53:54 +0000500 let start = align_up(layout::binary_end(), SIZE_4KB).unwrap();
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +0000501 // pvmfw is contained in a 2MiB region so the payload can't be larger than the 2MiB alignment.
Alice Wangeacb7382023-06-05 12:53:54 +0000502 let end = align_up(start, SIZE_2MB).unwrap();
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +0000503 start..end
504}
505
506/// Region allocated for the stack.
507pub fn stack_range() -> Range<usize> {
508 const STACK_PAGES: usize = 8;
509
510 layout::stack_range(STACK_PAGES * PVMFW_PAGE_SIZE)
511}
512
513pub fn init_page_table() -> result::Result<PageTable, MapError> {
514 let mut page_table: PageTable = IdMap::new(PT_ASID, PT_ROOT_LEVEL).into();
515
516 // Stack and scratch ranges are explicitly zeroed and flushed before jumping to payload,
517 // so dirty state management can be omitted.
518 page_table.map_data(&layout::scratch_range())?;
519 page_table.map_data(&stack_range())?;
520 page_table.map_code(&layout::text_range())?;
521 page_table.map_rodata(&layout::rodata_range())?;
522 page_table.map_data_dbm(&appended_payload_range())?;
Alice Wang807fa592023-06-02 09:54:43 +0000523 if let Err(e) = page_table.map_device(&layout::console_uart_range()) {
524 error!("Failed to remap the UART as a dynamic page table entry: {e}");
525 return Err(e);
526 }
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +0000527 Ok(page_table)
528}