blob: 8b73130ad190724021dcefaacba407dc7680bb59 [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 Wang4e082c32023-07-11 07:41:50 +000020mod communication;
Alice Wang9a8b39f2023-04-12 15:31:48 +000021mod error;
David Brazdil66fc1202022-07-04 21:48:45 +010022mod exceptions;
Alice Wang474c0ee2023-09-14 12:52:33 +000023mod fdt;
Alice Wang76a36a22023-07-27 12:11:01 +000024mod requests;
David Brazdil66fc1202022-07-04 21:48:45 +010025
26extern crate alloc;
David Brazdil66fc1202022-07-04 21:48:45 +010027
Alice Wang748b0322023-07-24 12:51:18 +000028use crate::communication::VsockStream;
Alice Wang9a8b39f2023-04-12 15:31:48 +000029use crate::error::{Error, Result};
Alice Wang474c0ee2023-09-14 12:52:33 +000030use crate::fdt::read_dice_range_from;
Alice Wang77639bf2023-09-21 06:57:12 +000031use alloc::boxed::Box;
Alice Wang953a6572023-08-24 13:40:10 +000032use ciborium_io::Write;
Alice Wang74f7f4b2023-06-13 08:24:50 +000033use core::num::NonZeroUsize;
Pierre-Clément Tosi3d4c5c32023-05-31 16:57:06 +000034use core::slice;
Alice Wang77639bf2023-09-21 06:57:12 +000035use diced_open_dice::{bcc_handover_parse, DiceArtifacts};
Alice Wangdda3ba92023-05-25 15:15:30 +000036use fdtpci::PciInfo;
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +000037use hyp::{get_mem_sharer, get_mmio_guard};
Alice Wangb6d2c642023-06-13 13:07:06 +000038use libfdt::FdtError;
Alice Wang9a8b39f2023-04-12 15:31:48 +000039use log::{debug, error, info};
Alice Wangfbdc85b2023-09-07 12:56:46 +000040use service_vm_comm::{ServiceVmRequest, VmType};
Alice Wang62183352023-07-04 08:33:27 +000041use virtio_drivers::{
Alice Wangd158e392023-08-30 12:51:12 +000042 device::socket::{VsockAddr, VMADDR_CID_HOST},
Alice Wang62183352023-07-04 08:33:27 +000043 transport::{pci::bus::PciRoot, DeviceType, Transport},
44 Hal,
45};
Alice Wang4b3cc112023-06-06 12:22:53 +000046use vmbase::{
Pierre-Clément Tosi6a4808c2023-06-29 09:19:38 +000047 configure_heap,
Alice Wangb6d2c642023-06-13 13:07:06 +000048 fdt::SwiotlbInfo,
Alice Wang89d29592023-06-12 09:41:29 +000049 layout::{self, crosvm},
50 main,
Alice Wang62183352023-07-04 08:33:27 +000051 memory::{MemoryTracker, PageTable, MEMORY, PAGE_SIZE, SIZE_128KB},
Alice Wang4b3cc112023-06-06 12:22:53 +000052 power::reboot,
Alice Wang62183352023-07-04 08:33:27 +000053 virtio::{
54 pci::{self, PciTransportIterator, VirtIOSocket},
55 HalImpl,
56 },
Alice Wang4b3cc112023-06-06 12:22:53 +000057};
David Brazdil66fc1202022-07-04 21:48:45 +010058
Alice Wang4e082c32023-07-11 07:41:50 +000059fn host_addr() -> VsockAddr {
Alice Wang1d9a5872023-09-06 14:32:36 +000060 VsockAddr { cid: VMADDR_CID_HOST, port: vm_type().port() }
Alice Wang4e082c32023-07-11 07:41:50 +000061}
62
Alice Wang1d9a5872023-09-06 14:32:36 +000063fn vm_type() -> VmType {
Alice Wang4e082c32023-07-11 07:41:50 +000064 // Use MMIO support to determine whether the VM is protected.
Alice Wang1d9a5872023-09-06 14:32:36 +000065 if get_mmio_guard().is_some() {
66 VmType::ProtectedVm
67 } else {
68 VmType::NonProtectedVm
69 }
Alice Wang4e082c32023-07-11 07:41:50 +000070}
71
Alice Wangb70bdb52023-06-12 08:17:58 +000072fn new_page_table() -> Result<PageTable> {
Alice Wangee5b1802023-06-07 07:41:54 +000073 let mut page_table = PageTable::default();
Pierre-Clément Tosi3d4c5c32023-05-31 16:57:06 +000074
Alice Wanga3931aa2023-07-05 12:52:09 +000075 page_table.map_data(&layout::scratch_range().into())?;
76 page_table.map_data(&layout::stack_range(40 * PAGE_SIZE).into())?;
77 page_table.map_code(&layout::text_range().into())?;
78 page_table.map_rodata(&layout::rodata_range().into())?;
79 page_table.map_device(&layout::console_uart_range().into())?;
David Brazdil66fc1202022-07-04 21:48:45 +010080
Alice Wangb70bdb52023-06-12 08:17:58 +000081 Ok(page_table)
David Brazdil66fc1202022-07-04 21:48:45 +010082}
83
Alice Wangdda3ba92023-05-25 15:15:30 +000084/// # Safety
85///
86/// Behavior is undefined if any of the following conditions are violated:
87/// * The `fdt_addr` must be a valid pointer and points to a valid `Fdt`.
88unsafe fn try_main(fdt_addr: usize) -> Result<()> {
David Brazdil66fc1202022-07-04 21:48:45 +010089 info!("Welcome to Rialto!");
Alice Wangb70bdb52023-06-12 08:17:58 +000090 let page_table = new_page_table()?;
91
92 MEMORY.lock().replace(MemoryTracker::new(
93 page_table,
94 crosvm::MEM_START..layout::MAX_VIRT_ADDR,
95 crosvm::MMIO_RANGE,
96 None, // Rialto doesn't have any payload for now.
97 ));
Alice Wang74f7f4b2023-06-13 08:24:50 +000098
99 let fdt_range = MEMORY
100 .lock()
101 .as_mut()
102 .unwrap()
103 .alloc(fdt_addr, NonZeroUsize::new(crosvm::FDT_MAX_SIZE).unwrap())?;
104 // SAFETY: The tracker validated the range to be in main memory, mapped, and not overlap.
105 let fdt = unsafe { slice::from_raw_parts(fdt_range.start as *mut u8, fdt_range.len()) };
Alice Wang674257a2023-06-13 09:44:53 +0000106 // We do not need to validate the DT since it is already validated in pvmfw.
Alice Wang74f7f4b2023-06-13 08:24:50 +0000107 let fdt = libfdt::Fdt::from_slice(fdt)?;
Alice Wang74f7f4b2023-06-13 08:24:50 +0000108
Alice Wang674257a2023-06-13 09:44:53 +0000109 let memory_range = fdt.first_memory_range()?;
110 MEMORY.lock().as_mut().unwrap().shrink(&memory_range).map_err(|e| {
111 error!("Failed to use memory range value from DT: {memory_range:#x?}");
112 e
113 })?;
Alice Wangb6d2c642023-06-13 13:07:06 +0000114
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000115 if let Some(mem_sharer) = get_mem_sharer() {
116 let granule = mem_sharer.granule()?;
Alice Wangb6d2c642023-06-13 13:07:06 +0000117 MEMORY.lock().as_mut().unwrap().init_dynamic_shared_pool(granule).map_err(|e| {
118 error!("Failed to initialize dynamically shared pool.");
119 e
120 })?;
Pierre-Clément Tosi8937cb82023-07-06 15:07:38 +0000121 } else if let Ok(swiotlb_info) = SwiotlbInfo::new_from_fdt(fdt) {
122 let range = swiotlb_info.fixed_range().ok_or_else(|| {
Alice Wangb6d2c642023-06-13 13:07:06 +0000123 error!("Pre-shared pool range not specified in swiotlb node");
124 Error::from(FdtError::BadValue)
125 })?;
126 MEMORY.lock().as_mut().unwrap().init_static_shared_pool(range).map_err(|e| {
127 error!("Failed to initialize pre-shared pool.");
128 e
129 })?;
Pierre-Clément Tosi8937cb82023-07-06 15:07:38 +0000130 } else {
131 info!("No MEM_SHARE capability detected or swiotlb found: allocating buffers from heap.");
132 MEMORY.lock().as_mut().unwrap().init_heap_shared_pool().map_err(|e| {
133 error!("Failed to initialize heap-based pseudo-shared pool.");
134 e
135 })?;
Alice Wangb6d2c642023-06-13 13:07:06 +0000136 }
Alice Wang77639bf2023-09-21 06:57:12 +0000137 let bcc_handover: Box<dyn DiceArtifacts> = match vm_type() {
Alice Wang474c0ee2023-09-14 12:52:33 +0000138 VmType::ProtectedVm => {
139 let dice_range = read_dice_range_from(fdt)?;
140 info!("DICE range: {dice_range:#x?}");
Alice Wang9f3ca832023-09-20 09:33:14 +0000141 // SAFETY: This region was written by pvmfw in its writable_data region. The region
142 // has no overlap with the main memory region and is safe to be mapped as read-only
143 // data.
144 let res = unsafe {
145 MEMORY.lock().as_mut().unwrap().alloc_range_outside_main_memory(&dice_range)
146 };
147 res.map_err(|e| {
148 error!("Failed to use DICE range from DT: {dice_range:#x?}");
149 e
150 })?;
151 let dice_start = dice_range.start as *const u8;
152 // SAFETY: There's no memory overlap and the region is mapped as read-only data.
153 let bcc_handover = unsafe { slice::from_raw_parts(dice_start, dice_range.len()) };
Alice Wang77639bf2023-09-21 06:57:12 +0000154 Box::new(bcc_handover_parse(bcc_handover)?)
Alice Wang474c0ee2023-09-14 12:52:33 +0000155 }
Alice Wang77639bf2023-09-21 06:57:12 +0000156 // Currently, a sample DICE data is used for non-protected VMs, as these VMs only run
157 // in tests at the moment.
158 // If we intend to run non-protected rialto in production, we should retrieve real
159 // DICE chain data instead.
160 VmType::NonProtectedVm => Box::new(diced_sample_inputs::make_sample_bcc_and_cdis()?),
Alice Wang474c0ee2023-09-14 12:52:33 +0000161 };
Alice Wangd36c7112023-07-04 09:50:45 +0000162
163 let pci_info = PciInfo::from_fdt(fdt)?;
164 debug!("PCI: {pci_info:#x?}");
Alice Wang62183352023-07-04 08:33:27 +0000165 let mut pci_root = pci::initialize(pci_info, MEMORY.lock().as_mut().unwrap())
Alice Wangd36c7112023-07-04 09:50:45 +0000166 .map_err(Error::PciInitializationFailed)?;
167 debug!("PCI root: {pci_root:#x?}");
Alice Wang62183352023-07-04 08:33:27 +0000168 let socket_device = find_socket_device::<HalImpl>(&mut pci_root)?;
169 debug!("Found socket device: guest cid = {:?}", socket_device.guest_cid());
Alice Wang4e082c32023-07-11 07:41:50 +0000170
Alice Wang748b0322023-07-24 12:51:18 +0000171 let mut vsock_stream = VsockStream::new(socket_device, host_addr())?;
Alice Wangfbdc85b2023-09-07 12:56:46 +0000172 while let ServiceVmRequest::Process(req) = vsock_stream.read_request()? {
Alice Wang77639bf2023-09-21 06:57:12 +0000173 let response = requests::process_request(req, bcc_handover.as_ref())?;
Alice Wangfbdc85b2023-09-07 12:56:46 +0000174 vsock_stream.write_response(&response)?;
175 vsock_stream.flush()?;
176 }
Alice Wang748b0322023-07-24 12:51:18 +0000177 vsock_stream.shutdown()?;
Alice Wang4e082c32023-07-11 07:41:50 +0000178
Alice Wang9a8b39f2023-04-12 15:31:48 +0000179 Ok(())
180}
181
Alice Wang62183352023-07-04 08:33:27 +0000182fn find_socket_device<T: Hal>(pci_root: &mut PciRoot) -> Result<VirtIOSocket<T>> {
183 PciTransportIterator::<T>::new(pci_root)
184 .find(|t| DeviceType::Socket == t.device_type())
185 .map(VirtIOSocket::<T>::new)
186 .transpose()
187 .map_err(Error::VirtIOSocketCreationFailed)?
188 .ok_or(Error::MissingVirtIOSocketDevice)
189}
190
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000191fn try_unshare_all_memory() -> Result<()> {
Alice Wang77d9dd32023-06-07 13:41:21 +0000192 info!("Starting unsharing memory...");
193
Alice Wang77d9dd32023-06-07 13:41:21 +0000194 // No logging after unmapping UART.
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000195 if let Some(mmio_guard) = get_mmio_guard() {
196 mmio_guard.unmap(vmbase::console::BASE_ADDRESS)?;
Alice Wangb70bdb52023-06-12 08:17:58 +0000197 }
198 // Unshares all memory and deactivates page table.
199 drop(MEMORY.lock().take());
Alice Wang77d9dd32023-06-07 13:41:21 +0000200 Ok(())
201}
202
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000203fn unshare_all_memory() {
204 if let Err(e) = try_unshare_all_memory() {
Alice Wang77d9dd32023-06-07 13:41:21 +0000205 error!("Failed to unshare the memory: {e}");
206 }
207}
208
Alice Wang9a8b39f2023-04-12 15:31:48 +0000209/// Entry point for Rialto.
Alice Wangdda3ba92023-05-25 15:15:30 +0000210pub fn main(fdt_addr: u64, _a1: u64, _a2: u64, _a3: u64) {
Pierre-Clément Tosid3305482023-06-29 15:03:48 +0000211 log::set_max_level(log::LevelFilter::Debug);
Alice Wangdda3ba92023-05-25 15:15:30 +0000212 // SAFETY: `fdt_addr` is supposed to be a valid pointer and points to
213 // a valid `Fdt`.
214 match unsafe { try_main(fdt_addr as usize) } {
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000215 Ok(()) => unshare_all_memory(),
Alice Wang9a8b39f2023-04-12 15:31:48 +0000216 Err(e) => {
217 error!("Rialto failed with {e}");
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000218 unshare_all_memory();
Alice Wang9a8b39f2023-04-12 15:31:48 +0000219 reboot()
220 }
221 }
David Brazdil66fc1202022-07-04 21:48:45 +0100222}
223
David Brazdil66fc1202022-07-04 21:48:45 +0100224main!(main);
Alice Wang62183352023-07-04 08:33:27 +0000225configure_heap!(SIZE_128KB);