blob: b223f82e077b29cbd46556c95883a466df33f6ca [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
19use crate::helpers::{self, align_down, align_up, page_4kb_of, SIZE_4KB};
Pierre-Clément Tosi4ce55c02023-03-09 15:31:03 +000020use crate::hypervisor::{hyp_meminfo, mem_share, mem_unshare};
Andrew Walbran19690632022-12-07 16:41:30 +000021use crate::mmio_guard;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000022use crate::mmu;
Andrew Walbran41ebe932022-12-14 15:22:30 +000023use crate::smccc;
Andrew Walbran848decf2022-12-15 14:39:38 +000024use alloc::alloc::alloc_zeroed;
25use alloc::alloc::dealloc;
26use alloc::alloc::handle_alloc_error;
27use core::alloc::Layout;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000028use core::cmp::max;
29use core::cmp::min;
30use core::fmt;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000031use core::num::NonZeroUsize;
32use core::ops::Range;
Andrew Walbran848decf2022-12-15 14:39:38 +000033use core::ptr::NonNull;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000034use core::result;
35use log::error;
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000036use tinyvec::ArrayVec;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000037
Jiyong Park0ee65392023-03-27 20:52:45 +090038/// Base of the system's contiguous "main" memory.
39pub const BASE_ADDR: usize = 0x8000_0000;
40/// First address that can't be translated by a level 1 TTBR0_EL1.
41pub const MAX_ADDR: usize = 1 << 40;
42
Andrew Walbran0d8b54d2022-12-08 16:32:33 +000043pub type MemoryRange = Range<usize>;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000044
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000045#[derive(Clone, Copy, Debug, Default)]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000046enum MemoryType {
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000047 #[default]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000048 ReadOnly,
49 ReadWrite,
50}
51
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000052#[derive(Clone, Debug, Default)]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000053struct MemoryRegion {
54 range: MemoryRange,
55 mem_type: MemoryType,
56}
57
58impl MemoryRegion {
59 /// True if the instance overlaps with the passed range.
60 pub fn overlaps(&self, range: &MemoryRange) -> bool {
Andrew Walbran19690632022-12-07 16:41:30 +000061 overlaps(&self.range, range)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000062 }
63
64 /// True if the instance is fully contained within the passed range.
65 pub fn is_within(&self, range: &MemoryRange) -> bool {
66 let our: &MemoryRange = self.as_ref();
67 self.as_ref() == &(max(our.start, range.start)..min(our.end, range.end))
68 }
69}
70
71impl AsRef<MemoryRange> for MemoryRegion {
72 fn as_ref(&self) -> &MemoryRange {
73 &self.range
74 }
75}
76
Andrew Walbran19690632022-12-07 16:41:30 +000077/// Returns true if one range overlaps with the other at all.
78fn overlaps<T: Copy + Ord>(a: &Range<T>, b: &Range<T>) -> bool {
79 max(a.start, b.start) < min(a.end, b.end)
80}
81
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000082/// Tracks non-overlapping slices of main memory.
83pub struct MemoryTracker {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000084 total: MemoryRange,
85 page_table: mmu::PageTable,
Andrew Walbran19690632022-12-07 16:41:30 +000086 regions: ArrayVec<[MemoryRegion; MemoryTracker::CAPACITY]>,
87 mmio_regions: ArrayVec<[MemoryRange; MemoryTracker::MMIO_CAPACITY]>,
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000088}
89
90/// Errors for MemoryTracker operations.
91#[derive(Debug, Clone)]
92pub enum MemoryTrackerError {
93 /// Tried to modify the memory base address.
94 DifferentBaseAddress,
95 /// Tried to shrink to a larger memory size.
96 SizeTooLarge,
97 /// Tracked regions would not fit in memory size.
98 SizeTooSmall,
99 /// Reached limit number of tracked regions.
100 Full,
101 /// Region is out of the tracked memory address space.
102 OutOfRange,
103 /// New region overlaps with tracked regions.
104 Overlaps,
105 /// Region couldn't be mapped.
106 FailedToMap,
Andrew Walbran19690632022-12-07 16:41:30 +0000107 /// Error from an MMIO guard call.
108 MmioGuard(mmio_guard::Error),
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000109}
110
111impl fmt::Display for MemoryTrackerError {
112 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
113 match self {
114 Self::DifferentBaseAddress => write!(f, "Received different base address"),
115 Self::SizeTooLarge => write!(f, "Tried to shrink to a larger memory size"),
116 Self::SizeTooSmall => write!(f, "Tracked regions would not fit in memory size"),
117 Self::Full => write!(f, "Reached limit number of tracked regions"),
118 Self::OutOfRange => write!(f, "Region is out of the tracked memory address space"),
119 Self::Overlaps => write!(f, "New region overlaps with tracked regions"),
120 Self::FailedToMap => write!(f, "Failed to map the new region"),
Andrew Walbran19690632022-12-07 16:41:30 +0000121 Self::MmioGuard(e) => e.fmt(f),
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000122 }
123 }
124}
125
Andrew Walbran19690632022-12-07 16:41:30 +0000126impl From<mmio_guard::Error> for MemoryTrackerError {
127 fn from(e: mmio_guard::Error) -> Self {
128 Self::MmioGuard(e)
129 }
130}
131
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000132type Result<T> = result::Result<T, MemoryTrackerError>;
133
134impl MemoryTracker {
135 const CAPACITY: usize = 5;
Andrew Walbran19690632022-12-07 16:41:30 +0000136 const MMIO_CAPACITY: usize = 5;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000137
138 /// Create a new instance from an active page table, covering the maximum RAM size.
139 pub fn new(page_table: mmu::PageTable) -> Self {
Andrew Walbran19690632022-12-07 16:41:30 +0000140 Self {
Jiyong Park0ee65392023-03-27 20:52:45 +0900141 total: BASE_ADDR..MAX_ADDR,
Andrew Walbran19690632022-12-07 16:41:30 +0000142 page_table,
143 regions: ArrayVec::new(),
144 mmio_regions: ArrayVec::new(),
145 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000146 }
147
148 /// Resize the total RAM size.
149 ///
150 /// This function fails if it contains regions that are not included within the new size.
151 pub fn shrink(&mut self, range: &MemoryRange) -> Result<()> {
152 if range.start != self.total.start {
153 return Err(MemoryTrackerError::DifferentBaseAddress);
154 }
155 if self.total.end < range.end {
156 return Err(MemoryTrackerError::SizeTooLarge);
157 }
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000158 if !self.regions.iter().all(|r| r.is_within(range)) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000159 return Err(MemoryTrackerError::SizeTooSmall);
160 }
161
162 self.total = range.clone();
163 Ok(())
164 }
165
166 /// Allocate the address range for a const slice; returns None if failed.
167 pub fn alloc_range(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
Andrew Walbranda65ab12022-12-07 15:10:13 +0000168 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadOnly };
169 self.check(&region)?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000170 self.page_table.map_rodata(range).map_err(|e| {
171 error!("Error during range allocation: {e}");
172 MemoryTrackerError::FailedToMap
173 })?;
Andrew Walbranda65ab12022-12-07 15:10:13 +0000174 self.add(region)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000175 }
176
177 /// Allocate the address range for a mutable slice; returns None if failed.
178 pub fn alloc_range_mut(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
Andrew Walbranda65ab12022-12-07 15:10:13 +0000179 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadWrite };
180 self.check(&region)?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000181 self.page_table.map_data(range).map_err(|e| {
182 error!("Error during mutable range allocation: {e}");
183 MemoryTrackerError::FailedToMap
184 })?;
Andrew Walbranda65ab12022-12-07 15:10:13 +0000185 self.add(region)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000186 }
187
188 /// Allocate the address range for a const slice; returns None if failed.
189 pub fn alloc(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
190 self.alloc_range(&(base..(base + size.get())))
191 }
192
193 /// Allocate the address range for a mutable slice; returns None if failed.
194 pub fn alloc_mut(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
195 self.alloc_range_mut(&(base..(base + size.get())))
196 }
197
Andrew Walbran19690632022-12-07 16:41:30 +0000198 /// Checks that the given range of addresses is within the MMIO region, and then maps it
199 /// appropriately.
200 pub fn map_mmio_range(&mut self, range: MemoryRange) -> Result<()> {
201 // MMIO space is below the main memory region.
202 if range.end > self.total.start {
203 return Err(MemoryTrackerError::OutOfRange);
204 }
205 if self.mmio_regions.iter().any(|r| overlaps(r, &range)) {
206 return Err(MemoryTrackerError::Overlaps);
207 }
208 if self.mmio_regions.len() == self.mmio_regions.capacity() {
209 return Err(MemoryTrackerError::Full);
210 }
211
212 self.page_table.map_device(&range).map_err(|e| {
213 error!("Error during MMIO device mapping: {e}");
214 MemoryTrackerError::FailedToMap
215 })?;
216
217 for page_base in page_iterator(&range) {
218 mmio_guard::map(page_base)?;
219 }
220
221 if self.mmio_regions.try_push(range).is_some() {
222 return Err(MemoryTrackerError::Full);
223 }
224
225 Ok(())
226 }
227
Andrew Walbranda65ab12022-12-07 15:10:13 +0000228 /// Checks that the given region is within the range of the `MemoryTracker` and doesn't overlap
229 /// with any other previously allocated regions, and that the regions ArrayVec has capacity to
230 /// add it.
231 fn check(&self, region: &MemoryRegion) -> Result<()> {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000232 if !region.is_within(&self.total) {
233 return Err(MemoryTrackerError::OutOfRange);
234 }
Andrew Walbranda65ab12022-12-07 15:10:13 +0000235 if self.regions.iter().any(|r| r.overlaps(&region.range)) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000236 return Err(MemoryTrackerError::Overlaps);
237 }
Andrew Walbranda65ab12022-12-07 15:10:13 +0000238 if self.regions.len() == self.regions.capacity() {
239 return Err(MemoryTrackerError::Full);
240 }
241 Ok(())
242 }
243
244 fn add(&mut self, region: MemoryRegion) -> Result<MemoryRange> {
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000245 if self.regions.try_push(region).is_some() {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000246 return Err(MemoryTrackerError::Full);
247 }
248
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000249 Ok(self.regions.last().unwrap().as_ref().clone())
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000250 }
Andrew Walbran19690632022-12-07 16:41:30 +0000251
252 /// Unmaps all tracked MMIO regions from the MMIO guard.
253 ///
254 /// Note that they are not unmapped from the page table.
255 pub fn mmio_unmap_all(&self) -> Result<()> {
256 for region in &self.mmio_regions {
257 for page_base in page_iterator(region) {
258 mmio_guard::unmap(page_base)?;
259 }
260 }
261
262 Ok(())
263 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000264}
265
266impl Drop for MemoryTracker {
267 fn drop(&mut self) {
Andrew Walbran19690632022-12-07 16:41:30 +0000268 for region in &self.regions {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000269 match region.mem_type {
270 MemoryType::ReadWrite => {
Pierre-Clément Tosi73c2d642023-02-17 14:56:48 +0000271 // TODO(b/269738062): Use PT's dirty bit to only flush pages that were touched.
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000272 helpers::flush_region(region.range.start, region.range.len())
273 }
274 MemoryType::ReadOnly => {}
275 }
276 }
277 }
278}
Andrew Walbran19690632022-12-07 16:41:30 +0000279
Andrew Walbran41ebe932022-12-14 15:22:30 +0000280/// Gives the KVM host read, write and execute permissions on the given memory range. If the range
281/// is not aligned with the memory protection granule then it will be extended on either end to
282/// align.
Andrew Walbran848decf2022-12-15 14:39:38 +0000283fn share_range(range: &MemoryRange, granule: usize) -> smccc::Result<()> {
Andrew Walbran41ebe932022-12-14 15:22:30 +0000284 for base in (align_down(range.start, granule)
285 .expect("Memory protection granule was not a power of two")..range.end)
286 .step_by(granule)
287 {
288 mem_share(base as u64)?;
289 }
290 Ok(())
291}
292
293/// Removes permission from the KVM host to access the given memory range which was previously
294/// shared. If the range is not aligned with the memory protection granule then it will be extended
295/// on either end to align.
Andrew Walbran848decf2022-12-15 14:39:38 +0000296fn unshare_range(range: &MemoryRange, granule: usize) -> smccc::Result<()> {
Andrew Walbran41ebe932022-12-14 15:22:30 +0000297 for base in (align_down(range.start, granule)
298 .expect("Memory protection granule was not a power of two")..range.end)
299 .step_by(granule)
300 {
301 mem_unshare(base as u64)?;
302 }
303 Ok(())
304}
305
Andrew Walbran848decf2022-12-15 14:39:38 +0000306/// Allocates a memory range of at least the given size from the global allocator, and shares it
307/// with the host. Returns a pointer to the buffer.
308///
309/// It will be aligned to the memory sharing granule size supported by the hypervisor.
310pub fn alloc_shared(size: usize) -> smccc::Result<NonNull<u8>> {
311 let layout = shared_buffer_layout(size)?;
312 let granule = layout.align();
313
314 // Safe because `shared_buffer_layout` panics if the size is 0, so the layout must have a
315 // non-zero size.
316 let buffer = unsafe { alloc_zeroed(layout) };
317
Pierre-Clément Tosiebb37602023-02-17 14:57:26 +0000318 let Some(buffer) = NonNull::new(buffer) else {
Andrew Walbran848decf2022-12-15 14:39:38 +0000319 handle_alloc_error(layout);
320 };
321
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000322 let paddr = virt_to_phys(buffer);
Andrew Walbran848decf2022-12-15 14:39:38 +0000323 // If share_range fails then we will leak the allocation, but that seems better than having it
324 // be reused while maybe still partially shared with the host.
325 share_range(&(paddr..paddr + layout.size()), granule)?;
326
327 Ok(buffer)
328}
329
330/// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`.
331///
332/// The size passed in must be the size passed to the original `alloc_shared` call.
333///
334/// # Safety
335///
336/// The memory must have been allocated by `alloc_shared` with the same size, and not yet
337/// deallocated.
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000338pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, size: usize) -> smccc::Result<()> {
Andrew Walbran848decf2022-12-15 14:39:38 +0000339 let layout = shared_buffer_layout(size)?;
340 let granule = layout.align();
341
342 let paddr = virt_to_phys(vaddr);
343 unshare_range(&(paddr..paddr + layout.size()), granule)?;
344 // Safe because the memory was allocated by `alloc_shared` above using the same allocator, and
345 // the layout is the same as was used then.
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000346 unsafe { dealloc(vaddr.as_ptr(), layout) };
Andrew Walbran848decf2022-12-15 14:39:38 +0000347
348 Ok(())
349}
350
351/// Returns the layout to use for allocating a buffer of at least the given size shared with the
352/// host.
353///
354/// It will be aligned to the memory sharing granule size supported by the hypervisor.
355///
356/// Panics if `size` is 0.
357fn shared_buffer_layout(size: usize) -> smccc::Result<Layout> {
358 assert_ne!(size, 0);
359 let granule = hyp_meminfo()? as usize;
360 let allocated_size =
361 align_up(size, granule).expect("Memory protection granule was not a power of two");
362 Ok(Layout::from_size_align(allocated_size, granule).unwrap())
363}
364
Andrew Walbran19690632022-12-07 16:41:30 +0000365/// Returns an iterator which yields the base address of each 4 KiB page within the given range.
366fn page_iterator(range: &MemoryRange) -> impl Iterator<Item = usize> {
367 (page_4kb_of(range.start)..range.end).step_by(SIZE_4KB)
368}
Andrew Walbran848decf2022-12-15 14:39:38 +0000369
370/// Returns the intermediate physical address corresponding to the given virtual address.
371///
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000372/// As we use identity mapping for everything, this is just a cast, but it's useful to use it to be
373/// explicit about where we are converting from virtual to physical address.
374pub fn virt_to_phys(vaddr: NonNull<u8>) -> usize {
375 vaddr.as_ptr() as _
376}
377
378/// Returns a pointer for the virtual address corresponding to the given non-zero intermediate
379/// physical address.
380///
381/// Panics if `paddr` is 0.
382pub fn phys_to_virt(paddr: usize) -> NonNull<u8> {
383 NonNull::new(paddr as _).unwrap()
Andrew Walbran848decf2022-12-15 14:39:38 +0000384}