blob: 34433ff232c38d610325bf5fee89935d10462bf3 [file] [log] [blame]
Imre Kis703482d2023-11-30 15:51:26 +01001// SPDX-FileCopyrightText: Copyright 2023 Arm Limited and/or its affiliates <open-source-office@arm.com>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Module for converting addresses between kernel virtual address space to physical address space
5
Imre Kis012f3ba2024-08-14 16:47:08 +02006use core::ops::{Deref, DerefMut, Range};
Imre Kis703482d2023-11-30 15:51:26 +01007
Imre Kis9a7440e2024-04-18 15:44:45 +02008use alloc::sync::Arc;
Imre Kisc1dab892024-03-26 12:03:58 +01009use spin::Mutex;
10
11use super::{
Imre Kisd5b96fd2024-09-11 17:04:32 +020012 address::{PhysicalAddress, VirtualAddress, VirtualAddressRange},
Imre Kisc1dab892024-03-26 12:03:58 +010013 page_pool::{Page, PagePool},
Imre Kis631127d2024-11-21 13:09:01 +010014 MemoryAccessRights, RegimeVaRange, TranslationGranule, TranslationRegime, Xlat, XlatError,
Imre Kisc1dab892024-03-26 12:03:58 +010015};
16
Imre Kis9a7440e2024-04-18 15:44:45 +020017#[derive(Clone)]
Imre Kisc1dab892024-03-26 12:03:58 +010018pub struct KernelSpace {
Imre Kis631127d2024-11-21 13:09:01 +010019 xlat: Arc<Mutex<Xlat<36>>>,
Imre Kisc1dab892024-03-26 12:03:58 +010020}
21
Imre Kis012f3ba2024-08-14 16:47:08 +020022/// # Kernel space memory mapping
Imre Kisc1dab892024-03-26 12:03:58 +010023///
24/// This object handles the translation tables of the kernel address space. The main goal is to
25/// limit the kernel's access to the memory and only map the ranges which are necessary for
26/// operation.
27/// The current implementation uses identity mapping into the upper virtual address range, e.g.
28/// PA = 0x0000_0001_2345_0000 -> VA = 0xffff_fff1_2345_0000.
Imre Kis703482d2023-11-30 15:51:26 +010029impl KernelSpace {
Imre Kisc1dab892024-03-26 12:03:58 +010030 pub const PAGE_SIZE: usize = Page::SIZE;
31
32 /// Creates the kernel memory mapping instance. This should be called from the main core's init
33 /// code.
34 /// # Arguments
35 /// * page_pool: Page pool for allocation kernel translation tables
Imre Kis9a7440e2024-04-18 15:44:45 +020036 pub fn new(page_pool: PagePool) -> Self {
37 Self {
Imre Kisb5146b52024-10-31 14:03:06 +010038 xlat: Arc::new(Mutex::new(Xlat::new(
39 page_pool,
40 unsafe { VirtualAddressRange::from_range(0x0000_0000..0x10_0000_0000) },
41 TranslationRegime::EL1_0(RegimeVaRange::Upper, 0),
Imre Kis631127d2024-11-21 13:09:01 +010042 TranslationGranule::Granule4k,
Imre Kisb5146b52024-10-31 14:03:06 +010043 ))),
Imre Kisc1dab892024-03-26 12:03:58 +010044 }
45 }
46
47 /// Maps the code (RX) and data (RW) segments of the SPMC itself.
48 /// # Arguments
49 /// * code_range: (start, end) addresses of the code segment
50 /// * data_range: (start, end) addresses of the data segment
51 /// # Return value
52 /// * The result of the operation
Imre Kis9a7440e2024-04-18 15:44:45 +020053 pub fn init(
54 &self,
55 code_range: Range<usize>,
56 data_range: Range<usize>,
57 ) -> Result<(), XlatError> {
58 let mut xlat = self.xlat.lock();
Imre Kisc1dab892024-03-26 12:03:58 +010059
Imre Kisd5b96fd2024-09-11 17:04:32 +020060 let code_pa = PhysicalAddress(code_range.start);
61 let data_pa = PhysicalAddress(data_range.start);
62
Imre Kis9a7440e2024-04-18 15:44:45 +020063 xlat.map_physical_address_range(
Imre Kisd5b96fd2024-09-11 17:04:32 +020064 Some(code_pa.identity_va()),
65 code_pa,
Imre Kis9a7440e2024-04-18 15:44:45 +020066 code_range.len(),
67 MemoryAccessRights::RX | MemoryAccessRights::GLOBAL,
68 )?;
Imre Kisc1dab892024-03-26 12:03:58 +010069
Imre Kis9a7440e2024-04-18 15:44:45 +020070 xlat.map_physical_address_range(
Imre Kisd5b96fd2024-09-11 17:04:32 +020071 Some(data_pa.identity_va()),
72 data_pa,
Imre Kis9a7440e2024-04-18 15:44:45 +020073 data_range.len(),
74 MemoryAccessRights::RW | MemoryAccessRights::GLOBAL,
75 )?;
Imre Kisc1dab892024-03-26 12:03:58 +010076
Imre Kis9a7440e2024-04-18 15:44:45 +020077 Ok(())
Imre Kisc1dab892024-03-26 12:03:58 +010078 }
79
80 /// Map memory range into the kernel address space
81 /// # Arguments
82 /// * pa: Physical address of the memory
83 /// * length: Length of the range in bytes
84 /// * access_right: Memory access rights
85 /// # Return value
86 /// * Virtual address of the mapped memory or error
87 pub fn map_memory(
Imre Kis9a7440e2024-04-18 15:44:45 +020088 &self,
Imre Kisc1dab892024-03-26 12:03:58 +010089 pa: usize,
90 length: usize,
91 access_rights: MemoryAccessRights,
92 ) -> Result<usize, XlatError> {
Imre Kisd5b96fd2024-09-11 17:04:32 +020093 let pa = PhysicalAddress(pa);
94
Imre Kis9a7440e2024-04-18 15:44:45 +020095 let lower_va = self.xlat.lock().map_physical_address_range(
Imre Kisd5b96fd2024-09-11 17:04:32 +020096 Some(pa.identity_va()),
Imre Kis9a7440e2024-04-18 15:44:45 +020097 pa,
98 length,
99 access_rights | MemoryAccessRights::GLOBAL,
100 )?;
Imre Kisc1dab892024-03-26 12:03:58 +0100101
Imre Kisd5b96fd2024-09-11 17:04:32 +0200102 Ok(Self::pa_to_kernel(lower_va.0 as u64) as usize)
Imre Kisc1dab892024-03-26 12:03:58 +0100103 }
104
105 /// Unmap memory range from the kernel address space
106 /// # Arguments
107 /// * va: Virtual address of the memory
108 /// * length: Length of the range in bytes
109 /// # Return value
110 /// The result of the operation
Imre Kis9a7440e2024-04-18 15:44:45 +0200111 pub fn unmap_memory(&self, va: usize, length: usize) -> Result<(), XlatError> {
Imre Kisd5b96fd2024-09-11 17:04:32 +0200112 self.xlat.lock().unmap_virtual_address_range(
113 VirtualAddress(Self::kernel_to_pa(va as u64) as usize),
114 length,
115 )
Imre Kisc1dab892024-03-26 12:03:58 +0100116 }
117
118 /// Activate kernel address space mapping
Imre Kisb5146b52024-10-31 14:03:06 +0100119 ///
120 /// # Safety
121 /// This changes the mapping of the running execution context. The caller
122 /// must ensure that existing references will be mapped to the same address
123 /// after activation.
124 pub unsafe fn activate(&self) {
125 self.xlat.lock().activate();
Imre Kisc1dab892024-03-26 12:03:58 +0100126 }
127
128 /// Rounds a value down to a kernel space page boundary
129 pub const fn round_down_to_page_size(size: usize) -> usize {
130 size & !(Self::PAGE_SIZE - 1)
131 }
132
133 /// Rounds a value up to a kernel space page boundary
134 pub const fn round_up_to_page_size(size: usize) -> usize {
135 (size + Self::PAGE_SIZE - 1) & !(Self::PAGE_SIZE - 1)
136 }
137
Imre Kis49c08e32024-04-19 14:16:39 +0200138 /// Returns the offset to the preceding page aligned address
139 pub const fn offset_in_page(address: usize) -> usize {
140 address & (Self::PAGE_SIZE - 1)
141 }
142
Imre Kis703482d2023-11-30 15:51:26 +0100143 /// Kernel virtual address to physical address
Imre Kisc1dab892024-03-26 12:03:58 +0100144 #[cfg(not(test))]
Imre Kis703482d2023-11-30 15:51:26 +0100145 pub const fn kernel_to_pa(kernel_address: u64) -> u64 {
146 kernel_address & 0x0000_000f_ffff_ffff
147 }
Imre Kis703482d2023-11-30 15:51:26 +0100148 /// Physical address to kernel virtual address
Imre Kisc1dab892024-03-26 12:03:58 +0100149 #[cfg(not(test))]
Imre Kis703482d2023-11-30 15:51:26 +0100150 pub const fn pa_to_kernel(pa: u64) -> u64 {
151 // TODO: make this consts assert_eq!(pa & 0xffff_fff0_0000_0000, 0);
152 pa | 0xffff_fff0_0000_0000
153 }
Imre Kis703482d2023-11-30 15:51:26 +0100154
Imre Kisc1dab892024-03-26 12:03:58 +0100155 // Do not use any mapping in test build
156 #[cfg(test)]
Imre Kis703482d2023-11-30 15:51:26 +0100157 pub const fn kernel_to_pa(kernel_address: u64) -> u64 {
158 kernel_address
159 }
160
Imre Kisc1dab892024-03-26 12:03:58 +0100161 #[cfg(test)]
Imre Kis703482d2023-11-30 15:51:26 +0100162 pub const fn pa_to_kernel(pa: u64) -> u64 {
163 pa
164 }
165}
Imre Kis012f3ba2024-08-14 16:47:08 +0200166
167/// # Kernel mapping wrapper
168///
169/// Objects in the physical address space can be wrapped into a KernelMapper which maps it to the
170/// virtual kernel address space and provides the same access to the object via the Deref trait.
171/// When the mapper is dropped it unmaps the mapped object from the virtual kernel space.
172pub struct KernelMapper<T>
173where
174 T: Deref,
175 T::Target: Sized,
176{
177 physical_instance: T,
178 va: *const T::Target,
179 kernel_space: KernelSpace,
180}
181
182impl<T> KernelMapper<T>
183where
184 T: Deref,
185 T::Target: Sized,
186{
187 /// Create new mapped object
188 /// The access_rights parameter must contain read access
189 pub fn new(
190 physical_instance: T,
191 kernel_space: KernelSpace,
192 access_rights: MemoryAccessRights,
193 ) -> Self {
194 assert!(access_rights.contains(MemoryAccessRights::R));
195
196 let pa = physical_instance.deref() as *const _ as usize;
197 let length = KernelSpace::round_up_to_page_size(core::mem::size_of::<T::Target>());
198
199 let va = kernel_space
200 .map_memory(pa, length, access_rights)
201 .expect("Failed to map area");
202
203 Self {
204 physical_instance,
205 va: va as *const T::Target,
206 kernel_space,
207 }
208 }
209}
210
211impl<T> Deref for KernelMapper<T>
212where
213 T: Deref,
214 T::Target: Sized,
215{
216 type Target = T::Target;
217
218 #[inline(always)]
219 fn deref(&self) -> &Self::Target {
220 unsafe { &*self.va }
221 }
222}
223
224impl<T> Drop for KernelMapper<T>
225where
226 T: Deref,
227 T::Target: Sized,
228{
229 fn drop(&mut self) {
230 let length = KernelSpace::round_up_to_page_size(core::mem::size_of::<T::Target>());
231 self.kernel_space
232 .unmap_memory(self.va as usize, length)
233 .expect("Failed to unmap area");
234 }
235}
236
237unsafe impl<T> Send for KernelMapper<T>
238where
239 T: Deref + Send,
240 T::Target: Sized,
241{
242}
243
244/// # Mutable version of kernel mapping wrapper
245pub struct KernelMapperMut<T>
246where
247 T: DerefMut,
248 T::Target: Sized,
249{
250 physical_instance: T,
251 va: *mut T::Target,
252 kernel_space: KernelSpace,
253}
254
255impl<T> KernelMapperMut<T>
256where
257 T: DerefMut,
258 T::Target: Sized,
259{
260 /// Create new mapped object
261 /// The access_rights parameter must contain read and write access
262 pub fn new(
263 physical_instance: T,
264 kernel_space: KernelSpace,
265 access_rights: MemoryAccessRights,
266 ) -> Self {
267 assert!(access_rights.contains(MemoryAccessRights::RW));
268
269 let pa = physical_instance.deref() as *const _ as usize;
270 let length = KernelSpace::round_up_to_page_size(core::mem::size_of::<T::Target>());
271
272 let va = kernel_space
273 .map_memory(pa, length, access_rights)
274 .expect("Failed to map area");
275
276 Self {
277 physical_instance,
278 va: va as *mut T::Target,
279 kernel_space,
280 }
281 }
282}
283
284impl<T> Deref for KernelMapperMut<T>
285where
286 T: DerefMut,
287 T::Target: Sized,
288{
289 type Target = T::Target;
290
291 #[inline(always)]
292 fn deref(&self) -> &Self::Target {
293 unsafe { &*self.va }
294 }
295}
296
297impl<T> DerefMut for KernelMapperMut<T>
298where
299 T: DerefMut,
300 T::Target: Sized,
301{
302 #[inline(always)]
303 fn deref_mut(&mut self) -> &mut Self::Target {
304 unsafe { &mut *self.va }
305 }
306}
307
308impl<T> Drop for KernelMapperMut<T>
309where
310 T: DerefMut,
311 T::Target: Sized,
312{
313 fn drop(&mut self) {
314 let length = KernelSpace::round_up_to_page_size(core::mem::size_of::<T::Target>());
315 self.kernel_space
316 .unmap_memory(self.va as usize, length)
317 .expect("Failed to unmap area");
318 }
319}
320
321unsafe impl<T> Send for KernelMapperMut<T>
322where
323 T: DerefMut + Send,
324 T::Target: Sized,
325{
326}