blob: 1069c1c1b2b6bb00d8d65d34e0e6c778a1c63e3d [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},
14 MemoryAccessRights, Xlat, XlatError,
15};
16
17static mut KERNEL_SPACE_INSTANCE: Option<KernelSpace> = None;
18
Imre Kis9a7440e2024-04-18 15:44:45 +020019#[derive(Clone)]
Imre Kisc1dab892024-03-26 12:03:58 +010020pub struct KernelSpace {
Imre Kis9a7440e2024-04-18 15:44:45 +020021 xlat: Arc<Mutex<Xlat>>,
Imre Kisc1dab892024-03-26 12:03:58 +010022}
23
Imre Kis012f3ba2024-08-14 16:47:08 +020024/// # Kernel space memory mapping
Imre Kisc1dab892024-03-26 12:03:58 +010025///
26/// This object handles the translation tables of the kernel address space. The main goal is to
27/// limit the kernel's access to the memory and only map the ranges which are necessary for
28/// operation.
29/// The current implementation uses identity mapping into the upper virtual address range, e.g.
30/// PA = 0x0000_0001_2345_0000 -> VA = 0xffff_fff1_2345_0000.
Imre Kis703482d2023-11-30 15:51:26 +010031impl KernelSpace {
Imre Kisc1dab892024-03-26 12:03:58 +010032 pub const PAGE_SIZE: usize = Page::SIZE;
33
34 /// Creates the kernel memory mapping instance. This should be called from the main core's init
35 /// code.
36 /// # Arguments
37 /// * page_pool: Page pool for allocation kernel translation tables
Imre Kis9a7440e2024-04-18 15:44:45 +020038 pub fn new(page_pool: PagePool) -> Self {
39 Self {
Imre Kisd5b96fd2024-09-11 17:04:32 +020040 xlat: Arc::new(Mutex::new(Xlat::new(page_pool, unsafe {
41 VirtualAddressRange::from_range(0x0000_0000..0x10_0000_0000)
42 }))),
Imre Kisc1dab892024-03-26 12:03:58 +010043 }
44 }
45
46 /// Maps the code (RX) and data (RW) segments of the SPMC itself.
47 /// # Arguments
48 /// * code_range: (start, end) addresses of the code segment
49 /// * data_range: (start, end) addresses of the data segment
50 /// # Return value
51 /// * The result of the operation
Imre Kis9a7440e2024-04-18 15:44:45 +020052 pub fn init(
53 &self,
54 code_range: Range<usize>,
55 data_range: Range<usize>,
56 ) -> Result<(), XlatError> {
57 let mut xlat = self.xlat.lock();
Imre Kisc1dab892024-03-26 12:03:58 +010058
Imre Kisd5b96fd2024-09-11 17:04:32 +020059 let code_pa = PhysicalAddress(code_range.start);
60 let data_pa = PhysicalAddress(data_range.start);
61
Imre Kis9a7440e2024-04-18 15:44:45 +020062 xlat.map_physical_address_range(
Imre Kisd5b96fd2024-09-11 17:04:32 +020063 Some(code_pa.identity_va()),
64 code_pa,
Imre Kis9a7440e2024-04-18 15:44:45 +020065 code_range.len(),
66 MemoryAccessRights::RX | MemoryAccessRights::GLOBAL,
67 )?;
Imre Kisc1dab892024-03-26 12:03:58 +010068
Imre Kis9a7440e2024-04-18 15:44:45 +020069 xlat.map_physical_address_range(
Imre Kisd5b96fd2024-09-11 17:04:32 +020070 Some(data_pa.identity_va()),
71 data_pa,
Imre Kis9a7440e2024-04-18 15:44:45 +020072 data_range.len(),
73 MemoryAccessRights::RW | MemoryAccessRights::GLOBAL,
74 )?;
Imre Kisc1dab892024-03-26 12:03:58 +010075
Imre Kis9a7440e2024-04-18 15:44:45 +020076 Ok(())
Imre Kisc1dab892024-03-26 12:03:58 +010077 }
78
79 /// Map memory range into the kernel address space
80 /// # Arguments
81 /// * pa: Physical address of the memory
82 /// * length: Length of the range in bytes
83 /// * access_right: Memory access rights
84 /// # Return value
85 /// * Virtual address of the mapped memory or error
86 pub fn map_memory(
Imre Kis9a7440e2024-04-18 15:44:45 +020087 &self,
Imre Kisc1dab892024-03-26 12:03:58 +010088 pa: usize,
89 length: usize,
90 access_rights: MemoryAccessRights,
91 ) -> Result<usize, XlatError> {
Imre Kisd5b96fd2024-09-11 17:04:32 +020092 let pa = PhysicalAddress(pa);
93
Imre Kis9a7440e2024-04-18 15:44:45 +020094 let lower_va = self.xlat.lock().map_physical_address_range(
Imre Kisd5b96fd2024-09-11 17:04:32 +020095 Some(pa.identity_va()),
Imre Kis9a7440e2024-04-18 15:44:45 +020096 pa,
97 length,
98 access_rights | MemoryAccessRights::GLOBAL,
99 )?;
Imre Kisc1dab892024-03-26 12:03:58 +0100100
Imre Kisd5b96fd2024-09-11 17:04:32 +0200101 Ok(Self::pa_to_kernel(lower_va.0 as u64) as usize)
Imre Kisc1dab892024-03-26 12:03:58 +0100102 }
103
104 /// Unmap memory range from the kernel address space
105 /// # Arguments
106 /// * va: Virtual address of the memory
107 /// * length: Length of the range in bytes
108 /// # Return value
109 /// The result of the operation
Imre Kis9a7440e2024-04-18 15:44:45 +0200110 pub fn unmap_memory(&self, va: usize, length: usize) -> Result<(), XlatError> {
Imre Kisd5b96fd2024-09-11 17:04:32 +0200111 self.xlat.lock().unmap_virtual_address_range(
112 VirtualAddress(Self::kernel_to_pa(va as u64) as usize),
113 length,
114 )
Imre Kisc1dab892024-03-26 12:03:58 +0100115 }
116
117 /// Activate kernel address space mapping
Imre Kis9a7440e2024-04-18 15:44:45 +0200118 pub fn activate(&self) {
119 self.xlat.lock().activate(0, super::TTBR::TTBR1_EL1);
Imre Kisc1dab892024-03-26 12:03:58 +0100120 }
121
122 /// Rounds a value down to a kernel space page boundary
123 pub const fn round_down_to_page_size(size: usize) -> usize {
124 size & !(Self::PAGE_SIZE - 1)
125 }
126
127 /// Rounds a value up to a kernel space page boundary
128 pub const fn round_up_to_page_size(size: usize) -> usize {
129 (size + Self::PAGE_SIZE - 1) & !(Self::PAGE_SIZE - 1)
130 }
131
Imre Kis49c08e32024-04-19 14:16:39 +0200132 /// Returns the offset to the preceding page aligned address
133 pub const fn offset_in_page(address: usize) -> usize {
134 address & (Self::PAGE_SIZE - 1)
135 }
136
Imre Kis703482d2023-11-30 15:51:26 +0100137 /// Kernel virtual address to physical address
Imre Kisc1dab892024-03-26 12:03:58 +0100138 #[cfg(not(test))]
Imre Kis703482d2023-11-30 15:51:26 +0100139 pub const fn kernel_to_pa(kernel_address: u64) -> u64 {
140 kernel_address & 0x0000_000f_ffff_ffff
141 }
Imre Kis703482d2023-11-30 15:51:26 +0100142 /// Physical address to kernel virtual address
Imre Kisc1dab892024-03-26 12:03:58 +0100143 #[cfg(not(test))]
Imre Kis703482d2023-11-30 15:51:26 +0100144 pub const fn pa_to_kernel(pa: u64) -> u64 {
145 // TODO: make this consts assert_eq!(pa & 0xffff_fff0_0000_0000, 0);
146 pa | 0xffff_fff0_0000_0000
147 }
Imre Kis703482d2023-11-30 15:51:26 +0100148
Imre Kisc1dab892024-03-26 12:03:58 +0100149 // Do not use any mapping in test build
150 #[cfg(test)]
Imre Kis703482d2023-11-30 15:51:26 +0100151 pub const fn kernel_to_pa(kernel_address: u64) -> u64 {
152 kernel_address
153 }
154
Imre Kisc1dab892024-03-26 12:03:58 +0100155 #[cfg(test)]
Imre Kis703482d2023-11-30 15:51:26 +0100156 pub const fn pa_to_kernel(pa: u64) -> u64 {
157 pa
158 }
159}
Imre Kis012f3ba2024-08-14 16:47:08 +0200160
161/// # Kernel mapping wrapper
162///
163/// Objects in the physical address space can be wrapped into a KernelMapper which maps it to the
164/// virtual kernel address space and provides the same access to the object via the Deref trait.
165/// When the mapper is dropped it unmaps the mapped object from the virtual kernel space.
166pub struct KernelMapper<T>
167where
168 T: Deref,
169 T::Target: Sized,
170{
171 physical_instance: T,
172 va: *const T::Target,
173 kernel_space: KernelSpace,
174}
175
176impl<T> KernelMapper<T>
177where
178 T: Deref,
179 T::Target: Sized,
180{
181 /// Create new mapped object
182 /// The access_rights parameter must contain read access
183 pub fn new(
184 physical_instance: T,
185 kernel_space: KernelSpace,
186 access_rights: MemoryAccessRights,
187 ) -> Self {
188 assert!(access_rights.contains(MemoryAccessRights::R));
189
190 let pa = physical_instance.deref() as *const _ as usize;
191 let length = KernelSpace::round_up_to_page_size(core::mem::size_of::<T::Target>());
192
193 let va = kernel_space
194 .map_memory(pa, length, access_rights)
195 .expect("Failed to map area");
196
197 Self {
198 physical_instance,
199 va: va as *const T::Target,
200 kernel_space,
201 }
202 }
203}
204
205impl<T> Deref for KernelMapper<T>
206where
207 T: Deref,
208 T::Target: Sized,
209{
210 type Target = T::Target;
211
212 #[inline(always)]
213 fn deref(&self) -> &Self::Target {
214 unsafe { &*self.va }
215 }
216}
217
218impl<T> Drop for KernelMapper<T>
219where
220 T: Deref,
221 T::Target: Sized,
222{
223 fn drop(&mut self) {
224 let length = KernelSpace::round_up_to_page_size(core::mem::size_of::<T::Target>());
225 self.kernel_space
226 .unmap_memory(self.va as usize, length)
227 .expect("Failed to unmap area");
228 }
229}
230
231unsafe impl<T> Send for KernelMapper<T>
232where
233 T: Deref + Send,
234 T::Target: Sized,
235{
236}
237
238/// # Mutable version of kernel mapping wrapper
239pub struct KernelMapperMut<T>
240where
241 T: DerefMut,
242 T::Target: Sized,
243{
244 physical_instance: T,
245 va: *mut T::Target,
246 kernel_space: KernelSpace,
247}
248
249impl<T> KernelMapperMut<T>
250where
251 T: DerefMut,
252 T::Target: Sized,
253{
254 /// Create new mapped object
255 /// The access_rights parameter must contain read and write access
256 pub fn new(
257 physical_instance: T,
258 kernel_space: KernelSpace,
259 access_rights: MemoryAccessRights,
260 ) -> Self {
261 assert!(access_rights.contains(MemoryAccessRights::RW));
262
263 let pa = physical_instance.deref() as *const _ as usize;
264 let length = KernelSpace::round_up_to_page_size(core::mem::size_of::<T::Target>());
265
266 let va = kernel_space
267 .map_memory(pa, length, access_rights)
268 .expect("Failed to map area");
269
270 Self {
271 physical_instance,
272 va: va as *mut T::Target,
273 kernel_space,
274 }
275 }
276}
277
278impl<T> Deref for KernelMapperMut<T>
279where
280 T: DerefMut,
281 T::Target: Sized,
282{
283 type Target = T::Target;
284
285 #[inline(always)]
286 fn deref(&self) -> &Self::Target {
287 unsafe { &*self.va }
288 }
289}
290
291impl<T> DerefMut for KernelMapperMut<T>
292where
293 T: DerefMut,
294 T::Target: Sized,
295{
296 #[inline(always)]
297 fn deref_mut(&mut self) -> &mut Self::Target {
298 unsafe { &mut *self.va }
299 }
300}
301
302impl<T> Drop for KernelMapperMut<T>
303where
304 T: DerefMut,
305 T::Target: Sized,
306{
307 fn drop(&mut self) {
308 let length = KernelSpace::round_up_to_page_size(core::mem::size_of::<T::Target>());
309 self.kernel_space
310 .unmap_memory(self.va as usize, length)
311 .expect("Failed to unmap area");
312 }
313}
314
315unsafe impl<T> Send for KernelMapperMut<T>
316where
317 T: DerefMut + Send,
318 T::Target: Sized,
319{
320}