blob: 0ecbe9d510d48157b418d050426a1cdc8a5782fb [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 Wang62183352023-07-04 08:33:27 +000036use virtio_drivers::{
Alice Wangd158e392023-08-30 12:51:12 +000037 device::socket::{VsockAddr, VMADDR_CID_HOST},
Alice Wang62183352023-07-04 08:33:27 +000038 transport::{pci::bus::PciRoot, DeviceType, Transport},
39 Hal,
40};
Alice Wang4b3cc112023-06-06 12:22:53 +000041use vmbase::{
Pierre-Clément Tosi6a4808c2023-06-29 09:19:38 +000042 configure_heap,
Alice Wangb6d2c642023-06-13 13:07:06 +000043 fdt::SwiotlbInfo,
Alice Wang89d29592023-06-12 09:41:29 +000044 layout::{self, crosvm},
45 main,
Alice Wang62183352023-07-04 08:33:27 +000046 memory::{MemoryTracker, PageTable, MEMORY, PAGE_SIZE, SIZE_128KB},
Alice Wang4b3cc112023-06-06 12:22:53 +000047 power::reboot,
Alice Wang62183352023-07-04 08:33:27 +000048 virtio::{
49 pci::{self, PciTransportIterator, VirtIOSocket},
50 HalImpl,
51 },
Alice Wang4b3cc112023-06-06 12:22:53 +000052};
David Brazdil66fc1202022-07-04 21:48:45 +010053
Alice Wang4e082c32023-07-11 07:41:50 +000054fn host_addr() -> VsockAddr {
Alice Wangd158e392023-08-30 12:51:12 +000055 VsockAddr { cid: VMADDR_CID_HOST, port: service_vm_comm::host_port(is_protected_vm()) }
Alice Wang4e082c32023-07-11 07:41:50 +000056}
57
58fn is_protected_vm() -> bool {
59 // Use MMIO support to determine whether the VM is protected.
60 get_mmio_guard().is_some()
61}
62
Alice Wangb70bdb52023-06-12 08:17:58 +000063fn new_page_table() -> Result<PageTable> {
Alice Wangee5b1802023-06-07 07:41:54 +000064 let mut page_table = PageTable::default();
Pierre-Clément Tosi3d4c5c32023-05-31 16:57:06 +000065
Alice Wanga3931aa2023-07-05 12:52:09 +000066 page_table.map_data(&layout::scratch_range().into())?;
67 page_table.map_data(&layout::stack_range(40 * PAGE_SIZE).into())?;
68 page_table.map_code(&layout::text_range().into())?;
69 page_table.map_rodata(&layout::rodata_range().into())?;
70 page_table.map_device(&layout::console_uart_range().into())?;
David Brazdil66fc1202022-07-04 21:48:45 +010071
Alice Wangb70bdb52023-06-12 08:17:58 +000072 Ok(page_table)
David Brazdil66fc1202022-07-04 21:48:45 +010073}
74
Alice Wangdda3ba92023-05-25 15:15:30 +000075/// # Safety
76///
77/// Behavior is undefined if any of the following conditions are violated:
78/// * The `fdt_addr` must be a valid pointer and points to a valid `Fdt`.
79unsafe fn try_main(fdt_addr: usize) -> Result<()> {
David Brazdil66fc1202022-07-04 21:48:45 +010080 info!("Welcome to Rialto!");
Alice Wangb70bdb52023-06-12 08:17:58 +000081 let page_table = new_page_table()?;
82
83 MEMORY.lock().replace(MemoryTracker::new(
84 page_table,
85 crosvm::MEM_START..layout::MAX_VIRT_ADDR,
86 crosvm::MMIO_RANGE,
87 None, // Rialto doesn't have any payload for now.
88 ));
Alice Wang74f7f4b2023-06-13 08:24:50 +000089
90 let fdt_range = MEMORY
91 .lock()
92 .as_mut()
93 .unwrap()
94 .alloc(fdt_addr, NonZeroUsize::new(crosvm::FDT_MAX_SIZE).unwrap())?;
95 // SAFETY: The tracker validated the range to be in main memory, mapped, and not overlap.
96 let fdt = unsafe { slice::from_raw_parts(fdt_range.start as *mut u8, fdt_range.len()) };
Alice Wang674257a2023-06-13 09:44:53 +000097 // We do not need to validate the DT since it is already validated in pvmfw.
Alice Wang74f7f4b2023-06-13 08:24:50 +000098 let fdt = libfdt::Fdt::from_slice(fdt)?;
Alice Wang74f7f4b2023-06-13 08:24:50 +000099
Alice Wang674257a2023-06-13 09:44:53 +0000100 let memory_range = fdt.first_memory_range()?;
101 MEMORY.lock().as_mut().unwrap().shrink(&memory_range).map_err(|e| {
102 error!("Failed to use memory range value from DT: {memory_range:#x?}");
103 e
104 })?;
Alice Wangb6d2c642023-06-13 13:07:06 +0000105
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000106 if let Some(mem_sharer) = get_mem_sharer() {
107 let granule = mem_sharer.granule()?;
Alice Wangb6d2c642023-06-13 13:07:06 +0000108 MEMORY.lock().as_mut().unwrap().init_dynamic_shared_pool(granule).map_err(|e| {
109 error!("Failed to initialize dynamically shared pool.");
110 e
111 })?;
Pierre-Clément Tosi8937cb82023-07-06 15:07:38 +0000112 } else if let Ok(swiotlb_info) = SwiotlbInfo::new_from_fdt(fdt) {
113 let range = swiotlb_info.fixed_range().ok_or_else(|| {
Alice Wangb6d2c642023-06-13 13:07:06 +0000114 error!("Pre-shared pool range not specified in swiotlb node");
115 Error::from(FdtError::BadValue)
116 })?;
117 MEMORY.lock().as_mut().unwrap().init_static_shared_pool(range).map_err(|e| {
118 error!("Failed to initialize pre-shared pool.");
119 e
120 })?;
Pierre-Clément Tosi8937cb82023-07-06 15:07:38 +0000121 } else {
122 info!("No MEM_SHARE capability detected or swiotlb found: allocating buffers from heap.");
123 MEMORY.lock().as_mut().unwrap().init_heap_shared_pool().map_err(|e| {
124 error!("Failed to initialize heap-based pseudo-shared pool.");
125 e
126 })?;
Alice Wangb6d2c642023-06-13 13:07:06 +0000127 }
Alice Wangd36c7112023-07-04 09:50:45 +0000128
129 let pci_info = PciInfo::from_fdt(fdt)?;
130 debug!("PCI: {pci_info:#x?}");
Alice Wang62183352023-07-04 08:33:27 +0000131 let mut pci_root = pci::initialize(pci_info, MEMORY.lock().as_mut().unwrap())
Alice Wangd36c7112023-07-04 09:50:45 +0000132 .map_err(Error::PciInitializationFailed)?;
133 debug!("PCI root: {pci_root:#x?}");
Alice Wang62183352023-07-04 08:33:27 +0000134 let socket_device = find_socket_device::<HalImpl>(&mut pci_root)?;
135 debug!("Found socket device: guest cid = {:?}", socket_device.guest_cid());
Alice Wang4e082c32023-07-11 07:41:50 +0000136
Alice Wang748b0322023-07-24 12:51:18 +0000137 let mut vsock_stream = VsockStream::new(socket_device, host_addr())?;
Alice Wang33f4cae2023-09-05 09:27:39 +0000138 let response = requests::process_request(vsock_stream.read_request()?)?;
Alice Wang748b0322023-07-24 12:51:18 +0000139 vsock_stream.write_response(&response)?;
Alice Wang953a6572023-08-24 13:40:10 +0000140 vsock_stream.flush()?;
Alice Wang748b0322023-07-24 12:51:18 +0000141 vsock_stream.shutdown()?;
Alice Wang4e082c32023-07-11 07:41:50 +0000142
Alice Wang9a8b39f2023-04-12 15:31:48 +0000143 Ok(())
144}
145
Alice Wang62183352023-07-04 08:33:27 +0000146fn find_socket_device<T: Hal>(pci_root: &mut PciRoot) -> Result<VirtIOSocket<T>> {
147 PciTransportIterator::<T>::new(pci_root)
148 .find(|t| DeviceType::Socket == t.device_type())
149 .map(VirtIOSocket::<T>::new)
150 .transpose()
151 .map_err(Error::VirtIOSocketCreationFailed)?
152 .ok_or(Error::MissingVirtIOSocketDevice)
153}
154
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000155fn try_unshare_all_memory() -> Result<()> {
Alice Wang77d9dd32023-06-07 13:41:21 +0000156 info!("Starting unsharing memory...");
157
Alice Wang77d9dd32023-06-07 13:41:21 +0000158 // No logging after unmapping UART.
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000159 if let Some(mmio_guard) = get_mmio_guard() {
160 mmio_guard.unmap(vmbase::console::BASE_ADDRESS)?;
Alice Wangb70bdb52023-06-12 08:17:58 +0000161 }
162 // Unshares all memory and deactivates page table.
163 drop(MEMORY.lock().take());
Alice Wang77d9dd32023-06-07 13:41:21 +0000164 Ok(())
165}
166
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000167fn unshare_all_memory() {
168 if let Err(e) = try_unshare_all_memory() {
Alice Wang77d9dd32023-06-07 13:41:21 +0000169 error!("Failed to unshare the memory: {e}");
170 }
171}
172
Alice Wang9a8b39f2023-04-12 15:31:48 +0000173/// Entry point for Rialto.
Alice Wangdda3ba92023-05-25 15:15:30 +0000174pub fn main(fdt_addr: u64, _a1: u64, _a2: u64, _a3: u64) {
Pierre-Clément Tosid3305482023-06-29 15:03:48 +0000175 log::set_max_level(log::LevelFilter::Debug);
Alice Wangdda3ba92023-05-25 15:15:30 +0000176 // SAFETY: `fdt_addr` is supposed to be a valid pointer and points to
177 // a valid `Fdt`.
178 match unsafe { try_main(fdt_addr as usize) } {
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000179 Ok(()) => unshare_all_memory(),
Alice Wang9a8b39f2023-04-12 15:31:48 +0000180 Err(e) => {
181 error!("Rialto failed with {e}");
Pierre-Clément Tosi910a72d2023-06-29 14:29:29 +0000182 unshare_all_memory();
Alice Wang9a8b39f2023-04-12 15:31:48 +0000183 reboot()
184 }
185 }
David Brazdil66fc1202022-07-04 21:48:45 +0100186}
187
David Brazdil66fc1202022-07-04 21:48:45 +0100188main!(main);
Alice Wang62183352023-07-04 08:33:27 +0000189configure_heap!(SIZE_128KB);