blob: 4e9157409c3253a46e98913252e10a4f83ae1a29 [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 Wang76a36a22023-07-27 12:11:01 +000023mod requests;
David Brazdil66fc1202022-07-04 21:48:45 +010024
25extern crate alloc;
David Brazdil66fc1202022-07-04 21:48:45 +010026
Alice Wang748b0322023-07-24 12:51:18 +000027use crate::communication::VsockStream;
Alice Wang9a8b39f2023-04-12 15:31:48 +000028use crate::error::{Error, Result};
Alice Wang953a6572023-08-24 13:40:10 +000029use ciborium_io::Write;
Alice Wang74f7f4b2023-06-13 08:24:50 +000030use core::num::NonZeroUsize;
Pierre-Clément Tosi3d4c5c32023-05-31 16:57:06 +000031use core::slice;
Alice Wangdda3ba92023-05-25 15:15:30 +000032use fdtpci::PciInfo;
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +000033use hyp::{get_mem_sharer, get_mmio_guard};
Alice Wangb6d2c642023-06-13 13:07:06 +000034use libfdt::FdtError;
Alice Wang9a8b39f2023-04-12 15:31:48 +000035use log::{debug, error, info};
Alice Wangfbdc85b2023-09-07 12:56:46 +000036use service_vm_comm::{ServiceVmRequest, VmType};
Alice Wang62183352023-07-04 08:33:27 +000037use virtio_drivers::{
Alice Wangd158e392023-08-30 12:51:12 +000038 device::socket::{VsockAddr, VMADDR_CID_HOST},
Alice Wang62183352023-07-04 08:33:27 +000039 transport::{pci::bus::PciRoot, DeviceType, Transport},
40 Hal,
41};
Alice Wang4b3cc112023-06-06 12:22:53 +000042use vmbase::{
Pierre-Clément Tosi6a4808c2023-06-29 09:19:38 +000043 configure_heap,
Alice Wangb6d2c642023-06-13 13:07:06 +000044 fdt::SwiotlbInfo,
Alice Wang89d29592023-06-12 09:41:29 +000045 layout::{self, crosvm},
46 main,
Alice Wang62183352023-07-04 08:33:27 +000047 memory::{MemoryTracker, PageTable, MEMORY, PAGE_SIZE, SIZE_128KB},
Alice Wang4b3cc112023-06-06 12:22:53 +000048 power::reboot,
Alice Wang62183352023-07-04 08:33:27 +000049 virtio::{
50 pci::{self, PciTransportIterator, VirtIOSocket},
51 HalImpl,
52 },
Alice Wang4b3cc112023-06-06 12:22:53 +000053};
David Brazdil66fc1202022-07-04 21:48:45 +010054
Alice Wang4e082c32023-07-11 07:41:50 +000055fn host_addr() -> VsockAddr {
Alice Wang1d9a5872023-09-06 14:32:36 +000056 VsockAddr { cid: VMADDR_CID_HOST, port: vm_type().port() }
Alice Wang4e082c32023-07-11 07:41:50 +000057}
58
Alice Wang1d9a5872023-09-06 14:32:36 +000059fn vm_type() -> VmType {
Alice Wang4e082c32023-07-11 07:41:50 +000060 // Use MMIO support to determine whether the VM is protected.
Alice Wang1d9a5872023-09-06 14:32:36 +000061 if get_mmio_guard().is_some() {
62 VmType::ProtectedVm
63 } else {
64 VmType::NonProtectedVm
65 }
Alice Wang4e082c32023-07-11 07:41:50 +000066}
67
Alice Wangb70bdb52023-06-12 08:17:58 +000068fn new_page_table() -> Result<PageTable> {
Alice Wangee5b1802023-06-07 07:41:54 +000069 let mut page_table = PageTable::default();
Pierre-Clément Tosi3d4c5c32023-05-31 16:57:06 +000070
Alice Wanga3931aa2023-07-05 12:52:09 +000071 page_table.map_data(&layout::scratch_range().into())?;
72 page_table.map_data(&layout::stack_range(40 * PAGE_SIZE).into())?;
73 page_table.map_code(&layout::text_range().into())?;
74 page_table.map_rodata(&layout::rodata_range().into())?;
75 page_table.map_device(&layout::console_uart_range().into())?;
David Brazdil66fc1202022-07-04 21:48:45 +010076
Alice Wangb70bdb52023-06-12 08:17:58 +000077 Ok(page_table)
David Brazdil66fc1202022-07-04 21:48:45 +010078}
79
Alice Wangdda3ba92023-05-25 15:15:30 +000080/// # Safety
81///
82/// Behavior is undefined if any of the following conditions are violated:
83/// * The `fdt_addr` must be a valid pointer and points to a valid `Fdt`.
84unsafe fn try_main(fdt_addr: usize) -> Result<()> {
David Brazdil66fc1202022-07-04 21:48:45 +010085 info!("Welcome to Rialto!");
Alice Wangb70bdb52023-06-12 08:17:58 +000086 let page_table = new_page_table()?;
87
88 MEMORY.lock().replace(MemoryTracker::new(
89 page_table,
90 crosvm::MEM_START..layout::MAX_VIRT_ADDR,
91 crosvm::MMIO_RANGE,
92 None, // Rialto doesn't have any payload for now.
93 ));
Alice Wang74f7f4b2023-06-13 08:24:50 +000094
95 let fdt_range = MEMORY
96 .lock()
97 .as_mut()
98 .unwrap()
99 .alloc(fdt_addr, NonZeroUsize::new(crosvm::FDT_MAX_SIZE).unwrap())?;
100 // SAFETY: The tracker validated the range to be in main memory, mapped, and not overlap.
101 let fdt = unsafe { slice::from_raw_parts(fdt_range.start as *mut u8, fdt_range.len()) };
Alice Wang674257a2023-06-13 09:44:53 +0000102 // We do not need to validate the DT since it is already validated in pvmfw.
Alice Wang74f7f4b2023-06-13 08:24:50 +0000103 let fdt = libfdt::Fdt::from_slice(fdt)?;
Alice Wang74f7f4b2023-06-13 08:24:50 +0000104
Alice Wang674257a2023-06-13 09:44:53 +0000105 let memory_range = fdt.first_memory_range()?;
106 MEMORY.lock().as_mut().unwrap().shrink(&memory_range).map_err(|e| {
107 error!("Failed to use memory range value from DT: {memory_range:#x?}");
108 e
109 })?;
Alice Wangb6d2c642023-06-13 13:07:06 +0000110
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000111 if let Some(mem_sharer) = get_mem_sharer() {
112 let granule = mem_sharer.granule()?;
Alice Wangb6d2c642023-06-13 13:07:06 +0000113 MEMORY.lock().as_mut().unwrap().init_dynamic_shared_pool(granule).map_err(|e| {
114 error!("Failed to initialize dynamically shared pool.");
115 e
116 })?;
Pierre-Clément Tosi8937cb82023-07-06 15:07:38 +0000117 } else if let Ok(swiotlb_info) = SwiotlbInfo::new_from_fdt(fdt) {
118 let range = swiotlb_info.fixed_range().ok_or_else(|| {
Alice Wangb6d2c642023-06-13 13:07:06 +0000119 error!("Pre-shared pool range not specified in swiotlb node");
120 Error::from(FdtError::BadValue)
121 })?;
122 MEMORY.lock().as_mut().unwrap().init_static_shared_pool(range).map_err(|e| {
123 error!("Failed to initialize pre-shared pool.");
124 e
125 })?;
Pierre-Clément Tosi8937cb82023-07-06 15:07:38 +0000126 } else {
127 info!("No MEM_SHARE capability detected or swiotlb found: allocating buffers from heap.");
128 MEMORY.lock().as_mut().unwrap().init_heap_shared_pool().map_err(|e| {
129 error!("Failed to initialize heap-based pseudo-shared pool.");
130 e
131 })?;
Alice Wangb6d2c642023-06-13 13:07:06 +0000132 }
Alice Wangd36c7112023-07-04 09:50:45 +0000133
134 let pci_info = PciInfo::from_fdt(fdt)?;
135 debug!("PCI: {pci_info:#x?}");
Alice Wang62183352023-07-04 08:33:27 +0000136 let mut pci_root = pci::initialize(pci_info, MEMORY.lock().as_mut().unwrap())
Alice Wangd36c7112023-07-04 09:50:45 +0000137 .map_err(Error::PciInitializationFailed)?;
138 debug!("PCI root: {pci_root:#x?}");
Alice Wang62183352023-07-04 08:33:27 +0000139 let socket_device = find_socket_device::<HalImpl>(&mut pci_root)?;
140 debug!("Found socket device: guest cid = {:?}", socket_device.guest_cid());
Alice Wang4e082c32023-07-11 07:41:50 +0000141
Alice Wang748b0322023-07-24 12:51:18 +0000142 let mut vsock_stream = VsockStream::new(socket_device, host_addr())?;
Alice Wangfbdc85b2023-09-07 12:56:46 +0000143 while let ServiceVmRequest::Process(req) = vsock_stream.read_request()? {
144 let response = requests::process_request(req)?;
145 vsock_stream.write_response(&response)?;
146 vsock_stream.flush()?;
147 }
Alice Wang748b0322023-07-24 12:51:18 +0000148 vsock_stream.shutdown()?;
Alice Wang4e082c32023-07-11 07:41:50 +0000149
Alice Wang9a8b39f2023-04-12 15:31:48 +0000150 Ok(())
151}
152
Alice Wang62183352023-07-04 08:33:27 +0000153fn find_socket_device<T: Hal>(pci_root: &mut PciRoot) -> Result<VirtIOSocket<T>> {
154 PciTransportIterator::<T>::new(pci_root)
155 .find(|t| DeviceType::Socket == t.device_type())
156 .map(VirtIOSocket::<T>::new)
157 .transpose()
158 .map_err(Error::VirtIOSocketCreationFailed)?
159 .ok_or(Error::MissingVirtIOSocketDevice)
160}
161
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000162fn try_unshare_all_memory() -> Result<()> {
Alice Wang77d9dd32023-06-07 13:41:21 +0000163 info!("Starting unsharing memory...");
164
Alice Wang77d9dd32023-06-07 13:41:21 +0000165 // No logging after unmapping UART.
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000166 if let Some(mmio_guard) = get_mmio_guard() {
167 mmio_guard.unmap(vmbase::console::BASE_ADDRESS)?;
Alice Wangb70bdb52023-06-12 08:17:58 +0000168 }
169 // Unshares all memory and deactivates page table.
170 drop(MEMORY.lock().take());
Alice Wang77d9dd32023-06-07 13:41:21 +0000171 Ok(())
172}
173
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000174fn unshare_all_memory() {
175 if let Err(e) = try_unshare_all_memory() {
Alice Wang77d9dd32023-06-07 13:41:21 +0000176 error!("Failed to unshare the memory: {e}");
177 }
178}
179
Alice Wang9a8b39f2023-04-12 15:31:48 +0000180/// Entry point for Rialto.
Alice Wangdda3ba92023-05-25 15:15:30 +0000181pub fn main(fdt_addr: u64, _a1: u64, _a2: u64, _a3: u64) {
Pierre-Clément Tosid3305482023-06-29 15:03:48 +0000182 log::set_max_level(log::LevelFilter::Debug);
Alice Wangdda3ba92023-05-25 15:15:30 +0000183 // SAFETY: `fdt_addr` is supposed to be a valid pointer and points to
184 // a valid `Fdt`.
185 match unsafe { try_main(fdt_addr as usize) } {
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000186 Ok(()) => unshare_all_memory(),
Alice Wang9a8b39f2023-04-12 15:31:48 +0000187 Err(e) => {
188 error!("Rialto failed with {e}");
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000189 unshare_all_memory();
Alice Wang9a8b39f2023-04-12 15:31:48 +0000190 reboot()
191 }
192 }
David Brazdil66fc1202022-07-04 21:48:45 +0100193}
194
David Brazdil66fc1202022-07-04 21:48:45 +0100195main!(main);
Alice Wang62183352023-07-04 08:33:27 +0000196configure_heap!(SIZE_128KB);