1 // 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
17 #![deny(unsafe_op_in_unsafe_fn)]
18
19 use crate::helpers::{self, page_4kb_of, RangeExt, SIZE_4KB, SIZE_4MB};
20 use crate::mmu;
21 use alloc::alloc::alloc_zeroed;
22 use alloc::alloc::dealloc;
23 use alloc::alloc::handle_alloc_error;
24 use alloc::boxed::Box;
25 use alloc::vec::Vec;
26 use buddy_system_allocator::{FrameAllocator, LockedFrameAllocator};
27 use core::alloc::Layout;
28 use core::cmp::max;
29 use core::cmp::min;
30 use core::fmt;
31 use core::num::NonZeroUsize;
32 use core::ops::Range;
33 use core::ptr::NonNull;
34 use core::result;
35 use hyp::get_hypervisor;
36 use log::error;
37 use log::trace;
38 use once_cell::race::OnceBox;
39 use spin::mutex::SpinMutex;
40 use tinyvec::ArrayVec;
41
42 /// Base of the system's contiguous "main" memory.
43 pub const BASE_ADDR: usize = 0x8000_0000;
44 /// First address that can't be translated by a level 1 TTBR0_EL1.
45 pub const MAX_ADDR: usize = 1 << 40;
46
47 pub type MemoryRange = Range<usize>;
48
49 pub static MEMORY: SpinMutex<Option<MemoryTracker>> = SpinMutex::new(None);
50 unsafe impl Send for MemoryTracker {}
51
52 #[derive(Clone, Copy, Debug, Default)]
53 enum MemoryType {
54 #[default]
55 ReadOnly,
56 ReadWrite,
57 }
58
59 #[derive(Clone, Debug, Default)]
60 struct MemoryRegion {
61 range: MemoryRange,
62 mem_type: MemoryType,
63 }
64
65 impl MemoryRegion {
66 /// True if the instance overlaps with the passed range.
overlaps(&self, range: &MemoryRange) -> bool67 pub fn overlaps(&self, range: &MemoryRange) -> bool {
68 overlaps(&self.range, range)
69 }
70
71 /// True if the instance is fully contained within the passed range.
is_within(&self, range: &MemoryRange) -> bool72 pub fn is_within(&self, range: &MemoryRange) -> bool {
73 self.as_ref().is_within(range)
74 }
75 }
76
77 impl AsRef<MemoryRange> for MemoryRegion {
as_ref(&self) -> &MemoryRange78 fn as_ref(&self) -> &MemoryRange {
79 &self.range
80 }
81 }
82
83 /// Returns true if one range overlaps with the other at all.
overlaps<T: Copy + Ord>(a: &Range<T>, b: &Range<T>) -> bool84 fn overlaps<T: Copy + Ord>(a: &Range<T>, b: &Range<T>) -> bool {
85 max(a.start, b.start) < min(a.end, b.end)
86 }
87
88 /// Tracks non-overlapping slices of main memory.
89 pub struct MemoryTracker {
90 total: MemoryRange,
91 page_table: mmu::PageTable,
92 regions: ArrayVec<[MemoryRegion; MemoryTracker::CAPACITY]>,
93 mmio_regions: ArrayVec<[MemoryRange; MemoryTracker::MMIO_CAPACITY]>,
94 }
95
96 /// Errors for MemoryTracker operations.
97 #[derive(Debug, Clone)]
98 pub enum MemoryTrackerError {
99 /// Tried to modify the memory base address.
100 DifferentBaseAddress,
101 /// Tried to shrink to a larger memory size.
102 SizeTooLarge,
103 /// Tracked regions would not fit in memory size.
104 SizeTooSmall,
105 /// Reached limit number of tracked regions.
106 Full,
107 /// Region is out of the tracked memory address space.
108 OutOfRange,
109 /// New region overlaps with tracked regions.
110 Overlaps,
111 /// Region couldn't be mapped.
112 FailedToMap,
113 /// Error from the interaction with the hypervisor.
114 Hypervisor(hyp::Error),
115 /// Failure to set `SHARED_MEMORY`.
116 SharedMemorySetFailure,
117 /// Failure to set `SHARED_POOL`.
118 SharedPoolSetFailure,
119 }
120
121 impl fmt::Display for MemoryTrackerError {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result122 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
123 match self {
124 Self::DifferentBaseAddress => write!(f, "Received different base address"),
125 Self::SizeTooLarge => write!(f, "Tried to shrink to a larger memory size"),
126 Self::SizeTooSmall => write!(f, "Tracked regions would not fit in memory size"),
127 Self::Full => write!(f, "Reached limit number of tracked regions"),
128 Self::OutOfRange => write!(f, "Region is out of the tracked memory address space"),
129 Self::Overlaps => write!(f, "New region overlaps with tracked regions"),
130 Self::FailedToMap => write!(f, "Failed to map the new region"),
131 Self::Hypervisor(e) => e.fmt(f),
132 Self::SharedMemorySetFailure => write!(f, "Failed to set SHARED_MEMORY"),
133 Self::SharedPoolSetFailure => write!(f, "Failed to set SHARED_POOL"),
134 }
135 }
136 }
137
138 impl From<hyp::Error> for MemoryTrackerError {
from(e: hyp::Error) -> Self139 fn from(e: hyp::Error) -> Self {
140 Self::Hypervisor(e)
141 }
142 }
143
144 type Result<T> = result::Result<T, MemoryTrackerError>;
145
146 static SHARED_POOL: OnceBox<LockedFrameAllocator<32>> = OnceBox::new();
147 static SHARED_MEMORY: SpinMutex<Option<MemorySharer>> = SpinMutex::new(None);
148
149 /// Allocates memory on the heap and shares it with the host.
150 ///
151 /// Unshares all pages when dropped.
152 pub struct MemorySharer {
153 granule: usize,
154 shared_regions: Vec<(usize, Layout)>,
155 }
156
157 impl MemorySharer {
158 const INIT_CAP: usize = 10;
159
new(granule: usize) -> Self160 pub fn new(granule: usize) -> Self {
161 assert!(granule.is_power_of_two());
162 Self { granule, shared_regions: Vec::with_capacity(Self::INIT_CAP) }
163 }
164
165 /// Get from the global allocator a granule-aligned region that suits `hint` and share it.
refill(&mut self, pool: &mut FrameAllocator<32>, hint: Layout)166 pub fn refill(&mut self, pool: &mut FrameAllocator<32>, hint: Layout) {
167 let layout = hint.align_to(self.granule).unwrap().pad_to_align();
168 assert_ne!(layout.size(), 0);
169 // SAFETY - layout has non-zero size.
170 let Some(shared) = NonNull::new(unsafe { alloc_zeroed(layout) }) else {
171 handle_alloc_error(layout);
172 };
173
174 let base = shared.as_ptr() as usize;
175 let end = base.checked_add(layout.size()).unwrap();
176 trace!("Sharing memory region {:#x?}", base..end);
177 for vaddr in (base..end).step_by(self.granule) {
178 let vaddr = NonNull::new(vaddr as *mut _).unwrap();
179 get_hypervisor().mem_share(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
180 }
181 self.shared_regions.push((base, layout));
182
183 pool.add_frame(base, end);
184 }
185 }
186
187 impl Drop for MemorySharer {
drop(&mut self)188 fn drop(&mut self) {
189 while let Some((base, layout)) = self.shared_regions.pop() {
190 let end = base.checked_add(layout.size()).unwrap();
191 trace!("Unsharing 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_unshare(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
195 }
196
197 // SAFETY - The region was obtained from alloc_zeroed() with the recorded layout.
198 unsafe { dealloc(base as *mut _, layout) };
199 }
200 }
201 }
202
203 impl MemoryTracker {
204 const CAPACITY: usize = 5;
205 const MMIO_CAPACITY: usize = 5;
206 const PVMFW_RANGE: MemoryRange = (BASE_ADDR - SIZE_4MB)..BASE_ADDR;
207
208 /// Create a new instance from an active page table, covering the maximum RAM size.
new(page_table: mmu::PageTable) -> Self209 pub fn new(page_table: mmu::PageTable) -> Self {
210 Self {
211 total: BASE_ADDR..MAX_ADDR,
212 page_table,
213 regions: ArrayVec::new(),
214 mmio_regions: ArrayVec::new(),
215 }
216 }
217
218 /// Resize the total RAM size.
219 ///
220 /// This function fails if it contains regions that are not included within the new size.
shrink(&mut self, range: &MemoryRange) -> Result<()>221 pub fn shrink(&mut self, range: &MemoryRange) -> Result<()> {
222 if range.start != self.total.start {
223 return Err(MemoryTrackerError::DifferentBaseAddress);
224 }
225 if self.total.end < range.end {
226 return Err(MemoryTrackerError::SizeTooLarge);
227 }
228 if !self.regions.iter().all(|r| r.is_within(range)) {
229 return Err(MemoryTrackerError::SizeTooSmall);
230 }
231
232 self.total = range.clone();
233 Ok(())
234 }
235
236 /// Allocate the address range for a const slice; returns None if failed.
alloc_range(&mut self, range: &MemoryRange) -> Result<MemoryRange>237 pub fn alloc_range(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
238 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadOnly };
239 self.check(®ion)?;
240 self.page_table.map_rodata(range).map_err(|e| {
241 error!("Error during range allocation: {e}");
242 MemoryTrackerError::FailedToMap
243 })?;
244 self.add(region)
245 }
246
247 /// Allocate the address range for a mutable slice; returns None if failed.
alloc_range_mut(&mut self, range: &MemoryRange) -> Result<MemoryRange>248 pub fn alloc_range_mut(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
249 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadWrite };
250 self.check(®ion)?;
251 self.page_table.map_data(range).map_err(|e| {
252 error!("Error during mutable range allocation: {e}");
253 MemoryTrackerError::FailedToMap
254 })?;
255 self.add(region)
256 }
257
258 /// Allocate the address range for a const slice; returns None if failed.
alloc(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange>259 pub fn alloc(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
260 self.alloc_range(&(base..(base + size.get())))
261 }
262
263 /// Allocate the address range for a mutable slice; returns None if failed.
alloc_mut(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange>264 pub fn alloc_mut(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
265 self.alloc_range_mut(&(base..(base + size.get())))
266 }
267
268 /// Checks that the given range of addresses is within the MMIO region, and then maps it
269 /// appropriately.
map_mmio_range(&mut self, range: MemoryRange) -> Result<()>270 pub fn map_mmio_range(&mut self, range: MemoryRange) -> Result<()> {
271 // MMIO space is below the main memory region.
272 if range.end > self.total.start || overlaps(&Self::PVMFW_RANGE, &range) {
273 return Err(MemoryTrackerError::OutOfRange);
274 }
275 if self.mmio_regions.iter().any(|r| overlaps(r, &range)) {
276 return Err(MemoryTrackerError::Overlaps);
277 }
278 if self.mmio_regions.len() == self.mmio_regions.capacity() {
279 return Err(MemoryTrackerError::Full);
280 }
281
282 self.page_table.map_device(&range).map_err(|e| {
283 error!("Error during MMIO device mapping: {e}");
284 MemoryTrackerError::FailedToMap
285 })?;
286
287 for page_base in page_iterator(&range) {
288 get_hypervisor().mmio_guard_map(page_base)?;
289 }
290
291 if self.mmio_regions.try_push(range).is_some() {
292 return Err(MemoryTrackerError::Full);
293 }
294
295 Ok(())
296 }
297
298 /// Checks that the given region is within the range of the `MemoryTracker` and doesn't overlap
299 /// with any other previously allocated regions, and that the regions ArrayVec has capacity to
300 /// add it.
check(&self, region: &MemoryRegion) -> Result<()>301 fn check(&self, region: &MemoryRegion) -> Result<()> {
302 if !region.is_within(&self.total) {
303 return Err(MemoryTrackerError::OutOfRange);
304 }
305 if self.regions.iter().any(|r| r.overlaps(®ion.range)) {
306 return Err(MemoryTrackerError::Overlaps);
307 }
308 if self.regions.len() == self.regions.capacity() {
309 return Err(MemoryTrackerError::Full);
310 }
311 Ok(())
312 }
313
add(&mut self, region: MemoryRegion) -> Result<MemoryRange>314 fn add(&mut self, region: MemoryRegion) -> Result<MemoryRange> {
315 if self.regions.try_push(region).is_some() {
316 return Err(MemoryTrackerError::Full);
317 }
318
319 Ok(self.regions.last().unwrap().as_ref().clone())
320 }
321
322 /// Unmaps all tracked MMIO regions from the MMIO guard.
323 ///
324 /// Note that they are not unmapped from the page table.
mmio_unmap_all(&self) -> Result<()>325 pub fn mmio_unmap_all(&self) -> Result<()> {
326 for region in &self.mmio_regions {
327 for page_base in page_iterator(region) {
328 get_hypervisor().mmio_guard_unmap(page_base)?;
329 }
330 }
331
332 Ok(())
333 }
334
335 /// Initialize the shared heap to dynamically share memory from the global allocator.
init_dynamic_shared_pool(&mut self) -> Result<()>336 pub fn init_dynamic_shared_pool(&mut self) -> Result<()> {
337 let granule = get_hypervisor().memory_protection_granule()?;
338 let previous = SHARED_MEMORY.lock().replace(MemorySharer::new(granule));
339 if previous.is_some() {
340 return Err(MemoryTrackerError::SharedMemorySetFailure);
341 }
342
343 SHARED_POOL
344 .set(Box::new(LockedFrameAllocator::new()))
345 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
346
347 Ok(())
348 }
349
350 /// Initialize the shared heap from a static region of memory.
351 ///
352 /// Some hypervisors such as Gunyah do not support a MemShare API for guest
353 /// to share its memory with host. Instead they allow host to designate part
354 /// of guest memory as "shared" ahead of guest starting its execution. The
355 /// shared memory region is indicated in swiotlb node. On such platforms use
356 /// a separate heap to allocate buffers that can be shared with host.
init_static_shared_pool(&mut self, range: Range<usize>) -> Result<()>357 pub fn init_static_shared_pool(&mut self, range: Range<usize>) -> Result<()> {
358 let size = NonZeroUsize::new(range.len()).unwrap();
359 let range = self.alloc_mut(range.start, size)?;
360 let shared_pool = LockedFrameAllocator::<32>::new();
361
362 shared_pool.lock().insert(range);
363
364 SHARED_POOL
365 .set(Box::new(shared_pool))
366 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
367
368 Ok(())
369 }
370
371 /// Unshares any memory that may have been shared.
unshare_all_memory(&mut self)372 pub fn unshare_all_memory(&mut self) {
373 drop(SHARED_MEMORY.lock().take());
374 }
375 }
376
377 impl Drop for MemoryTracker {
drop(&mut self)378 fn drop(&mut self) {
379 for region in &self.regions {
380 match region.mem_type {
381 MemoryType::ReadWrite => {
382 // TODO(b/269738062): Use PT's dirty bit to only flush pages that were touched.
383 helpers::flush_region(region.range.start, region.range.len())
384 }
385 MemoryType::ReadOnly => {}
386 }
387 }
388 self.unshare_all_memory()
389 }
390 }
391
392 /// Allocates a memory range of at least the given size that is shared with
393 /// host. Returns a pointer to the buffer.
394 ///
395 /// It will be aligned to the memory sharing granule size supported by the hypervisor.
alloc_shared(layout: Layout) -> hyp::Result<NonNull<u8>>396 pub fn alloc_shared(layout: Layout) -> hyp::Result<NonNull<u8>> {
397 assert_ne!(layout.size(), 0);
398 let Some(buffer) = try_shared_alloc(layout) else {
399 handle_alloc_error(layout);
400 };
401
402 trace!("Allocated shared buffer at {buffer:?} with {layout:?}");
403 Ok(buffer)
404 }
405
try_shared_alloc(layout: Layout) -> Option<NonNull<u8>>406 fn try_shared_alloc(layout: Layout) -> Option<NonNull<u8>> {
407 let mut shared_pool = SHARED_POOL.get().unwrap().lock();
408
409 if let Some(buffer) = shared_pool.alloc_aligned(layout) {
410 Some(NonNull::new(buffer as _).unwrap())
411 } else if let Some(shared_memory) = SHARED_MEMORY.lock().as_mut() {
412 shared_memory.refill(&mut shared_pool, layout);
413 shared_pool.alloc_aligned(layout).map(|buffer| NonNull::new(buffer as _).unwrap())
414 } else {
415 None
416 }
417 }
418
419 /// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`.
420 ///
421 /// The size passed in must be the size passed to the original `alloc_shared` call.
422 ///
423 /// # Safety
424 ///
425 /// The memory must have been allocated by `alloc_shared` with the same size, and not yet
426 /// deallocated.
dealloc_shared(vaddr: NonNull<u8>, layout: Layout) -> hyp::Result<()>427 pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, layout: Layout) -> hyp::Result<()> {
428 SHARED_POOL.get().unwrap().lock().dealloc_aligned(vaddr.as_ptr() as usize, layout);
429
430 trace!("Deallocated shared buffer at {vaddr:?} with {layout:?}");
431 Ok(())
432 }
433
434 /// Returns an iterator which yields the base address of each 4 KiB page within the given range.
page_iterator(range: &MemoryRange) -> impl Iterator<Item = usize>435 fn page_iterator(range: &MemoryRange) -> impl Iterator<Item = usize> {
436 (page_4kb_of(range.start)..range.end).step_by(SIZE_4KB)
437 }
438
439 /// Returns the intermediate physical address corresponding to the given virtual address.
440 ///
441 /// As we use identity mapping for everything, this is just a cast, but it's useful to use it to be
442 /// explicit about where we are converting from virtual to physical address.
virt_to_phys(vaddr: NonNull<u8>) -> usize443 pub fn virt_to_phys(vaddr: NonNull<u8>) -> usize {
444 vaddr.as_ptr() as _
445 }
446
447 /// Returns a pointer for the virtual address corresponding to the given non-zero intermediate
448 /// physical address.
449 ///
450 /// Panics if `paddr` is 0.
phys_to_virt(paddr: usize) -> NonNull<u8>451 pub fn phys_to_virt(paddr: usize) -> NonNull<u8> {
452 NonNull::new(paddr as _).unwrap()
453 }
454