blob: a2b7e09d439185f88eafcfb21ed396e5e9d2cf78 [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;
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -070037use once_cell::race::OnceBox;
Jakob Vukalovic85a00d72023-04-20 09:51:10 +010038use spin::mutex::SpinMutex;
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000039use tinyvec::ArrayVec;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000040
Jiyong Park0ee65392023-03-27 20:52:45 +090041/// Base of the system's contiguous "main" memory.
42pub const BASE_ADDR: usize = 0x8000_0000;
43/// First address that can't be translated by a level 1 TTBR0_EL1.
44pub const MAX_ADDR: usize = 1 << 40;
45
Andrew Walbran0d8b54d2022-12-08 16:32:33 +000046pub type MemoryRange = Range<usize>;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000047
Jakob Vukalovic85a00d72023-04-20 09:51:10 +010048pub static MEMORY: SpinMutex<Option<MemoryTracker>> = SpinMutex::new(None);
49unsafe impl Send for MemoryTracker {}
50
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000051#[derive(Clone, Copy, Debug, Default)]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000052enum MemoryType {
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000053 #[default]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000054 ReadOnly,
55 ReadWrite,
56}
57
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +000058#[derive(Clone, Debug, Default)]
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000059struct MemoryRegion {
60 range: MemoryRange,
61 mem_type: MemoryType,
62}
63
64impl MemoryRegion {
65 /// True if the instance overlaps with the passed range.
66 pub fn overlaps(&self, range: &MemoryRange) -> bool {
Andrew Walbran19690632022-12-07 16:41:30 +000067 overlaps(&self.range, range)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000068 }
69
70 /// True if the instance is fully contained within the passed range.
71 pub fn is_within(&self, range: &MemoryRange) -> bool {
Srivatsa Vaddagiric25d68e2023-04-19 22:56:33 -070072 self.as_ref().is_within(range)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000073 }
74}
75
76impl AsRef<MemoryRange> for MemoryRegion {
77 fn as_ref(&self) -> &MemoryRange {
78 &self.range
79 }
80}
81
Andrew Walbran19690632022-12-07 16:41:30 +000082/// Returns true if one range overlaps with the other at all.
83fn overlaps<T: Copy + Ord>(a: &Range<T>, b: &Range<T>) -> bool {
84 max(a.start, b.start) < min(a.end, b.end)
85}
86
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000087/// Tracks non-overlapping slices of main memory.
88pub struct MemoryTracker {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000089 total: MemoryRange,
90 page_table: mmu::PageTable,
Andrew Walbran19690632022-12-07 16:41:30 +000091 regions: ArrayVec<[MemoryRegion; MemoryTracker::CAPACITY]>,
92 mmio_regions: ArrayVec<[MemoryRange; MemoryTracker::MMIO_CAPACITY]>,
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000093}
94
95/// Errors for MemoryTracker operations.
96#[derive(Debug, Clone)]
97pub enum MemoryTrackerError {
98 /// Tried to modify the memory base address.
99 DifferentBaseAddress,
100 /// Tried to shrink to a larger memory size.
101 SizeTooLarge,
102 /// Tracked regions would not fit in memory size.
103 SizeTooSmall,
104 /// Reached limit number of tracked regions.
105 Full,
106 /// Region is out of the tracked memory address space.
107 OutOfRange,
108 /// New region overlaps with tracked regions.
109 Overlaps,
110 /// Region couldn't be mapped.
111 FailedToMap,
Alice Wang90e6f162023-04-17 13:49:45 +0000112 /// Error from the interaction with the hypervisor.
113 Hypervisor(hyp::Error),
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700114 /// Failure to set `SHARED_POOL`.
115 SharedPoolSetFailure,
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000116}
117
118impl fmt::Display for MemoryTrackerError {
119 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
120 match self {
121 Self::DifferentBaseAddress => write!(f, "Received different base address"),
122 Self::SizeTooLarge => write!(f, "Tried to shrink to a larger memory size"),
123 Self::SizeTooSmall => write!(f, "Tracked regions would not fit in memory size"),
124 Self::Full => write!(f, "Reached limit number of tracked regions"),
125 Self::OutOfRange => write!(f, "Region is out of the tracked memory address space"),
126 Self::Overlaps => write!(f, "New region overlaps with tracked regions"),
127 Self::FailedToMap => write!(f, "Failed to map the new region"),
Alice Wang90e6f162023-04-17 13:49:45 +0000128 Self::Hypervisor(e) => e.fmt(f),
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700129 Self::SharedPoolSetFailure => write!(f, "Failed to set SHARED_POOL"),
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000130 }
131 }
132}
133
Alice Wang90e6f162023-04-17 13:49:45 +0000134impl From<hyp::Error> for MemoryTrackerError {
135 fn from(e: hyp::Error) -> Self {
136 Self::Hypervisor(e)
Andrew Walbran19690632022-12-07 16:41:30 +0000137 }
138}
139
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000140type Result<T> = result::Result<T, MemoryTrackerError>;
141
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700142static SHARED_POOL: OnceBox<LockedHeap<32>> = OnceBox::new();
143
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000144impl MemoryTracker {
145 const CAPACITY: usize = 5;
Andrew Walbran19690632022-12-07 16:41:30 +0000146 const MMIO_CAPACITY: usize = 5;
Pierre-Clément Tosi164a6f52023-04-18 19:29:11 +0100147 const PVMFW_RANGE: MemoryRange = (BASE_ADDR - SIZE_4MB)..BASE_ADDR;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000148
149 /// Create a new instance from an active page table, covering the maximum RAM size.
150 pub fn new(page_table: mmu::PageTable) -> Self {
Andrew Walbran19690632022-12-07 16:41:30 +0000151 Self {
Jiyong Park0ee65392023-03-27 20:52:45 +0900152 total: BASE_ADDR..MAX_ADDR,
Andrew Walbran19690632022-12-07 16:41:30 +0000153 page_table,
154 regions: ArrayVec::new(),
155 mmio_regions: ArrayVec::new(),
156 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000157 }
158
159 /// Resize the total RAM size.
160 ///
161 /// This function fails if it contains regions that are not included within the new size.
162 pub fn shrink(&mut self, range: &MemoryRange) -> Result<()> {
163 if range.start != self.total.start {
164 return Err(MemoryTrackerError::DifferentBaseAddress);
165 }
166 if self.total.end < range.end {
167 return Err(MemoryTrackerError::SizeTooLarge);
168 }
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000169 if !self.regions.iter().all(|r| r.is_within(range)) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000170 return Err(MemoryTrackerError::SizeTooSmall);
171 }
172
173 self.total = range.clone();
174 Ok(())
175 }
176
177 /// Allocate the address range for a const slice; returns None if failed.
178 pub fn alloc_range(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
Andrew Walbranda65ab12022-12-07 15:10:13 +0000179 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadOnly };
180 self.check(&region)?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000181 self.page_table.map_rodata(range).map_err(|e| {
182 error!("Error during 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 mutable slice; returns None if failed.
189 pub fn alloc_range_mut(&mut self, range: &MemoryRange) -> Result<MemoryRange> {
Andrew Walbranda65ab12022-12-07 15:10:13 +0000190 let region = MemoryRegion { range: range.clone(), mem_type: MemoryType::ReadWrite };
191 self.check(&region)?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000192 self.page_table.map_data(range).map_err(|e| {
193 error!("Error during mutable range allocation: {e}");
194 MemoryTrackerError::FailedToMap
195 })?;
Andrew Walbranda65ab12022-12-07 15:10:13 +0000196 self.add(region)
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000197 }
198
199 /// Allocate the address range for a const slice; returns None if failed.
200 pub fn alloc(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
201 self.alloc_range(&(base..(base + size.get())))
202 }
203
204 /// Allocate the address range for a mutable slice; returns None if failed.
205 pub fn alloc_mut(&mut self, base: usize, size: NonZeroUsize) -> Result<MemoryRange> {
206 self.alloc_range_mut(&(base..(base + size.get())))
207 }
208
Andrew Walbran19690632022-12-07 16:41:30 +0000209 /// Checks that the given range of addresses is within the MMIO region, and then maps it
210 /// appropriately.
211 pub fn map_mmio_range(&mut self, range: MemoryRange) -> Result<()> {
212 // MMIO space is below the main memory region.
Pierre-Clément Tosi164a6f52023-04-18 19:29:11 +0100213 if range.end > self.total.start || overlaps(&Self::PVMFW_RANGE, &range) {
Andrew Walbran19690632022-12-07 16:41:30 +0000214 return Err(MemoryTrackerError::OutOfRange);
215 }
216 if self.mmio_regions.iter().any(|r| overlaps(r, &range)) {
217 return Err(MemoryTrackerError::Overlaps);
218 }
219 if self.mmio_regions.len() == self.mmio_regions.capacity() {
220 return Err(MemoryTrackerError::Full);
221 }
222
223 self.page_table.map_device(&range).map_err(|e| {
224 error!("Error during MMIO device mapping: {e}");
225 MemoryTrackerError::FailedToMap
226 })?;
227
228 for page_base in page_iterator(&range) {
Alice Wang90e6f162023-04-17 13:49:45 +0000229 get_hypervisor().mmio_guard_map(page_base)?;
Andrew Walbran19690632022-12-07 16:41:30 +0000230 }
231
232 if self.mmio_regions.try_push(range).is_some() {
233 return Err(MemoryTrackerError::Full);
234 }
235
236 Ok(())
237 }
238
Andrew Walbranda65ab12022-12-07 15:10:13 +0000239 /// Checks that the given region is within the range of the `MemoryTracker` and doesn't overlap
240 /// with any other previously allocated regions, and that the regions ArrayVec has capacity to
241 /// add it.
242 fn check(&self, region: &MemoryRegion) -> Result<()> {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000243 if !region.is_within(&self.total) {
244 return Err(MemoryTrackerError::OutOfRange);
245 }
Andrew Walbranda65ab12022-12-07 15:10:13 +0000246 if self.regions.iter().any(|r| r.overlaps(&region.range)) {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000247 return Err(MemoryTrackerError::Overlaps);
248 }
Andrew Walbranda65ab12022-12-07 15:10:13 +0000249 if self.regions.len() == self.regions.capacity() {
250 return Err(MemoryTrackerError::Full);
251 }
252 Ok(())
253 }
254
255 fn add(&mut self, region: MemoryRegion) -> Result<MemoryRange> {
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000256 if self.regions.try_push(region).is_some() {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000257 return Err(MemoryTrackerError::Full);
258 }
259
Pierre-Clément Tosi328dfb62022-11-25 18:20:42 +0000260 Ok(self.regions.last().unwrap().as_ref().clone())
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000261 }
Andrew Walbran19690632022-12-07 16:41:30 +0000262
263 /// Unmaps all tracked MMIO regions from the MMIO guard.
264 ///
265 /// Note that they are not unmapped from the page table.
266 pub fn mmio_unmap_all(&self) -> Result<()> {
267 for region in &self.mmio_regions {
268 for page_base in page_iterator(region) {
Alice Wang90e6f162023-04-17 13:49:45 +0000269 get_hypervisor().mmio_guard_unmap(page_base)?;
Andrew Walbran19690632022-12-07 16:41:30 +0000270 }
271 }
272
273 Ok(())
274 }
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700275
276 /// Initialize a separate heap for shared memory allocations.
277 ///
278 /// Some hypervisors such as Gunyah do not support a MemShare API for guest
279 /// to share its memory with host. Instead they allow host to designate part
280 /// of guest memory as "shared" ahead of guest starting its execution. The
281 /// shared memory region is indicated in swiotlb node. On such platforms use
282 /// a separate heap to allocate buffers that can be shared with host.
283 pub fn init_shared_pool(&mut self, range: Range<usize>) -> Result<()> {
284 let size = NonZeroUsize::new(range.len()).unwrap();
285 let range = self.alloc_mut(range.start, size)?;
286 let shared_pool = LockedHeap::<32>::new();
287
288 // SAFETY - `range` should be a valid region of memory as validated by
289 // `validate_swiotlb_info` and not used by any other rust code.
290 unsafe {
291 shared_pool.lock().init(range.start, range.len());
292 }
293
294 SHARED_POOL
295 .set(Box::new(shared_pool))
296 .map_err(|_| MemoryTrackerError::SharedPoolSetFailure)?;
297
298 Ok(())
299 }
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000300}
301
302impl Drop for MemoryTracker {
303 fn drop(&mut self) {
Andrew Walbran19690632022-12-07 16:41:30 +0000304 for region in &self.regions {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000305 match region.mem_type {
306 MemoryType::ReadWrite => {
Pierre-Clément Tosi73c2d642023-02-17 14:56:48 +0000307 // TODO(b/269738062): Use PT's dirty bit to only flush pages that were touched.
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000308 helpers::flush_region(region.range.start, region.range.len())
309 }
310 MemoryType::ReadOnly => {}
311 }
312 }
313 }
314}
Andrew Walbran19690632022-12-07 16:41:30 +0000315
Andrew Walbran41ebe932022-12-14 15:22:30 +0000316/// Gives the KVM host read, write and execute permissions on the given memory range. If the range
317/// is not aligned with the memory protection granule then it will be extended on either end to
318/// align.
Alice Wang90e6f162023-04-17 13:49:45 +0000319fn share_range(range: &MemoryRange, granule: usize) -> hyp::Result<()> {
Andrew Walbran41ebe932022-12-14 15:22:30 +0000320 for base in (align_down(range.start, granule)
321 .expect("Memory protection granule was not a power of two")..range.end)
322 .step_by(granule)
323 {
Alice Wang31329112023-04-13 09:02:36 +0000324 get_hypervisor().mem_share(base as u64)?;
Andrew Walbran41ebe932022-12-14 15:22:30 +0000325 }
326 Ok(())
327}
328
329/// Removes permission from the KVM host to access the given memory range which was previously
330/// shared. If the range is not aligned with the memory protection granule then it will be extended
331/// on either end to align.
Alice Wang90e6f162023-04-17 13:49:45 +0000332fn unshare_range(range: &MemoryRange, granule: usize) -> hyp::Result<()> {
Andrew Walbran41ebe932022-12-14 15:22:30 +0000333 for base in (align_down(range.start, granule)
334 .expect("Memory protection granule was not a power of two")..range.end)
335 .step_by(granule)
336 {
Alice Wang31329112023-04-13 09:02:36 +0000337 get_hypervisor().mem_unshare(base as u64)?;
Andrew Walbran41ebe932022-12-14 15:22:30 +0000338 }
339 Ok(())
340}
341
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700342/// Allocates a memory range of at least the given size that is shared with
343/// host. Returns a pointer to the buffer.
Andrew Walbran848decf2022-12-15 14:39:38 +0000344///
345/// It will be aligned to the memory sharing granule size supported by the hypervisor.
Alice Wang90e6f162023-04-17 13:49:45 +0000346pub fn alloc_shared(size: usize) -> hyp::Result<NonNull<u8>> {
Andrew Walbran848decf2022-12-15 14:39:38 +0000347 let layout = shared_buffer_layout(size)?;
348 let granule = layout.align();
349
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700350 if let Some(shared_pool) = SHARED_POOL.get() {
351 // Safe because `shared_buffer_layout` panics if the size is 0, so the
352 // layout must have a non-zero size.
353 let buffer = unsafe { shared_pool.alloc_zeroed(layout) };
354
355 let Some(buffer) = NonNull::new(buffer) else {
356 handle_alloc_error(layout);
357 };
358
359 return Ok(buffer);
360 }
361
Andrew Walbran848decf2022-12-15 14:39:38 +0000362 // Safe because `shared_buffer_layout` panics if the size is 0, so the layout must have a
363 // non-zero size.
364 let buffer = unsafe { alloc_zeroed(layout) };
365
Pierre-Clément Tosiebb37602023-02-17 14:57:26 +0000366 let Some(buffer) = NonNull::new(buffer) else {
Andrew Walbran848decf2022-12-15 14:39:38 +0000367 handle_alloc_error(layout);
368 };
369
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000370 let paddr = virt_to_phys(buffer);
Andrew Walbran848decf2022-12-15 14:39:38 +0000371 // If share_range fails then we will leak the allocation, but that seems better than having it
372 // be reused while maybe still partially shared with the host.
373 share_range(&(paddr..paddr + layout.size()), granule)?;
374
375 Ok(buffer)
376}
377
378/// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`.
379///
380/// The size passed in must be the size passed to the original `alloc_shared` call.
381///
382/// # Safety
383///
384/// The memory must have been allocated by `alloc_shared` with the same size, and not yet
385/// deallocated.
Alice Wang90e6f162023-04-17 13:49:45 +0000386pub unsafe fn dealloc_shared(vaddr: NonNull<u8>, size: usize) -> hyp::Result<()> {
Andrew Walbran848decf2022-12-15 14:39:38 +0000387 let layout = shared_buffer_layout(size)?;
388 let granule = layout.align();
389
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700390 if let Some(shared_pool) = SHARED_POOL.get() {
391 // Safe because the memory was allocated by `alloc_shared` above using
392 // the same allocator, and the layout is the same as was used then.
393 unsafe { shared_pool.dealloc(vaddr.as_ptr(), layout) };
394
395 return Ok(());
396 }
397
Andrew Walbran848decf2022-12-15 14:39:38 +0000398 let paddr = virt_to_phys(vaddr);
399 unshare_range(&(paddr..paddr + layout.size()), granule)?;
400 // Safe because the memory was allocated by `alloc_shared` above using the same allocator, and
401 // the layout is the same as was used then.
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000402 unsafe { dealloc(vaddr.as_ptr(), layout) };
Andrew Walbran848decf2022-12-15 14:39:38 +0000403
404 Ok(())
405}
406
407/// Returns the layout to use for allocating a buffer of at least the given size shared with the
408/// host.
409///
410/// It will be aligned to the memory sharing granule size supported by the hypervisor.
411///
412/// Panics if `size` is 0.
Alice Wang90e6f162023-04-17 13:49:45 +0000413fn shared_buffer_layout(size: usize) -> hyp::Result<Layout> {
Andrew Walbran848decf2022-12-15 14:39:38 +0000414 assert_ne!(size, 0);
Alice Wang31329112023-04-13 09:02:36 +0000415 let granule = get_hypervisor().memory_protection_granule()?;
Andrew Walbran848decf2022-12-15 14:39:38 +0000416 let allocated_size =
417 align_up(size, granule).expect("Memory protection granule was not a power of two");
418 Ok(Layout::from_size_align(allocated_size, granule).unwrap())
419}
420
Andrew Walbran19690632022-12-07 16:41:30 +0000421/// Returns an iterator which yields the base address of each 4 KiB page within the given range.
422fn page_iterator(range: &MemoryRange) -> impl Iterator<Item = usize> {
423 (page_4kb_of(range.start)..range.end).step_by(SIZE_4KB)
424}
Andrew Walbran848decf2022-12-15 14:39:38 +0000425
426/// Returns the intermediate physical address corresponding to the given virtual address.
427///
Andrew Walbran272bd7a2023-01-24 14:02:36 +0000428/// As we use identity mapping for everything, this is just a cast, but it's useful to use it to be
429/// explicit about where we are converting from virtual to physical address.
430pub fn virt_to_phys(vaddr: NonNull<u8>) -> usize {
431 vaddr.as_ptr() as _
432}
433
434/// Returns a pointer for the virtual address corresponding to the given non-zero intermediate
435/// physical address.
436///
437/// Panics if `paddr` is 0.
438pub fn phys_to_virt(paddr: usize) -> NonNull<u8> {
439 NonNull::new(paddr as _).unwrap()
Andrew Walbran848decf2022-12-15 14:39:38 +0000440}