blob: 714815bb0eaec24e89f08b8df7006f77d75ea01a [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
Srivatsa Vaddagiric25d68e2023-04-19 22:56:33 -070019use crate::helpers::{self, align_down, align_up, page_4kb_of, RangeExt, SIZE_4KB, SIZE_4MB};
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000020use crate::mmu;
Andrew Walbran848decf2022-12-15 14:39:38 +000021use alloc::alloc::alloc_zeroed;
22use alloc::alloc::dealloc;
23use alloc::alloc::handle_alloc_error;
24use core::alloc::Layout;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000025use core::cmp::max;
26use core::cmp::min;
27use core::fmt;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000028use core::num::NonZeroUsize;
29use core::ops::Range;
Andrew Walbran848decf2022-12-15 14:39:38 +000030use core::ptr::NonNull;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000031use core::result;
Alice Wang90e6f162023-04-17 13:49:45 +000032use hyp::get_hypervisor;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000033use log::error;
Jakob Vukalovic85a00d72023-04-20 09:51:10 +010034use spin::mutex::SpinMutex;
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000035use tinyvec::ArrayVec;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000036
Jiyong Park0ee65392023-03-27 20:52:45 +090037/// Base of the system's contiguous "main" memory.
38pub const BASE_ADDR: usize = 0x8000_0000;
39/// First address that can't be translated by a level 1 TTBR0_EL1.
40pub const MAX_ADDR: usize = 1 << 40;
41
Andrew Walbran0d8b54d2022-12-08 16:32:33 +000042pub type MemoryRange = Range<usize>;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000043
Jakob Vukalovic85a00d72023-04-20 09:51:10 +010044pub static MEMORY: SpinMutex<Option<MemoryTracker>> = SpinMutex::new(None);
45unsafe impl Send for MemoryTracker {}
46
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000047#[derive(Clone, Copy, Debug, Default)]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000048enum MemoryType {
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000049 #[default]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000050 ReadOnly,
51 ReadWrite,
52}
53
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000054#[derive(Clone, Debug, Default)]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000055struct MemoryRegion {
56 range: MemoryRange,
57 mem_type: MemoryType,
58}
59
60impl MemoryRegion {
61 /// True if the instance overlaps with the passed range.
62 pub fn overlaps(&self, range: &MemoryRange) -> bool {
Andrew Walbran19690632022-12-07 16:41:30 +000063 overlaps(&self.range, range)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000064 }
65
66 /// True if the instance is fully contained within the passed range.
67 pub fn is_within(&self, range: &MemoryRange) -> bool {
Srivatsa Vaddagiric25d68e2023-04-19 22:56:33 -070068 self.as_ref().is_within(range)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000069 }
70}
71
72impl AsRef<MemoryRange> for MemoryRegion {
73 fn as_ref(&self) -> &MemoryRange {
74 &self.range
75 }
76}
77
Andrew Walbran19690632022-12-07 16:41:30 +000078/// Returns true if one range overlaps with the other at all.
79fn overlaps<T: Copy + Ord>(a: &Range<T>, b: &Range<T>) -> bool {
80 max(a.start, b.start) < min(a.end, b.end)
81}
82
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000083/// Tracks non-overlapping slices of main memory.
84pub struct MemoryTracker {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000085 total: MemoryRange,
86 page_table: mmu::PageTable,
Andrew Walbran19690632022-12-07 16:41:30 +000087 regions: ArrayVec<[MemoryRegion; MemoryTracker::CAPACITY]>,
88 mmio_regions: ArrayVec<[MemoryRange; MemoryTracker::MMIO_CAPACITY]>,
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000089}
90
91/// Errors for MemoryTracker operations.
92#[derive(Debug, Clone)]
93pub enum MemoryTrackerError {
94 /// Tried to modify the memory base address.
95 DifferentBaseAddress,
96 /// Tried to shrink to a larger memory size.
97 SizeTooLarge,
98 /// Tracked regions would not fit in memory size.
99 SizeTooSmall,
100 /// Reached limit number of tracked regions.
101 Full,
102 /// Region is out of the tracked memory address space.
103 OutOfRange,
104 /// New region overlaps with tracked regions.
105 Overlaps,
106 /// Region couldn't be mapped.
107 FailedToMap,
Alice Wang90e6f162023-04-17 13:49:45 +0000108 /// Error from the interaction with the hypervisor.
109 Hypervisor(hyp::Error),
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000110}
111
112impl fmt::Display for MemoryTrackerError {
113 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
114 match self {
115 Self::DifferentBaseAddress => write!(f, "Received different base address"),
116 Self::SizeTooLarge => write!(f, "Tried to shrink to a larger memory size"),
117 Self::SizeTooSmall => write!(f, "Tracked regions would not fit in memory size"),
118 Self::Full => write!(f, "Reached limit number of tracked regions"),
119 Self::OutOfRange => write!(f, "Region is out of the tracked memory address space"),
120 Self::Overlaps => write!(f, "New region overlaps with tracked regions"),
121 Self::FailedToMap => write!(f, "Failed to map the new region"),
Alice Wang90e6f162023-04-17 13:49:45 +0000122 Self::Hypervisor(e) => e.fmt(f),
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000123 }
124 }
125}
126
Alice Wang90e6f162023-04-17 13:49:45 +0000127impl From<hyp::Error> for MemoryTrackerError {
128 fn from(e: hyp::Error) -> Self {
129 Self::Hypervisor(e)
Andrew Walbran19690632022-12-07 16:41:30 +0000130 }
131}
132
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000133type Result<T> = result::Result<T, MemoryTrackerError>;
134
135impl MemoryTracker {
136 const CAPACITY: usize = 5;
Andrew Walbran19690632022-12-07 16:41:30 +0000137 const MMIO_CAPACITY: usize = 5;
Pierre-Clément Tosi164a6f52023-04-18 19:29:11 +0100138 const PVMFW_RANGE: MemoryRange = (BASE_ADDR - SIZE_4MB)..BASE_ADDR;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000139
140 /// Create a new instance from an active page table, covering the maximum RAM size.
141 pub fn new(page_table: mmu::PageTable) -> Self {
Andrew Walbran19690632022-12-07 16:41:30 +0000142 Self {
Jiyong Park0ee65392023-03-27 20:52:45 +0900143 total: BASE_ADDR..MAX_ADDR,
Andrew Walbran19690632022-12-07 16:41:30 +0000144 page_table,
145 regions: ArrayVec::new(),
146 mmio_regions: ArrayVec::new(),
147 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000148 }
149
150 /// Resize the total RAM size.
151 ///
152 /// This function fails if it contains regions that are not included within the new size.
153 pub fn shrink(&mut self, range: &MemoryRange) -> Result<()> {
154 if range.start != self.total.start {
155 return Err(MemoryTrackerError::DifferentBaseAddress);
156 }
157 if self.total.end < range.end {
158 return Err(MemoryTrackerError::SizeTooLarge);
159 }
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000160 if !self.regions.iter().all(|r| r.is_within(range)) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000161 return Err(MemoryTrackerError::SizeTooSmall);
162 }
163
164 self.total = range.clone();
165 Ok(())
166 }
167
168 /// Allocate the address range for a const slice; returns None if failed.
169 pub fn alloc_range(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
Andrew Walbranda65ab12022-12-07 15:10:13 +0000170 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadOnly };
171 self.check(&region)?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000172 self.page_table.map_rodata(range).map_err(|e| {
173 error!("Error during range allocation: {e}");
174 MemoryTrackerError::FailedToMap
175 })?;
Andrew Walbranda65ab12022-12-07 15:10:13 +0000176 self.add(region)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000177 }
178
179 /// Allocate the address range for a mutable slice; returns None if failed.
180 pub fn alloc_range_mut(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
Andrew Walbranda65ab12022-12-07 15:10:13 +0000181 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadWrite };
182 self.check(&region)?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000183 self.page_table.map_data(range).map_err(|e| {
184 error!("Error during mutable range allocation: {e}");
185 MemoryTrackerError::FailedToMap
186 })?;
Andrew Walbranda65ab12022-12-07 15:10:13 +0000187 self.add(region)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000188 }
189
190 /// Allocate the address range for a const slice; returns None if failed.
191 pub fn alloc(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
192 self.alloc_range(&(base..(base + size.get())))
193 }
194
195 /// Allocate the address range for a mutable slice; returns None if failed.
196 pub fn alloc_mut(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
197 self.alloc_range_mut(&(base..(base + size.get())))
198 }
199
Andrew Walbran19690632022-12-07 16:41:30 +0000200 /// Checks that the given range of addresses is within the MMIO region, and then maps it
201 /// appropriately.
202 pub fn map_mmio_range(&mut self, range: MemoryRange) -> Result<()> {
203 // MMIO space is below the main memory region.
Pierre-Clément Tosi164a6f52023-04-18 19:29:11 +0100204 if range.end > self.total.start || overlaps(&Self::PVMFW_RANGE, &range) {
Andrew Walbran19690632022-12-07 16:41:30 +0000205 return Err(MemoryTrackerError::OutOfRange);
206 }
207 if self.mmio_regions.iter().any(|r| overlaps(r, &range)) {
208 return Err(MemoryTrackerError::Overlaps);
209 }
210 if self.mmio_regions.len() == self.mmio_regions.capacity() {
211 return Err(MemoryTrackerError::Full);
212 }
213
214 self.page_table.map_device(&range).map_err(|e| {
215 error!("Error during MMIO device mapping: {e}");
216 MemoryTrackerError::FailedToMap
217 })?;
218
219 for page_base in page_iterator(&range) {
Alice Wang90e6f162023-04-17 13:49:45 +0000220 get_hypervisor().mmio_guard_map(page_base)?;
Andrew Walbran19690632022-12-07 16:41:30 +0000221 }
222
223 if self.mmio_regions.try_push(range).is_some() {
224 return Err(MemoryTrackerError::Full);
225 }
226
227 Ok(())
228 }
229
Andrew Walbranda65ab12022-12-07 15:10:13 +0000230 /// Checks that the given region is within the range of the `MemoryTracker` and doesn't overlap
231 /// with any other previously allocated regions, and that the regions ArrayVec has capacity to
232 /// add it.
233 fn check(&self, region: &MemoryRegion) -> Result<()> {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000234 if !region.is_within(&self.total) {
235 return Err(MemoryTrackerError::OutOfRange);
236 }
Andrew Walbranda65ab12022-12-07 15:10:13 +0000237 if self.regions.iter().any(|r| r.overlaps(&region.range)) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000238 return Err(MemoryTrackerError::Overlaps);
239 }
Andrew Walbranda65ab12022-12-07 15:10:13 +0000240 if self.regions.len() == self.regions.capacity() {
241 return Err(MemoryTrackerError::Full);
242 }
243 Ok(())
244 }
245
246 fn add(&mut self, region: MemoryRegion) -> Result<MemoryRange> {
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000247 if self.regions.try_push(region).is_some() {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000248 return Err(MemoryTrackerError::Full);
249 }
250
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000251 Ok(self.regions.last().unwrap().as_ref().clone())
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000252 }
Andrew Walbran19690632022-12-07 16:41:30 +0000253
254 /// Unmaps all tracked MMIO regions from the MMIO guard.
255 ///
256 /// Note that they are not unmapped from the page table.
257 pub fn mmio_unmap_all(&self) -> Result<()> {
258 for region in &self.mmio_regions {
259 for page_base in page_iterator(region) {
Alice Wang90e6f162023-04-17 13:49:45 +0000260 get_hypervisor().mmio_guard_unmap(page_base)?;
Andrew Walbran19690632022-12-07 16:41:30 +0000261 }
262 }
263
264 Ok(())
265 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000266}
267
268impl Drop for MemoryTracker {
269 fn drop(&mut self) {
Andrew Walbran19690632022-12-07 16:41:30 +0000270 for region in &self.regions {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000271 match region.mem_type {
272 MemoryType::ReadWrite => {
Pierre-Clément Tosi73c2d642023-02-17 14:56:48 +0000273 // TODO(b/269738062): Use PT's dirty bit to only flush pages that were touched.
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000274 helpers::flush_region(region.range.start, region.range.len())
275 }
276 MemoryType::ReadOnly => {}
277 }
278 }
279 }
280}
Andrew Walbran19690632022-12-07 16:41:30 +0000281
Andrew Walbran41ebe932022-12-14 15:22:30 +0000282/// Gives the KVM host read, write and execute permissions on the given memory range. If the range
283/// is not aligned with the memory protection granule then it will be extended on either end to
284/// align.
Alice Wang90e6f162023-04-17 13:49:45 +0000285fn share_range(range: &MemoryRange, granule: usize) -> hyp::Result<()> {
Andrew Walbran41ebe932022-12-14 15:22:30 +0000286 for base in (align_down(range.start, granule)
287 .expect("Memory protection granule was not a power of two")..range.end)
288 .step_by(granule)
289 {
Alice Wang31329112023-04-13 09:02:36 +0000290 get_hypervisor().mem_share(base as u64)?;
Andrew Walbran41ebe932022-12-14 15:22:30 +0000291 }
292 Ok(())
293}
294
295/// Removes permission from the KVM host to access the given memory range which was previously
296/// shared. If the range is not aligned with the memory protection granule then it will be extended
297/// on either end to align.
Alice Wang90e6f162023-04-17 13:49:45 +0000298fn unshare_range(range: &MemoryRange, granule: usize) -> hyp::Result<()> {
Andrew Walbran41ebe932022-12-14 15:22:30 +0000299 for base in (align_down(range.start, granule)
300 .expect("Memory protection granule was not a power of two")..range.end)
301 .step_by(granule)
302 {
Alice Wang31329112023-04-13 09:02:36 +0000303 get_hypervisor().mem_unshare(base as u64)?;
Andrew Walbran41ebe932022-12-14 15:22:30 +0000304 }
305 Ok(())
306}
307
Andrew Walbran848decf2022-12-15 14:39:38 +0000308/// Allocates a memory range of at least the given size from the global allocator, and shares it
309/// with the host. Returns a pointer to the buffer.
310///
311/// It will be aligned to the memory sharing granule size supported by the hypervisor.
Alice Wang90e6f162023-04-17 13:49:45 +0000312pub fn alloc_shared(size: usize) -> hyp::Result<NonNull<u8>> {
Andrew Walbran848decf2022-12-15 14:39:38 +0000313 let layout = shared_buffer_layout(size)?;
314 let granule = layout.align();
315
316 // Safe because `shared_buffer_layout` panics if the size is 0, so the layout must have a
317 // non-zero size.
318 let buffer = unsafe { alloc_zeroed(layout) };
319
Pierre-Clément Tosiebb37602023-02-17 14:57:26 +0000320 let Some(buffer) = NonNull::new(buffer) else {
Andrew Walbran848decf2022-12-15 14:39:38 +0000321 handle_alloc_error(layout);
322 };
323
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000324 let paddr = virt_to_phys(buffer);
Andrew Walbran848decf2022-12-15 14:39:38 +0000325 // If share_range fails then we will leak the allocation, but that seems better than having it
326 // be reused while maybe still partially shared with the host.
327 share_range(&(paddr..paddr + layout.size()), granule)?;
328
329 Ok(buffer)
330}
331
332/// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`.
333///
334/// The size passed in must be the size passed to the original `alloc_shared` call.
335///
336/// # Safety
337///
338/// The memory must have been allocated by `alloc_shared` with the same size, and not yet
339/// deallocated.
Alice Wang90e6f162023-04-17 13:49:45 +0000340pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, size: usize) -> hyp::Result<()> {
Andrew Walbran848decf2022-12-15 14:39:38 +0000341 let layout = shared_buffer_layout(size)?;
342 let granule = layout.align();
343
344 let paddr = virt_to_phys(vaddr);
345 unshare_range(&(paddr..paddr + layout.size()), granule)?;
346 // Safe because the memory was allocated by `alloc_shared` above using the same allocator, and
347 // the layout is the same as was used then.
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000348 unsafe { dealloc(vaddr.as_ptr(), layout) };
Andrew Walbran848decf2022-12-15 14:39:38 +0000349
350 Ok(())
351}
352
353/// Returns the layout to use for allocating a buffer of at least the given size shared with the
354/// host.
355///
356/// It will be aligned to the memory sharing granule size supported by the hypervisor.
357///
358/// Panics if `size` is 0.
Alice Wang90e6f162023-04-17 13:49:45 +0000359fn shared_buffer_layout(size: usize) -> hyp::Result<Layout> {
Andrew Walbran848decf2022-12-15 14:39:38 +0000360 assert_ne!(size, 0);
Alice Wang31329112023-04-13 09:02:36 +0000361 let granule = get_hypervisor().memory_protection_granule()?;
Andrew Walbran848decf2022-12-15 14:39:38 +0000362 let allocated_size =
363 align_up(size, granule).expect("Memory protection granule was not a power of two");
364 Ok(Layout::from_size_align(allocated_size, granule).unwrap())
365}
366
Andrew Walbran19690632022-12-07 16:41:30 +0000367/// Returns an iterator which yields the base address of each 4 KiB page within the given range.
368fn page_iterator(range: &MemoryRange) -> impl Iterator<Item = usize> {
369 (page_4kb_of(range.start)..range.end).step_by(SIZE_4KB)
370}
Andrew Walbran848decf2022-12-15 14:39:38 +0000371
372/// Returns the intermediate physical address corresponding to the given virtual address.
373///
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000374/// As we use identity mapping for everything, this is just a cast, but it's useful to use it to be
375/// explicit about where we are converting from virtual to physical address.
376pub fn virt_to_phys(vaddr: NonNull<u8>) -> usize {
377 vaddr.as_ptr() as _
378}
379
380/// Returns a pointer for the virtual address corresponding to the given non-zero intermediate
381/// physical address.
382///
383/// Panics if `paddr` is 0.
384pub fn phys_to_virt(paddr: usize) -> NonNull<u8> {
385 NonNull::new(paddr as _).unwrap()
Andrew Walbran848decf2022-12-15 14:39:38 +0000386}