blob: 0ff7270484ce851e48228adc96f86073580a0e6a [file] [log] [blame]
Pierre-Clément Tosi5bbfca52022-10-21 12:14:35 +01001// 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 entry and exit points of pvmfw.
16
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010017use crate::config;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000018use crate::fdt;
Alice Wang93ee98a2023-06-08 08:20:39 +000019use crate::memory;
Maurice Lam0322b8c2023-12-18 22:13:48 +000020use bssl_sys::CRYPTO_library_init;
Pierre-Clément Tosi645e90e2022-10-21 13:27:19 +010021use core::arch::asm;
Jakob Vukalovic4c1edbe2023-04-17 19:10:57 +010022use core::mem::{drop, size_of};
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000023use core::num::NonZeroUsize;
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +010024use core::ops::Range;
Pierre-Clément Tosi5bbfca52022-10-21 12:14:35 +010025use core::slice;
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +010026use log::debug;
27use log::error;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000028use log::info;
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010029use log::warn;
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +010030use log::LevelFilter;
Alice Wang4be4dd02023-06-07 07:50:40 +000031use vmbase::util::RangeExt as _;
Alice Wangeacb7382023-06-05 12:53:54 +000032use vmbase::{
Pierre-Clément Tosib5a3ab12023-09-15 11:18:38 +010033 configure_heap, console_writeln,
Pierre-Clément Tosia9b345f2024-04-27 01:01:42 +010034 hyp::{get_mem_sharer, get_mmio_guard},
Pierre-Clément Tosi38a36212024-06-06 11:30:39 +010035 layout::{self, crosvm, UART_PAGE_ADDR},
Pierre-Clément Tosid3305482023-06-29 15:03:48 +000036 main,
Pierre-Clément Tosif3681e82023-06-22 11:38:22 +000037 memory::{min_dcache_line_size, MemoryTracker, MEMORY, SIZE_128KB, SIZE_4KB},
Alice Wangeacb7382023-06-05 12:53:54 +000038 power::reboot,
39};
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +010040use zeroize::Zeroize;
Pierre-Clément Tosi5bbfca52022-10-21 12:14:35 +010041
42#[derive(Debug, Clone)]
Andrew Walbran19690632022-12-07 16:41:30 +000043pub enum RebootReason {
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +010044 /// A malformed BCC was received.
45 InvalidBcc,
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010046 /// An invalid configuration was appended to pvmfw.
47 InvalidConfig,
Pierre-Clément Tosi5bbfca52022-10-21 12:14:35 +010048 /// An unexpected internal error happened.
49 InternalError,
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000050 /// The provided FDT was invalid.
51 InvalidFdt,
52 /// The provided payload was invalid.
53 InvalidPayload,
54 /// The provided ramdisk was invalid.
55 InvalidRamdisk,
Alice Wang28cbcf12022-12-01 07:58:28 +000056 /// Failed to verify the payload.
57 PayloadVerificationError,
Pierre-Clément Tosi4f4f5eb2022-12-08 14:31:42 +000058 /// DICE layering process failed.
59 SecretDerivationError,
Pierre-Clément Tosi5bbfca52022-10-21 12:14:35 +010060}
61
Pierre-Clément Tosib5a3ab12023-09-15 11:18:38 +010062impl RebootReason {
63 pub fn as_avf_reboot_string(&self) -> &'static str {
64 match self {
65 Self::InvalidBcc => "PVM_FIRMWARE_INVALID_BCC",
66 Self::InvalidConfig => "PVM_FIRMWARE_INVALID_CONFIG_DATA",
67 Self::InternalError => "PVM_FIRMWARE_INTERNAL_ERROR",
68 Self::InvalidFdt => "PVM_FIRMWARE_INVALID_FDT",
69 Self::InvalidPayload => "PVM_FIRMWARE_INVALID_PAYLOAD",
70 Self::InvalidRamdisk => "PVM_FIRMWARE_INVALID_RAMDISK",
71 Self::PayloadVerificationError => "PVM_FIRMWARE_PAYLOAD_VERIFICATION_FAILED",
72 Self::SecretDerivationError => "PVM_FIRMWARE_SECRET_DERIVATION_FAILED",
73 }
74 }
75}
76
Pierre-Clément Tosi5bbfca52022-10-21 12:14:35 +010077main!(start);
Pierre-Clément Tosi6a4808c2023-06-29 09:19:38 +000078configure_heap!(SIZE_128KB);
Pierre-Clément Tosi5bbfca52022-10-21 12:14:35 +010079
80/// Entry point for pVM firmware.
81pub fn start(fdt_address: u64, payload_start: u64, payload_size: u64, _arg3: u64) {
82 // Limitations in this function:
83 // - can't access non-pvmfw memory (only statically-mapped memory)
Pierre-Clément Tosi8e92d1a2024-06-18 16:15:14 +010084 // - can't access MMIO (except the console, already configured by vmbase)
Pierre-Clément Tosi5bbfca52022-10-21 12:14:35 +010085
86 match main_wrapper(fdt_address as usize, payload_start as usize, payload_size as usize) {
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +010087 Ok((entry, bcc)) => jump_to_payload(fdt_address, entry.try_into().unwrap(), bcc),
Pierre-Clément Tosib5a3ab12023-09-15 11:18:38 +010088 Err(e) => {
89 const REBOOT_REASON_CONSOLE: usize = 1;
90 console_writeln!(REBOOT_REASON_CONSOLE, "{}", e.as_avf_reboot_string());
91 reboot()
92 }
Pierre-Clément Tosi5bbfca52022-10-21 12:14:35 +010093 }
94
95 // if we reach this point and return, vmbase::entry::rust_entry() will call power::shutdown().
96}
97
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +000098struct MemorySlices<'a> {
99 fdt: &'a mut libfdt::Fdt,
100 kernel: &'a [u8],
101 ramdisk: Option<&'a [u8]>,
102}
103
104impl<'a> MemorySlices<'a> {
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900105 fn new(
106 fdt: usize,
107 kernel: usize,
108 kernel_size: usize,
109 vm_dtbo: Option<&mut [u8]>,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900110 vm_ref_dt: Option<&[u8]>,
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900111 ) -> Result<Self, RebootReason> {
Pierre-Clément Tosid88fd2d2023-07-07 15:54:33 +0000112 let fdt_size = NonZeroUsize::new(crosvm::FDT_MAX_SIZE).unwrap();
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000113 // TODO - Only map the FDT as read-only, until we modify it right before jump_to_payload()
114 // e.g. by generating a DTBO for a template DT in main() and, on return, re-map DT as RW,
115 // overwrite with the template DT and apply the DTBO.
Pierre-Clément Tosid88fd2d2023-07-07 15:54:33 +0000116 let range = MEMORY.lock().as_mut().unwrap().alloc_mut(fdt, fdt_size).map_err(|e| {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000117 error!("Failed to allocate the FDT range: {e}");
118 RebootReason::InternalError
119 })?;
120
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100121 // SAFETY: The tracker validated the range to be in main memory, mapped, and not overlap.
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000122 let fdt = unsafe { slice::from_raw_parts_mut(range.start as *mut u8, range.len()) };
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900123
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900124 let info = fdt::sanitize_device_tree(fdt, vm_dtbo, vm_ref_dt)?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000125 let fdt = libfdt::Fdt::from_mut_slice(fdt).map_err(|e| {
Jaewan Kimc6e023b2023-10-12 15:11:05 +0900126 error!("Failed to load sanitized FDT: {e}");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000127 RebootReason::InvalidFdt
128 })?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000129 debug!("Fdt passed validation!");
130
Jiyong Park6a8789a2023-03-21 14:50:59 +0900131 let memory_range = info.memory_range;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000132 debug!("Resizing MemoryTracker to range {memory_range:#x?}");
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100133 MEMORY.lock().as_mut().unwrap().shrink(&memory_range).map_err(|e| {
134 error!("Failed to use memory range value from DT: {memory_range:#x?}: {e}");
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000135 RebootReason::InvalidFdt
136 })?;
137
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000138 if let Some(mem_sharer) = get_mem_sharer() {
139 let granule = mem_sharer.granule().map_err(|e| {
Alice Wangb6d2c642023-06-13 13:07:06 +0000140 error!("Failed to get memory protection granule: {e}");
141 RebootReason::InternalError
142 })?;
143 MEMORY.lock().as_mut().unwrap().init_dynamic_shared_pool(granule).map_err(|e| {
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000144 error!("Failed to initialize dynamically shared pool: {e}");
145 RebootReason::InternalError
146 })?;
147 } else {
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700148 let range = info.swiotlb_info.fixed_range().ok_or_else(|| {
149 error!("Pre-shared pool range not specified in swiotlb node");
150 RebootReason::InvalidFdt
151 })?;
152
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100153 MEMORY.lock().as_mut().unwrap().init_static_shared_pool(range).map_err(|e| {
Srivatsa Vaddagiri37713ec2023-04-20 04:04:08 -0700154 error!("Failed to initialize pre-shared pool {e}");
155 RebootReason::InvalidFdt
156 })?;
157 }
158
Jiyong Park6a8789a2023-03-21 14:50:59 +0900159 let kernel_range = if let Some(r) = info.kernel_range {
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100160 MEMORY.lock().as_mut().unwrap().alloc_range(&r).map_err(|e| {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +0000161 error!("Failed to obtain the kernel range with DT range: {e}");
162 RebootReason::InternalError
163 })?
164 } else if cfg!(feature = "legacy") {
165 warn!("Failed to find the kernel range in the DT; falling back to legacy ABI");
166
167 let kernel_size = NonZeroUsize::new(kernel_size).ok_or_else(|| {
168 error!("Invalid kernel size: {kernel_size:#x}");
169 RebootReason::InvalidPayload
170 })?;
171
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100172 MEMORY.lock().as_mut().unwrap().alloc(kernel, kernel_size).map_err(|e| {
Pierre-Clément Tosic3811b82022-11-29 11:24:16 +0000173 error!("Failed to obtain the kernel range with legacy range: {e}");
174 RebootReason::InternalError
175 })?
176 } else {
177 error!("Failed to locate the kernel from the DT");
178 return Err(RebootReason::InvalidPayload);
179 };
180
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100181 let kernel = kernel_range.start as *const u8;
182 // SAFETY: The tracker validated the range to be in main memory, mapped, and not overlap.
183 let kernel = unsafe { slice::from_raw_parts(kernel, kernel_range.len()) };
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000184
Jiyong Park6a8789a2023-03-21 14:50:59 +0900185 let ramdisk = if let Some(r) = info.initrd_range {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000186 debug!("Located ramdisk at {r:?}");
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100187 let r = MEMORY.lock().as_mut().unwrap().alloc_range(&r).map_err(|e| {
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000188 error!("Failed to obtain the initrd range: {e}");
189 RebootReason::InvalidRamdisk
190 })?;
191
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100192 // SAFETY: The region was validated by memory to be in main memory, mapped, and
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000193 // not overlap.
194 Some(unsafe { slice::from_raw_parts(r.start as *const u8, r.len()) })
195 } else {
196 info!("Couldn't locate the ramdisk from the device tree");
197 None
198 };
199
200 Ok(Self { fdt, kernel, ramdisk })
201 }
202}
203
Pierre-Clément Tosi5bbfca52022-10-21 12:14:35 +0100204/// Sets up the environment for main() and wraps its result for start().
205///
206/// Provide the abstractions necessary for start() to abort the pVM boot and for main() to run with
207/// the assumption that its environment has been properly configured.
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +0100208fn main_wrapper(
209 fdt: usize,
210 payload: usize,
211 payload_size: usize,
212) -> Result<(usize, Range<usize>), RebootReason> {
Pierre-Clément Tosi5bbfca52022-10-21 12:14:35 +0100213 // Limitations in this function:
214 // - only access MMIO once (and while) it has been mapped and configured
215 // - only perform logging once the logger has been initialized
216 // - only access non-pvmfw memory once (and while) it has been mapped
Pierre-Clément Tosifc531152022-10-20 12:22:23 +0100217
Pierre-Clément Tosid3305482023-06-29 15:03:48 +0000218 log::set_max_level(LevelFilter::Info);
Alice Wangee07f722023-10-03 15:20:17 +0000219 // TODO(https://crbug.com/boringssl/35): Remove this init when BoringSSL can handle this
220 // internally.
221 // SAFETY: Configures the internal state of the library - may be called multiple times.
222 unsafe {
223 CRYPTO_library_init();
224 }
Pierre-Clément Tosi41748ed2023-03-31 18:20:40 +0100225
Alice Wang807fa592023-06-02 09:54:43 +0000226 let page_table = memory::init_page_table().map_err(|e| {
Pierre-Clément Tosia8a4a202022-11-03 14:16:46 +0000227 error!("Failed to set up the dynamic page tables: {e}");
228 RebootReason::InternalError
229 })?;
Alan Stokesc3829f12023-06-02 15:02:23 +0100230
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100231 // SAFETY: We only get the appended payload from here, once. The region was statically mapped,
Alan Stokesc3829f12023-06-02 15:02:23 +0100232 // then remapped by `init_page_table()`.
233 let appended_data = unsafe { get_appended_data_slice() };
234
Alan Stokes65618332023-12-15 14:09:25 +0000235 let appended = AppendedPayload::new(appended_data).ok_or_else(|| {
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100236 error!("No valid configuration found");
237 RebootReason::InvalidConfig
Pierre-Clément Tosia8a4a202022-11-03 14:16:46 +0000238 })?;
239
Alan Stokesd0cf3cd2023-12-12 14:36:37 +0000240 let config_entries = appended.get_entries();
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +0100241
Jakob Vukalovic4c1edbe2023-04-17 19:10:57 +0100242 // Up to this point, we were using the built-in static (from .rodata) page tables.
Alice Wang4c70d142023-06-06 11:52:33 +0000243 MEMORY.lock().replace(MemoryTracker::new(
244 page_table,
Alice Wang63f4c9e2023-06-12 09:36:43 +0000245 crosvm::MEM_START..layout::MAX_VIRT_ADDR,
Alice Wang89d29592023-06-12 09:41:29 +0000246 crosvm::MMIO_RANGE,
Alice Wang5bb79502023-06-12 09:25:07 +0000247 Some(memory::appended_payload_range()),
Alice Wang4c70d142023-06-06 11:52:33 +0000248 ));
Jakob Vukalovic4c1edbe2023-04-17 19:10:57 +0100249
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900250 let slices = MemorySlices::new(
251 fdt,
252 payload,
253 payload_size,
254 config_entries.vm_dtbo,
Seungjae Yoof0af81d2024-01-17 13:48:36 +0900255 config_entries.vm_ref_dt,
Seungjae Yoo013f4c42024-01-02 13:04:19 +0900256 )?;
Pierre-Clément Tosia0934c12022-11-25 20:54:11 +0000257
Pierre-Clément Tosi072969b2022-10-19 17:32:24 +0100258 // This wrapper allows main() to be blissfully ignorant of platform details.
Alan Stokesd0cf3cd2023-12-12 14:36:37 +0000259 let next_bcc = crate::main(
260 slices.fdt,
261 slices.kernel,
262 slices.ramdisk,
263 config_entries.bcc,
264 config_entries.debug_policy,
265 )?;
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +0100266
Jakob Vukalovic44b1ce32023-04-17 19:10:10 +0100267 // Writable-dirty regions will be flushed when MemoryTracker is dropped.
Alan Stokesd0cf3cd2023-12-12 14:36:37 +0000268 config_entries.bcc.zeroize();
Pierre-Clément Tosi072969b2022-10-19 17:32:24 +0100269
Andrew Walbran19690632022-12-07 16:41:30 +0000270 info!("Expecting a bug making MMIO_GUARD_UNMAP return NOT_SUPPORTED on success");
Pierre-Clément Tosi6b867532024-04-29 02:29:42 +0100271 MEMORY.lock().as_mut().unwrap().unshare_all_mmio().map_err(|e| {
Andrew Walbran19690632022-12-07 16:41:30 +0000272 error!("Failed to unshare MMIO ranges: {e}");
273 RebootReason::InternalError
274 })?;
Pierre-Clément Tosif19c0e62023-05-02 13:56:58 +0000275 // Call unshare_all_memory here (instead of relying on the dtor) while UART is still mapped.
276 MEMORY.lock().as_mut().unwrap().unshare_all_memory();
Pierre-Clément Tosid643cfe2023-06-29 09:30:51 +0000277 if let Some(mmio_guard) = get_mmio_guard() {
Pierre-Clément Tosi38a36212024-06-06 11:30:39 +0100278 mmio_guard.unmap(UART_PAGE_ADDR).map_err(|e| {
Pierre-Clément Tosi5ad1e8c2023-06-29 10:36:48 +0000279 error!("Failed to unshare the UART: {e}");
280 RebootReason::InternalError
281 })?;
282 }
Jakob Vukalovic4c1edbe2023-04-17 19:10:57 +0100283
284 // Drop MemoryTracker and deactivate page table.
285 drop(MEMORY.lock().take());
Pierre-Clément Tosia99bfa62022-10-06 13:30:52 +0100286
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +0100287 Ok((slices.kernel.as_ptr() as usize, next_bcc))
Pierre-Clément Tosi5bbfca52022-10-21 12:14:35 +0100288}
Pierre-Clément Tosi645e90e2022-10-21 13:27:19 +0100289
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +0100290fn jump_to_payload(fdt_address: u64, payload_start: u64, bcc: Range<usize>) -> ! {
291 const ASM_STP_ALIGN: usize = size_of::<u64>() * 2;
Pierre-Clément Tosi6c0d48b2022-11-07 11:00:32 +0000292 const SCTLR_EL1_RES1: u64 = (0b11 << 28) | (0b101 << 20) | (0b1 << 11);
Pierre-Clément Tosi645e90e2022-10-21 13:27:19 +0100293 // Stage 1 instruction access cacheability is unaffected.
Pierre-Clément Tosi6c0d48b2022-11-07 11:00:32 +0000294 const SCTLR_EL1_I: u64 = 0b1 << 12;
Pierre-Clément Tosi645e90e2022-10-21 13:27:19 +0100295 // SETEND instruction disabled at EL0 in aarch32 mode.
Pierre-Clément Tosi6c0d48b2022-11-07 11:00:32 +0000296 const SCTLR_EL1_SED: u64 = 0b1 << 8;
Pierre-Clément Tosi645e90e2022-10-21 13:27:19 +0100297 // Various IT instructions are disabled at EL0 in aarch32 mode.
Pierre-Clément Tosi6c0d48b2022-11-07 11:00:32 +0000298 const SCTLR_EL1_ITD: u64 = 0b1 << 7;
Pierre-Clément Tosi645e90e2022-10-21 13:27:19 +0100299
Pierre-Clément Tosi6c0d48b2022-11-07 11:00:32 +0000300 const SCTLR_EL1_VAL: u64 = SCTLR_EL1_RES1 | SCTLR_EL1_ITD | SCTLR_EL1_SED | SCTLR_EL1_I;
Pierre-Clément Tosi645e90e2022-10-21 13:27:19 +0100301
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +0100302 let scratch = layout::scratch_range();
303
Alice Wanga3931aa2023-07-05 12:52:09 +0000304 assert_ne!(scratch.end - scratch.start, 0, "scratch memory is empty.");
305 assert_eq!(scratch.start.0 % ASM_STP_ALIGN, 0, "scratch memory is misaligned.");
306 assert_eq!(scratch.end.0 % ASM_STP_ALIGN, 0, "scratch memory is misaligned.");
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +0100307
Alice Wanga3931aa2023-07-05 12:52:09 +0000308 assert!(bcc.is_within(&(scratch.start.0..scratch.end.0)));
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +0100309 assert_eq!(bcc.start % ASM_STP_ALIGN, 0, "Misaligned guest BCC.");
310 assert_eq!(bcc.end % ASM_STP_ALIGN, 0, "Misaligned guest BCC.");
311
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +0000312 let stack = memory::stack_range();
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +0100313
Alice Wanga3931aa2023-07-05 12:52:09 +0000314 assert_ne!(stack.end - stack.start, 0, "stack region is empty.");
315 assert_eq!(stack.start.0 % ASM_STP_ALIGN, 0, "Misaligned stack region.");
316 assert_eq!(stack.end.0 % ASM_STP_ALIGN, 0, "Misaligned stack region.");
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +0100317
318 // Zero all memory that could hold secrets and that can't be safely written to from Rust.
Pierre-Clément Tosi6c0d48b2022-11-07 11:00:32 +0000319 // Disable the exception vector, caches and page table and then jump to the payload at the
320 // given address, passing it the given FDT pointer.
321 //
Andrew Walbran20bb4e42023-07-07 13:55:55 +0100322 // SAFETY: We're exiting pvmfw by passing the register values we need to a noreturn asm!().
Pierre-Clément Tosi645e90e2022-10-21 13:27:19 +0100323 unsafe {
324 asm!(
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +0100325 "cmp {scratch}, {bcc}",
326 "b.hs 1f",
327
328 // Zero .data & .bss until BCC.
329 "0: stp xzr, xzr, [{scratch}], 16",
330 "cmp {scratch}, {bcc}",
331 "b.lo 0b",
332
333 "1:",
334 // Skip BCC.
335 "mov {scratch}, {bcc_end}",
336 "cmp {scratch}, {scratch_end}",
337 "b.hs 1f",
338
339 // Keep zeroing .data & .bss.
340 "0: stp xzr, xzr, [{scratch}], 16",
341 "cmp {scratch}, {scratch_end}",
342 "b.lo 0b",
343
344 "1:",
345 // Flush d-cache over .data & .bss (including BCC).
346 "0: dc cvau, {cache_line}",
347 "add {cache_line}, {cache_line}, {dcache_line_size}",
348 "cmp {cache_line}, {scratch_end}",
349 "b.lo 0b",
350
351 "mov {cache_line}, {stack}",
352 // Zero stack region.
353 "0: stp xzr, xzr, [{stack}], 16",
354 "cmp {stack}, {stack_end}",
355 "b.lo 0b",
356
357 // Flush d-cache over stack region.
358 "0: dc cvau, {cache_line}",
359 "add {cache_line}, {cache_line}, {dcache_line_size}",
360 "cmp {cache_line}, {stack_end}",
361 "b.lo 0b",
362
Pierre-Clément Tosi645e90e2022-10-21 13:27:19 +0100363 "msr sctlr_el1, {sctlr_el1_val}",
364 "isb",
365 "mov x1, xzr",
366 "mov x2, xzr",
367 "mov x3, xzr",
368 "mov x4, xzr",
369 "mov x5, xzr",
370 "mov x6, xzr",
371 "mov x7, xzr",
372 "mov x8, xzr",
373 "mov x9, xzr",
374 "mov x10, xzr",
375 "mov x11, xzr",
376 "mov x12, xzr",
377 "mov x13, xzr",
378 "mov x14, xzr",
379 "mov x15, xzr",
380 "mov x16, xzr",
381 "mov x17, xzr",
382 "mov x18, xzr",
383 "mov x19, xzr",
384 "mov x20, xzr",
385 "mov x21, xzr",
386 "mov x22, xzr",
387 "mov x23, xzr",
388 "mov x24, xzr",
389 "mov x25, xzr",
390 "mov x26, xzr",
391 "mov x27, xzr",
392 "mov x28, xzr",
393 "mov x29, xzr",
394 "msr ttbr0_el1, xzr",
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +0100395 // Ensure that CMOs have completed before entering payload.
Pierre-Clément Tosi645e90e2022-10-21 13:27:19 +0100396 "dsb nsh",
397 "br x30",
398 sctlr_el1_val = in(reg) SCTLR_EL1_VAL,
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +0100399 bcc = in(reg) u64::try_from(bcc.start).unwrap(),
400 bcc_end = in(reg) u64::try_from(bcc.end).unwrap(),
Alice Wanga3931aa2023-07-05 12:52:09 +0000401 cache_line = in(reg) u64::try_from(scratch.start.0).unwrap(),
402 scratch = in(reg) u64::try_from(scratch.start.0).unwrap(),
403 scratch_end = in(reg) u64::try_from(scratch.end.0).unwrap(),
404 stack = in(reg) u64::try_from(stack.start.0).unwrap(),
405 stack_end = in(reg) u64::try_from(stack.end.0).unwrap(),
Alice Wang3fa9b802023-06-06 07:52:31 +0000406 dcache_line_size = in(reg) u64::try_from(min_dcache_line_size()).unwrap(),
Pierre-Clément Tosi645e90e2022-10-21 13:27:19 +0100407 in("x0") fdt_address,
408 in("x30") payload_start,
Pierre-Clément Tosi97f52492023-04-04 15:52:17 +0100409 options(noreturn),
Pierre-Clément Tosi645e90e2022-10-21 13:27:19 +0100410 );
411 };
412}
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +0100413
Alan Stokesc3829f12023-06-02 15:02:23 +0100414/// # Safety
415///
416/// This must only be called once, since we are returning a mutable reference.
417/// The appended data region must be mapped.
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +0100418unsafe fn get_appended_data_slice() -> &'static mut [u8] {
Pierre-Clément Tosiad1fc752023-05-31 16:56:56 +0000419 let range = memory::appended_payload_range();
Alan Stokesa0e42962023-04-14 17:59:50 +0100420 // SAFETY: This region is mapped and the linker script prevents it from overlapping with other
421 // objects.
Alice Wanga3931aa2023-07-05 12:52:09 +0000422 unsafe { slice::from_raw_parts_mut(range.start.0 as *mut u8, range.end - range.start) }
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +0100423}
424
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100425enum AppendedPayload<'a> {
426 /// Configuration data.
427 Config(config::Config<'a>),
428 /// Deprecated raw BCC, as used in Android T.
429 LegacyBcc(&'a mut [u8]),
430}
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +0100431
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100432impl<'a> AppendedPayload<'a> {
Alan Stokesc3829f12023-06-02 15:02:23 +0100433 fn new(data: &'a mut [u8]) -> Option<Self> {
Pierre-Clément Tosi147addf2024-04-15 15:07:58 +0100434 // The borrow checker gets confused about the ownership of data (see inline comments) so we
435 // intentionally obfuscate it using a raw pointer; see a similar issue (still not addressed
436 // in v1.77) in https://users.rust-lang.org/t/78467.
437 let data_ptr = data as *mut [u8];
438
439 // Config::new() borrows data as mutable ...
440 match config::Config::new(data) {
441 // ... so this branch has a mutable reference to data, from the Ok(Config<'a>). But ...
442 Ok(valid) => Some(Self::Config(valid)),
443 // ... if Config::new(data).is_err(), the Err holds no ref to data. However ...
444 Err(config::Error::InvalidMagic) if cfg!(feature = "legacy") => {
445 // ... the borrow checker still complains about a second mutable ref without this.
446 // SAFETY: Pointer to a valid mut (not accessed elsewhere), 'a lifetime re-used.
447 let data: &'a mut _ = unsafe { &mut *data_ptr };
448
Alice Wangeacb7382023-06-05 12:53:54 +0000449 const BCC_SIZE: usize = SIZE_4KB;
Pierre-Clément Tosi7aca7ff2022-12-12 14:04:30 +0000450 warn!("Assuming the appended data at {:?} to be a raw BCC", data.as_ptr());
451 Some(Self::LegacyBcc(&mut data[..BCC_SIZE]))
452 }
Pierre-Clément Tosi7aca7ff2022-12-12 14:04:30 +0000453 Err(e) => {
Pierre-Clément Tosi147addf2024-04-15 15:07:58 +0100454 error!("Invalid configuration data at {data_ptr:?}: {e}");
455 None
Pierre-Clément Tosi7aca7ff2022-12-12 14:04:30 +0000456 }
Pierre-Clément Tosi7aca7ff2022-12-12 14:04:30 +0000457 }
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100458 }
459
Alan Stokes65618332023-12-15 14:09:25 +0000460 fn get_entries(self) -> config::Entries<'a> {
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100461 match self {
Alan Stokesd0cf3cd2023-12-12 14:36:37 +0000462 Self::Config(cfg) => cfg.get_entries(),
463 Self::LegacyBcc(bcc) => config::Entries { bcc, ..Default::default() },
Pierre-Clément Tosi8edf72e2022-12-06 16:02:57 +0000464 }
Pierre-Clément Tosie8726e42022-10-17 13:35:27 +0100465 }
466}