blob: 16c1a3706ed71c315eed32cb38f28eb19c586cfc [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;
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -070024use alloc::boxed::Box;
25use buddy_system_allocator::LockedHeap;
26use core::alloc::GlobalAlloc as _;
Andrew Walbran848decf2022-12-15 14:39:38 +000027use 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;
Alice Wang90e6f162023-04-17 13:49:45 +000035use hyp::get_hypervisor;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000036use log::error;
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +000037use log::trace;
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -070038use once_cell::race::OnceBox;
Jakob Vukalovic85a00d72023-04-20 09:51:10 +010039use spin::mutex::SpinMutex;
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000040use tinyvec::ArrayVec;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000041
Jiyong Park0ee65392023-03-27 20:52:45 +090042/// Base of the system's contiguous "main" memory.
43pub const BASE_ADDR: usize = 0x8000_0000;
44/// First address that can't be translated by a level 1 TTBR0_EL1.
45pub const MAX_ADDR: usize = 1 << 40;
46
Andrew Walbran0d8b54d2022-12-08 16:32:33 +000047pub type MemoryRange = Range<usize>;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000048
Jakob Vukalovic85a00d72023-04-20 09:51:10 +010049pub static MEMORY: SpinMutex<Option<MemoryTracker>> = SpinMutex::new(None);
50unsafe impl Send for MemoryTracker {}
51
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000052#[derive(Clone, Copy, Debug, Default)]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000053enum MemoryType {
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000054 #[default]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000055 ReadOnly,
56 ReadWrite,
57}
58
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000059#[derive(Clone, Debug, Default)]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000060struct MemoryRegion {
61 range: MemoryRange,
62 mem_type: MemoryType,
63}
64
65impl MemoryRegion {
66 /// True if the instance overlaps with the passed range.
67 pub fn overlaps(&self, range: &MemoryRange) -> bool {
Andrew Walbran19690632022-12-07 16:41:30 +000068 overlaps(&self.range, range)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000069 }
70
71 /// True if the instance is fully contained within the passed range.
72 pub fn is_within(&self, range: &MemoryRange) -> bool {
Srivatsa Vaddagiric25d68e2023-04-19 22:56:33 -070073 self.as_ref().is_within(range)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000074 }
75}
76
77impl AsRef<MemoryRange> for MemoryRegion {
78 fn as_ref(&self) -> &MemoryRange {
79 &self.range
80 }
81}
82
Andrew Walbran19690632022-12-07 16:41:30 +000083/// Returns true if one range overlaps with the other at all.
84fn 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 Tosia0934c12022-11-25 20:54:11 +000088/// Tracks non-overlapping slices of main memory.
89pub struct MemoryTracker {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000090 total: MemoryRange,
91 page_table: mmu::PageTable,
Andrew Walbran19690632022-12-07 16:41:30 +000092 regions: ArrayVec<[MemoryRegion; MemoryTracker::CAPACITY]>,
93 mmio_regions: ArrayVec<[MemoryRange; MemoryTracker::MMIO_CAPACITY]>,
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000094}
95
96/// Errors for MemoryTracker operations.
97#[derive(Debug, Clone)]
98pub 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 Wang90e6f162023-04-17 13:49:45 +0000113 /// Error from the interaction with the hypervisor.
114 Hypervisor(hyp::Error),
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700115 /// Failure to set `SHARED_POOL`.
116 SharedPoolSetFailure,
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000117}
118
119impl 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 Wang90e6f162023-04-17 13:49:45 +0000129 Self::Hypervisor(e) => e.fmt(f),
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700130 Self::SharedPoolSetFailure => write!(f, "Failed to set SHARED_POOL"),
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000131 }
132 }
133}
134
Alice Wang90e6f162023-04-17 13:49:45 +0000135impl From<hyp::Error> for MemoryTrackerError {
136 fn from(e: hyp::Error) -> Self {
137 Self::Hypervisor(e)
Andrew Walbran19690632022-12-07 16:41:30 +0000138 }
139}
140
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000141type Result<T> = result::Result<T, MemoryTrackerError>;
142
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700143static SHARED_POOL: OnceBox<LockedHeap<32>> = OnceBox::new();
144
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000145impl MemoryTracker {
146 const CAPACITY: usize = 5;
Andrew Walbran19690632022-12-07 16:41:30 +0000147 const MMIO_CAPACITY: usize = 5;
Pierre-Clément Tosi164a6f52023-04-18 19:29:11 +0100148 const PVMFW_RANGE: MemoryRange = (BASE_ADDR - SIZE_4MB)..BASE_ADDR;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000149
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 Walbran19690632022-12-07 16:41:30 +0000152 Self {
Jiyong Park0ee65392023-03-27 20:52:45 +0900153 total: BASE_ADDR..MAX_ADDR,
Andrew Walbran19690632022-12-07 16:41:30 +0000154 page_table,
155 regions: ArrayVec::new(),
156 mmio_regions: ArrayVec::new(),
157 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000158 }
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 Tosi328dfb62022-11-25 18:20:42 +0000170 if !self.regions.iter().all(|r| r.is_within(range)) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000171 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 Walbranda65ab12022-12-07 15:10:13 +0000180 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadOnly };
181 self.check(&region)?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000182 self.page_table.map_rodata(range).map_err(|e| {
183 error!("Error during range allocation: {e}");
184 MemoryTrackerError::FailedToMap
185 })?;
Andrew Walbranda65ab12022-12-07 15:10:13 +0000186 self.add(region)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000187 }
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 Walbranda65ab12022-12-07 15:10:13 +0000191 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadWrite };
192 self.check(&region)?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000193 self.page_table.map_data(range).map_err(|e| {
194 error!("Error during mutable range allocation: {e}");
195 MemoryTrackerError::FailedToMap
196 })?;
Andrew Walbranda65ab12022-12-07 15:10:13 +0000197 self.add(region)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000198 }
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 Walbran19690632022-12-07 16:41:30 +0000210 /// 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 Tosi164a6f52023-04-18 19:29:11 +0100214 if range.end > self.total.start || overlaps(&Self::PVMFW_RANGE, &range) {
Andrew Walbran19690632022-12-07 16:41:30 +0000215 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 Wang90e6f162023-04-17 13:49:45 +0000230 get_hypervisor().mmio_guard_map(page_base)?;
Andrew Walbran19690632022-12-07 16:41:30 +0000231 }
232
233 if self.mmio_regions.try_push(range).is_some() {
234 return Err(MemoryTrackerError::Full);
235 }
236
237 Ok(())
238 }
239
Andrew Walbranda65ab12022-12-07 15:10:13 +0000240 /// 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 Tosia0934c12022-11-25 20:54:11 +0000244 if !region.is_within(&self.total) {
245 return Err(MemoryTrackerError::OutOfRange);
246 }
Andrew Walbranda65ab12022-12-07 15:10:13 +0000247 if self.regions.iter().any(|r| r.overlaps(&region.range)) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000248 return Err(MemoryTrackerError::Overlaps);
249 }
Andrew Walbranda65ab12022-12-07 15:10:13 +0000250 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 Tosi328dfb62022-11-25 18:20:42 +0000257 if self.regions.try_push(region).is_some() {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000258 return Err(MemoryTrackerError::Full);
259 }
260
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000261 Ok(self.regions.last().unwrap().as_ref().clone())
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000262 }
Andrew Walbran19690632022-12-07 16:41:30 +0000263
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 Wang90e6f162023-04-17 13:49:45 +0000270 get_hypervisor().mmio_guard_unmap(page_base)?;
Andrew Walbran19690632022-12-07 16:41:30 +0000271 }
272 }
273
274 Ok(())
275 }
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700276
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 Tosia0934c12022-11-25 20:54:11 +0000301}
302
303impl Drop for MemoryTracker {
304 fn drop(&mut self) {
Andrew Walbran19690632022-12-07 16:41:30 +0000305 for region in &self.regions {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000306 match region.mem_type {
307 MemoryType::ReadWrite => {
Pierre-Clément Tosi73c2d642023-02-17 14:56:48 +0000308 // TODO(b/269738062): Use PT's dirty bit to only flush pages that were touched.
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000309 helpers::flush_region(region.range.start, region.range.len())
310 }
311 MemoryType::ReadOnly => {}
312 }
313 }
314 }
315}
Andrew Walbran19690632022-12-07 16:41:30 +0000316
Andrew Walbran41ebe932022-12-14 15:22:30 +0000317/// 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 Wang90e6f162023-04-17 13:49:45 +0000320fn share_range(range: &MemoryRange, granule: usize) -> hyp::Result<()> {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000321 trace!("Sharing memory region {range:#x?}");
Andrew Walbran41ebe932022-12-14 15:22:30 +0000322 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 Wang31329112023-04-13 09:02:36 +0000326 get_hypervisor().mem_share(base as u64)?;
Andrew Walbran41ebe932022-12-14 15:22:30 +0000327 }
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 Wang90e6f162023-04-17 13:49:45 +0000334fn unshare_range(range: &MemoryRange, granule: usize) -> hyp::Result<()> {
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000335 trace!("Unsharing memory region {range:#x?}");
Andrew Walbran41ebe932022-12-14 15:22:30 +0000336 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 Wang31329112023-04-13 09:02:36 +0000340 get_hypervisor().mem_unshare(base as u64)?;
Andrew Walbran41ebe932022-12-14 15:22:30 +0000341 }
342 Ok(())
343}
344
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700345/// Allocates a memory range of at least the given size that is shared with
346/// host. Returns a pointer to the buffer.
Andrew Walbran848decf2022-12-15 14:39:38 +0000347///
348/// It will be aligned to the memory sharing granule size supported by the hypervisor.
Alice Wang90e6f162023-04-17 13:49:45 +0000349pub fn alloc_shared(size: usize) -> hyp::Result<NonNull<u8>> {
Andrew Walbran848decf2022-12-15 14:39:38 +0000350 let layout = shared_buffer_layout(size)?;
351 let granule = layout.align();
352
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700353 if let Some(shared_pool) = SHARED_POOL.get() {
354 // Safe because `shared_buffer_layout` panics if the size is 0, so the
355 // layout must have a non-zero size.
356 let buffer = unsafe { shared_pool.alloc_zeroed(layout) };
357
358 let Some(buffer) = NonNull::new(buffer) else {
359 handle_alloc_error(layout);
360 };
361
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000362 trace!("Allocated shared buffer at {buffer:?} with {layout:?}");
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700363 return Ok(buffer);
364 }
365
Andrew Walbran848decf2022-12-15 14:39:38 +0000366 // Safe because `shared_buffer_layout` panics if the size is 0, so the layout must have a
367 // non-zero size.
368 let buffer = unsafe { alloc_zeroed(layout) };
369
Pierre-Clément Tosiebb37602023-02-17 14:57:26 +0000370 let Some(buffer) = NonNull::new(buffer) else {
Andrew Walbran848decf2022-12-15 14:39:38 +0000371 handle_alloc_error(layout);
372 };
373
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000374 let paddr = virt_to_phys(buffer);
Andrew Walbran848decf2022-12-15 14:39:38 +0000375 // If share_range fails then we will leak the allocation, but that seems better than having it
376 // be reused while maybe still partially shared with the host.
377 share_range(&(paddr..paddr + layout.size()), granule)?;
378
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000379 trace!("Allocated shared memory at {buffer:?} with {layout:?}");
Andrew Walbran848decf2022-12-15 14:39:38 +0000380 Ok(buffer)
381}
382
383/// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`.
384///
385/// The size passed in must be the size passed to the original `alloc_shared` call.
386///
387/// # Safety
388///
389/// The memory must have been allocated by `alloc_shared` with the same size, and not yet
390/// deallocated.
Alice Wang90e6f162023-04-17 13:49:45 +0000391pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, size: usize) -> hyp::Result<()> {
Andrew Walbran848decf2022-12-15 14:39:38 +0000392 let layout = shared_buffer_layout(size)?;
393 let granule = layout.align();
394
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700395 if let Some(shared_pool) = SHARED_POOL.get() {
396 // Safe because the memory was allocated by `alloc_shared` above using
397 // the same allocator, and the layout is the same as was used then.
398 unsafe { shared_pool.dealloc(vaddr.as_ptr(), layout) };
399
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000400 trace!("Deallocated shared buffer at {vaddr:?} with {layout:?}");
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700401 return Ok(());
402 }
403
Andrew Walbran848decf2022-12-15 14:39:38 +0000404 let paddr = virt_to_phys(vaddr);
405 unshare_range(&(paddr..paddr + layout.size()), granule)?;
406 // Safe because the memory was allocated by `alloc_shared` above using the same allocator, and
407 // the layout is the same as was used then.
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000408 unsafe { dealloc(vaddr.as_ptr(), layout) };
Andrew Walbran848decf2022-12-15 14:39:38 +0000409
Pierre-Clément Tosi90238c52023-04-27 17:59:10 +0000410 trace!("Deallocated shared memory at {vaddr:?} with {layout:?}");
Andrew Walbran848decf2022-12-15 14:39:38 +0000411 Ok(())
412}
413
414/// Returns the layout to use for allocating a buffer of at least the given size shared with the
415/// host.
416///
417/// It will be aligned to the memory sharing granule size supported by the hypervisor.
418///
419/// Panics if `size` is 0.
Alice Wang90e6f162023-04-17 13:49:45 +0000420fn shared_buffer_layout(size: usize) -> hyp::Result<Layout> {
Andrew Walbran848decf2022-12-15 14:39:38 +0000421 assert_ne!(size, 0);
Alice Wang31329112023-04-13 09:02:36 +0000422 let granule = get_hypervisor().memory_protection_granule()?;
Andrew Walbran848decf2022-12-15 14:39:38 +0000423 let allocated_size =
424 align_up(size, granule).expect("Memory protection granule was not a power of two");
425 Ok(Layout::from_size_align(allocated_size, granule).unwrap())
426}
427
Andrew Walbran19690632022-12-07 16:41:30 +0000428/// Returns an iterator which yields the base address of each 4 KiB page within the given range.
429fn page_iterator(range: &MemoryRange) -> impl Iterator<Item = usize> {
430 (page_4kb_of(range.start)..range.end).step_by(SIZE_4KB)
431}
Andrew Walbran848decf2022-12-15 14:39:38 +0000432
433/// Returns the intermediate physical address corresponding to the given virtual address.
434///
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000435/// As we use identity mapping for everything, this is just a cast, but it's useful to use it to be
436/// explicit about where we are converting from virtual to physical address.
437pub fn virt_to_phys(vaddr: NonNull<u8>) -> usize {
438 vaddr.as_ptr() as _
439}
440
441/// Returns a pointer for the virtual address corresponding to the given non-zero intermediate
442/// physical address.
443///
444/// Panics if `paddr` is 0.
445pub fn phys_to_virt(paddr: usize) -> NonNull<u8> {
446 NonNull::new(paddr as _).unwrap()
Andrew Walbran848decf2022-12-15 14:39:38 +0000447}