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 | 164a6f5 | 2023-04-18 19:29:11 +0100 | [diff] [blame^] | 19 | use crate::helpers::{self, align_down, align_up, page_4kb_of, 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; |
| 24 | use core::alloc::Layout; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 25 | use core::cmp::max; |
| 26 | use core::cmp::min; |
| 27 | use core::fmt; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 28 | use core::num::NonZeroUsize; |
| 29 | use core::ops::Range; |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 30 | use core::ptr::NonNull; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 31 | use core::result; |
Alice Wang | 3132911 | 2023-04-13 09:02:36 +0000 | [diff] [blame] | 32 | use hyp::{get_hypervisor, mmio_guard}; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 33 | use log::error; |
Pierre-Clément Tosi | 328dfb6 | 2022-11-25 18:20:42 +0000 | [diff] [blame] | 34 | use tinyvec::ArrayVec; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 35 | |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 36 | /// Base of the system's contiguous "main" memory. |
| 37 | pub const BASE_ADDR: usize = 0x8000_0000; |
| 38 | /// First address that can't be translated by a level 1 TTBR0_EL1. |
| 39 | pub const MAX_ADDR: usize = 1 << 40; |
| 40 | |
Andrew Walbran | 0d8b54d | 2022-12-08 16:32:33 +0000 | [diff] [blame] | 41 | pub type MemoryRange = Range<usize>; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 42 | |
Pierre-Clément Tosi | 328dfb6 | 2022-11-25 18:20:42 +0000 | [diff] [blame] | 43 | #[derive(Clone, Copy, Debug, Default)] |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 44 | enum MemoryType { |
Pierre-Clément Tosi | 328dfb6 | 2022-11-25 18:20:42 +0000 | [diff] [blame] | 45 | #[default] |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 46 | ReadOnly, |
| 47 | ReadWrite, |
| 48 | } |
| 49 | |
Pierre-Clément Tosi | 328dfb6 | 2022-11-25 18:20:42 +0000 | [diff] [blame] | 50 | #[derive(Clone, Debug, Default)] |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 51 | struct MemoryRegion { |
| 52 | range: MemoryRange, |
| 53 | mem_type: MemoryType, |
| 54 | } |
| 55 | |
| 56 | impl MemoryRegion { |
| 57 | /// True if the instance overlaps with the passed range. |
| 58 | pub fn overlaps(&self, range: &MemoryRange) -> bool { |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 59 | overlaps(&self.range, range) |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 60 | } |
| 61 | |
| 62 | /// True if the instance is fully contained within the passed range. |
| 63 | pub fn is_within(&self, range: &MemoryRange) -> bool { |
| 64 | let our: &MemoryRange = self.as_ref(); |
| 65 | self.as_ref() == &(max(our.start, range.start)..min(our.end, range.end)) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | impl AsRef<MemoryRange> for MemoryRegion { |
| 70 | fn as_ref(&self) -> &MemoryRange { |
| 71 | &self.range |
| 72 | } |
| 73 | } |
| 74 | |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 75 | /// Returns true if one range overlaps with the other at all. |
| 76 | fn overlaps<T: Copy + Ord>(a: &Range<T>, b: &Range<T>) -> bool { |
| 77 | max(a.start, b.start) < min(a.end, b.end) |
| 78 | } |
| 79 | |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 80 | /// Tracks non-overlapping slices of main memory. |
| 81 | pub struct MemoryTracker { |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 82 | total: MemoryRange, |
| 83 | page_table: mmu::PageTable, |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 84 | regions: ArrayVec<[MemoryRegion; MemoryTracker::CAPACITY]>, |
| 85 | mmio_regions: ArrayVec<[MemoryRange; MemoryTracker::MMIO_CAPACITY]>, |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 86 | } |
| 87 | |
| 88 | /// Errors for MemoryTracker operations. |
| 89 | #[derive(Debug, Clone)] |
| 90 | pub enum MemoryTrackerError { |
| 91 | /// Tried to modify the memory base address. |
| 92 | DifferentBaseAddress, |
| 93 | /// Tried to shrink to a larger memory size. |
| 94 | SizeTooLarge, |
| 95 | /// Tracked regions would not fit in memory size. |
| 96 | SizeTooSmall, |
| 97 | /// Reached limit number of tracked regions. |
| 98 | Full, |
| 99 | /// Region is out of the tracked memory address space. |
| 100 | OutOfRange, |
| 101 | /// New region overlaps with tracked regions. |
| 102 | Overlaps, |
| 103 | /// Region couldn't be mapped. |
| 104 | FailedToMap, |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 105 | /// Error from an MMIO guard call. |
| 106 | MmioGuard(mmio_guard::Error), |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 107 | } |
| 108 | |
| 109 | impl fmt::Display for MemoryTrackerError { |
| 110 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 111 | match self { |
| 112 | Self::DifferentBaseAddress => write!(f, "Received different base address"), |
| 113 | Self::SizeTooLarge => write!(f, "Tried to shrink to a larger memory size"), |
| 114 | Self::SizeTooSmall => write!(f, "Tracked regions would not fit in memory size"), |
| 115 | Self::Full => write!(f, "Reached limit number of tracked regions"), |
| 116 | Self::OutOfRange => write!(f, "Region is out of the tracked memory address space"), |
| 117 | Self::Overlaps => write!(f, "New region overlaps with tracked regions"), |
| 118 | Self::FailedToMap => write!(f, "Failed to map the new region"), |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 119 | Self::MmioGuard(e) => e.fmt(f), |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 124 | impl From<mmio_guard::Error> for MemoryTrackerError { |
| 125 | fn from(e: mmio_guard::Error) -> Self { |
| 126 | Self::MmioGuard(e) |
| 127 | } |
| 128 | } |
| 129 | |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 130 | type Result<T> = result::Result<T, MemoryTrackerError>; |
| 131 | |
| 132 | impl MemoryTracker { |
| 133 | const CAPACITY: usize = 5; |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 134 | const MMIO_CAPACITY: usize = 5; |
Pierre-Clément Tosi | 164a6f5 | 2023-04-18 19:29:11 +0100 | [diff] [blame^] | 135 | const PVMFW_RANGE: MemoryRange = (BASE_ADDR - SIZE_4MB)..BASE_ADDR; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 136 | |
| 137 | /// Create a new instance from an active page table, covering the maximum RAM size. |
| 138 | pub fn new(page_table: mmu::PageTable) -> Self { |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 139 | Self { |
Jiyong Park | 0ee6539 | 2023-03-27 20:52:45 +0900 | [diff] [blame] | 140 | total: BASE_ADDR..MAX_ADDR, |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 141 | page_table, |
| 142 | regions: ArrayVec::new(), |
| 143 | mmio_regions: ArrayVec::new(), |
| 144 | } |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 145 | } |
| 146 | |
| 147 | /// Resize the total RAM size. |
| 148 | /// |
| 149 | /// This function fails if it contains regions that are not included within the new size. |
| 150 | pub fn shrink(&mut self, range: &MemoryRange) -> Result<()> { |
| 151 | if range.start != self.total.start { |
| 152 | return Err(MemoryTrackerError::DifferentBaseAddress); |
| 153 | } |
| 154 | if self.total.end < range.end { |
| 155 | return Err(MemoryTrackerError::SizeTooLarge); |
| 156 | } |
Pierre-Clément Tosi | 328dfb6 | 2022-11-25 18:20:42 +0000 | [diff] [blame] | 157 | if !self.regions.iter().all(|r| r.is_within(range)) { |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 158 | return Err(MemoryTrackerError::SizeTooSmall); |
| 159 | } |
| 160 | |
| 161 | self.total = range.clone(); |
| 162 | Ok(()) |
| 163 | } |
| 164 | |
| 165 | /// Allocate the address range for a const slice; returns None if failed. |
| 166 | pub fn alloc_range(&mut self, range: &MemoryRange) -> Result<MemoryRange> { |
Andrew Walbran | da65ab1 | 2022-12-07 15:10:13 +0000 | [diff] [blame] | 167 | let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadOnly }; |
| 168 | self.check(®ion)?; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 169 | self.page_table.map_rodata(range).map_err(|e| { |
| 170 | error!("Error during range allocation: {e}"); |
| 171 | MemoryTrackerError::FailedToMap |
| 172 | })?; |
Andrew Walbran | da65ab1 | 2022-12-07 15:10:13 +0000 | [diff] [blame] | 173 | self.add(region) |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 174 | } |
| 175 | |
| 176 | /// Allocate the address range for a mutable slice; returns None if failed. |
| 177 | pub fn alloc_range_mut(&mut self, range: &MemoryRange) -> Result<MemoryRange> { |
Andrew Walbran | da65ab1 | 2022-12-07 15:10:13 +0000 | [diff] [blame] | 178 | let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadWrite }; |
| 179 | self.check(®ion)?; |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 180 | self.page_table.map_data(range).map_err(|e| { |
| 181 | error!("Error during mutable range allocation: {e}"); |
| 182 | MemoryTrackerError::FailedToMap |
| 183 | })?; |
Andrew Walbran | da65ab1 | 2022-12-07 15:10:13 +0000 | [diff] [blame] | 184 | self.add(region) |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 185 | } |
| 186 | |
| 187 | /// Allocate the address range for a const slice; returns None if failed. |
| 188 | pub fn alloc(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> { |
| 189 | self.alloc_range(&(base..(base + size.get()))) |
| 190 | } |
| 191 | |
| 192 | /// Allocate the address range for a mutable slice; returns None if failed. |
| 193 | pub fn alloc_mut(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> { |
| 194 | self.alloc_range_mut(&(base..(base + size.get()))) |
| 195 | } |
| 196 | |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 197 | /// Checks that the given range of addresses is within the MMIO region, and then maps it |
| 198 | /// appropriately. |
| 199 | pub fn map_mmio_range(&mut self, range: MemoryRange) -> Result<()> { |
| 200 | // MMIO space is below the main memory region. |
Pierre-Clément Tosi | 164a6f5 | 2023-04-18 19:29:11 +0100 | [diff] [blame^] | 201 | if range.end > self.total.start || overlaps(&Self::PVMFW_RANGE, &range) { |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 202 | return Err(MemoryTrackerError::OutOfRange); |
| 203 | } |
| 204 | if self.mmio_regions.iter().any(|r| overlaps(r, &range)) { |
| 205 | return Err(MemoryTrackerError::Overlaps); |
| 206 | } |
| 207 | if self.mmio_regions.len() == self.mmio_regions.capacity() { |
| 208 | return Err(MemoryTrackerError::Full); |
| 209 | } |
| 210 | |
| 211 | self.page_table.map_device(&range).map_err(|e| { |
| 212 | error!("Error during MMIO device mapping: {e}"); |
| 213 | MemoryTrackerError::FailedToMap |
| 214 | })?; |
| 215 | |
| 216 | for page_base in page_iterator(&range) { |
| 217 | mmio_guard::map(page_base)?; |
| 218 | } |
| 219 | |
| 220 | if self.mmio_regions.try_push(range).is_some() { |
| 221 | return Err(MemoryTrackerError::Full); |
| 222 | } |
| 223 | |
| 224 | Ok(()) |
| 225 | } |
| 226 | |
Andrew Walbran | da65ab1 | 2022-12-07 15:10:13 +0000 | [diff] [blame] | 227 | /// Checks that the given region is within the range of the `MemoryTracker` and doesn't overlap |
| 228 | /// with any other previously allocated regions, and that the regions ArrayVec has capacity to |
| 229 | /// add it. |
| 230 | fn check(&self, region: &MemoryRegion) -> Result<()> { |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 231 | if !region.is_within(&self.total) { |
| 232 | return Err(MemoryTrackerError::OutOfRange); |
| 233 | } |
Andrew Walbran | da65ab1 | 2022-12-07 15:10:13 +0000 | [diff] [blame] | 234 | if self.regions.iter().any(|r| r.overlaps(®ion.range)) { |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 235 | return Err(MemoryTrackerError::Overlaps); |
| 236 | } |
Andrew Walbran | da65ab1 | 2022-12-07 15:10:13 +0000 | [diff] [blame] | 237 | if self.regions.len() == self.regions.capacity() { |
| 238 | return Err(MemoryTrackerError::Full); |
| 239 | } |
| 240 | Ok(()) |
| 241 | } |
| 242 | |
| 243 | fn add(&mut self, region: MemoryRegion) -> Result<MemoryRange> { |
Pierre-Clément Tosi | 328dfb6 | 2022-11-25 18:20:42 +0000 | [diff] [blame] | 244 | if self.regions.try_push(region).is_some() { |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 245 | return Err(MemoryTrackerError::Full); |
| 246 | } |
| 247 | |
Pierre-Clément Tosi | 328dfb6 | 2022-11-25 18:20:42 +0000 | [diff] [blame] | 248 | Ok(self.regions.last().unwrap().as_ref().clone()) |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 249 | } |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 250 | |
| 251 | /// Unmaps all tracked MMIO regions from the MMIO guard. |
| 252 | /// |
| 253 | /// Note that they are not unmapped from the page table. |
| 254 | pub fn mmio_unmap_all(&self) -> Result<()> { |
| 255 | for region in &self.mmio_regions { |
| 256 | for page_base in page_iterator(region) { |
| 257 | mmio_guard::unmap(page_base)?; |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | Ok(()) |
| 262 | } |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 263 | } |
| 264 | |
| 265 | impl Drop for MemoryTracker { |
| 266 | fn drop(&mut self) { |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 267 | for region in &self.regions { |
Pierre-Clément Tosi | a0934c1 | 2022-11-25 20:54:11 +0000 | [diff] [blame] | 268 | match region.mem_type { |
| 269 | MemoryType::ReadWrite => { |
Pierre-Clément Tosi | 73c2d64 | 2023-02-17 14:56:48 +0000 | [diff] [blame] | 270 | // 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] | 271 | helpers::flush_region(region.range.start, region.range.len()) |
| 272 | } |
| 273 | MemoryType::ReadOnly => {} |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | } |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 278 | |
Andrew Walbran | 41ebe93 | 2022-12-14 15:22:30 +0000 | [diff] [blame] | 279 | /// Gives the KVM host read, write and execute permissions on the given memory range. If the range |
| 280 | /// is not aligned with the memory protection granule then it will be extended on either end to |
| 281 | /// align. |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 282 | fn share_range(range: &MemoryRange, granule: usize) -> smccc::Result<()> { |
Andrew Walbran | 41ebe93 | 2022-12-14 15:22:30 +0000 | [diff] [blame] | 283 | for base in (align_down(range.start, granule) |
| 284 | .expect("Memory protection granule was not a power of two")..range.end) |
| 285 | .step_by(granule) |
| 286 | { |
Alice Wang | 3132911 | 2023-04-13 09:02:36 +0000 | [diff] [blame] | 287 | get_hypervisor().mem_share(base as u64)?; |
Andrew Walbran | 41ebe93 | 2022-12-14 15:22:30 +0000 | [diff] [blame] | 288 | } |
| 289 | Ok(()) |
| 290 | } |
| 291 | |
| 292 | /// Removes permission from the KVM host to access the given memory range which was previously |
| 293 | /// shared. If the range is not aligned with the memory protection granule then it will be extended |
| 294 | /// on either end to align. |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 295 | fn unshare_range(range: &MemoryRange, granule: usize) -> smccc::Result<()> { |
Andrew Walbran | 41ebe93 | 2022-12-14 15:22:30 +0000 | [diff] [blame] | 296 | for base in (align_down(range.start, granule) |
| 297 | .expect("Memory protection granule was not a power of two")..range.end) |
| 298 | .step_by(granule) |
| 299 | { |
Alice Wang | 3132911 | 2023-04-13 09:02:36 +0000 | [diff] [blame] | 300 | get_hypervisor().mem_unshare(base as u64)?; |
Andrew Walbran | 41ebe93 | 2022-12-14 15:22:30 +0000 | [diff] [blame] | 301 | } |
| 302 | Ok(()) |
| 303 | } |
| 304 | |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 305 | /// Allocates a memory range of at least the given size from the global allocator, and shares it |
| 306 | /// with the host. Returns a pointer to the buffer. |
| 307 | /// |
| 308 | /// It will be aligned to the memory sharing granule size supported by the hypervisor. |
| 309 | pub fn alloc_shared(size: usize) -> smccc::Result<NonNull<u8>> { |
| 310 | let layout = shared_buffer_layout(size)?; |
| 311 | let granule = layout.align(); |
| 312 | |
| 313 | // Safe because `shared_buffer_layout` panics if the size is 0, so the layout must have a |
| 314 | // non-zero size. |
| 315 | let buffer = unsafe { alloc_zeroed(layout) }; |
| 316 | |
Pierre-Clément Tosi | ebb3760 | 2023-02-17 14:57:26 +0000 | [diff] [blame] | 317 | let Some(buffer) = NonNull::new(buffer) else { |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 318 | handle_alloc_error(layout); |
| 319 | }; |
| 320 | |
Andrew Walbran | 272bd7a | 2023-01-24 14:02:36 +0000 | [diff] [blame] | 321 | let paddr = virt_to_phys(buffer); |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 322 | // If share_range fails then we will leak the allocation, but that seems better than having it |
| 323 | // be reused while maybe still partially shared with the host. |
| 324 | share_range(&(paddr..paddr + layout.size()), granule)?; |
| 325 | |
| 326 | Ok(buffer) |
| 327 | } |
| 328 | |
| 329 | /// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`. |
| 330 | /// |
| 331 | /// The size passed in must be the size passed to the original `alloc_shared` call. |
| 332 | /// |
| 333 | /// # Safety |
| 334 | /// |
| 335 | /// The memory must have been allocated by `alloc_shared` with the same size, and not yet |
| 336 | /// deallocated. |
Andrew Walbran | 272bd7a | 2023-01-24 14:02:36 +0000 | [diff] [blame] | 337 | pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, size: usize) -> smccc::Result<()> { |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 338 | let layout = shared_buffer_layout(size)?; |
| 339 | let granule = layout.align(); |
| 340 | |
| 341 | let paddr = virt_to_phys(vaddr); |
| 342 | unshare_range(&(paddr..paddr + layout.size()), granule)?; |
| 343 | // Safe because the memory was allocated by `alloc_shared` above using the same allocator, and |
| 344 | // the layout is the same as was used then. |
Andrew Walbran | 272bd7a | 2023-01-24 14:02:36 +0000 | [diff] [blame] | 345 | unsafe { dealloc(vaddr.as_ptr(), layout) }; |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 346 | |
| 347 | Ok(()) |
| 348 | } |
| 349 | |
| 350 | /// Returns the layout to use for allocating a buffer of at least the given size shared with the |
| 351 | /// host. |
| 352 | /// |
| 353 | /// It will be aligned to the memory sharing granule size supported by the hypervisor. |
| 354 | /// |
| 355 | /// Panics if `size` is 0. |
| 356 | fn shared_buffer_layout(size: usize) -> smccc::Result<Layout> { |
| 357 | assert_ne!(size, 0); |
Alice Wang | 3132911 | 2023-04-13 09:02:36 +0000 | [diff] [blame] | 358 | let granule = get_hypervisor().memory_protection_granule()?; |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 359 | let allocated_size = |
| 360 | align_up(size, granule).expect("Memory protection granule was not a power of two"); |
| 361 | Ok(Layout::from_size_align(allocated_size, granule).unwrap()) |
| 362 | } |
| 363 | |
Andrew Walbran | 1969063 | 2022-12-07 16:41:30 +0000 | [diff] [blame] | 364 | /// Returns an iterator which yields the base address of each 4 KiB page within the given range. |
| 365 | fn page_iterator(range: &MemoryRange) -> impl Iterator<Item = usize> { |
| 366 | (page_4kb_of(range.start)..range.end).step_by(SIZE_4KB) |
| 367 | } |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 368 | |
| 369 | /// Returns the intermediate physical address corresponding to the given virtual address. |
| 370 | /// |
Andrew Walbran | 272bd7a | 2023-01-24 14:02:36 +0000 | [diff] [blame] | 371 | /// As we use identity mapping for everything, this is just a cast, but it's useful to use it to be |
| 372 | /// explicit about where we are converting from virtual to physical address. |
| 373 | pub fn virt_to_phys(vaddr: NonNull<u8>) -> usize { |
| 374 | vaddr.as_ptr() as _ |
| 375 | } |
| 376 | |
| 377 | /// Returns a pointer for the virtual address corresponding to the given non-zero intermediate |
| 378 | /// physical address. |
| 379 | /// |
| 380 | /// Panics if `paddr` is 0. |
| 381 | pub fn phys_to_virt(paddr: usize) -> NonNull<u8> { |
| 382 | NonNull::new(paddr as _).unwrap() |
Andrew Walbran | 848decf | 2022-12-15 14:39:38 +0000 | [diff] [blame] | 383 | } |