aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / aienos-kernel / src / mem / map_plan.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Pure planning for the identity map used by the EL2 to EL1h handoff. |
| 17 | use super::pagetable::{MapFlags, MemoryAttribute}; |
| 18 | use alloc::vec::Vec; |
| 19 | |
| 20 | pub const EFI_MEMORY_RUNTIME: u64 = 1 << 63; |
| 21 | pub const EFI_MEMORY_RO: u64 = 1 << 17; |
| 22 | pub const EFI_MEMORY_XP: u64 = 1 << 14; |
| 23 | |
| 24 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 25 | pub struct AddressRange { |
| 26 | pub start: u64, |
| 27 | pub length: u64, |
| 28 | } |
| 29 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 30 | pub struct EfiMemoryDescriptor { |
| 31 | pub memory_type: u32, |
| 32 | pub phys_start: u64, |
| 33 | pub page_count: u64, |
| 34 | pub attribute: u64, |
| 35 | } |
| 36 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 37 | pub struct PeSection { |
| 38 | pub va: u64, |
| 39 | pub size: u64, |
| 40 | pub characteristics: u32, |
| 41 | } |
| 42 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 43 | pub struct RuntimeAttributes { |
| 44 | pub range: AddressRange, |
| 45 | pub read_only: bool, |
| 46 | pub execute_protect: bool, |
| 47 | } |
| 48 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 49 | pub struct PlannedMapping { |
| 50 | pub range: AddressRange, |
| 51 | pub flags: MapFlags, |
| 52 | } |
| 53 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 54 | pub enum RuntimeDecision { |
| 55 | RuntimeCodeRxUnsplit, |
| 56 | } |
| 57 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 58 | pub enum PlanError { |
| 59 | EmptyRange, |
| 60 | Overflow, |
| 61 | RuntimeCodeAttributesMissing, |
| 62 | RuntimeCodeCannotSplit, |
| 63 | Overlap, |
| 64 | ImageSectionOutsideAllocation, |
| 65 | } |
| 66 | |
| 67 | const EFI_LOADER_CODE: u32 = 1; |
| 68 | const EFI_RUNTIME_CODE: u32 = 5; |
| 69 | const EFI_RUNTIME_DATA: u32 = 6; |
| 70 | const EFI_MMIO: u32 = 11; |
| 71 | const IMAGE_SCN_MEM_EXECUTE: u32 = 0x2000_0000; |
| 72 | const IMAGE_SCN_MEM_WRITE: u32 = 0x8000_0000; |
| 73 | |
| 74 | fn flags(write: bool, execute: bool, attribute: MemoryAttribute) -> MapFlags { |
| 75 | MapFlags { |
| 76 | attribute, |
| 77 | writable: write, |
| 78 | executable: execute, |
| 79 | user: false, |
| 80 | shareable: true, |
| 81 | global: true, |
| 82 | } |
| 83 | } |
| 84 | fn end(r: AddressRange) -> Result<u64, PlanError> { |
| 85 | r.start.checked_add(r.length).ok_or(PlanError::Overflow) |
| 86 | } |
| 87 | fn overlap(a: AddressRange, b: AddressRange) -> Result<bool, PlanError> { |
| 88 | Ok(a.start < end(b)? && b.start < end(a)?) |
| 89 | } |
| 90 | |
| 91 | /// Produces page-aligned identity mappings. If runtime code attributes are unavailable, |
| 92 | /// the explicit decision is to finish runtime calls before entering EL1h. |
| 93 | pub fn build_map_plan( |
| 94 | memory: &[EfiMemoryDescriptor], |
| 95 | _image_base: u64, |
| 96 | image_allocation: AddressRange, |
| 97 | sections: &[PeSection], |
| 98 | runtime_attributes: Option<&[RuntimeAttributes]>, |
| 99 | mmio: &[AddressRange], |
| 100 | ) -> Result<(Vec<PlannedMapping>, Option<RuntimeDecision>), PlanError> { |
| 101 | let mut out = Vec::new(); |
| 102 | let mut decision = None; |
| 103 | for d in memory { |
| 104 | let length = d.page_count.checked_mul(4096).ok_or(PlanError::Overflow)?; |
| 105 | if length == 0 { |
| 106 | continue; |
| 107 | } |
| 108 | let region = AddressRange { |
| 109 | start: d.phys_start, |
| 110 | length, |
| 111 | }; |
| 112 | if d.memory_type == EFI_LOADER_CODE { |
| 113 | let mut covered = 0; |
| 114 | for section in sections { |
| 115 | let size = section.size; |
| 116 | if size == 0 { |
| 117 | continue; |
| 118 | } |
| 119 | let start = section.va; |
| 120 | let aligned_start = start & !4095; |
| 121 | let aligned_end = start |
| 122 | .checked_add(size) |
| 123 | .and_then(|value| value.checked_add(4095)) |
| 124 | .ok_or(PlanError::Overflow)? |
| 125 | & !4095; |
| 126 | let r = AddressRange { |
| 127 | start: aligned_start, |
| 128 | length: aligned_end |
| 129 | .checked_sub(aligned_start) |
| 130 | .ok_or(PlanError::Overflow)?, |
| 131 | }; |
| 132 | if !overlap(r, image_allocation)? { |
| 133 | return Err(PlanError::ImageSectionOutsideAllocation); |
| 134 | } |
| 135 | if section.characteristics & IMAGE_SCN_MEM_EXECUTE != 0 |
| 136 | && section.characteristics & IMAGE_SCN_MEM_WRITE != 0 |
| 137 | { |
| 138 | return Err(PlanError::Overlap); |
| 139 | } |
| 140 | let f = flags( |
| 141 | section.characteristics & IMAGE_SCN_MEM_WRITE != 0, |
| 142 | section.characteristics & IMAGE_SCN_MEM_EXECUTE != 0, |
| 143 | MemoryAttribute::NormalWriteBack, |
| 144 | ); |
| 145 | out.push(PlannedMapping { range: r, flags: f }); |
| 146 | covered += r.length; |
| 147 | } |
| 148 | if covered == 0 { |
| 149 | out.push(PlannedMapping { |
| 150 | range: region, |
| 151 | flags: MapFlags::KERNEL_DATA, |
| 152 | }); |
| 153 | } |
| 154 | } else if d.memory_type == EFI_MMIO { |
| 155 | out.push(PlannedMapping { |
| 156 | range: region, |
| 157 | flags: flags(true, false, MemoryAttribute::DeviceNgnre), |
| 158 | }); |
| 159 | } else if d.memory_type == EFI_RUNTIME_CODE |
| 160 | || (d.attribute & EFI_MEMORY_RUNTIME != 0 && d.memory_type != EFI_RUNTIME_DATA) |
| 161 | { |
| 162 | let Some(attrs) = runtime_attributes else { |
| 163 | out.push(PlannedMapping { |
| 164 | range: region, |
| 165 | flags: flags(false, true, MemoryAttribute::NormalWriteBack), |
| 166 | }); |
| 167 | decision = Some(RuntimeDecision::RuntimeCodeRxUnsplit); |
| 168 | continue; |
| 169 | }; |
| 170 | let mut cursor = region.start; |
| 171 | while cursor < end(region)? { |
| 172 | let attr = attrs |
| 173 | .iter() |
| 174 | .find(|a| a.range.start <= cursor && end(a.range).is_ok_and(|e| e > cursor)) |
| 175 | .ok_or(PlanError::RuntimeCodeAttributesMissing)?; |
| 176 | let stop = end(attr.range)?.min(end(region)?); |
| 177 | let executable = !attr.execute_protect; |
| 178 | if executable && !attr.read_only { |
| 179 | // Some firmware MATs describe a writable executable |
| 180 | // runtime range. Preserve execution while enforcing W^X. |
| 181 | decision = Some(RuntimeDecision::RuntimeCodeRxUnsplit); |
| 182 | } |
| 183 | out.push(PlannedMapping { |
| 184 | range: AddressRange { |
| 185 | start: cursor, |
| 186 | length: stop - cursor, |
| 187 | }, |
| 188 | flags: flags( |
| 189 | !attr.read_only && attr.execute_protect, |
| 190 | executable, |
| 191 | MemoryAttribute::NormalWriteBack, |
| 192 | ), |
| 193 | }); |
| 194 | cursor = stop; |
| 195 | } |
| 196 | } else if matches!(d.memory_type, 2 | 3 | 4 | 7 | 9 | 10 | EFI_RUNTIME_DATA) { |
| 197 | out.push(PlannedMapping { |
| 198 | range: region, |
| 199 | flags: MapFlags::KERNEL_DATA, |
| 200 | }); |
| 201 | } |
| 202 | } |
| 203 | let descriptor_mappings = out.len(); |
| 204 | for r in mmio { |
| 205 | if !out[..descriptor_mappings].iter().any(|m| { |
| 206 | m.flags.attribute == MemoryAttribute::DeviceNgnre |
| 207 | && m.range.start <= r.start |
| 208 | && end(m.range).is_ok_and(|e| e >= end(*r).unwrap_or(u64::MAX)) |
| 209 | }) { |
| 210 | out.push(PlannedMapping { |
| 211 | range: *r, |
| 212 | flags: flags(true, false, MemoryAttribute::DeviceNgnre), |
| 213 | }); |
| 214 | } |
| 215 | } |
| 216 | for i in 0..out.len() { |
| 217 | for j in i + 1..out.len() { |
| 218 | if overlap(out[i].range, out[j].range)? { |
| 219 | return Err(PlanError::Overlap); |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | Ok((out, decision)) |
| 224 | } |
| 225 | |
| 226 | pub const fn mair_el1() -> u64 { |
| 227 | 0x04ff |
| 228 | } |
| 229 | /// PARange is ID_AA64MMFR0_EL1[3:0], encoded as the IPS field. |
| 230 | /// TTBR0: T0SZ=16 (48-bit), WB-WA walks, inner shareable, 4 KiB granule. |
| 231 | /// TTBR1 walks are disabled (EPD1) but T1SZ/TG1 still get valid values, since |
| 232 | /// TG1 = 0b00 is a reserved encoding. |
| 233 | pub const fn tcr_el1(parange: u8) -> u64 { |
| 234 | 16 | (1 << 8) |
| 235 | | (1 << 10) |
| 236 | | (3 << 12) |
| 237 | | (16 << 16) |
| 238 | | (1 << 23) |
| 239 | | (0b10 << 30) |
| 240 | | (((parange as u64) & 7) << 32) |
| 241 | } |
| 242 | /// Architectural RES1 bits plus M, C and I. Alignment and access checks stay disabled. |
| 243 | pub const fn sctlr_el1() -> u64 { |
| 244 | 0x30d0_0800 | 1 | (1 << 2) | (1 << 12) |
| 245 | } |
| 246 | |
| 247 | #[cfg(test)] |
| 248 | mod tests { |
| 249 | use super::*; |
| 250 | fn d(t: u32, p: u64, pages: u64, a: u64) -> EfiMemoryDescriptor { |
| 251 | EfiMemoryDescriptor { |
| 252 | memory_type: t, |
| 253 | phys_start: p, |
| 254 | page_count: pages, |
| 255 | attribute: a, |
| 256 | } |
| 257 | } |
| 258 | const RX: u32 = 0x4000_0000 | IMAGE_SCN_MEM_EXECUTE; |
| 259 | const RW: u32 = 0x4000_0000 | IMAGE_SCN_MEM_WRITE; |
| 260 | #[test] |
| 261 | fn translation_register_values_match_the_architecture() { |
| 262 | assert_eq!(mair_el1() & 0xff, 0xff, "idx0 Normal WB RA/WA"); |
| 263 | assert_eq!((mair_el1() >> 8) & 0xff, 0x04, "idx1 Device-nGnRE"); |
| 264 | let tcr = tcr_el1(0b0101); // 48-bit PA |
| 265 | assert_eq!(tcr & 0x3f, 16, "T0SZ"); |
| 266 | assert_eq!((tcr >> 8) & 0b11, 0b01, "IRGN0 WB-WA"); |
| 267 | assert_eq!((tcr >> 10) & 0b11, 0b01, "ORGN0 WB-WA"); |
| 268 | assert_eq!((tcr >> 12) & 0b11, 0b11, "SH0 inner"); |
| 269 | assert_eq!((tcr >> 14) & 0b11, 0b00, "TG0 4 KiB"); |
| 270 | assert_eq!((tcr >> 16) & 0x3f, 16, "T1SZ"); |
| 271 | assert_ne!(tcr & (1 << 23), 0, "EPD1"); |
| 272 | assert_eq!((tcr >> 30) & 0b11, 0b10, "TG1 4 KiB, not reserved 0b00"); |
| 273 | assert_eq!((tcr >> 32) & 0b111, 0b101, "IPS from PARange"); |
| 274 | let sctlr = sctlr_el1(); |
| 275 | assert_eq!(sctlr & 0x30d0_0800, 0x30d0_0800, "RES1 bits"); |
| 276 | assert_eq!( |
| 277 | sctlr & ((1 << 0) | (1 << 2) | (1 << 12)), |
| 278 | 0b1_0000_0000_0101, |
| 279 | "M, C, I" |
| 280 | ); |
| 281 | assert_eq!( |
| 282 | sctlr & ((1 << 1) | (1 << 19) | (1 << 25)), |
| 283 | 0, |
| 284 | "A, WXN, EE clear" |
| 285 | ); |
| 286 | } |
| 287 | |
| 288 | #[test] |
| 289 | fn section_permissions_are_wx_safe() { |
| 290 | let mem = [d(EFI_LOADER_CODE, 0x100000, 4, 0)]; |
| 291 | let sec = [ |
| 292 | PeSection { |
| 293 | va: 0x100000, |
| 294 | size: 4096, |
| 295 | characteristics: RX, |
| 296 | }, |
| 297 | PeSection { |
| 298 | va: 0x101000, |
| 299 | size: 4096, |
| 300 | characteristics: RW, |
| 301 | }, |
| 302 | ]; |
| 303 | let (p, decision) = build_map_plan( |
| 304 | &mem, |
| 305 | 0x100000, |
| 306 | AddressRange { |
| 307 | start: 0x100000, |
| 308 | length: 16384, |
| 309 | }, |
| 310 | &sec, |
| 311 | None, |
| 312 | &[], |
| 313 | ) |
| 314 | .unwrap(); |
| 315 | assert_eq!(decision, None); |
| 316 | assert_eq!(p.len(), 2); |
| 317 | assert!(p.iter().all(|m| !(m.flags.writable && m.flags.executable))); |
| 318 | assert!(p[0].flags.executable && !p[0].flags.writable); |
| 319 | assert!(p[1].flags.writable && !p[1].flags.executable); |
| 320 | } |
| 321 | #[test] |
| 322 | fn missing_mat_maps_runtime_code_rx_without_wx() { |
| 323 | let (p, d) = build_map_plan( |
| 324 | &[d(EFI_RUNTIME_CODE, 0x400000, 1, EFI_MEMORY_RUNTIME)], |
| 325 | 0, |
| 326 | AddressRange { |
| 327 | start: 0, |
| 328 | length: 1, |
| 329 | }, |
| 330 | &[], |
| 331 | None, |
| 332 | &[], |
| 333 | ) |
| 334 | .unwrap(); |
| 335 | assert_eq!(p.len(), 1); |
| 336 | assert!(p[0].flags.executable && !p[0].flags.writable); |
| 337 | assert_eq!(d, Some(RuntimeDecision::RuntimeCodeRxUnsplit)); |
| 338 | } |
| 339 | #[test] |
| 340 | fn runtime_code_needs_ro_xp_split() { |
| 341 | let mem = [d(EFI_RUNTIME_CODE, 0x400000, 2, EFI_MEMORY_RUNTIME)]; |
| 342 | let attrs = [ |
| 343 | RuntimeAttributes { |
| 344 | range: AddressRange { |
| 345 | start: 0x400000, |
| 346 | length: 4096, |
| 347 | }, |
| 348 | read_only: true, |
| 349 | execute_protect: false, |
| 350 | }, |
| 351 | RuntimeAttributes { |
| 352 | range: AddressRange { |
| 353 | start: 0x401000, |
| 354 | length: 4096, |
| 355 | }, |
| 356 | read_only: false, |
| 357 | execute_protect: true, |
| 358 | }, |
| 359 | ]; |
| 360 | let (p, _) = build_map_plan( |
| 361 | &mem, |
| 362 | 0, |
| 363 | AddressRange { |
| 364 | start: 0, |
| 365 | length: 1, |
| 366 | }, |
| 367 | &[], |
| 368 | Some(&attrs), |
| 369 | &[], |
| 370 | ) |
| 371 | .unwrap(); |
| 372 | assert_eq!(p.len(), 2); |
| 373 | assert!(p[0].flags.executable && !p[0].flags.writable); |
| 374 | assert!(p[1].flags.writable && !p[1].flags.executable); |
| 375 | } |
| 376 | #[test] |
| 377 | fn writable_executable_runtime_code_is_mapped_rx() { |
| 378 | let m = [d(EFI_RUNTIME_CODE, 0x400000, 1, EFI_MEMORY_RUNTIME)]; |
| 379 | let a = [RuntimeAttributes { |
| 380 | range: AddressRange { |
| 381 | start: 0x400000, |
| 382 | length: 4096, |
| 383 | }, |
| 384 | read_only: false, |
| 385 | execute_protect: false, |
| 386 | }]; |
| 387 | let (plan, decision) = build_map_plan( |
| 388 | &m, |
| 389 | 0, |
| 390 | AddressRange { |
| 391 | start: 0, |
| 392 | length: 1, |
| 393 | }, |
| 394 | &[], |
| 395 | Some(&a), |
| 396 | &[], |
| 397 | ) |
| 398 | .unwrap(); |
| 399 | assert_eq!(decision, Some(RuntimeDecision::RuntimeCodeRxUnsplit)); |
| 400 | assert!(plan[0].flags.executable && !plan[0].flags.writable); |
| 401 | } |
| 402 | #[test] |
| 403 | fn mmio_is_device_nx_and_overlap_rejected() { |
| 404 | let (p, _) = build_map_plan( |
| 405 | &[], |
| 406 | 0, |
| 407 | AddressRange { |
| 408 | start: 0, |
| 409 | length: 1, |
| 410 | }, |
| 411 | &[], |
| 412 | None, |
| 413 | &[AddressRange { |
| 414 | start: 0x90000000, |
| 415 | length: 4096, |
| 416 | }], |
| 417 | ) |
| 418 | .unwrap(); |
| 419 | assert_eq!(p[0].flags.attribute, MemoryAttribute::DeviceNgnre); |
| 420 | assert!(!p[0].flags.executable); |
| 421 | assert_eq!( |
| 422 | build_map_plan( |
| 423 | &[], |
| 424 | 0, |
| 425 | AddressRange { |
| 426 | start: 0, |
| 427 | length: 1 |
| 428 | }, |
| 429 | &[], |
| 430 | None, |
| 431 | &[ |
| 432 | AddressRange { |
| 433 | start: 4096, |
| 434 | length: 8192 |
| 435 | }, |
| 436 | AddressRange { |
| 437 | start: 8192, |
| 438 | length: 4096 |
| 439 | } |
| 440 | ] |
| 441 | ), |
| 442 | Err(PlanError::Overlap) |
| 443 | ); |
| 444 | } |
| 445 | #[test] |
| 446 | fn register_values_encode_required_fields() { |
| 447 | assert_eq!(mair_el1(), 0x04ff); |
| 448 | assert_eq!(tcr_el1(5) & 7 << 32, 5 << 32); |
| 449 | assert_eq!(sctlr_el1() & (1 | 4 | 1 << 12), 1 | 4 | 1 << 12); |
| 450 | } |
| 451 | } |