Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 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 | |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 17 | #![deny(unsafe_op_in_unsafe_fn)] |
| 18 | |
Pierre-Clément Tosi | 2d5bc58 | 2023-05-03 11:23:11 +0000 | [diff] [blame] | 19 | use crate::helpers::{self, align_down, page_4kb_of, RangeExt, SIZE_4KB, SIZE_4MB}; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 20 | use crate::mmu; |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 21 | use alloc::alloc::alloc_zeroed; |
| 22 | use alloc::alloc::dealloc; |
| 23 | use alloc::alloc::handle_alloc_error; |
Srivatsa Vaddagiri | 37713ec | 2023-04-20 04:04:08 -0700 | [diff] [blame] | 24 | use alloc::boxed::Box; |
| 25 | use buddy_system_allocator::LockedHeap; |
| 26 | use core::alloc::GlobalAlloc as _; |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 27 | use core::alloc::Layout; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 28 | use core::cmp::max; |
| 29 | use core::cmp::min; |
| 30 | use core::fmt; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 31 | use core::num::NonZeroUsize; |
| 32 | use core::ops::Range; |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 33 | use core::ptr::NonNull; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 34 | use core::result; |
Alice Wang | 90e6f16 | 2023-04-17 13:49:45 +0000 | [diff] [blame] | 35 | use hyp::get_hypervisor; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 36 | use log::error; |
Pierre-Clément Tosi | 90238c5 | 2023-04-27 17:59:10 +0000 | [diff] [blame] | 37 | use log::trace; |
Srivatsa Vaddagiri | 37713ec | 2023-04-20 04:04:08 -0700 | [diff] [blame] | 38 | use once_cell::race::OnceBox; |
Jakob Vukalovic | 85a00d7 | 2023-04-20 09:51:10 +0100 | [diff] [blame] | 39 | use spin::mutex::SpinMutex; |
Pierre-Clément Tosi | 328dfb6 | 2022-11-25 18:20:42 +0000 | [diff] [blame] | 40 | use tinyvec::ArrayVec; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 41 | |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 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 | |
Andrew Walbran | 0d8b54d | 2022-12-08 16:32:33 +0000 | [diff] [blame] | 47 | pub type MemoryRange = Range<usize>; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 48 | |
Jakob Vukalovic | 85a00d7 | 2023-04-20 09:51:10 +0100 | [diff] [blame] | 49 | pub static MEMORY: SpinMutex<Option<MemoryTracker>> = SpinMutex::new(None); |
| 50 | unsafe impl Send for MemoryTracker {} |
| 51 | |
Pierre-Clément Tosi | 328dfb6 | 2022-11-25 18:20:42 +0000 | [diff] [blame] | 52 | #[derive(Clone, Copy, Debug, Default)] |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 53 | enum MemoryType { |
Pierre-Clément Tosi | 328dfb6 | 2022-11-25 18:20:42 +0000 | [diff] [blame] | 54 | #[default] |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 55 | ReadOnly, |
| 56 | ReadWrite, |
| 57 | } |
| 58 | |
Pierre-Clément Tosi | 328dfb6 | 2022-11-25 18:20:42 +0000 | [diff] [blame] | 59 | #[derive(Clone, Debug, Default)] |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 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. |
| 67 | pub fn overlaps(&self, range: &MemoryRange) -> bool { |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 68 | overlaps(&self.range, range) |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 69 | } |
| 70 | |
| 71 | /// True if the instance is fully contained within the passed range. |
| 72 | pub fn is_within(&self, range: &MemoryRange) -> bool { |
Srivatsa Vaddagiri | c25d68e | 2023-04-19 22:56:33 -0700 | [diff] [blame] | 73 | self.as_ref().is_within(range) |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 74 | } |
| 75 | } |
| 76 | |
| 77 | impl AsRef<MemoryRange> for MemoryRegion { |
| 78 | fn as_ref(&self) -> &MemoryRange { |
| 79 | &self.range |
| 80 | } |
| 81 | } |
| 82 | |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 83 | /// Returns true if one range overlaps with the other at all. |
| 84 | 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 | |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 88 | /// Tracks non-overlapping slices of main memory. |
| 89 | pub struct MemoryTracker { |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 90 | total: MemoryRange, |
| 91 | page_table: mmu::PageTable, |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 92 | regions: ArrayVec<[MemoryRegion; MemoryTracker::CAPACITY]>, |
| 93 | mmio_regions: ArrayVec<[MemoryRange; MemoryTracker::MMIO_CAPACITY]>, |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 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, |
Alice Wang | 90e6f16 | 2023-04-17 13:49:45 +0000 | [diff] [blame] | 113 | /// Error from the interaction with the hypervisor. |
| 114 | Hypervisor(hyp::Error), |
Srivatsa Vaddagiri | 37713ec | 2023-04-20 04:04:08 -0700 | [diff] [blame] | 115 | /// Failure to set `SHARED_POOL`. |
| 116 | SharedPoolSetFailure, |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 117 | } |
| 118 | |
| 119 | impl fmt::Display for MemoryTrackerError { |
| 120 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 121 | match self { |
| 122 | Self::DifferentBaseAddress => write!(f, "Received different base address"), |
| 123 | Self::SizeTooLarge => write!(f, "Tried to shrink to a larger memory size"), |
| 124 | Self::SizeTooSmall => write!(f, "Tracked regions would not fit in memory size"), |
| 125 | Self::Full => write!(f, "Reached limit number of tracked regions"), |
| 126 | Self::OutOfRange => write!(f, "Region is out of the tracked memory address space"), |
| 127 | Self::Overlaps => write!(f, "New region overlaps with tracked regions"), |
| 128 | Self::FailedToMap => write!(f, "Failed to map the new region"), |
Alice Wang | 90e6f16 | 2023-04-17 13:49:45 +0000 | [diff] [blame] | 129 | Self::Hypervisor(e) => e.fmt(f), |
Srivatsa Vaddagiri | 37713ec | 2023-04-20 04:04:08 -0700 | [diff] [blame] | 130 | Self::SharedPoolSetFailure => write!(f, "Failed to set SHARED_POOL"), |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 131 | } |
| 132 | } |
| 133 | } |
| 134 | |
Alice Wang | 90e6f16 | 2023-04-17 13:49:45 +0000 | [diff] [blame] | 135 | impl From<hyp::Error> for MemoryTrackerError { |
| 136 | fn from(e: hyp::Error) -> Self { |
| 137 | Self::Hypervisor(e) |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 138 | } |
| 139 | } |
| 140 | |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 141 | type Result<T> = result::Result<T, MemoryTrackerError>; |
| 142 | |
Srivatsa Vaddagiri | 37713ec | 2023-04-20 04:04:08 -0700 | [diff] [blame] | 143 | static SHARED_POOL: OnceBox<LockedHeap<32>> = OnceBox::new(); |
| 144 | |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 145 | impl MemoryTracker { |
| 146 | const CAPACITY: usize = 5; |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 147 | const MMIO_CAPACITY: usize = 5; |
Pierre-Clément Tosi | 164a6f5 | 2023-04-18 19:29:11 +0100 | [diff] [blame] | 148 | const PVMFW_RANGE: MemoryRange = (BASE_ADDR - SIZE_4MB)..BASE_ADDR; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 149 | |
| 150 | /// Create a new instance from an active page table, covering the maximum RAM size. |
| 151 | pub fn new(page_table: mmu::PageTable) -> Self { |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 152 | Self { |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 153 | total: BASE_ADDR..MAX_ADDR, |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 154 | page_table, |
| 155 | regions: ArrayVec::new(), |
| 156 | mmio_regions: ArrayVec::new(), |
| 157 | } |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 158 | } |
| 159 | |
| 160 | /// Resize the total RAM size. |
| 161 | /// |
| 162 | /// This function fails if it contains regions that are not included within the new size. |
| 163 | pub fn shrink(&mut self, range: &MemoryRange) -> Result<()> { |
| 164 | if range.start != self.total.start { |
| 165 | return Err(MemoryTrackerError::DifferentBaseAddress); |
| 166 | } |
| 167 | if self.total.end < range.end { |
| 168 | return Err(MemoryTrackerError::SizeTooLarge); |
| 169 | } |
Pierre-Clément Tosi | 328dfb6 | 2022-11-25 18:20:42 +0000 | [diff] [blame] | 170 | if !self.regions.iter().all(|r| r.is_within(range)) { |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 171 | return Err(MemoryTrackerError::SizeTooSmall); |
| 172 | } |
| 173 | |
| 174 | self.total = range.clone(); |
| 175 | Ok(()) |
| 176 | } |
| 177 | |
| 178 | /// Allocate the address range for a const slice; returns None if failed. |
| 179 | pub fn alloc_range(&mut self, range: &MemoryRange) -> Result<MemoryRange> { |
Andrew Walbran | da65ab1 | 2022-12-07 15:10:13 +0000 | [diff] [blame] | 180 | let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadOnly }; |
| 181 | self.check(®ion)?; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 182 | self.page_table.map_rodata(range).map_err(|e| { |
| 183 | error!("Error during range allocation: {e}"); |
| 184 | MemoryTrackerError::FailedToMap |
| 185 | })?; |
Andrew Walbran | da65ab1 | 2022-12-07 15:10:13 +0000 | [diff] [blame] | 186 | self.add(region) |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 187 | } |
| 188 | |
| 189 | /// Allocate the address range for a mutable slice; returns None if failed. |
| 190 | pub fn alloc_range_mut(&mut self, range: &MemoryRange) -> Result<MemoryRange> { |
Andrew Walbran | da65ab1 | 2022-12-07 15:10:13 +0000 | [diff] [blame] | 191 | let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadWrite }; |
| 192 | self.check(®ion)?; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 193 | self.page_table.map_data(range).map_err(|e| { |
| 194 | error!("Error during mutable range allocation: {e}"); |
| 195 | MemoryTrackerError::FailedToMap |
| 196 | })?; |
Andrew Walbran | da65ab1 | 2022-12-07 15:10:13 +0000 | [diff] [blame] | 197 | self.add(region) |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 198 | } |
| 199 | |
| 200 | /// Allocate the address range for a const slice; returns None if failed. |
| 201 | pub fn alloc(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> { |
| 202 | self.alloc_range(&(base..(base + size.get()))) |
| 203 | } |
| 204 | |
| 205 | /// Allocate the address range for a mutable slice; returns None if failed. |
| 206 | pub fn alloc_mut(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> { |
| 207 | self.alloc_range_mut(&(base..(base + size.get()))) |
| 208 | } |
| 209 | |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 210 | /// Checks that the given range of addresses is within the MMIO region, and then maps it |
| 211 | /// appropriately. |
| 212 | pub fn map_mmio_range(&mut self, range: MemoryRange) -> Result<()> { |
| 213 | // MMIO space is below the main memory region. |
Pierre-Clément Tosi | 164a6f5 | 2023-04-18 19:29:11 +0100 | [diff] [blame] | 214 | if range.end > self.total.start || overlaps(&Self::PVMFW_RANGE, &range) { |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 215 | return Err(MemoryTrackerError::OutOfRange); |
| 216 | } |
| 217 | if self.mmio_regions.iter().any(|r| overlaps(r, &range)) { |
| 218 | return Err(MemoryTrackerError::Overlaps); |
| 219 | } |
| 220 | if self.mmio_regions.len() == self.mmio_regions.capacity() { |
| 221 | return Err(MemoryTrackerError::Full); |
| 222 | } |
| 223 | |
| 224 | self.page_table.map_device(&range).map_err(|e| { |
| 225 | error!("Error during MMIO device mapping: {e}"); |
| 226 | MemoryTrackerError::FailedToMap |
| 227 | })?; |
| 228 | |
| 229 | for page_base in page_iterator(&range) { |
Alice Wang | 90e6f16 | 2023-04-17 13:49:45 +0000 | [diff] [blame] | 230 | get_hypervisor().mmio_guard_map(page_base)?; |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 231 | } |
| 232 | |
| 233 | if self.mmio_regions.try_push(range).is_some() { |
| 234 | return Err(MemoryTrackerError::Full); |
| 235 | } |
| 236 | |
| 237 | Ok(()) |
| 238 | } |
| 239 | |
Andrew Walbran | da65ab1 | 2022-12-07 15:10:13 +0000 | [diff] [blame] | 240 | /// Checks that the given region is within the range of the `MemoryTracker` and doesn't overlap |
| 241 | /// with any other previously allocated regions, and that the regions ArrayVec has capacity to |
| 242 | /// add it. |
| 243 | fn check(&self, region: &MemoryRegion) -> Result<()> { |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 244 | if !region.is_within(&self.total) { |
| 245 | return Err(MemoryTrackerError::OutOfRange); |
| 246 | } |
Andrew Walbran | da65ab1 | 2022-12-07 15:10:13 +0000 | [diff] [blame] | 247 | if self.regions.iter().any(|r| r.overlaps(®ion.range)) { |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 248 | return Err(MemoryTrackerError::Overlaps); |
| 249 | } |
Andrew Walbran | da65ab1 | 2022-12-07 15:10:13 +0000 | [diff] [blame] | 250 | if self.regions.len() == self.regions.capacity() { |
| 251 | return Err(MemoryTrackerError::Full); |
| 252 | } |
| 253 | Ok(()) |
| 254 | } |
| 255 | |
| 256 | fn add(&mut self, region: MemoryRegion) -> Result<MemoryRange> { |
Pierre-Clément Tosi | 328dfb6 | 2022-11-25 18:20:42 +0000 | [diff] [blame] | 257 | if self.regions.try_push(region).is_some() { |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 258 | return Err(MemoryTrackerError::Full); |
| 259 | } |
| 260 | |
Pierre-Clément Tosi | 328dfb6 | 2022-11-25 18:20:42 +0000 | [diff] [blame] | 261 | Ok(self.regions.last().unwrap().as_ref().clone()) |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 262 | } |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 263 | |
| 264 | /// Unmaps all tracked MMIO regions from the MMIO guard. |
| 265 | /// |
| 266 | /// Note that they are not unmapped from the page table. |
| 267 | pub fn mmio_unmap_all(&self) -> Result<()> { |
| 268 | for region in &self.mmio_regions { |
| 269 | for page_base in page_iterator(region) { |
Alice Wang | 90e6f16 | 2023-04-17 13:49:45 +0000 | [diff] [blame] | 270 | get_hypervisor().mmio_guard_unmap(page_base)?; |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 271 | } |
| 272 | } |
| 273 | |
| 274 | Ok(()) |
| 275 | } |
Srivatsa Vaddagiri | 37713ec | 2023-04-20 04:04:08 -0700 | [diff] [blame] | 276 | |
| 277 | /// Initialize a separate heap for shared memory allocations. |
| 278 | /// |
| 279 | /// Some hypervisors such as Gunyah do not support a MemShare API for guest |
| 280 | /// to share its memory with host. Instead they allow host to designate part |
| 281 | /// of guest memory as "shared" ahead of guest starting its execution. The |
| 282 | /// shared memory region is indicated in swiotlb node. On such platforms use |
| 283 | /// a separate heap to allocate buffers that can be shared with host. |
| 284 | pub fn init_shared_pool(&mut self, range: Range<usize>) -> Result<()> { |
| 285 | let size = NonZeroUsize::new(range.len()).unwrap(); |
| 286 | let range = self.alloc_mut(range.start, size)?; |
| 287 | let shared_pool = LockedHeap::<32>::new(); |
| 288 | |
| 289 | // SAFETY - `range` should be a valid region of memory as validated by |
| 290 | // `validate_swiotlb_info` and not used by any other rust code. |
| 291 | unsafe { |
| 292 | shared_pool.lock().init(range.start, range.len()); |
| 293 | } |
| 294 | |
| 295 | SHARED_POOL |
| 296 | .set(Box::new(shared_pool)) |
| 297 | .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?; |
| 298 | |
| 299 | Ok(()) |
| 300 | } |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 301 | } |
| 302 | |
| 303 | impl Drop for MemoryTracker { |
| 304 | fn drop(&mut self) { |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 305 | for region in &self.regions { |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 306 | match region.mem_type { |
| 307 | MemoryType::ReadWrite => { |
Pierre-Clément Tosi | 73c2d64 | 2023-02-17 14:56:48 +0000 | [diff] [blame] | 308 | // TODO(b/269738062): Use PT's dirty bit to only flush pages that were touched. |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 309 | helpers::flush_region(region.range.start, region.range.len()) |
| 310 | } |
| 311 | MemoryType::ReadOnly => {} |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | } |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 316 | |
Andrew Walbran | 41ebe93 | 2022-12-14 15:22:30 +0000 | [diff] [blame] | 317 | /// Gives the KVM host read, write and execute permissions on the given memory range. If the range |
| 318 | /// is not aligned with the memory protection granule then it will be extended on either end to |
| 319 | /// align. |
Alice Wang | 90e6f16 | 2023-04-17 13:49:45 +0000 | [diff] [blame] | 320 | fn share_range(range: &MemoryRange, granule: usize) -> hyp::Result<()> { |
Pierre-Clément Tosi | 90238c5 | 2023-04-27 17:59:10 +0000 | [diff] [blame] | 321 | trace!("Sharing memory region {range:#x?}"); |
Andrew Walbran | 41ebe93 | 2022-12-14 15:22:30 +0000 | [diff] [blame] | 322 | for base in (align_down(range.start, granule) |
| 323 | .expect("Memory protection granule was not a power of two")..range.end) |
| 324 | .step_by(granule) |
| 325 | { |
Alice Wang | 3132911 | 2023-04-13 09:02:36 +0000 | [diff] [blame] | 326 | get_hypervisor().mem_share(base as u64)?; |
Andrew Walbran | 41ebe93 | 2022-12-14 15:22:30 +0000 | [diff] [blame] | 327 | } |
| 328 | Ok(()) |
| 329 | } |
| 330 | |
| 331 | /// Removes permission from the KVM host to access the given memory range which was previously |
| 332 | /// shared. If the range is not aligned with the memory protection granule then it will be extended |
| 333 | /// on either end to align. |
Alice Wang | 90e6f16 | 2023-04-17 13:49:45 +0000 | [diff] [blame] | 334 | fn unshare_range(range: &MemoryRange, granule: usize) -> hyp::Result<()> { |
Pierre-Clément Tosi | 90238c5 | 2023-04-27 17:59:10 +0000 | [diff] [blame] | 335 | trace!("Unsharing memory region {range:#x?}"); |
Andrew Walbran | 41ebe93 | 2022-12-14 15:22:30 +0000 | [diff] [blame] | 336 | for base in (align_down(range.start, granule) |
| 337 | .expect("Memory protection granule was not a power of two")..range.end) |
| 338 | .step_by(granule) |
| 339 | { |
Alice Wang | 3132911 | 2023-04-13 09:02:36 +0000 | [diff] [blame] | 340 | get_hypervisor().mem_unshare(base as u64)?; |
Andrew Walbran | 41ebe93 | 2022-12-14 15:22:30 +0000 | [diff] [blame] | 341 | } |
| 342 | Ok(()) |
| 343 | } |
| 344 | |
Srivatsa Vaddagiri | 37713ec | 2023-04-20 04:04:08 -0700 | [diff] [blame] | 345 | /// Allocates a memory range of at least the given size that is shared with |
| 346 | /// host. Returns a pointer to the buffer. |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 347 | /// |
| 348 | /// It will be aligned to the memory sharing granule size supported by the hypervisor. |
Pierre-Clément Tosi | 2d5bc58 | 2023-05-03 11:23:11 +0000 | [diff] [blame] | 349 | pub fn alloc_shared(layout: Layout) -> hyp::Result<NonNull<u8>> { |
| 350 | assert_ne!(layout.size(), 0); |
| 351 | let granule = get_hypervisor().memory_protection_granule()?; |
| 352 | let layout = layout.align_to(granule).unwrap().pad_to_align(); |
Srivatsa Vaddagiri | 37713ec | 2023-04-20 04:04:08 -0700 | [diff] [blame] | 353 | if let Some(shared_pool) = SHARED_POOL.get() { |
Pierre-Clément Tosi | 2d5bc58 | 2023-05-03 11:23:11 +0000 | [diff] [blame] | 354 | // SAFETY - layout has a non-zero size. |
Srivatsa Vaddagiri | 37713ec | 2023-04-20 04:04:08 -0700 | [diff] [blame] | 355 | let buffer = unsafe { shared_pool.alloc_zeroed(layout) }; |
| 356 | |
| 357 | let Some(buffer) = NonNull::new(buffer) else { |
| 358 | handle_alloc_error(layout); |
| 359 | }; |
| 360 | |
Pierre-Clément Tosi | 90238c5 | 2023-04-27 17:59:10 +0000 | [diff] [blame] | 361 | trace!("Allocated shared buffer at {buffer:?} with {layout:?}"); |
Srivatsa Vaddagiri | 37713ec | 2023-04-20 04:04:08 -0700 | [diff] [blame] | 362 | return Ok(buffer); |
| 363 | } |
| 364 | |
Pierre-Clément Tosi | 2d5bc58 | 2023-05-03 11:23:11 +0000 | [diff] [blame] | 365 | // SAFETY - layout has a non-zero size. |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 366 | let buffer = unsafe { alloc_zeroed(layout) }; |
| 367 | |
Pierre-Clément Tosi | ebb3760 | 2023-02-17 14:57:26 +0000 | [diff] [blame] | 368 | let Some(buffer) = NonNull::new(buffer) else { |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 369 | handle_alloc_error(layout); |
| 370 | }; |
| 371 | |
Andrew Walbran | 272bd7a | 2023-01-24 14:02:36 +0000 | [diff] [blame] | 372 | let paddr = virt_to_phys(buffer); |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 373 | // If share_range fails then we will leak the allocation, but that seems better than having it |
| 374 | // be reused while maybe still partially shared with the host. |
| 375 | share_range(&(paddr..paddr + layout.size()), granule)?; |
| 376 | |
Pierre-Clément Tosi | 90238c5 | 2023-04-27 17:59:10 +0000 | [diff] [blame] | 377 | trace!("Allocated shared memory at {buffer:?} with {layout:?}"); |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 378 | Ok(buffer) |
| 379 | } |
| 380 | |
| 381 | /// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`. |
| 382 | /// |
| 383 | /// The size passed in must be the size passed to the original `alloc_shared` call. |
| 384 | /// |
| 385 | /// # Safety |
| 386 | /// |
| 387 | /// The memory must have been allocated by `alloc_shared` with the same size, and not yet |
| 388 | /// deallocated. |
Pierre-Clément Tosi | 2d5bc58 | 2023-05-03 11:23:11 +0000 | [diff] [blame] | 389 | pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, layout: Layout) -> hyp::Result<()> { |
| 390 | let granule = get_hypervisor().memory_protection_granule()?; |
| 391 | let layout = layout.align_to(granule).unwrap().pad_to_align(); |
Srivatsa Vaddagiri | 37713ec | 2023-04-20 04:04:08 -0700 | [diff] [blame] | 392 | if let Some(shared_pool) = SHARED_POOL.get() { |
| 393 | // Safe because the memory was allocated by `alloc_shared` above using |
| 394 | // the same allocator, and the layout is the same as was used then. |
| 395 | unsafe { shared_pool.dealloc(vaddr.as_ptr(), layout) }; |
| 396 | |
Pierre-Clément Tosi | 90238c5 | 2023-04-27 17:59:10 +0000 | [diff] [blame] | 397 | trace!("Deallocated shared buffer at {vaddr:?} with {layout:?}"); |
Srivatsa Vaddagiri | 37713ec | 2023-04-20 04:04:08 -0700 | [diff] [blame] | 398 | return Ok(()); |
| 399 | } |
| 400 | |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 401 | let paddr = virt_to_phys(vaddr); |
| 402 | unshare_range(&(paddr..paddr + layout.size()), granule)?; |
| 403 | // Safe because the memory was allocated by `alloc_shared` above using the same allocator, and |
| 404 | // the layout is the same as was used then. |
Andrew Walbran | 272bd7a | 2023-01-24 14:02:36 +0000 | [diff] [blame] | 405 | unsafe { dealloc(vaddr.as_ptr(), layout) }; |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 406 | |
Pierre-Clément Tosi | 90238c5 | 2023-04-27 17:59:10 +0000 | [diff] [blame] | 407 | trace!("Deallocated shared memory at {vaddr:?} with {layout:?}"); |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 408 | Ok(()) |
| 409 | } |
| 410 | |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 411 | /// Returns an iterator which yields the base address of each 4 KiB page within the given range. |
| 412 | fn page_iterator(range: &MemoryRange) -> impl Iterator<Item = usize> { |
| 413 | (page_4kb_of(range.start)..range.end).step_by(SIZE_4KB) |
| 414 | } |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 415 | |
| 416 | /// Returns the intermediate physical address corresponding to the given virtual address. |
| 417 | /// |
Andrew Walbran | 272bd7a | 2023-01-24 14:02:36 +0000 | [diff] [blame] | 418 | /// As we use identity mapping for everything, this is just a cast, but it's useful to use it to be |
| 419 | /// explicit about where we are converting from virtual to physical address. |
| 420 | pub fn virt_to_phys(vaddr: NonNull<u8>) -> usize { |
| 421 | vaddr.as_ptr() as _ |
| 422 | } |
| 423 | |
| 424 | /// Returns a pointer for the virtual address corresponding to the given non-zero intermediate |
| 425 | /// physical address. |
| 426 | /// |
| 427 | /// Panics if `paddr` is 0. |
| 428 | pub fn phys_to_virt(paddr: usize) -> NonNull<u8> { |
| 429 | NonNull::new(paddr as _).unwrap() |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 430 | } |