blob: 61cbeb022e6e0cdd87e38e3219e74ad3d66fc09a [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.
Alice Wangb6d2c642023-06-13 13:07:06 +0000223 pub fn init_dynamic_shared_pool(&mut self, granule: usize) -> Result<()> {
Alice Wang93ee98a2023-06-08 08:20:39 +0000224 const INIT_CAP: usize = 10;
225
Alice Wang93ee98a2023-06-08 08:20:39 +0000226 let previous = SHARED_MEMORY.lock().replace(MemorySharer::new(granule, INIT_CAP));
227 if previous.is_some() {
228 return Err(MemoryTrackerError::SharedMemorySetFailure);
229 }
230
231 SHARED_POOL
232 .set(Box::new(LockedFrameAllocator::new()))
233 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
234
235 Ok(())
236 }
237
238 /// Initialize the shared heap from a static region of memory.
239 ///
240 /// Some hypervisors such as Gunyah do not support a MemShare API for guest
241 /// to share its memory with host. Instead they allow host to designate part
242 /// of guest memory as "shared" ahead of guest starting its execution. The
243 /// shared memory region is indicated in swiotlb node. On such platforms use
244 /// a separate heap to allocate buffers that can be shared with host.
245 pub fn init_static_shared_pool(&mut self, range: Range<usize>) -> Result<()> {
246 let size = NonZeroUsize::new(range.len()).unwrap();
247 let range = self.alloc_mut(range.start, size)?;
248 let shared_pool = LockedFrameAllocator::<32>::new();
249
250 shared_pool.lock().insert(range);
251
252 SHARED_POOL
253 .set(Box::new(shared_pool))
254 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
255
256 Ok(())
257 }
258
259 /// Unshares any memory that may have been shared.
260 pub fn unshare_all_memory(&mut self) {
261 drop(SHARED_MEMORY.lock().take());
262 }
263
264 /// Handles translation fault for blocks flagged for lazy MMIO mapping by enabling the page
265 /// table entry and MMIO guard mapping the block. Breaks apart a block entry if required.
266 pub fn handle_mmio_fault(&mut self, addr: usize) -> Result<()> {
267 let page_range = page_4kb_of(addr)..page_4kb_of(addr) + MMIO_GUARD_GRANULE_SIZE;
268 self.page_table
269 .modify_range(&page_range, &verify_lazy_mapped_block)
270 .map_err(|_| MemoryTrackerError::InvalidPte)?;
271 get_hypervisor().mmio_guard_map(page_range.start)?;
272 // Maps a single device page, breaking up block mappings if necessary.
273 self.page_table.map_device(&page_range).map_err(|_| MemoryTrackerError::FailedToMap)
274 }
275
276 /// Flush all memory regions marked as writable-dirty.
277 fn flush_dirty_pages(&mut self) -> Result<()> {
278 // Collect memory ranges for which dirty state is tracked.
279 let writable_regions =
280 self.regions.iter().filter(|r| r.mem_type == MemoryType::ReadWrite).map(|r| &r.range);
281 // Execute a barrier instruction to ensure all hardware updates to the page table have been
282 // observed before reading PTE flags to determine dirty state.
283 dsb!("ish");
284 // Now flush writable-dirty pages in those regions.
Alice Wang5bb79502023-06-12 09:25:07 +0000285 for range in writable_regions.chain(self.payload_range.as_ref().into_iter()) {
Alice Wang93ee98a2023-06-08 08:20:39 +0000286 self.page_table
287 .modify_range(range, &flush_dirty_range)
288 .map_err(|_| MemoryTrackerError::FlushRegionFailed)?;
289 }
290 Ok(())
291 }
292
293 /// Handles permission fault for read-only blocks by setting writable-dirty state.
294 /// In general, this should be called from the exception handler when hardware dirty
295 /// state management is disabled or unavailable.
296 pub fn handle_permission_fault(&mut self, addr: usize) -> Result<()> {
297 self.page_table
298 .modify_range(&(addr..addr + 1), &mark_dirty_block)
299 .map_err(|_| MemoryTrackerError::SetPteDirtyFailed)
300 }
301}
302
303impl Drop for MemoryTracker {
304 fn drop(&mut self) {
305 set_dbm_enabled(false);
306 self.flush_dirty_pages().unwrap();
307 self.unshare_all_memory();
308 }
309}
310
311/// Allocates a memory range of at least the given size and alignment that is shared with the host.
312/// Returns a pointer to the buffer.
313pub fn alloc_shared(layout: Layout) -> hyp::Result<NonNull<u8>> {
314 assert_ne!(layout.size(), 0);
315 let Some(buffer) = try_shared_alloc(layout) else {
316 handle_alloc_error(layout);
317 };
318
319 trace!("Allocated shared buffer at {buffer:?} with {layout:?}");
320 Ok(buffer)
321}
322
323fn try_shared_alloc(layout: Layout) -> Option<NonNull<u8>> {
324 let mut shared_pool = SHARED_POOL.get().unwrap().lock();
325
326 if let Some(buffer) = shared_pool.alloc_aligned(layout) {
327 Some(NonNull::new(buffer as _).unwrap())
328 } else if let Some(shared_memory) = SHARED_MEMORY.lock().as_mut() {
329 shared_memory.refill(&mut shared_pool, layout);
330 shared_pool.alloc_aligned(layout).map(|buffer| NonNull::new(buffer as _).unwrap())
331 } else {
332 None
333 }
334}
335
336/// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`.
337///
338/// The layout passed in must be the same layout passed to the original `alloc_shared` call.
339///
340/// # Safety
341///
342/// The memory must have been allocated by `alloc_shared` with the same layout, and not yet
343/// deallocated.
344pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, layout: Layout) -> hyp::Result<()> {
345 SHARED_POOL.get().unwrap().lock().dealloc_aligned(vaddr.as_ptr() as usize, layout);
346
347 trace!("Deallocated shared buffer at {vaddr:?} with {layout:?}");
348 Ok(())
349}
Alice Wangf47b2342023-06-02 11:51:57 +0000350
351/// Allocates memory on the heap and shares it with the host.
352///
353/// Unshares all pages when dropped.
Alice Wang93ee98a2023-06-08 08:20:39 +0000354struct MemorySharer {
Alice Wangf47b2342023-06-02 11:51:57 +0000355 granule: usize,
356 shared_regions: Vec<(usize, Layout)>,
357}
358
359impl MemorySharer {
360 /// Constructs a new `MemorySharer` instance with the specified granule size and capacity.
361 /// `granule` must be a power of 2.
Alice Wang93ee98a2023-06-08 08:20:39 +0000362 fn new(granule: usize, capacity: usize) -> Self {
Alice Wangf47b2342023-06-02 11:51:57 +0000363 assert!(granule.is_power_of_two());
364 Self { granule, shared_regions: Vec::with_capacity(capacity) }
365 }
366
Alice Wang93ee98a2023-06-08 08:20:39 +0000367 /// Gets from the global allocator a granule-aligned region that suits `hint` and share it.
368 fn refill(&mut self, pool: &mut FrameAllocator<32>, hint: Layout) {
Alice Wangf47b2342023-06-02 11:51:57 +0000369 let layout = hint.align_to(self.granule).unwrap().pad_to_align();
370 assert_ne!(layout.size(), 0);
371 // SAFETY - layout has non-zero size.
372 let Some(shared) = NonNull::new(unsafe { alloc_zeroed(layout) }) else {
373 handle_alloc_error(layout);
374 };
375
376 let base = shared.as_ptr() as usize;
377 let end = base.checked_add(layout.size()).unwrap();
378 trace!("Sharing memory region {:#x?}", base..end);
379 for vaddr in (base..end).step_by(self.granule) {
380 let vaddr = NonNull::new(vaddr as *mut _).unwrap();
381 get_hypervisor().mem_share(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
382 }
383 self.shared_regions.push((base, layout));
384
385 pool.add_frame(base, end);
386 }
387}
388
389impl Drop for MemorySharer {
390 fn drop(&mut self) {
391 while let Some((base, layout)) = self.shared_regions.pop() {
392 let end = base.checked_add(layout.size()).unwrap();
393 trace!("Unsharing memory region {:#x?}", base..end);
394 for vaddr in (base..end).step_by(self.granule) {
395 let vaddr = NonNull::new(vaddr as *mut _).unwrap();
396 get_hypervisor().mem_unshare(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
397 }
398
399 // SAFETY - The region was obtained from alloc_zeroed() with the recorded layout.
400 unsafe { dealloc(base as *mut _, layout) };
401 }
402 }
403}
Alice Wangb73a81b2023-06-07 13:05:09 +0000404
405/// Checks whether block flags indicate it should be MMIO guard mapped.
Alice Wang93ee98a2023-06-08 08:20:39 +0000406fn verify_lazy_mapped_block(
Alice Wangb73a81b2023-06-07 13:05:09 +0000407 _range: &VaRange,
408 desc: &mut Descriptor,
409 level: usize,
410) -> result::Result<(), ()> {
411 let flags = desc.flags().expect("Unsupported PTE flags set");
412 if !is_leaf_pte(&flags, level) {
413 return Ok(()); // Skip table PTEs as they aren't tagged with MMIO_LAZY_MAP_FLAG.
414 }
415 if flags.contains(MMIO_LAZY_MAP_FLAG) && !flags.contains(Attributes::VALID) {
416 Ok(())
417 } else {
418 Err(())
419 }
420}
421
422/// MMIO guard unmaps page
Alice Wang93ee98a2023-06-08 08:20:39 +0000423fn mmio_guard_unmap_page(
Alice Wangb73a81b2023-06-07 13:05:09 +0000424 va_range: &VaRange,
425 desc: &mut Descriptor,
426 level: usize,
427) -> result::Result<(), ()> {
428 let flags = desc.flags().expect("Unsupported PTE flags set");
429 if !is_leaf_pte(&flags, level) {
430 return Ok(());
431 }
432 // This function will be called on an address range that corresponds to a device. Only if a
433 // page has been accessed (written to or read from), will it contain the VALID flag and be MMIO
434 // guard mapped. Therefore, we can skip unmapping invalid pages, they were never MMIO guard
435 // mapped anyway.
436 if flags.contains(Attributes::VALID) {
437 assert!(
438 flags.contains(MMIO_LAZY_MAP_FLAG),
439 "Attempting MMIO guard unmap for non-device pages"
440 );
441 assert_eq!(
442 va_range.len(),
Pierre-Clément Tosi92154762023-06-07 15:32:15 +0000443 MMIO_GUARD_GRANULE_SIZE,
Alice Wangb73a81b2023-06-07 13:05:09 +0000444 "Failed to break down block mapping before MMIO guard mapping"
445 );
446 let page_base = va_range.start().0;
Pierre-Clément Tosi92154762023-06-07 15:32:15 +0000447 assert_eq!(page_base % MMIO_GUARD_GRANULE_SIZE, 0);
Alice Wangb73a81b2023-06-07 13:05:09 +0000448 // Since mmio_guard_map takes IPAs, if pvmfw moves non-ID address mapping, page_base
449 // should be converted to IPA. However, since 0x0 is a valid MMIO address, we don't use
450 // virt_to_phys here, and just pass page_base instead.
451 get_hypervisor().mmio_guard_unmap(page_base).map_err(|e| {
452 error!("Error MMIO guard unmapping: {e}");
453 })?;
454 }
455 Ok(())
456}