1 // Copyright 2023, 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 //! Shared memory management.
16
17 use super::error::MemoryTrackerError;
18 use super::util::virt_to_phys;
19 use crate::arch::VirtualAddress;
20 use crate::layout;
21 use crate::util::unchecked_align_down;
22 use aarch64_paging::paging::{MemoryRegion as VaRange, PAGE_SIZE};
23 use alloc::alloc::{alloc_zeroed, dealloc, handle_alloc_error};
24 use alloc::collections::BTreeSet;
25 use alloc::vec::Vec;
26 use buddy_system_allocator::{FrameAllocator, LockedFrameAllocator};
27 use core::alloc::Layout;
28 use core::cmp::max;
29 use core::ops::Range;
30 use core::ptr::NonNull;
31 use core::result;
32 use hypervisor_backends::{self, get_mem_sharer, get_mmio_guard};
33 use log::trace;
34 use once_cell::race::OnceBox;
35 use spin::mutex::SpinMutex;
36
37 pub(crate) static SHARED_POOL: OnceBox<LockedFrameAllocator<32>> = OnceBox::new();
38 pub(crate) static SHARED_MEMORY: SpinMutex<Option<MemorySharer>> = SpinMutex::new(None);
39
40 /// Memory range.
41 pub type MemoryRange = Range<usize>;
42
43 type Result<T> = result::Result<T, MemoryTrackerError>;
44
45 pub(crate) struct MmioSharer {
46 granule: usize,
47 frames: BTreeSet<usize>,
48 }
49
50 impl MmioSharer {
new() -> Result<Self>51 pub fn new() -> Result<Self> {
52 let granule = Self::get_granule()?;
53 let frames = BTreeSet::new();
54
55 // Allows safely calling util::unchecked_align_down().
56 assert!(granule.is_power_of_two());
57
58 Ok(Self { granule, frames })
59 }
60
get_granule() -> Result<usize>61 pub fn get_granule() -> Result<usize> {
62 let Some(mmio_guard) = get_mmio_guard() else {
63 return Ok(PAGE_SIZE);
64 };
65 match mmio_guard.granule()? {
66 granule if granule % PAGE_SIZE == 0 => Ok(granule), // For good measure.
67 granule => Err(MemoryTrackerError::UnsupportedMmioGuardGranule(granule)),
68 }
69 }
70
71 /// Share the MMIO region aligned to the granule size containing addr (not validated as MMIO).
share(&mut self, addr: VirtualAddress) -> Result<VaRange>72 pub fn share(&mut self, addr: VirtualAddress) -> Result<VaRange> {
73 // This can't use virt_to_phys() since 0x0 is a valid MMIO address and we are ID-mapped.
74 let phys = addr.0;
75 let base = unchecked_align_down(phys, self.granule);
76
77 // TODO(ptosi): Share the UART using this method and remove the hardcoded check.
78 if self.frames.contains(&base) || base == layout::crosvm::UART_PAGE_ADDR {
79 return Err(MemoryTrackerError::DuplicateMmioShare(base));
80 }
81
82 if let Some(mmio_guard) = get_mmio_guard() {
83 mmio_guard.map(base)?;
84 }
85
86 let inserted = self.frames.insert(base);
87 assert!(inserted);
88
89 let base_va = VirtualAddress(base);
90 Ok((base_va..base_va + self.granule).into())
91 }
92
unshare_all(&mut self)93 pub fn unshare_all(&mut self) {
94 let Some(mmio_guard) = get_mmio_guard() else {
95 return self.frames.clear();
96 };
97
98 while let Some(base) = self.frames.pop_first() {
99 mmio_guard.unmap(base).unwrap();
100 }
101 }
102 }
103
104 impl Drop for MmioSharer {
drop(&mut self)105 fn drop(&mut self) {
106 self.unshare_all();
107 }
108 }
109
110 /// Allocates a memory range of at least the given size and alignment that is shared with the host.
111 /// Returns a pointer to the buffer.
alloc_shared(layout: Layout) -> hypervisor_backends::Result<NonNull<u8>>112 pub(crate) fn alloc_shared(layout: Layout) -> hypervisor_backends::Result<NonNull<u8>> {
113 assert_ne!(layout.size(), 0);
114 let Some(buffer) = try_shared_alloc(layout) else {
115 handle_alloc_error(layout);
116 };
117
118 trace!("Allocated shared buffer at {buffer:?} with {layout:?}");
119 Ok(buffer)
120 }
121
try_shared_alloc(layout: Layout) -> Option<NonNull<u8>>122 fn try_shared_alloc(layout: Layout) -> Option<NonNull<u8>> {
123 let mut shared_pool = SHARED_POOL.get().unwrap().lock();
124
125 if let Some(buffer) = shared_pool.alloc_aligned(layout) {
126 Some(NonNull::new(buffer as _).unwrap())
127 } else if let Some(shared_memory) = SHARED_MEMORY.lock().as_mut() {
128 // Adjusts the layout size to the max of the next power of two and the alignment,
129 // as this is the actual size of the memory allocated in `alloc_aligned()`.
130 let size = max(layout.size().next_power_of_two(), layout.align());
131 let refill_layout = Layout::from_size_align(size, layout.align()).unwrap();
132 shared_memory.refill(&mut shared_pool, refill_layout);
133 shared_pool.alloc_aligned(layout).map(|buffer| NonNull::new(buffer as _).unwrap())
134 } else {
135 None
136 }
137 }
138
139 /// Unshares and deallocates a memory range which was previously allocated by `alloc_shared`.
140 ///
141 /// The layout passed in must be the same layout passed to the original `alloc_shared` call.
142 ///
143 /// # Safety
144 ///
145 /// The memory must have been allocated by `alloc_shared` with the same layout, and not yet
146 /// deallocated.
dealloc_shared( vaddr: NonNull<u8>, layout: Layout, ) -> hypervisor_backends::Result<()>147 pub(crate) unsafe fn dealloc_shared(
148 vaddr: NonNull<u8>,
149 layout: Layout,
150 ) -> hypervisor_backends::Result<()> {
151 SHARED_POOL.get().unwrap().lock().dealloc_aligned(vaddr.as_ptr() as usize, layout);
152
153 trace!("Deallocated shared buffer at {vaddr:?} with {layout:?}");
154 Ok(())
155 }
156
157 /// Allocates memory on the heap and shares it with the host.
158 ///
159 /// Unshares all pages when dropped.
160 pub(crate) struct MemorySharer {
161 granule: usize,
162 frames: Vec<(usize, Layout)>,
163 }
164
165 impl MemorySharer {
166 /// Constructs a new `MemorySharer` instance with the specified granule size and capacity.
167 /// `granule` must be a power of 2.
new(granule: usize, capacity: usize) -> Self168 pub fn new(granule: usize, capacity: usize) -> Self {
169 assert!(granule.is_power_of_two());
170 Self { granule, frames: Vec::with_capacity(capacity) }
171 }
172
173 /// Gets from the global allocator a granule-aligned region that suits `hint` and share it.
refill(&mut self, pool: &mut FrameAllocator<32>, hint: Layout)174 pub fn refill(&mut self, pool: &mut FrameAllocator<32>, hint: Layout) {
175 let layout = hint.align_to(self.granule).unwrap().pad_to_align();
176 assert_ne!(layout.size(), 0);
177 // SAFETY: layout has non-zero size.
178 let Some(shared) = NonNull::new(unsafe { alloc_zeroed(layout) }) else {
179 handle_alloc_error(layout);
180 };
181
182 let base = shared.as_ptr() as usize;
183 let end = base.checked_add(layout.size()).unwrap();
184
185 if let Some(mem_sharer) = get_mem_sharer() {
186 trace!("Sharing memory region {:#x?}", base..end);
187 for vaddr in (base..end).step_by(self.granule) {
188 let vaddr = NonNull::new(vaddr as *mut _).unwrap();
189 mem_sharer.share(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
190 }
191 }
192
193 self.frames.push((base, layout));
194 pool.add_frame(base, end);
195 }
196 }
197
198 impl Drop for MemorySharer {
drop(&mut self)199 fn drop(&mut self) {
200 while let Some((base, layout)) = self.frames.pop() {
201 if let Some(mem_sharer) = get_mem_sharer() {
202 let end = base.checked_add(layout.size()).unwrap();
203 trace!("Unsharing memory region {:#x?}", base..end);
204 for vaddr in (base..end).step_by(self.granule) {
205 let vaddr = NonNull::new(vaddr as *mut _).unwrap();
206 mem_sharer.unshare(virt_to_phys(vaddr).try_into().unwrap()).unwrap();
207 }
208 }
209
210 // SAFETY: The region was obtained from alloc_zeroed() with the recorded layout.
211 unsafe { dealloc(base as *mut _, layout) };
212 }
213 }
214 }
215