blob: 29056f1881886dcfa30ea7da2205cfc0ef9ecc0e [file] [log] [blame]
David Brazdil66fc1202022-07-04 21:48:45 +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//! Project Rialto main source file.
16
17#![no_main]
18#![no_std]
David Brazdil66fc1202022-07-04 21:48:45 +010019
Alice Wang9a8b39f2023-04-12 15:31:48 +000020mod error;
David Brazdil66fc1202022-07-04 21:48:45 +010021mod exceptions;
22
23extern crate alloc;
David Brazdil66fc1202022-07-04 21:48:45 +010024
Alice Wang9a8b39f2023-04-12 15:31:48 +000025use crate::error::{Error, Result};
David Brazdil66fc1202022-07-04 21:48:45 +010026use buddy_system_allocator::LockedHeap;
Alice Wang74f7f4b2023-06-13 08:24:50 +000027use core::num::NonZeroUsize;
Alice Wangb6d2c642023-06-13 13:07:06 +000028use core::result;
Pierre-Clément Tosi3d4c5c32023-05-31 16:57:06 +000029use core::slice;
Alice Wangdda3ba92023-05-25 15:15:30 +000030use fdtpci::PciInfo;
Alice Wangb6d2c642023-06-13 13:07:06 +000031use hyp::{get_hypervisor, HypervisorCap, KvmError};
32use libfdt::FdtError;
Alice Wang9a8b39f2023-04-12 15:31:48 +000033use log::{debug, error, info};
Alice Wang4b3cc112023-06-06 12:22:53 +000034use vmbase::{
Alice Wangb6d2c642023-06-13 13:07:06 +000035 fdt::SwiotlbInfo,
Alice Wang89d29592023-06-12 09:41:29 +000036 layout::{self, crosvm},
37 main,
Alice Wangb70bdb52023-06-12 08:17:58 +000038 memory::{MemoryTracker, PageTable, MEMORY, PAGE_SIZE},
Alice Wang4b3cc112023-06-06 12:22:53 +000039 power::reboot,
40};
David Brazdil66fc1202022-07-04 21:48:45 +010041
42const SZ_1K: usize = 1024;
43const SZ_64K: usize = 64 * SZ_1K;
David Brazdil66fc1202022-07-04 21:48:45 +010044
David Brazdil66fc1202022-07-04 21:48:45 +010045#[global_allocator]
46static HEAP_ALLOCATOR: LockedHeap<32> = LockedHeap::<32>::new();
47
48static mut HEAP: [u8; SZ_64K] = [0; SZ_64K];
49
David Brazdil66fc1202022-07-04 21:48:45 +010050fn init_heap() {
51 // SAFETY: Allocator set to otherwise unused, static memory.
52 unsafe {
53 HEAP_ALLOCATOR.lock().init(&mut HEAP as *mut u8 as usize, HEAP.len());
54 }
David Brazdil66fc1202022-07-04 21:48:45 +010055}
56
Alice Wangb70bdb52023-06-12 08:17:58 +000057fn new_page_table() -> Result<PageTable> {
Alice Wangee5b1802023-06-07 07:41:54 +000058 let mut page_table = PageTable::default();
Pierre-Clément Tosi3d4c5c32023-05-31 16:57:06 +000059
Alice Wang89d29592023-06-12 09:41:29 +000060 page_table.map_device(&crosvm::MMIO_RANGE)?;
Pierre-Clément Tosi3d4c5c32023-05-31 16:57:06 +000061 page_table.map_data(&layout::scratch_range())?;
Alice Wang4b3cc112023-06-06 12:22:53 +000062 page_table.map_data(&layout::stack_range(40 * PAGE_SIZE))?;
Pierre-Clément Tosi3d4c5c32023-05-31 16:57:06 +000063 page_table.map_code(&layout::text_range())?;
64 page_table.map_rodata(&layout::rodata_range())?;
Alice Wang807fa592023-06-02 09:54:43 +000065 page_table.map_device(&layout::console_uart_range())?;
David Brazdil66fc1202022-07-04 21:48:45 +010066
Alice Wangb70bdb52023-06-12 08:17:58 +000067 Ok(page_table)
David Brazdil66fc1202022-07-04 21:48:45 +010068}
69
Alice Wang77d9dd32023-06-07 13:41:21 +000070fn try_init_logger() -> Result<bool> {
71 let mmio_guard_supported = match get_hypervisor().mmio_guard_init() {
Alice Wang9a8b39f2023-04-12 15:31:48 +000072 // pKVM blocks MMIO by default, we need to enable MMIO guard to support logging.
Alice Wang77d9dd32023-06-07 13:41:21 +000073 Ok(()) => {
74 get_hypervisor().mmio_guard_map(vmbase::console::BASE_ADDRESS)?;
75 true
76 }
Alice Wang9a8b39f2023-04-12 15:31:48 +000077 // MMIO guard enroll is not supported in unprotected VM.
Alice Wang77d9dd32023-06-07 13:41:21 +000078 Err(hyp::Error::MmioGuardNotsupported) => false,
Alice Wang9a8b39f2023-04-12 15:31:48 +000079 Err(e) => return Err(e.into()),
80 };
Alice Wang77d9dd32023-06-07 13:41:21 +000081 vmbase::logger::init(log::LevelFilter::Debug).map_err(|_| Error::LoggerInit)?;
82 Ok(mmio_guard_supported)
Alice Wang9a8b39f2023-04-12 15:31:48 +000083}
David Brazdil66fc1202022-07-04 21:48:45 +010084
Alice Wangdda3ba92023-05-25 15:15:30 +000085/// # Safety
86///
87/// Behavior is undefined if any of the following conditions are violated:
88/// * The `fdt_addr` must be a valid pointer and points to a valid `Fdt`.
89unsafe fn try_main(fdt_addr: usize) -> Result<()> {
David Brazdil66fc1202022-07-04 21:48:45 +010090 info!("Welcome to Rialto!");
Alice Wangb70bdb52023-06-12 08:17:58 +000091 let page_table = new_page_table()?;
92
93 MEMORY.lock().replace(MemoryTracker::new(
94 page_table,
95 crosvm::MEM_START..layout::MAX_VIRT_ADDR,
96 crosvm::MMIO_RANGE,
97 None, // Rialto doesn't have any payload for now.
98 ));
Alice Wang74f7f4b2023-06-13 08:24:50 +000099
100 let fdt_range = MEMORY
101 .lock()
102 .as_mut()
103 .unwrap()
104 .alloc(fdt_addr, NonZeroUsize::new(crosvm::FDT_MAX_SIZE).unwrap())?;
105 // SAFETY: The tracker validated the range to be in main memory, mapped, and not overlap.
106 let fdt = unsafe { slice::from_raw_parts(fdt_range.start as *mut u8, fdt_range.len()) };
Alice Wang674257a2023-06-13 09:44:53 +0000107 // We do not need to validate the DT since it is already validated in pvmfw.
Alice Wang74f7f4b2023-06-13 08:24:50 +0000108 let fdt = libfdt::Fdt::from_slice(fdt)?;
109 let pci_info = PciInfo::from_fdt(fdt)?;
110 debug!("PCI: {pci_info:#x?}");
111
Alice Wang674257a2023-06-13 09:44:53 +0000112 let memory_range = fdt.first_memory_range()?;
113 MEMORY.lock().as_mut().unwrap().shrink(&memory_range).map_err(|e| {
114 error!("Failed to use memory range value from DT: {memory_range:#x?}");
115 e
116 })?;
Alice Wangb6d2c642023-06-13 13:07:06 +0000117
118 if get_hypervisor().has_cap(HypervisorCap::DYNAMIC_MEM_SHARE) {
119 let granule = memory_protection_granule()?;
120 MEMORY.lock().as_mut().unwrap().init_dynamic_shared_pool(granule).map_err(|e| {
121 error!("Failed to initialize dynamically shared pool.");
122 e
123 })?;
124 } else {
125 let range = SwiotlbInfo::new_from_fdt(fdt)?.fixed_range().ok_or_else(|| {
126 error!("Pre-shared pool range not specified in swiotlb node");
127 Error::from(FdtError::BadValue)
128 })?;
129 MEMORY.lock().as_mut().unwrap().init_static_shared_pool(range).map_err(|e| {
130 error!("Failed to initialize pre-shared pool.");
131 e
132 })?;
133 }
Alice Wang9a8b39f2023-04-12 15:31:48 +0000134 Ok(())
135}
136
Alice Wangb6d2c642023-06-13 13:07:06 +0000137fn memory_protection_granule() -> result::Result<usize, hyp::Error> {
138 match get_hypervisor().memory_protection_granule() {
139 Ok(granule) => Ok(granule),
140 // Take the default page size when KVM call is not supported in non-protected VMs.
141 Err(hyp::Error::KvmError(KvmError::NotSupported, _)) => Ok(PAGE_SIZE),
142 Err(e) => Err(e),
143 }
144}
145
Alice Wang77d9dd32023-06-07 13:41:21 +0000146fn try_unshare_all_memory(mmio_guard_supported: bool) -> Result<()> {
Alice Wang77d9dd32023-06-07 13:41:21 +0000147 info!("Starting unsharing memory...");
148
Alice Wang77d9dd32023-06-07 13:41:21 +0000149 // No logging after unmapping UART.
Alice Wangb70bdb52023-06-12 08:17:58 +0000150 if mmio_guard_supported {
151 get_hypervisor().mmio_guard_unmap(vmbase::console::BASE_ADDRESS)?;
152 }
153 // Unshares all memory and deactivates page table.
154 drop(MEMORY.lock().take());
Alice Wang77d9dd32023-06-07 13:41:21 +0000155 Ok(())
156}
157
158fn unshare_all_memory(mmio_guard_supported: bool) {
159 if let Err(e) = try_unshare_all_memory(mmio_guard_supported) {
160 error!("Failed to unshare the memory: {e}");
161 }
162}
163
Alice Wang9a8b39f2023-04-12 15:31:48 +0000164/// Entry point for Rialto.
Alice Wangdda3ba92023-05-25 15:15:30 +0000165pub fn main(fdt_addr: u64, _a1: u64, _a2: u64, _a3: u64) {
Pierre-Clément Tosiff277572023-04-27 10:06:44 +0000166 init_heap();
Alice Wang77d9dd32023-06-07 13:41:21 +0000167 let Ok(mmio_guard_supported) = try_init_logger() else {
Alice Wang9a8b39f2023-04-12 15:31:48 +0000168 // Don't log anything if the logger initialization fails.
169 reboot();
Alice Wang77d9dd32023-06-07 13:41:21 +0000170 };
Alice Wangdda3ba92023-05-25 15:15:30 +0000171 // SAFETY: `fdt_addr` is supposed to be a valid pointer and points to
172 // a valid `Fdt`.
173 match unsafe { try_main(fdt_addr as usize) } {
Alice Wang77d9dd32023-06-07 13:41:21 +0000174 Ok(()) => unshare_all_memory(mmio_guard_supported),
Alice Wang9a8b39f2023-04-12 15:31:48 +0000175 Err(e) => {
176 error!("Rialto failed with {e}");
Alice Wang77d9dd32023-06-07 13:41:21 +0000177 unshare_all_memory(mmio_guard_supported);
Alice Wang9a8b39f2023-04-12 15:31:48 +0000178 reboot()
179 }
180 }
David Brazdil66fc1202022-07-04 21:48:45 +0100181}
182
David Brazdil66fc1202022-07-04 21:48:45 +0100183main!(main);