blob: 5d60c85f75270eeb91d9a86146e41b8cd28ec63a [file] [log] [blame]
Alice Wangf47b2342023-06-02 11:51:57 +00001// Copyright 2023, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Shared memory management.
16
Alice Wang93ee98a2023-06-08 08:20:39 +000017use super::dbm::{flush_dirty_range, mark_dirty_block, set_dbm_enabled};
18use super::error::MemoryTrackerError;
19use super::page_table::{is_leaf_pte, PageTable, MMIO_LAZY_MAP_FLAG};
20use super::util::{page_4kb_of, virt_to_phys};
21use crate::dsb;
22use crate::util::RangeExt as _;
Alice Wangb73a81b2023-06-07 13:05:09 +000023use aarch64_paging::paging::{Attributes, Descriptor, MemoryRegion as VaRange};
Alice Wangf47b2342023-06-02 11:51:57 +000024use alloc::alloc::{alloc_zeroed, dealloc, handle_alloc_error};
Alice Wang93ee98a2023-06-08 08:20:39 +000025use alloc::boxed::Box;
Alice Wangf47b2342023-06-02 11:51:57 +000026use alloc::vec::Vec;
Alice Wang93ee98a2023-06-08 08:20:39 +000027use buddy_system_allocator::{FrameAllocator, LockedFrameAllocator};
Alice Wangf47b2342023-06-02 11:51:57 +000028use core::alloc::Layout;
Alice Wang93ee98a2023-06-08 08:20:39 +000029use core::num::NonZeroUsize;
30use core::ops::Range;
Alice Wangf47b2342023-06-02 11:51:57 +000031use core::ptr::NonNull;
Alice Wangb73a81b2023-06-07 13:05:09 +000032use core::result;
Pierre-Clément Tosi92154762023-06-07 15:32:15 +000033use hyp::{get_hypervisor, MMIO_GUARD_GRANULE_SIZE};
Alice Wang93ee98a2023-06-08 08:20:39 +000034use log::{debug, error, trace};
35use once_cell::race::OnceBox;
36use spin::mutex::SpinMutex;
37use tinyvec::ArrayVec;
38
39/// A global static variable representing the system memory tracker, protected by a spin mutex.
40pub static MEMORY: SpinMutex<Option<MemoryTracker>> = SpinMutex::new(None);
41
42static SHARED_POOL: OnceBox<LockedFrameAllocator<32>> = OnceBox::new();
43static SHARED_MEMORY: SpinMutex<Option<MemorySharer>> = SpinMutex::new(None);
44
45/// Memory range.
46pub type MemoryRange = Range<usize>;
47type Result<T> = result::Result<T, MemoryTrackerError>;
48
49#[derive(Clone, Copy, Debug, Default, PartialEq)]
50enum MemoryType {
51 #[default]
52 ReadOnly,
53 ReadWrite,
54}
55
56#[derive(Clone, Debug, Default)]
57struct MemoryRegion {
58 range: MemoryRange,
59 mem_type: MemoryType,
60}
61
62/// Tracks non-overlapping slices of main memory.
63pub struct MemoryTracker {
64 total: MemoryRange,
65 page_table: PageTable,
66 regions: ArrayVec<[MemoryRegion; MemoryTracker::CAPACITY]>,
67 mmio_regions: ArrayVec<[MemoryRange; MemoryTracker::MMIO_CAPACITY]>,
68 mmio_range: MemoryRange,
Alice Wang5bb79502023-06-12 09:25:07 +000069 payload_range: Option<MemoryRange>,
Alice Wang93ee98a2023-06-08 08:20:39 +000070}
71
72unsafe impl Send for MemoryTracker {}
73
74impl MemoryTracker {
75 const CAPACITY: usize = 5;
76 const MMIO_CAPACITY: usize = 5;
77
78 /// Creates a new instance from an active page table, covering the maximum RAM size.
79 pub fn new(
80 mut page_table: PageTable,
81 total: MemoryRange,
82 mmio_range: MemoryRange,
Alice Wang5bb79502023-06-12 09:25:07 +000083 payload_range: Option<MemoryRange>,
Alice Wang93ee98a2023-06-08 08:20:39 +000084 ) -> Self {
85 assert!(
86 !total.overlaps(&mmio_range),
87 "MMIO space should not overlap with the main memory region."
88 );
89
90 // Activate dirty state management first, otherwise we may get permission faults immediately
91 // after activating the new page table. This has no effect before the new page table is
92 // activated because none of the entries in the initial idmap have the DBM flag.
93 set_dbm_enabled(true);
94
95 debug!("Activating dynamic page table...");
96 // SAFETY - page_table duplicates the static mappings for everything that the Rust code is
97 // aware of so activating it shouldn't have any visible effect.
98 unsafe { page_table.activate() }
99 debug!("... Success!");
100
101 Self {
102 total,
103 page_table,
104 regions: ArrayVec::new(),
105 mmio_regions: ArrayVec::new(),
106 mmio_range,
107 payload_range,
108 }
109 }
110
111 /// Resize the total RAM size.
112 ///
113 /// This function fails if it contains regions that are not included within the new size.
114 pub fn shrink(&mut self, range: &MemoryRange) -> Result<()> {
115 if range.start != self.total.start {
116 return Err(MemoryTrackerError::DifferentBaseAddress);
117 }
118 if self.total.end < range.end {
119 return Err(MemoryTrackerError::SizeTooLarge);
120 }
121 if !self.regions.iter().all(|r| r.range.is_within(range)) {
122 return Err(MemoryTrackerError::SizeTooSmall);
123 }
124
125 self.total = range.clone();
126 Ok(())
127 }
128
129 /// Allocate the address range for a const slice; returns None if failed.
130 pub fn alloc_range(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
131 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadOnly };
132 self.check(&region)?;
133 self.page_table.map_rodata(range).map_err(|e| {
134 error!("Error during range allocation: {e}");
135 MemoryTrackerError::FailedToMap
136 })?;
137 self.add(region)
138 }
139
140 /// Allocate the address range for a mutable slice; returns None if failed.
141 pub fn alloc_range_mut(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
142 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadWrite };
143 self.check(&region)?;
144 self.page_table.map_data_dbm(range).map_err(|e| {
145 error!("Error during mutable range allocation: {e}");
146 MemoryTrackerError::FailedToMap
147 })?;
148 self.add(region)
149 }
150
151 /// Allocate the address range for a const slice; returns None if failed.
152 pub fn alloc(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
153 self.alloc_range(&(base..(base + size.get())))
154 }
155
156 /// Allocate the address range for a mutable slice; returns None if failed.
157 pub fn alloc_mut(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
158 self.alloc_range_mut(&(base..(base + size.get())))
159 }
160
161 /// Checks that the given range of addresses is within the MMIO region, and then maps it
162 /// appropriately.
163 pub fn map_mmio_range(&mut self, range: MemoryRange) -> Result<()> {
164 if !range.is_within(&self.mmio_range) {
165 return Err(MemoryTrackerError::OutOfRange);
166 }
167 if self.mmio_regions.iter().any(|r| range.overlaps(r)) {
168 return Err(MemoryTrackerError::Overlaps);
169 }
170 if self.mmio_regions.len() == self.mmio_regions.capacity() {
171 return Err(MemoryTrackerError::Full);
172 }
173
174 self.page_table.map_device_lazy(&range).map_err(|e| {
175 error!("Error during MMIO device mapping: {e}");
176 MemoryTrackerError::FailedToMap
177 })?;
178
179 if self.mmio_regions.try_push(range).is_some() {
180 return Err(MemoryTrackerError::Full);
181 }
182
183 Ok(())
184 }
185
186 /// Checks that the given region is within the range of the `MemoryTracker` and doesn't overlap
187 /// with any other previously allocated regions, and that the regions ArrayVec has capacity to
188 /// add it.
189 fn check(&self, region: &MemoryRegion) -> Result<()> {
190 if !region.range.is_within(&self.total) {
191 return Err(MemoryTrackerError::OutOfRange);
192 }
193 if self.regions.iter().any(|r| region.range.overlaps(&r.range)) {
194 return Err(MemoryTrackerError::Overlaps);
195 }
196 if self.regions.len() == self.regions.capacity() {
197 return Err(MemoryTrackerError::Full);
198 }
199 Ok(())
200 }
201
202 fn add(&mut self, region: MemoryRegion) -> Result<MemoryRange> {
203 if self.regions.try_push(region).is_some() {
204 return Err(MemoryTrackerError::Full);
205 }
206
207 Ok(self.regions.last().unwrap().range.clone())
208 }
209
210 /// Unmaps all tracked MMIO regions from the MMIO guard.
211 ///
212 /// Note that they are not unmapped from the page table.
213 pub fn mmio_unmap_all(&mut self) -> Result<()> {
214 for range in &self.mmio_regions {
215 self.page_table
216 .modify_range(range, &mmio_guard_unmap_page)
217 .map_err(|_| MemoryTrackerError::FailedToUnmap)?;
218 }
219 Ok(())
220 }
221
222 /// Initialize the shared heap to dynamically share memory from the global allocator.
223 pub fn init_dynamic_shared_pool(&mut self) -> Result<()> {
224 const INIT_CAP: usize = 10;
225
226 let granule = get_hypervisor().memory_protection_granule()?;
227 let previous = SHARED_MEMORY.lock().replace(MemorySharer::new(granule, INIT_CAP));
228 if previous.is_some() {
229 return Err(MemoryTrackerError::SharedMemorySetFailure);
230 }
231
232 SHARED_POOL
233 .set(Box::new(LockedFrameAllocator::new()))
234 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
235
236 Ok(())
237 }
238
239 /// Initialize the shared heap from a static region of memory.
240 ///
241 /// Some hypervisors such as Gunyah do not support a MemShare API for guest
242 /// to share its memory with host. Instead they allow host to designate part
243 /// of guest memory as "shared" ahead of guest starting its execution. The
244 /// shared memory region is indicated in swiotlb node. On such platforms use
245 /// a separate heap to allocate buffers that can be shared with host.
246 pub fn init_static_shared_pool(&mut self, range: Range<usize>) -> Result<()> {
247 let size = NonZeroUsize::new(range.len()).unwrap();
248 let range = self.alloc_mut(range.start, size)?;
249 let shared_pool = LockedFrameAllocator::<32>::new();
250
251 shared_pool.lock().insert(range);
252
253 SHARED_POOL
254 .set(Box::new(shared_pool))
255 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
256
257 Ok(())
258 }
259
260 /// Unshares any memory that may have been shared.
261 pub fn unshare_all_memory(&mut self) {
262 drop(SHARED_MEMORY.lock().take());
263 }
264
265 /// Handles translation fault for blocks flagged for lazy MMIO mapping by enabling the page
266 /// table entry and MMIO guard mapping the block. Breaks apart a block entry if required.
267 pub fn handle_mmio_fault(&mut self, addr: usize) -> Result<()> {
268 let page_range = page_4kb_of(addr)..page_4kb_of(addr) + MMIO_GUARD_GRANULE_SIZE;
269 self.page_table
270 .modify_range(&page_range, &verify_lazy_mapped_block)
271 .map_err(|_| MemoryTrackerError::InvalidPte)?;
272 get_hypervisor().mmio_guard_map(page_range.start)?;
273 // Maps a single device page, breaking up block mappings if necessary.
274 self.page_table.map_device(&page_range).map_err(|_| MemoryTrackerError::FailedToMap)
275 }
276
277 /// Flush all memory regions marked as writable-dirty.
278 fn flush_dirty_pages(&mut self) -> Result<()> {
279 // Collect memory ranges for which dirty state is tracked.
280 let writable_regions =
281 self.regions.iter().filter(|r| r.mem_type == MemoryType::ReadWrite).map(|r| &r.range);
282 // Execute a barrier instruction to ensure all hardware updates to the page table have been
283 // observed before reading PTE flags to determine dirty state.
284 dsb!("ish");
285 // Now flush writable-dirty pages in those regions.
Alice Wang5bb79502023-06-12 09:25:07 +0000286 for range in writable_regions.chain(self.payload_range.as_ref().into_iter()) {
Alice Wang93ee98a2023-06-08 08:20:39 +0000287 self.page_table
288 .modify_range(range, &flush_dirty_range)
289 .map_err(|_| MemoryTrackerError::FlushRegionFailed)?;
290 }
291 Ok(())
292 }
293
294 /// Handles permission fault for read-only blocks by setting writable-dirty state.
295 /// In general, this should be called from the exception handler when hardware dirty
296 /// state management is disabled or unavailable.
297 pub fn handle_permission_fault(&mut self, addr: usize) -> Result<()> {
298 self.page_table
299 .modify_range(&(addr..addr + 1), &mark_dirty_block)
300 .map_err(|_| MemoryTrackerError::SetPteDirtyFailed)
301 }
302}
303
304impl Drop for MemoryTracker {
305 fn drop(&mut self) {
306 set_dbm_enabled(false);
307 self.flush_dirty_pages().unwrap();
308 self.unshare_all_memory();
309 }
310}
311
312/// Allocates a memory range of at least the given size and alignment that is shared with the host.
313/// Returns a pointer to the buffer.
314pub fn alloc_shared(layout: Layout) -> hyp::Result<NonNull<u8>> {
315 assert_ne!(layout.size(), 0);
316 let Some(buffer) = try_shared_alloc(layout) else {
317 handle_alloc_error(layout);
318 };
319
320 trace!("Allocated shared buffer at {buffer:?} with {layout:?}");
321 Ok(buffer)
322}
323
324fn try_shared_alloc(layout: Layout) -> Option<NonNull<u8>> {
325 let mut shared_pool = SHARED_POOL.get().unwrap().lock();
326
327 if let Some(buffer) = shared_pool.alloc_aligned(layout) {
328 Some(NonNull::new(buffer as _).unwrap())
329 } else if let Some(shared_memory) = SHARED_MEMORY.lock().as_mut() {
330 shared_memory.refill(&mut shared_pool, layout);
331 shared_pool.alloc_aligned(layout).map(|buffer| NonNull::new(buffer as _).unwrap())
332 } else {
333 None
334 }
335}
336
337/// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`.
338///
339/// The layout passed in must be the same layout passed to the original `alloc_shared` call.
340///
341/// # Safety
342///
343/// The memory must have been allocated by `alloc_shared` with the same layout, and not yet
344/// deallocated.
345pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, layout: Layout) -> hyp::Result<()> {
346 SHARED_POOL.get().unwrap().lock().dealloc_aligned(vaddr.as_ptr() as usize, layout);
347
348 trace!("Deallocated shared buffer at {vaddr:?} with {layout:?}");
349 Ok(())
350}
Alice Wangf47b2342023-06-02 11:51:57 +0000351
352/// Allocates memory on the heap and shares it with the host.
353///
354/// Unshares all pages when dropped.
Alice Wang93ee98a2023-06-08 08:20:39 +0000355struct MemorySharer {
Alice Wangf47b2342023-06-02 11:51:57 +0000356 granule: usize,
357 shared_regions: Vec<(usize, Layout)>,
358}
359
360impl MemorySharer {
361 /// Constructs a new `MemorySharer` instance with the specified granule size and capacity.
362 /// `granule` must be a power of 2.
Alice Wang93ee98a2023-06-08 08:20:39 +0000363 fn new(granule: usize, capacity: usize) -> Self {
Alice Wangf47b2342023-06-02 11:51:57 +0000364 assert!(granule.is_power_of_two());
365 Self { granule, shared_regions: Vec::with_capacity(capacity) }
366 }
367
Alice Wang93ee98a2023-06-08 08:20:39 +0000368 /// Gets from the global allocator a granule-aligned region that suits `hint` and share it.
369 fn refill(&mut self, pool: &mut FrameAllocator<32>, hint: Layout) {
Alice Wangf47b2342023-06-02 11:51:57 +0000370 let layout = hint.align_to(self.granule).unwrap().pad_to_align();
371 assert_ne!(layout.size(), 0);
372 // SAFETY - layout has non-zero size.
373 let Some(shared) = NonNull::new(unsafe { alloc_zeroed(layout) }) else {
374 handle_alloc_error(layout);
375 };
376
377 let base = shared.as_ptr() as usize;
378 let end = base.checked_add(layout.size()).unwrap();
379 trace!("Sharing memory region {:#x?}", base..end);
380 for vaddr in (base..end).step_by(self.granule) {
381 let vaddr = NonNull::new(vaddr as *mut _).unwrap();
382 get_hypervisor().mem_share(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
383 }
384 self.shared_regions.push((base, layout));
385
386 pool.add_frame(base, end);
387 }
388}
389
390impl Drop for MemorySharer {
391 fn drop(&mut self) {
392 while let Some((base, layout)) = self.shared_regions.pop() {
393 let end = base.checked_add(layout.size()).unwrap();
394 trace!("Unsharing memory region {:#x?}", base..end);
395 for vaddr in (base..end).step_by(self.granule) {
396 let vaddr = NonNull::new(vaddr as *mut _).unwrap();
397 get_hypervisor().mem_unshare(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
398 }
399
400 // SAFETY - The region was obtained from alloc_zeroed() with the recorded layout.
401 unsafe { dealloc(base as *mut _, layout) };
402 }
403 }
404}
Alice Wangb73a81b2023-06-07 13:05:09 +0000405
406/// Checks whether block flags indicate it should be MMIO guard mapped.
Alice Wang93ee98a2023-06-08 08:20:39 +0000407fn verify_lazy_mapped_block(
Alice Wangb73a81b2023-06-07 13:05:09 +0000408 _range: &VaRange,
409 desc: &mut Descriptor,
410 level: usize,
411) -> result::Result<(), ()> {
412 let flags = desc.flags().expect("Unsupported PTE flags set");
413 if !is_leaf_pte(&flags, level) {
414 return Ok(()); // Skip table PTEs as they aren't tagged with MMIO_LAZY_MAP_FLAG.
415 }
416 if flags.contains(MMIO_LAZY_MAP_FLAG) && !flags.contains(Attributes::VALID) {
417 Ok(())
418 } else {
419 Err(())
420 }
421}
422
423/// MMIO guard unmaps page
Alice Wang93ee98a2023-06-08 08:20:39 +0000424fn mmio_guard_unmap_page(
Alice Wangb73a81b2023-06-07 13:05:09 +0000425 va_range: &VaRange,
426 desc: &mut Descriptor,
427 level: usize,
428) -> result::Result<(), ()> {
429 let flags = desc.flags().expect("Unsupported PTE flags set");
430 if !is_leaf_pte(&flags, level) {
431 return Ok(());
432 }
433 // This function will be called on an address range that corresponds to a device. Only if a
434 // page has been accessed (written to or read from), will it contain the VALID flag and be MMIO
435 // guard mapped. Therefore, we can skip unmapping invalid pages, they were never MMIO guard
436 // mapped anyway.
437 if flags.contains(Attributes::VALID) {
438 assert!(
439 flags.contains(MMIO_LAZY_MAP_FLAG),
440 "Attempting MMIO guard unmap for non-device pages"
441 );
442 assert_eq!(
443 va_range.len(),
Pierre-Clément Tosi92154762023-06-07 15:32:15 +0000444 MMIO_GUARD_GRANULE_SIZE,
Alice Wangb73a81b2023-06-07 13:05:09 +0000445 "Failed to break down block mapping before MMIO guard mapping"
446 );
447 let page_base = va_range.start().0;
Pierre-Clément Tosi92154762023-06-07 15:32:15 +0000448 assert_eq!(page_base % MMIO_GUARD_GRANULE_SIZE, 0);
Alice Wangb73a81b2023-06-07 13:05:09 +0000449 // Since mmio_guard_map takes IPAs, if pvmfw moves non-ID address mapping, page_base
450 // should be converted to IPA. However, since 0x0 is a valid MMIO address, we don't use
451 // virt_to_phys here, and just pass page_base instead.
452 get_hypervisor().mmio_guard_unmap(page_base).map_err(|e| {
453 error!("Error MMIO guard unmapping: {e}");
454 })?;
455 }
456 Ok(())
457}