1 // Copyright © 2019 Intel Corporation 2 // 3 // SPDX-License-Identifier: Apache-2.0 4 // 5 6 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] 7 use std::collections::BTreeMap; 8 use std::collections::HashMap; 9 use std::fs::{File, OpenOptions}; 10 use std::io::{self}; 11 use std::ops::{BitAnd, Deref, Not, Sub}; 12 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] 13 use std::os::fd::AsFd; 14 use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; 15 use std::path::PathBuf; 16 use std::sync::atomic::{AtomicU32, Ordering}; 17 use std::sync::{Arc, Barrier, Mutex}; 18 use std::{ffi, result, thread}; 19 20 use acpi_tables::{aml, Aml}; 21 use anyhow::anyhow; 22 #[cfg(target_arch = "x86_64")] 23 use arch::x86_64::{SgxEpcRegion, SgxEpcSection}; 24 use arch::RegionType; 25 #[cfg(target_arch = "x86_64")] 26 use devices::ioapic; 27 #[cfg(target_arch = "aarch64")] 28 use hypervisor::HypervisorVmError; 29 use libc::_SC_NPROCESSORS_ONLN; 30 #[cfg(target_arch = "x86_64")] 31 use libc::{MAP_NORESERVE, MAP_POPULATE, MAP_SHARED, PROT_READ, PROT_WRITE}; 32 use serde::{Deserialize, Serialize}; 33 use tracer::trace_scoped; 34 use virtio_devices::BlocksState; 35 #[cfg(target_arch = "x86_64")] 36 use vm_allocator::GsiApic; 37 use vm_allocator::{AddressAllocator, MemorySlotAllocator, SystemAllocator}; 38 use vm_device::BusDevice; 39 use vm_memory::bitmap::AtomicBitmap; 40 use vm_memory::guest_memory::FileOffset; 41 use vm_memory::mmap::MmapRegionError; 42 use vm_memory::{ 43 Address, Error as MmapError, GuestAddress, GuestAddressSpace, GuestMemory, GuestMemoryAtomic, 44 GuestMemoryError, GuestMemoryRegion, GuestUsize, MmapRegion, ReadVolatile, 45 }; 46 use vm_migration::protocol::{MemoryRange, MemoryRangeTable}; 47 use vm_migration::{ 48 Migratable, MigratableError, Pausable, Snapshot, SnapshotData, Snapshottable, Transportable, 49 }; 50 51 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] 52 use crate::coredump::{ 53 CoredumpMemoryRegion, CoredumpMemoryRegions, DumpState, GuestDebuggableError, 54 }; 55 use crate::migration::url_to_path; 56 #[cfg(target_arch = "x86_64")] 57 use crate::vm_config::SgxEpcConfig; 58 use crate::vm_config::{HotplugMethod, MemoryConfig, MemoryZoneConfig}; 59 use crate::{GuestMemoryMmap, GuestRegionMmap, MEMORY_MANAGER_SNAPSHOT_ID}; 60 61 pub const MEMORY_MANAGER_ACPI_SIZE: usize = 0x18; 62 63 const DEFAULT_MEMORY_ZONE: &str = "mem0"; 64 65 const SNAPSHOT_FILENAME: &str = "memory-ranges"; 66 67 #[cfg(target_arch = "x86_64")] 68 const X86_64_IRQ_BASE: u32 = 5; 69 70 #[cfg(target_arch = "x86_64")] 71 const SGX_PAGE_SIZE: u64 = 1 << 12; 72 73 const HOTPLUG_COUNT: usize = 8; 74 75 // Memory policy constants 76 const MPOL_BIND: u32 = 2; 77 const MPOL_MF_STRICT: u32 = 1; 78 const MPOL_MF_MOVE: u32 = 1 << 1; 79 80 // Reserve 1 MiB for platform MMIO devices (e.g. ACPI control devices) 81 const PLATFORM_DEVICE_AREA_SIZE: u64 = 1 << 20; 82 83 const MAX_PREFAULT_THREAD_COUNT: usize = 16; 84 85 #[derive(Clone, Default, Serialize, Deserialize)] 86 struct HotPlugState { 87 base: u64, 88 length: u64, 89 active: bool, 90 inserting: bool, 91 removing: bool, 92 } 93 94 pub struct VirtioMemZone { 95 region: Arc<GuestRegionMmap>, 96 virtio_device: Option<Arc<Mutex<virtio_devices::Mem>>>, 97 hotplugged_size: u64, 98 hugepages: bool, 99 blocks_state: Arc<Mutex<BlocksState>>, 100 } 101 102 impl VirtioMemZone { 103 pub fn region(&self) -> &Arc<GuestRegionMmap> { 104 &self.region 105 } 106 pub fn set_virtio_device(&mut self, virtio_device: Arc<Mutex<virtio_devices::Mem>>) { 107 self.virtio_device = Some(virtio_device); 108 } 109 pub fn hotplugged_size(&self) -> u64 { 110 self.hotplugged_size 111 } 112 pub fn hugepages(&self) -> bool { 113 self.hugepages 114 } 115 pub fn blocks_state(&self) -> &Arc<Mutex<BlocksState>> { 116 &self.blocks_state 117 } 118 pub fn plugged_ranges(&self) -> MemoryRangeTable { 119 self.blocks_state 120 .lock() 121 .unwrap() 122 .memory_ranges(self.region.start_addr().raw_value(), true) 123 } 124 } 125 126 #[derive(Default)] 127 pub struct MemoryZone { 128 regions: Vec<Arc<GuestRegionMmap>>, 129 virtio_mem_zone: Option<VirtioMemZone>, 130 } 131 132 impl MemoryZone { 133 pub fn regions(&self) -> &Vec<Arc<GuestRegionMmap>> { 134 &self.regions 135 } 136 pub fn virtio_mem_zone(&self) -> &Option<VirtioMemZone> { 137 &self.virtio_mem_zone 138 } 139 pub fn virtio_mem_zone_mut(&mut self) -> Option<&mut VirtioMemZone> { 140 self.virtio_mem_zone.as_mut() 141 } 142 } 143 144 pub type MemoryZones = HashMap<String, MemoryZone>; 145 146 #[derive(Clone, Serialize, Deserialize)] 147 struct GuestRamMapping { 148 slot: u32, 149 gpa: u64, 150 size: u64, 151 zone_id: String, 152 virtio_mem: bool, 153 file_offset: u64, 154 } 155 156 #[derive(Clone, Serialize, Deserialize)] 157 struct ArchMemRegion { 158 base: u64, 159 size: usize, 160 r_type: RegionType, 161 } 162 163 pub struct MemoryManager { 164 boot_guest_memory: GuestMemoryMmap, 165 guest_memory: GuestMemoryAtomic<GuestMemoryMmap>, 166 next_memory_slot: Arc<AtomicU32>, 167 memory_slot_free_list: Arc<Mutex<Vec<u32>>>, 168 start_of_device_area: GuestAddress, 169 end_of_device_area: GuestAddress, 170 end_of_ram_area: GuestAddress, 171 pub vm: Arc<dyn hypervisor::Vm>, 172 hotplug_slots: Vec<HotPlugState>, 173 selected_slot: usize, 174 mergeable: bool, 175 allocator: Arc<Mutex<SystemAllocator>>, 176 hotplug_method: HotplugMethod, 177 boot_ram: u64, 178 current_ram: u64, 179 next_hotplug_slot: usize, 180 shared: bool, 181 hugepages: bool, 182 hugepage_size: Option<u64>, 183 prefault: bool, 184 thp: bool, 185 #[cfg(target_arch = "x86_64")] 186 sgx_epc_region: Option<SgxEpcRegion>, 187 user_provided_zones: bool, 188 snapshot_memory_ranges: MemoryRangeTable, 189 memory_zones: MemoryZones, 190 log_dirty: bool, // Enable dirty logging for created RAM regions 191 arch_mem_regions: Vec<ArchMemRegion>, 192 ram_allocator: AddressAllocator, 193 dynamic: bool, 194 195 // Keep track of calls to create_userspace_mapping() for guest RAM. 196 // This is useful for getting the dirty pages as we need to know the 197 // slots that the mapping is created in. 198 guest_ram_mappings: Vec<GuestRamMapping>, 199 200 pub acpi_address: Option<GuestAddress>, 201 #[cfg(target_arch = "aarch64")] 202 uefi_flash: Option<GuestMemoryAtomic<GuestMemoryMmap>>, 203 } 204 205 #[derive(Debug)] 206 pub enum Error { 207 /// Failed to create shared file. 208 SharedFileCreate(io::Error), 209 210 /// Failed to set shared file length. 211 SharedFileSetLen(io::Error), 212 213 /// Mmap backed guest memory error 214 GuestMemory(MmapError), 215 216 /// Failed to allocate a memory range. 217 MemoryRangeAllocation, 218 219 /// Error from region creation 220 GuestMemoryRegion(MmapRegionError), 221 222 /// No ACPI slot available 223 NoSlotAvailable, 224 225 /// Not enough space in the hotplug RAM region 226 InsufficientHotplugRam, 227 228 /// The requested hotplug memory addition is not a valid size 229 InvalidSize, 230 231 /// Failed to create the user memory region. 232 CreateUserMemoryRegion(hypervisor::HypervisorVmError), 233 234 /// Failed to remove the user memory region. 235 RemoveUserMemoryRegion(hypervisor::HypervisorVmError), 236 237 /// Failed to EventFd. 238 EventFdFail(io::Error), 239 240 /// Eventfd write error 241 EventfdError(io::Error), 242 243 /// Failed to virtio-mem resize 244 VirtioMemResizeFail(virtio_devices::mem::Error), 245 246 /// Cannot restore VM 247 Restore(MigratableError), 248 249 /// Cannot restore VM because source URL is missing 250 RestoreMissingSourceUrl, 251 252 /// Cannot create the system allocator 253 CreateSystemAllocator, 254 255 /// Invalid SGX EPC section size 256 #[cfg(target_arch = "x86_64")] 257 EpcSectionSizeInvalid, 258 259 /// Failed allocating SGX EPC region 260 #[cfg(target_arch = "x86_64")] 261 SgxEpcRangeAllocation, 262 263 /// Failed opening SGX virtual EPC device 264 #[cfg(target_arch = "x86_64")] 265 SgxVirtEpcOpen(io::Error), 266 267 /// Failed setting the SGX virtual EPC section size 268 #[cfg(target_arch = "x86_64")] 269 SgxVirtEpcFileSetLen(io::Error), 270 271 /// Failed opening SGX provisioning device 272 #[cfg(target_arch = "x86_64")] 273 SgxProvisionOpen(io::Error), 274 275 /// Failed enabling SGX provisioning 276 #[cfg(target_arch = "x86_64")] 277 SgxEnableProvisioning(hypervisor::HypervisorVmError), 278 279 /// Failed creating a new MmapRegion instance. 280 #[cfg(target_arch = "x86_64")] 281 NewMmapRegion(vm_memory::mmap::MmapRegionError), 282 283 /// No memory zones found. 284 MissingMemoryZones, 285 286 /// Memory configuration is not valid. 287 InvalidMemoryParameters, 288 289 /// Forbidden operation. Impossible to resize guest memory if it is 290 /// backed by user defined memory regions. 291 InvalidResizeWithMemoryZones, 292 293 /// It's invalid to try applying a NUMA policy to a memory zone that is 294 /// memory mapped with MAP_SHARED. 295 InvalidSharedMemoryZoneWithHostNuma, 296 297 /// Failed applying NUMA memory policy. 298 ApplyNumaPolicy(io::Error), 299 300 /// Memory zone identifier is not unique. 301 DuplicateZoneId, 302 303 /// No virtio-mem resizing handler found. 304 MissingVirtioMemHandler, 305 306 /// Unknown memory zone. 307 UnknownMemoryZone, 308 309 /// Invalid size for resizing. Can be anything except 0. 310 InvalidHotplugSize, 311 312 /// Invalid hotplug method associated with memory zones resizing capability. 313 InvalidHotplugMethodWithMemoryZones, 314 315 /// Could not find specified memory zone identifier from hash map. 316 MissingZoneIdentifier, 317 318 /// Resizing the memory zone failed. 319 ResizeZone, 320 321 /// Guest address overflow 322 GuestAddressOverFlow, 323 324 /// Error opening snapshot file 325 SnapshotOpen(io::Error), 326 327 // Error copying snapshot into region 328 SnapshotCopy(GuestMemoryError), 329 330 /// Failed to allocate MMIO address 331 AllocateMmioAddress, 332 333 #[cfg(target_arch = "aarch64")] 334 /// Failed to create UEFI flash 335 CreateUefiFlash(HypervisorVmError), 336 337 /// Using a directory as a backing file for memory is not supported 338 DirectoryAsBackingFileForMemory, 339 340 /// Failed to stat filesystem 341 GetFileSystemBlockSize(io::Error), 342 343 /// Memory size is misaligned with default page size or its hugepage size 344 MisalignedMemorySize, 345 } 346 347 const ENABLE_FLAG: usize = 0; 348 const INSERTING_FLAG: usize = 1; 349 const REMOVING_FLAG: usize = 2; 350 const EJECT_FLAG: usize = 3; 351 352 const BASE_OFFSET_LOW: u64 = 0; 353 const BASE_OFFSET_HIGH: u64 = 0x4; 354 const LENGTH_OFFSET_LOW: u64 = 0x8; 355 const LENGTH_OFFSET_HIGH: u64 = 0xC; 356 const STATUS_OFFSET: u64 = 0x14; 357 const SELECTION_OFFSET: u64 = 0; 358 359 // The MMIO address space size is subtracted with 64k. This is done for the 360 // following reasons: 361 // - Reduce the addressable space size by at least 4k to workaround a Linux 362 // bug when the VMM allocates devices at the end of the addressable space 363 // - Windows requires the addressable space size to be 64k aligned 364 fn mmio_address_space_size(phys_bits: u8) -> u64 { 365 (1 << phys_bits) - (1 << 16) 366 } 367 368 // The `statfs` function can get information of hugetlbfs, and the hugepage size is in the 369 // `f_bsize` field. 370 // 371 // See: https://github.com/torvalds/linux/blob/v6.3/fs/hugetlbfs/inode.c#L1169 372 fn statfs_get_bsize(path: &str) -> Result<u64, Error> { 373 let path = std::ffi::CString::new(path).map_err(|_| Error::InvalidMemoryParameters)?; 374 let mut buf = std::mem::MaybeUninit::<libc::statfs>::uninit(); 375 376 // SAFETY: FFI call with a valid path and buffer 377 let ret = unsafe { libc::statfs(path.as_ptr(), buf.as_mut_ptr()) }; 378 if ret != 0 { 379 return Err(Error::GetFileSystemBlockSize( 380 std::io::Error::last_os_error(), 381 )); 382 } 383 384 // SAFETY: `buf` is valid at this point 385 // Because this value is always positive, just convert it directly. 386 // Note that the `f_bsize` is `i64` in glibc and `u64` in musl, using `as u64` will be warned 387 // by `clippy` on musl target. To avoid the warning, there should be `as _` instead of 388 // `as u64`. 389 let bsize = unsafe { (*buf.as_ptr()).f_bsize } as _; 390 Ok(bsize) 391 } 392 393 fn memory_zone_get_align_size(zone: &MemoryZoneConfig) -> Result<u64, Error> { 394 // SAFETY: FFI call. Trivially safe. 395 let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as u64 }; 396 397 // There is no backend file and the `hugepages` is disabled, just use system page size. 398 if zone.file.is_none() && !zone.hugepages { 399 return Ok(page_size); 400 } 401 402 // The `hugepages` is enabled and the `hugepage_size` is specified, just use it directly. 403 if zone.hugepages && zone.hugepage_size.is_some() { 404 return Ok(zone.hugepage_size.unwrap()); 405 } 406 407 // There are two scenarios here: 408 // - `hugepages` is enabled but `hugepage_size` is not specified: 409 // Call `statfs` for `/dev/hugepages` for getting the default size of hugepage 410 // - The backing file is specified: 411 // Call `statfs` for the file and get its `f_bsize`. If the value is larger than the page 412 // size of normal page, just use the `f_bsize` because the file is in a hugetlbfs. If the 413 // value is less than or equal to the page size, just use the page size. 414 let path = zone.file.as_ref().map_or(Ok("/dev/hugepages"), |pathbuf| { 415 pathbuf.to_str().ok_or(Error::InvalidMemoryParameters) 416 })?; 417 418 let align_size = std::cmp::max(page_size, statfs_get_bsize(path)?); 419 420 Ok(align_size) 421 } 422 423 #[inline] 424 fn align_down<T>(val: T, align: T) -> T 425 where 426 T: BitAnd<Output = T> + Not<Output = T> + Sub<Output = T> + From<u8>, 427 { 428 val & !(align - 1u8.into()) 429 } 430 431 #[inline] 432 fn is_aligned<T>(val: T, align: T) -> bool 433 where 434 T: BitAnd<Output = T> + Sub<Output = T> + From<u8> + PartialEq, 435 { 436 (val & (align - 1u8.into())) == 0u8.into() 437 } 438 439 impl BusDevice for MemoryManager { 440 fn read(&mut self, _base: u64, offset: u64, data: &mut [u8]) { 441 if self.selected_slot < self.hotplug_slots.len() { 442 let state = &self.hotplug_slots[self.selected_slot]; 443 match offset { 444 BASE_OFFSET_LOW => { 445 data.copy_from_slice(&state.base.to_le_bytes()[..4]); 446 } 447 BASE_OFFSET_HIGH => { 448 data.copy_from_slice(&state.base.to_le_bytes()[4..]); 449 } 450 LENGTH_OFFSET_LOW => { 451 data.copy_from_slice(&state.length.to_le_bytes()[..4]); 452 } 453 LENGTH_OFFSET_HIGH => { 454 data.copy_from_slice(&state.length.to_le_bytes()[4..]); 455 } 456 STATUS_OFFSET => { 457 // The Linux kernel, quite reasonably, doesn't zero the memory it gives us. 458 data.fill(0); 459 if state.active { 460 data[0] |= 1 << ENABLE_FLAG; 461 } 462 if state.inserting { 463 data[0] |= 1 << INSERTING_FLAG; 464 } 465 if state.removing { 466 data[0] |= 1 << REMOVING_FLAG; 467 } 468 } 469 _ => { 470 warn!( 471 "Unexpected offset for accessing memory manager device: {:#}", 472 offset 473 ); 474 } 475 } 476 } else { 477 warn!("Out of range memory slot: {}", self.selected_slot); 478 } 479 } 480 481 fn write(&mut self, _base: u64, offset: u64, data: &[u8]) -> Option<Arc<Barrier>> { 482 match offset { 483 SELECTION_OFFSET => { 484 self.selected_slot = usize::from(data[0]); 485 } 486 STATUS_OFFSET => { 487 if self.selected_slot < self.hotplug_slots.len() { 488 let state = &mut self.hotplug_slots[self.selected_slot]; 489 // The ACPI code writes back a 1 to acknowledge the insertion 490 if (data[0] & (1 << INSERTING_FLAG) == 1 << INSERTING_FLAG) && state.inserting { 491 state.inserting = false; 492 } 493 // Ditto for removal 494 if (data[0] & (1 << REMOVING_FLAG) == 1 << REMOVING_FLAG) && state.removing { 495 state.removing = false; 496 } 497 // Trigger removal of "DIMM" 498 if data[0] & (1 << EJECT_FLAG) == 1 << EJECT_FLAG { 499 warn!("Ejection of memory not currently supported"); 500 } 501 } else { 502 warn!("Out of range memory slot: {}", self.selected_slot); 503 } 504 } 505 _ => { 506 warn!( 507 "Unexpected offset for accessing memory manager device: {:#}", 508 offset 509 ); 510 } 511 }; 512 None 513 } 514 } 515 516 impl MemoryManager { 517 /// Creates all memory regions based on the available RAM ranges defined 518 /// by `ram_regions`, and based on the description of the memory zones. 519 /// In practice, this function can perform multiple memory mappings of the 520 /// same backing file if there's a hole in the address space between two 521 /// RAM ranges. 522 /// 523 /// One example might be ram_regions containing 2 regions (0-3G and 4G-6G) 524 /// and zones containing two zones (size 1G and size 4G). 525 /// 526 /// This function will create 3 resulting memory regions: 527 /// - First one mapping entirely the first memory zone on 0-1G range 528 /// - Second one mapping partially the second memory zone on 1G-3G range 529 /// - Third one mapping partially the second memory zone on 4G-6G range 530 /// 531 /// Also, all memory regions are page-size aligned (e.g. their sizes must 532 /// be multiple of page-size), which may leave an additional hole in the 533 /// address space when hugepage is used. 534 fn create_memory_regions_from_zones( 535 ram_regions: &[(GuestAddress, usize)], 536 zones: &[MemoryZoneConfig], 537 prefault: Option<bool>, 538 thp: bool, 539 ) -> Result<(Vec<Arc<GuestRegionMmap>>, MemoryZones), Error> { 540 let mut zone_iter = zones.iter(); 541 let mut mem_regions = Vec::new(); 542 let mut zone = zone_iter.next().ok_or(Error::MissingMemoryZones)?; 543 let mut zone_align_size = memory_zone_get_align_size(zone)?; 544 let mut zone_offset = 0u64; 545 let mut memory_zones = HashMap::new(); 546 547 if !is_aligned(zone.size, zone_align_size) { 548 return Err(Error::MisalignedMemorySize); 549 } 550 551 // Add zone id to the list of memory zones. 552 memory_zones.insert(zone.id.clone(), MemoryZone::default()); 553 554 for ram_region in ram_regions.iter() { 555 let mut ram_region_offset = 0; 556 let mut exit = false; 557 558 loop { 559 let mut ram_region_consumed = false; 560 let mut pull_next_zone = false; 561 562 let ram_region_available_size = 563 align_down(ram_region.1 as u64 - ram_region_offset, zone_align_size); 564 if ram_region_available_size == 0 { 565 break; 566 } 567 let zone_sub_size = zone.size - zone_offset; 568 569 let file_offset = zone_offset; 570 let region_start = ram_region 571 .0 572 .checked_add(ram_region_offset) 573 .ok_or(Error::GuestAddressOverFlow)?; 574 let region_size = if zone_sub_size <= ram_region_available_size { 575 if zone_sub_size == ram_region_available_size { 576 ram_region_consumed = true; 577 } 578 579 ram_region_offset += zone_sub_size; 580 pull_next_zone = true; 581 582 zone_sub_size 583 } else { 584 zone_offset += ram_region_available_size; 585 ram_region_consumed = true; 586 587 ram_region_available_size 588 }; 589 590 info!( 591 "create ram region for zone {}, region_start: {:#x}, region_size: {:#x}", 592 zone.id, 593 region_start.raw_value(), 594 region_size 595 ); 596 let region = MemoryManager::create_ram_region( 597 &zone.file, 598 file_offset, 599 region_start, 600 region_size as usize, 601 prefault.unwrap_or(zone.prefault), 602 zone.shared, 603 zone.hugepages, 604 zone.hugepage_size, 605 zone.host_numa_node, 606 None, 607 thp, 608 )?; 609 610 // Add region to the list of regions associated with the 611 // current memory zone. 612 if let Some(memory_zone) = memory_zones.get_mut(&zone.id) { 613 memory_zone.regions.push(region.clone()); 614 } 615 616 mem_regions.push(region); 617 618 if pull_next_zone { 619 // Get the next zone and reset the offset. 620 zone_offset = 0; 621 if let Some(z) = zone_iter.next() { 622 zone = z; 623 } else { 624 exit = true; 625 break; 626 } 627 zone_align_size = memory_zone_get_align_size(zone)?; 628 if !is_aligned(zone.size, zone_align_size) { 629 return Err(Error::MisalignedMemorySize); 630 } 631 632 // Check if zone id already exist. In case it does, throw 633 // an error as we need unique identifiers. Otherwise, add 634 // the new zone id to the list of memory zones. 635 if memory_zones.contains_key(&zone.id) { 636 error!( 637 "Memory zone identifier '{}' found more than once. \ 638 It must be unique", 639 zone.id, 640 ); 641 return Err(Error::DuplicateZoneId); 642 } 643 memory_zones.insert(zone.id.clone(), MemoryZone::default()); 644 } 645 646 if ram_region_consumed { 647 break; 648 } 649 } 650 651 if exit { 652 break; 653 } 654 } 655 656 Ok((mem_regions, memory_zones)) 657 } 658 659 // Restore both GuestMemory regions along with MemoryZone zones. 660 fn restore_memory_regions_and_zones( 661 guest_ram_mappings: &[GuestRamMapping], 662 zones_config: &[MemoryZoneConfig], 663 prefault: Option<bool>, 664 mut existing_memory_files: HashMap<u32, File>, 665 thp: bool, 666 ) -> Result<(Vec<Arc<GuestRegionMmap>>, MemoryZones), Error> { 667 let mut memory_regions = Vec::new(); 668 let mut memory_zones = HashMap::new(); 669 670 for zone_config in zones_config { 671 memory_zones.insert(zone_config.id.clone(), MemoryZone::default()); 672 } 673 674 for guest_ram_mapping in guest_ram_mappings { 675 for zone_config in zones_config { 676 if guest_ram_mapping.zone_id == zone_config.id { 677 let region = MemoryManager::create_ram_region( 678 if guest_ram_mapping.virtio_mem { 679 &None 680 } else { 681 &zone_config.file 682 }, 683 guest_ram_mapping.file_offset, 684 GuestAddress(guest_ram_mapping.gpa), 685 guest_ram_mapping.size as usize, 686 prefault.unwrap_or(zone_config.prefault), 687 zone_config.shared, 688 zone_config.hugepages, 689 zone_config.hugepage_size, 690 zone_config.host_numa_node, 691 existing_memory_files.remove(&guest_ram_mapping.slot), 692 thp, 693 )?; 694 memory_regions.push(Arc::clone(®ion)); 695 if let Some(memory_zone) = memory_zones.get_mut(&guest_ram_mapping.zone_id) { 696 if guest_ram_mapping.virtio_mem { 697 let hotplugged_size = zone_config.hotplugged_size.unwrap_or(0); 698 let region_size = region.len(); 699 memory_zone.virtio_mem_zone = Some(VirtioMemZone { 700 region, 701 virtio_device: None, 702 hotplugged_size, 703 hugepages: zone_config.hugepages, 704 blocks_state: Arc::new(Mutex::new(BlocksState::new(region_size))), 705 }); 706 } else { 707 memory_zone.regions.push(region); 708 } 709 } 710 } 711 } 712 } 713 714 memory_regions.sort_by_key(|x| x.start_addr()); 715 716 Ok((memory_regions, memory_zones)) 717 } 718 719 fn fill_saved_regions( 720 &mut self, 721 file_path: PathBuf, 722 saved_regions: MemoryRangeTable, 723 ) -> Result<(), Error> { 724 if saved_regions.is_empty() { 725 return Ok(()); 726 } 727 728 // Open (read only) the snapshot file. 729 let mut memory_file = OpenOptions::new() 730 .read(true) 731 .open(file_path) 732 .map_err(Error::SnapshotOpen)?; 733 734 let guest_memory = self.guest_memory.memory(); 735 for range in saved_regions.regions() { 736 let mut offset: u64 = 0; 737 // Here we are manually handling the retry in case we can't write 738 // the whole region at once because we can't use the implementation 739 // from vm-memory::GuestMemory of read_exact_from() as it is not 740 // following the correct behavior. For more info about this issue 741 // see: https://github.com/rust-vmm/vm-memory/issues/174 742 loop { 743 let bytes_read = guest_memory 744 .read_volatile_from( 745 GuestAddress(range.gpa + offset), 746 &mut memory_file, 747 (range.length - offset) as usize, 748 ) 749 .map_err(Error::SnapshotCopy)?; 750 offset += bytes_read as u64; 751 752 if offset == range.length { 753 break; 754 } 755 } 756 } 757 758 Ok(()) 759 } 760 761 fn validate_memory_config( 762 config: &MemoryConfig, 763 user_provided_zones: bool, 764 ) -> Result<(u64, Vec<MemoryZoneConfig>, bool), Error> { 765 let mut allow_mem_hotplug = false; 766 767 if !user_provided_zones { 768 if config.zones.is_some() { 769 error!( 770 "User defined memory regions can't be provided if the \ 771 memory size is not 0" 772 ); 773 return Err(Error::InvalidMemoryParameters); 774 } 775 776 if config.hotplug_size.is_some() { 777 allow_mem_hotplug = true; 778 } 779 780 if let Some(hotplugged_size) = config.hotplugged_size { 781 if let Some(hotplug_size) = config.hotplug_size { 782 if hotplugged_size > hotplug_size { 783 error!( 784 "'hotplugged_size' {} can't be bigger than \ 785 'hotplug_size' {}", 786 hotplugged_size, hotplug_size, 787 ); 788 return Err(Error::InvalidMemoryParameters); 789 } 790 } else { 791 error!( 792 "Invalid to define 'hotplugged_size' when there is\ 793 no 'hotplug_size'" 794 ); 795 return Err(Error::InvalidMemoryParameters); 796 } 797 if config.hotplug_method == HotplugMethod::Acpi { 798 error!( 799 "Invalid to define 'hotplugged_size' with hotplug \ 800 method 'acpi'" 801 ); 802 return Err(Error::InvalidMemoryParameters); 803 } 804 } 805 806 // Create a single zone from the global memory config. This lets 807 // us reuse the codepath for user defined memory zones. 808 let zones = vec![MemoryZoneConfig { 809 id: String::from(DEFAULT_MEMORY_ZONE), 810 size: config.size, 811 file: None, 812 shared: config.shared, 813 hugepages: config.hugepages, 814 hugepage_size: config.hugepage_size, 815 host_numa_node: None, 816 hotplug_size: config.hotplug_size, 817 hotplugged_size: config.hotplugged_size, 818 prefault: config.prefault, 819 }]; 820 821 Ok((config.size, zones, allow_mem_hotplug)) 822 } else { 823 if config.zones.is_none() { 824 error!( 825 "User defined memory regions must be provided if the \ 826 memory size is 0" 827 ); 828 return Err(Error::MissingMemoryZones); 829 } 830 831 // Safe to unwrap as we checked right above there were some 832 // regions. 833 let zones = config.zones.clone().unwrap(); 834 if zones.is_empty() { 835 return Err(Error::MissingMemoryZones); 836 } 837 838 let mut total_ram_size: u64 = 0; 839 for zone in zones.iter() { 840 total_ram_size += zone.size; 841 842 if zone.shared && zone.file.is_some() && zone.host_numa_node.is_some() { 843 error!( 844 "Invalid to set host NUMA policy for a memory zone \ 845 backed by a regular file and mapped as 'shared'" 846 ); 847 return Err(Error::InvalidSharedMemoryZoneWithHostNuma); 848 } 849 850 if zone.hotplug_size.is_some() && config.hotplug_method == HotplugMethod::Acpi { 851 error!("Invalid to set ACPI hotplug method for memory zones"); 852 return Err(Error::InvalidHotplugMethodWithMemoryZones); 853 } 854 855 if let Some(hotplugged_size) = zone.hotplugged_size { 856 if let Some(hotplug_size) = zone.hotplug_size { 857 if hotplugged_size > hotplug_size { 858 error!( 859 "'hotplugged_size' {} can't be bigger than \ 860 'hotplug_size' {}", 861 hotplugged_size, hotplug_size, 862 ); 863 return Err(Error::InvalidMemoryParameters); 864 } 865 } else { 866 error!( 867 "Invalid to define 'hotplugged_size' when there is\ 868 no 'hotplug_size' for a memory zone" 869 ); 870 return Err(Error::InvalidMemoryParameters); 871 } 872 if config.hotplug_method == HotplugMethod::Acpi { 873 error!( 874 "Invalid to define 'hotplugged_size' with hotplug \ 875 method 'acpi'" 876 ); 877 return Err(Error::InvalidMemoryParameters); 878 } 879 } 880 } 881 882 Ok((total_ram_size, zones, allow_mem_hotplug)) 883 } 884 } 885 886 pub fn allocate_address_space(&mut self) -> Result<(), Error> { 887 let mut list = Vec::new(); 888 889 for (zone_id, memory_zone) in self.memory_zones.iter() { 890 let mut regions: Vec<(Arc<vm_memory::GuestRegionMmap<AtomicBitmap>>, bool)> = 891 memory_zone 892 .regions() 893 .iter() 894 .map(|r| (r.clone(), false)) 895 .collect(); 896 897 if let Some(virtio_mem_zone) = memory_zone.virtio_mem_zone() { 898 regions.push((virtio_mem_zone.region().clone(), true)); 899 } 900 901 list.push((zone_id.clone(), regions)); 902 } 903 904 for (zone_id, regions) in list { 905 for (region, virtio_mem) in regions { 906 let slot = self.create_userspace_mapping( 907 region.start_addr().raw_value(), 908 region.len(), 909 region.as_ptr() as u64, 910 self.mergeable, 911 false, 912 self.log_dirty, 913 )?; 914 915 let file_offset = if let Some(file_offset) = region.file_offset() { 916 file_offset.start() 917 } else { 918 0 919 }; 920 921 self.guest_ram_mappings.push(GuestRamMapping { 922 gpa: region.start_addr().raw_value(), 923 size: region.len(), 924 slot, 925 zone_id: zone_id.clone(), 926 virtio_mem, 927 file_offset, 928 }); 929 self.ram_allocator 930 .allocate(Some(region.start_addr()), region.len(), None) 931 .ok_or(Error::MemoryRangeAllocation)?; 932 } 933 } 934 935 // Allocate SubRegion and Reserved address ranges. 936 for region in self.arch_mem_regions.iter() { 937 if region.r_type == RegionType::Ram { 938 // Ignore the RAM type since ranges have already been allocated 939 // based on the GuestMemory regions. 940 continue; 941 } 942 self.ram_allocator 943 .allocate( 944 Some(GuestAddress(region.base)), 945 region.size as GuestUsize, 946 None, 947 ) 948 .ok_or(Error::MemoryRangeAllocation)?; 949 } 950 951 Ok(()) 952 } 953 954 #[cfg(target_arch = "aarch64")] 955 fn add_uefi_flash(&mut self) -> Result<(), Error> { 956 // On AArch64, the UEFI binary requires a flash device at address 0. 957 // 4 MiB memory is mapped to simulate the flash. 958 let uefi_mem_slot = self.allocate_memory_slot(); 959 let uefi_region = GuestRegionMmap::new( 960 MmapRegion::new(arch::layout::UEFI_SIZE as usize).unwrap(), 961 arch::layout::UEFI_START, 962 ) 963 .unwrap(); 964 let uefi_mem_region = self.vm.make_user_memory_region( 965 uefi_mem_slot, 966 uefi_region.start_addr().raw_value(), 967 uefi_region.len(), 968 uefi_region.as_ptr() as u64, 969 false, 970 false, 971 ); 972 self.vm 973 .create_user_memory_region(uefi_mem_region) 974 .map_err(Error::CreateUefiFlash)?; 975 976 let uefi_flash = 977 GuestMemoryAtomic::new(GuestMemoryMmap::from_regions(vec![uefi_region]).unwrap()); 978 979 self.uefi_flash = Some(uefi_flash); 980 981 Ok(()) 982 } 983 984 #[allow(clippy::too_many_arguments)] 985 pub fn new( 986 vm: Arc<dyn hypervisor::Vm>, 987 config: &MemoryConfig, 988 prefault: Option<bool>, 989 phys_bits: u8, 990 #[cfg(feature = "tdx")] tdx_enabled: bool, 991 restore_data: Option<&MemoryManagerSnapshotData>, 992 existing_memory_files: Option<HashMap<u32, File>>, 993 #[cfg(target_arch = "x86_64")] sgx_epc_config: Option<Vec<SgxEpcConfig>>, 994 ) -> Result<Arc<Mutex<MemoryManager>>, Error> { 995 trace_scoped!("MemoryManager::new"); 996 997 let user_provided_zones = config.size == 0; 998 999 let mmio_address_space_size = mmio_address_space_size(phys_bits); 1000 debug_assert_eq!( 1001 (((mmio_address_space_size) >> 16) << 16), 1002 mmio_address_space_size 1003 ); 1004 let start_of_platform_device_area = 1005 GuestAddress(mmio_address_space_size - PLATFORM_DEVICE_AREA_SIZE); 1006 let end_of_device_area = start_of_platform_device_area.unchecked_sub(1); 1007 1008 let (ram_size, zones, allow_mem_hotplug) = 1009 Self::validate_memory_config(config, user_provided_zones)?; 1010 1011 let ( 1012 start_of_device_area, 1013 boot_ram, 1014 current_ram, 1015 arch_mem_regions, 1016 memory_zones, 1017 guest_memory, 1018 boot_guest_memory, 1019 hotplug_slots, 1020 next_memory_slot, 1021 selected_slot, 1022 next_hotplug_slot, 1023 ) = if let Some(data) = restore_data { 1024 let (regions, memory_zones) = Self::restore_memory_regions_and_zones( 1025 &data.guest_ram_mappings, 1026 &zones, 1027 prefault, 1028 existing_memory_files.unwrap_or_default(), 1029 config.thp, 1030 )?; 1031 let guest_memory = 1032 GuestMemoryMmap::from_arc_regions(regions).map_err(Error::GuestMemory)?; 1033 let boot_guest_memory = guest_memory.clone(); 1034 ( 1035 GuestAddress(data.start_of_device_area), 1036 data.boot_ram, 1037 data.current_ram, 1038 data.arch_mem_regions.clone(), 1039 memory_zones, 1040 guest_memory, 1041 boot_guest_memory, 1042 data.hotplug_slots.clone(), 1043 data.next_memory_slot, 1044 data.selected_slot, 1045 data.next_hotplug_slot, 1046 ) 1047 } else { 1048 // Init guest memory 1049 let arch_mem_regions = arch::arch_memory_regions(); 1050 1051 let ram_regions: Vec<(GuestAddress, usize)> = arch_mem_regions 1052 .iter() 1053 .filter(|r| r.2 == RegionType::Ram) 1054 .map(|r| (r.0, r.1)) 1055 .collect(); 1056 1057 let arch_mem_regions: Vec<ArchMemRegion> = arch_mem_regions 1058 .iter() 1059 .map(|(a, b, c)| ArchMemRegion { 1060 base: a.0, 1061 size: *b, 1062 r_type: *c, 1063 }) 1064 .collect(); 1065 1066 let (mem_regions, mut memory_zones) = 1067 Self::create_memory_regions_from_zones(&ram_regions, &zones, prefault, config.thp)?; 1068 1069 let mut guest_memory = 1070 GuestMemoryMmap::from_arc_regions(mem_regions).map_err(Error::GuestMemory)?; 1071 1072 let boot_guest_memory = guest_memory.clone(); 1073 1074 let mut start_of_device_area = 1075 MemoryManager::start_addr(guest_memory.last_addr(), allow_mem_hotplug)?; 1076 1077 // Update list of memory zones for resize. 1078 for zone in zones.iter() { 1079 if let Some(memory_zone) = memory_zones.get_mut(&zone.id) { 1080 if let Some(hotplug_size) = zone.hotplug_size { 1081 if hotplug_size == 0 { 1082 error!("'hotplug_size' can't be 0"); 1083 return Err(Error::InvalidHotplugSize); 1084 } 1085 1086 if !user_provided_zones && config.hotplug_method == HotplugMethod::Acpi { 1087 start_of_device_area = start_of_device_area 1088 .checked_add(hotplug_size) 1089 .ok_or(Error::GuestAddressOverFlow)?; 1090 } else { 1091 // Alignment must be "natural" i.e. same as size of block 1092 let start_addr = GuestAddress( 1093 start_of_device_area 1094 .0 1095 .div_ceil(virtio_devices::VIRTIO_MEM_ALIGN_SIZE) 1096 * virtio_devices::VIRTIO_MEM_ALIGN_SIZE, 1097 ); 1098 1099 // When `prefault` is set by vm_restore, memory manager 1100 // will create ram region with `prefault` option in 1101 // restore config rather than same option in zone 1102 let region = MemoryManager::create_ram_region( 1103 &None, 1104 0, 1105 start_addr, 1106 hotplug_size as usize, 1107 prefault.unwrap_or(zone.prefault), 1108 zone.shared, 1109 zone.hugepages, 1110 zone.hugepage_size, 1111 zone.host_numa_node, 1112 None, 1113 config.thp, 1114 )?; 1115 1116 guest_memory = guest_memory 1117 .insert_region(Arc::clone(®ion)) 1118 .map_err(Error::GuestMemory)?; 1119 1120 let hotplugged_size = zone.hotplugged_size.unwrap_or(0); 1121 let region_size = region.len(); 1122 memory_zone.virtio_mem_zone = Some(VirtioMemZone { 1123 region, 1124 virtio_device: None, 1125 hotplugged_size, 1126 hugepages: zone.hugepages, 1127 blocks_state: Arc::new(Mutex::new(BlocksState::new(region_size))), 1128 }); 1129 1130 start_of_device_area = start_addr 1131 .checked_add(hotplug_size) 1132 .ok_or(Error::GuestAddressOverFlow)?; 1133 } 1134 } 1135 } else { 1136 return Err(Error::MissingZoneIdentifier); 1137 } 1138 } 1139 1140 let mut hotplug_slots = Vec::with_capacity(HOTPLUG_COUNT); 1141 hotplug_slots.resize_with(HOTPLUG_COUNT, HotPlugState::default); 1142 1143 ( 1144 start_of_device_area, 1145 ram_size, 1146 ram_size, 1147 arch_mem_regions, 1148 memory_zones, 1149 guest_memory, 1150 boot_guest_memory, 1151 hotplug_slots, 1152 0, 1153 0, 1154 0, 1155 ) 1156 }; 1157 1158 let guest_memory = GuestMemoryAtomic::new(guest_memory); 1159 1160 let allocator = Arc::new(Mutex::new( 1161 SystemAllocator::new( 1162 GuestAddress(0), 1163 1 << 16, 1164 start_of_platform_device_area, 1165 PLATFORM_DEVICE_AREA_SIZE, 1166 #[cfg(target_arch = "x86_64")] 1167 vec![GsiApic::new( 1168 X86_64_IRQ_BASE, 1169 ioapic::NUM_IOAPIC_PINS as u32 - X86_64_IRQ_BASE, 1170 )], 1171 ) 1172 .ok_or(Error::CreateSystemAllocator)?, 1173 )); 1174 1175 #[cfg(not(feature = "tdx"))] 1176 let dynamic = true; 1177 #[cfg(feature = "tdx")] 1178 let dynamic = !tdx_enabled; 1179 1180 let acpi_address = if dynamic 1181 && config.hotplug_method == HotplugMethod::Acpi 1182 && (config.hotplug_size.unwrap_or_default() > 0) 1183 { 1184 Some( 1185 allocator 1186 .lock() 1187 .unwrap() 1188 .allocate_platform_mmio_addresses(None, MEMORY_MANAGER_ACPI_SIZE as u64, None) 1189 .ok_or(Error::AllocateMmioAddress)?, 1190 ) 1191 } else { 1192 None 1193 }; 1194 1195 // If running on SGX the start of device area and RAM area may diverge but 1196 // at this point they are next to each other. 1197 let end_of_ram_area = start_of_device_area.unchecked_sub(1); 1198 let ram_allocator = AddressAllocator::new(GuestAddress(0), start_of_device_area.0).unwrap(); 1199 1200 let mut memory_manager = MemoryManager { 1201 boot_guest_memory, 1202 guest_memory, 1203 next_memory_slot: Arc::new(AtomicU32::new(next_memory_slot)), 1204 memory_slot_free_list: Arc::new(Mutex::new(Vec::new())), 1205 start_of_device_area, 1206 end_of_device_area, 1207 end_of_ram_area, 1208 vm, 1209 hotplug_slots, 1210 selected_slot, 1211 mergeable: config.mergeable, 1212 allocator, 1213 hotplug_method: config.hotplug_method, 1214 boot_ram, 1215 current_ram, 1216 next_hotplug_slot, 1217 shared: config.shared, 1218 hugepages: config.hugepages, 1219 hugepage_size: config.hugepage_size, 1220 prefault: config.prefault, 1221 #[cfg(target_arch = "x86_64")] 1222 sgx_epc_region: None, 1223 user_provided_zones, 1224 snapshot_memory_ranges: MemoryRangeTable::default(), 1225 memory_zones, 1226 guest_ram_mappings: Vec::new(), 1227 acpi_address, 1228 log_dirty: dynamic, // Cannot log dirty pages on a TD 1229 arch_mem_regions, 1230 ram_allocator, 1231 dynamic, 1232 #[cfg(target_arch = "aarch64")] 1233 uefi_flash: None, 1234 thp: config.thp, 1235 }; 1236 1237 #[cfg(target_arch = "aarch64")] 1238 { 1239 // For Aarch64 we cannot lazily allocate the address space like we 1240 // do for x86, because while restoring a VM from snapshot we would 1241 // need the address space to be allocated to properly restore VGIC. 1242 // And the restore of VGIC happens before we attempt to run the vCPUs 1243 // for the first time, thus we need to allocate the address space 1244 // beforehand. 1245 memory_manager.allocate_address_space()?; 1246 memory_manager.add_uefi_flash()?; 1247 } 1248 1249 #[cfg(target_arch = "x86_64")] 1250 if let Some(sgx_epc_config) = sgx_epc_config { 1251 memory_manager.setup_sgx(sgx_epc_config)?; 1252 } 1253 1254 Ok(Arc::new(Mutex::new(memory_manager))) 1255 } 1256 1257 pub fn new_from_snapshot( 1258 snapshot: &Snapshot, 1259 vm: Arc<dyn hypervisor::Vm>, 1260 config: &MemoryConfig, 1261 source_url: Option<&str>, 1262 prefault: bool, 1263 phys_bits: u8, 1264 ) -> Result<Arc<Mutex<MemoryManager>>, Error> { 1265 if let Some(source_url) = source_url { 1266 let mut memory_file_path = url_to_path(source_url).map_err(Error::Restore)?; 1267 memory_file_path.push(String::from(SNAPSHOT_FILENAME)); 1268 1269 let mem_snapshot: MemoryManagerSnapshotData = 1270 snapshot.to_state().map_err(Error::Restore)?; 1271 1272 let mm = MemoryManager::new( 1273 vm, 1274 config, 1275 Some(prefault), 1276 phys_bits, 1277 #[cfg(feature = "tdx")] 1278 false, 1279 Some(&mem_snapshot), 1280 None, 1281 #[cfg(target_arch = "x86_64")] 1282 None, 1283 )?; 1284 1285 mm.lock() 1286 .unwrap() 1287 .fill_saved_regions(memory_file_path, mem_snapshot.memory_ranges)?; 1288 1289 Ok(mm) 1290 } else { 1291 Err(Error::RestoreMissingSourceUrl) 1292 } 1293 } 1294 1295 fn memfd_create(name: &ffi::CStr, flags: u32) -> Result<RawFd, io::Error> { 1296 // SAFETY: FFI call with correct arguments 1297 let res = unsafe { libc::syscall(libc::SYS_memfd_create, name.as_ptr(), flags) }; 1298 1299 if res < 0 { 1300 Err(io::Error::last_os_error()) 1301 } else { 1302 Ok(res as RawFd) 1303 } 1304 } 1305 1306 fn mbind( 1307 addr: *mut u8, 1308 len: u64, 1309 mode: u32, 1310 nodemask: Vec<u64>, 1311 maxnode: u64, 1312 flags: u32, 1313 ) -> Result<(), io::Error> { 1314 // SAFETY: FFI call with correct arguments 1315 let res = unsafe { 1316 libc::syscall( 1317 libc::SYS_mbind, 1318 addr as *mut libc::c_void, 1319 len, 1320 mode, 1321 nodemask.as_ptr(), 1322 maxnode, 1323 flags, 1324 ) 1325 }; 1326 1327 if res < 0 { 1328 Err(io::Error::last_os_error()) 1329 } else { 1330 Ok(()) 1331 } 1332 } 1333 1334 fn create_anonymous_file( 1335 size: usize, 1336 hugepages: bool, 1337 hugepage_size: Option<u64>, 1338 ) -> Result<FileOffset, Error> { 1339 let fd = Self::memfd_create( 1340 &ffi::CString::new("ch_ram").unwrap(), 1341 libc::MFD_CLOEXEC 1342 | if hugepages { 1343 libc::MFD_HUGETLB 1344 | if let Some(hugepage_size) = hugepage_size { 1345 /* 1346 * From the Linux kernel: 1347 * Several system calls take a flag to request "hugetlb" huge pages. 1348 * Without further specification, these system calls will use the 1349 * system's default huge page size. If a system supports multiple 1350 * huge page sizes, the desired huge page size can be specified in 1351 * bits [26:31] of the flag arguments. The value in these 6 bits 1352 * will encode the log2 of the huge page size. 1353 */ 1354 1355 hugepage_size.trailing_zeros() << 26 1356 } else { 1357 // Use the system default huge page size 1358 0 1359 } 1360 } else { 1361 0 1362 }, 1363 ) 1364 .map_err(Error::SharedFileCreate)?; 1365 1366 // SAFETY: fd is valid 1367 let f = unsafe { File::from_raw_fd(fd) }; 1368 f.set_len(size as u64).map_err(Error::SharedFileSetLen)?; 1369 1370 Ok(FileOffset::new(f, 0)) 1371 } 1372 1373 fn open_backing_file(backing_file: &PathBuf, file_offset: u64) -> Result<FileOffset, Error> { 1374 if backing_file.is_dir() { 1375 Err(Error::DirectoryAsBackingFileForMemory) 1376 } else { 1377 let f = OpenOptions::new() 1378 .read(true) 1379 .write(true) 1380 .open(backing_file) 1381 .map_err(Error::SharedFileCreate)?; 1382 1383 Ok(FileOffset::new(f, file_offset)) 1384 } 1385 } 1386 1387 #[allow(clippy::too_many_arguments)] 1388 pub fn create_ram_region( 1389 backing_file: &Option<PathBuf>, 1390 file_offset: u64, 1391 start_addr: GuestAddress, 1392 size: usize, 1393 prefault: bool, 1394 shared: bool, 1395 hugepages: bool, 1396 hugepage_size: Option<u64>, 1397 host_numa_node: Option<u32>, 1398 existing_memory_file: Option<File>, 1399 thp: bool, 1400 ) -> Result<Arc<GuestRegionMmap>, Error> { 1401 let mut mmap_flags = libc::MAP_NORESERVE; 1402 1403 // The duplication of mmap_flags ORing here is unfortunate but it also makes 1404 // the complexity of the handling clear. 1405 let fo = if let Some(f) = existing_memory_file { 1406 // It must be MAP_SHARED as we wouldn't already have an FD 1407 mmap_flags |= libc::MAP_SHARED; 1408 Some(FileOffset::new(f, file_offset)) 1409 } else if let Some(backing_file) = backing_file { 1410 if shared { 1411 mmap_flags |= libc::MAP_SHARED; 1412 } else { 1413 mmap_flags |= libc::MAP_PRIVATE; 1414 } 1415 Some(Self::open_backing_file(backing_file, file_offset)?) 1416 } else if shared || hugepages { 1417 // For hugepages we must also MAP_SHARED otherwise we will trigger #4805 1418 // because the MAP_PRIVATE will trigger CoW against the backing file with 1419 // the VFIO pinning 1420 mmap_flags |= libc::MAP_SHARED; 1421 Some(Self::create_anonymous_file(size, hugepages, hugepage_size)?) 1422 } else { 1423 mmap_flags |= libc::MAP_PRIVATE | libc::MAP_ANONYMOUS; 1424 None 1425 }; 1426 1427 let region = GuestRegionMmap::new( 1428 MmapRegion::build(fo, size, libc::PROT_READ | libc::PROT_WRITE, mmap_flags) 1429 .map_err(Error::GuestMemoryRegion)?, 1430 start_addr, 1431 ) 1432 .map_err(Error::GuestMemory)?; 1433 1434 // Apply NUMA policy if needed. 1435 if let Some(node) = host_numa_node { 1436 let addr = region.deref().as_ptr(); 1437 let len = region.deref().size() as u64; 1438 let mode = MPOL_BIND; 1439 let mut nodemask: Vec<u64> = Vec::new(); 1440 let flags = MPOL_MF_STRICT | MPOL_MF_MOVE; 1441 1442 // Linux is kind of buggy in the way it interprets maxnode as it 1443 // will cut off the last node. That's why we have to add 1 to what 1444 // we would consider as the proper maxnode value. 1445 let maxnode = node as u64 + 1 + 1; 1446 1447 // Allocate the right size for the vector. 1448 nodemask.resize((node as usize / 64) + 1, 0); 1449 1450 // Fill the global bitmask through the nodemask vector. 1451 let idx = (node / 64) as usize; 1452 let shift = node % 64; 1453 nodemask[idx] |= 1u64 << shift; 1454 1455 // Policies are enforced by using MPOL_MF_MOVE flag as it will 1456 // force the kernel to move all pages that might have been already 1457 // allocated to the proper set of NUMA nodes. MPOL_MF_STRICT is 1458 // used to throw an error if MPOL_MF_MOVE didn't succeed. 1459 // MPOL_BIND is the selected mode as it specifies a strict policy 1460 // that restricts memory allocation to the nodes specified in the 1461 // nodemask. 1462 Self::mbind(addr, len, mode, nodemask, maxnode, flags) 1463 .map_err(Error::ApplyNumaPolicy)?; 1464 } 1465 1466 // Prefault the region if needed, in parallel. 1467 if prefault { 1468 let page_size = 1469 Self::get_prefault_align_size(backing_file, hugepages, hugepage_size)? as usize; 1470 1471 if !is_aligned(size, page_size) { 1472 warn!( 1473 "Prefaulting memory size {} misaligned with page size {}", 1474 size, page_size 1475 ); 1476 } 1477 1478 let num_pages = size / page_size; 1479 1480 let num_threads = Self::get_prefault_num_threads(page_size, num_pages); 1481 1482 let pages_per_thread = num_pages / num_threads; 1483 let remainder = num_pages % num_threads; 1484 1485 let barrier = Arc::new(Barrier::new(num_threads)); 1486 thread::scope(|s| { 1487 let r = ®ion; 1488 for i in 0..num_threads { 1489 let barrier = Arc::clone(&barrier); 1490 s.spawn(move || { 1491 // Wait until all threads have been spawned to avoid contention 1492 // over mmap_sem between thread stack allocation and page faulting. 1493 barrier.wait(); 1494 let pages = pages_per_thread + if i < remainder { 1 } else { 0 }; 1495 let offset = 1496 page_size * ((i * pages_per_thread) + std::cmp::min(i, remainder)); 1497 // SAFETY: FFI call with correct arguments 1498 let ret = unsafe { 1499 let addr = r.as_ptr().add(offset); 1500 libc::madvise(addr as _, pages * page_size, libc::MADV_POPULATE_WRITE) 1501 }; 1502 if ret != 0 { 1503 let e = io::Error::last_os_error(); 1504 warn!("Failed to prefault pages: {}", e); 1505 } 1506 }); 1507 } 1508 }); 1509 } 1510 1511 if region.file_offset().is_none() && thp { 1512 info!( 1513 "Anonymous mapping at 0x{:x} (size = 0x{:x})", 1514 region.as_ptr() as u64, 1515 size 1516 ); 1517 // SAFETY: FFI call with correct arguments 1518 let ret = unsafe { libc::madvise(region.as_ptr() as _, size, libc::MADV_HUGEPAGE) }; 1519 if ret != 0 { 1520 let e = io::Error::last_os_error(); 1521 warn!("Failed to mark pages as THP eligible: {}", e); 1522 } 1523 } 1524 1525 Ok(Arc::new(region)) 1526 } 1527 1528 // Duplicate of `memory_zone_get_align_size` that does not require a `zone` 1529 fn get_prefault_align_size( 1530 backing_file: &Option<PathBuf>, 1531 hugepages: bool, 1532 hugepage_size: Option<u64>, 1533 ) -> Result<u64, Error> { 1534 // SAFETY: FFI call. Trivially safe. 1535 let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as u64 }; 1536 match (hugepages, hugepage_size, backing_file) { 1537 (false, _, _) => Ok(page_size), 1538 (true, Some(hugepage_size), _) => Ok(hugepage_size), 1539 (true, None, _) => { 1540 // There are two scenarios here: 1541 // - `hugepages` is enabled but `hugepage_size` is not specified: 1542 // Call `statfs` for `/dev/hugepages` for getting the default size of hugepage 1543 // - The backing file is specified: 1544 // Call `statfs` for the file and get its `f_bsize`. If the value is larger than the page 1545 // size of normal page, just use the `f_bsize` because the file is in a hugetlbfs. If the 1546 // value is less than or equal to the page size, just use the page size. 1547 let path = backing_file 1548 .as_ref() 1549 .map_or(Ok("/dev/hugepages"), |pathbuf| { 1550 pathbuf.to_str().ok_or(Error::InvalidMemoryParameters) 1551 })?; 1552 let align_size = std::cmp::max(page_size, statfs_get_bsize(path)?); 1553 Ok(align_size) 1554 } 1555 } 1556 } 1557 1558 fn get_prefault_num_threads(page_size: usize, num_pages: usize) -> usize { 1559 let mut n: usize = 1; 1560 1561 // Do not create more threads than processors available. 1562 // SAFETY: FFI call. Trivially safe. 1563 let procs = unsafe { libc::sysconf(_SC_NPROCESSORS_ONLN) }; 1564 if procs > 0 { 1565 n = std::cmp::min(procs as usize, MAX_PREFAULT_THREAD_COUNT); 1566 } 1567 1568 // Do not create more threads than pages being allocated. 1569 n = std::cmp::min(n, num_pages); 1570 1571 // Do not create threads to allocate less than 64 MiB of memory. 1572 n = std::cmp::min( 1573 n, 1574 std::cmp::max(1, page_size * num_pages / (64 * (1 << 26))), 1575 ); 1576 1577 n 1578 } 1579 1580 // Update the GuestMemoryMmap with the new range 1581 fn add_region(&mut self, region: Arc<GuestRegionMmap>) -> Result<(), Error> { 1582 let guest_memory = self 1583 .guest_memory 1584 .memory() 1585 .insert_region(region) 1586 .map_err(Error::GuestMemory)?; 1587 self.guest_memory.lock().unwrap().replace(guest_memory); 1588 1589 Ok(()) 1590 } 1591 1592 // 1593 // Calculate the start address of an area next to RAM. 1594 // 1595 // If memory hotplug is allowed, the start address needs to be aligned 1596 // (rounded-up) to 128MiB boundary. 1597 // If memory hotplug is not allowed, there is no alignment required. 1598 // And it must also start at the 64bit start. 1599 fn start_addr(mem_end: GuestAddress, allow_mem_hotplug: bool) -> Result<GuestAddress, Error> { 1600 let mut start_addr = if allow_mem_hotplug { 1601 GuestAddress(mem_end.0 | ((128 << 20) - 1)) 1602 } else { 1603 mem_end 1604 }; 1605 1606 start_addr = start_addr 1607 .checked_add(1) 1608 .ok_or(Error::GuestAddressOverFlow)?; 1609 1610 if mem_end < arch::layout::MEM_32BIT_RESERVED_START { 1611 return Ok(arch::layout::RAM_64BIT_START); 1612 } 1613 1614 Ok(start_addr) 1615 } 1616 1617 pub fn add_ram_region( 1618 &mut self, 1619 start_addr: GuestAddress, 1620 size: usize, 1621 ) -> Result<Arc<GuestRegionMmap>, Error> { 1622 // Allocate memory for the region 1623 let region = MemoryManager::create_ram_region( 1624 &None, 1625 0, 1626 start_addr, 1627 size, 1628 self.prefault, 1629 self.shared, 1630 self.hugepages, 1631 self.hugepage_size, 1632 None, 1633 None, 1634 self.thp, 1635 )?; 1636 1637 // Map it into the guest 1638 let slot = self.create_userspace_mapping( 1639 region.start_addr().0, 1640 region.len(), 1641 region.as_ptr() as u64, 1642 self.mergeable, 1643 false, 1644 self.log_dirty, 1645 )?; 1646 self.guest_ram_mappings.push(GuestRamMapping { 1647 gpa: region.start_addr().raw_value(), 1648 size: region.len(), 1649 slot, 1650 zone_id: DEFAULT_MEMORY_ZONE.to_string(), 1651 virtio_mem: false, 1652 file_offset: 0, 1653 }); 1654 1655 self.add_region(Arc::clone(®ion))?; 1656 1657 Ok(region) 1658 } 1659 1660 fn hotplug_ram_region(&mut self, size: usize) -> Result<Arc<GuestRegionMmap>, Error> { 1661 info!("Hotplugging new RAM: {}", size); 1662 1663 // Check that there is a free slot 1664 if self.next_hotplug_slot >= HOTPLUG_COUNT { 1665 return Err(Error::NoSlotAvailable); 1666 } 1667 1668 // "Inserted" DIMM must have a size that is a multiple of 128MiB 1669 if size % (128 << 20) != 0 { 1670 return Err(Error::InvalidSize); 1671 } 1672 1673 let start_addr = MemoryManager::start_addr(self.guest_memory.memory().last_addr(), true)?; 1674 1675 if start_addr 1676 .checked_add((size - 1).try_into().unwrap()) 1677 .unwrap() 1678 > self.end_of_ram_area 1679 { 1680 return Err(Error::InsufficientHotplugRam); 1681 } 1682 1683 let region = self.add_ram_region(start_addr, size)?; 1684 1685 // Add region to the list of regions associated with the default 1686 // memory zone. 1687 if let Some(memory_zone) = self.memory_zones.get_mut(DEFAULT_MEMORY_ZONE) { 1688 memory_zone.regions.push(Arc::clone(®ion)); 1689 } 1690 1691 // Tell the allocator 1692 self.ram_allocator 1693 .allocate(Some(start_addr), size as GuestUsize, None) 1694 .ok_or(Error::MemoryRangeAllocation)?; 1695 1696 // Update the slot so that it can be queried via the I/O port 1697 let slot = &mut self.hotplug_slots[self.next_hotplug_slot]; 1698 slot.active = true; 1699 slot.inserting = true; 1700 slot.base = region.start_addr().0; 1701 slot.length = region.len(); 1702 1703 self.next_hotplug_slot += 1; 1704 1705 Ok(region) 1706 } 1707 1708 pub fn guest_memory(&self) -> GuestMemoryAtomic<GuestMemoryMmap> { 1709 self.guest_memory.clone() 1710 } 1711 1712 pub fn boot_guest_memory(&self) -> GuestMemoryMmap { 1713 self.boot_guest_memory.clone() 1714 } 1715 1716 pub fn allocator(&self) -> Arc<Mutex<SystemAllocator>> { 1717 self.allocator.clone() 1718 } 1719 1720 pub fn start_of_device_area(&self) -> GuestAddress { 1721 self.start_of_device_area 1722 } 1723 1724 pub fn end_of_device_area(&self) -> GuestAddress { 1725 self.end_of_device_area 1726 } 1727 1728 pub fn memory_slot_allocator(&mut self) -> MemorySlotAllocator { 1729 let memory_slot_free_list = Arc::clone(&self.memory_slot_free_list); 1730 let next_memory_slot = Arc::clone(&self.next_memory_slot); 1731 MemorySlotAllocator::new(next_memory_slot, memory_slot_free_list) 1732 } 1733 1734 pub fn allocate_memory_slot(&mut self) -> u32 { 1735 self.memory_slot_allocator().next_memory_slot() 1736 } 1737 1738 pub fn create_userspace_mapping( 1739 &mut self, 1740 guest_phys_addr: u64, 1741 memory_size: u64, 1742 userspace_addr: u64, 1743 mergeable: bool, 1744 readonly: bool, 1745 log_dirty: bool, 1746 ) -> Result<u32, Error> { 1747 let slot = self.allocate_memory_slot(); 1748 let mem_region = self.vm.make_user_memory_region( 1749 slot, 1750 guest_phys_addr, 1751 memory_size, 1752 userspace_addr, 1753 readonly, 1754 log_dirty, 1755 ); 1756 1757 info!( 1758 "Creating userspace mapping: {:x} -> {:x} {:x}, slot {}", 1759 guest_phys_addr, userspace_addr, memory_size, slot 1760 ); 1761 1762 self.vm 1763 .create_user_memory_region(mem_region) 1764 .map_err(Error::CreateUserMemoryRegion)?; 1765 1766 // SAFETY: the address and size are valid since the 1767 // mmap succeeded. 1768 let ret = unsafe { 1769 libc::madvise( 1770 userspace_addr as *mut libc::c_void, 1771 memory_size as libc::size_t, 1772 libc::MADV_DONTDUMP, 1773 ) 1774 }; 1775 if ret != 0 { 1776 let e = io::Error::last_os_error(); 1777 warn!("Failed to mark mapping as MADV_DONTDUMP: {}", e); 1778 } 1779 1780 // Mark the pages as mergeable if explicitly asked for. 1781 if mergeable { 1782 // SAFETY: the address and size are valid since the 1783 // mmap succeeded. 1784 let ret = unsafe { 1785 libc::madvise( 1786 userspace_addr as *mut libc::c_void, 1787 memory_size as libc::size_t, 1788 libc::MADV_MERGEABLE, 1789 ) 1790 }; 1791 if ret != 0 { 1792 let err = io::Error::last_os_error(); 1793 // Safe to unwrap because the error is constructed with 1794 // last_os_error(), which ensures the output will be Some(). 1795 let errno = err.raw_os_error().unwrap(); 1796 if errno == libc::EINVAL { 1797 warn!("kernel not configured with CONFIG_KSM"); 1798 } else { 1799 warn!("madvise error: {}", err); 1800 } 1801 warn!("failed to mark pages as mergeable"); 1802 } 1803 } 1804 1805 info!( 1806 "Created userspace mapping: {:x} -> {:x} {:x}", 1807 guest_phys_addr, userspace_addr, memory_size 1808 ); 1809 1810 Ok(slot) 1811 } 1812 1813 pub fn remove_userspace_mapping( 1814 &mut self, 1815 guest_phys_addr: u64, 1816 memory_size: u64, 1817 userspace_addr: u64, 1818 mergeable: bool, 1819 slot: u32, 1820 ) -> Result<(), Error> { 1821 let mem_region = self.vm.make_user_memory_region( 1822 slot, 1823 guest_phys_addr, 1824 memory_size, 1825 userspace_addr, 1826 false, /* readonly -- don't care */ 1827 false, /* log dirty */ 1828 ); 1829 1830 self.vm 1831 .remove_user_memory_region(mem_region) 1832 .map_err(Error::RemoveUserMemoryRegion)?; 1833 1834 // Mark the pages as unmergeable if there were previously marked as 1835 // mergeable. 1836 if mergeable { 1837 // SAFETY: the address and size are valid as the region was 1838 // previously advised. 1839 let ret = unsafe { 1840 libc::madvise( 1841 userspace_addr as *mut libc::c_void, 1842 memory_size as libc::size_t, 1843 libc::MADV_UNMERGEABLE, 1844 ) 1845 }; 1846 if ret != 0 { 1847 let err = io::Error::last_os_error(); 1848 // Safe to unwrap because the error is constructed with 1849 // last_os_error(), which ensures the output will be Some(). 1850 let errno = err.raw_os_error().unwrap(); 1851 if errno == libc::EINVAL { 1852 warn!("kernel not configured with CONFIG_KSM"); 1853 } else { 1854 warn!("madvise error: {}", err); 1855 } 1856 warn!("failed to mark pages as unmergeable"); 1857 } 1858 } 1859 1860 info!( 1861 "Removed userspace mapping: {:x} -> {:x} {:x}", 1862 guest_phys_addr, userspace_addr, memory_size 1863 ); 1864 1865 Ok(()) 1866 } 1867 1868 pub fn virtio_mem_resize(&mut self, id: &str, size: u64) -> Result<(), Error> { 1869 if let Some(memory_zone) = self.memory_zones.get_mut(id) { 1870 if let Some(virtio_mem_zone) = &mut memory_zone.virtio_mem_zone { 1871 if let Some(virtio_mem_device) = virtio_mem_zone.virtio_device.as_ref() { 1872 virtio_mem_device 1873 .lock() 1874 .unwrap() 1875 .resize(size) 1876 .map_err(Error::VirtioMemResizeFail)?; 1877 } 1878 1879 // Keep the hotplugged_size up to date. 1880 virtio_mem_zone.hotplugged_size = size; 1881 } else { 1882 error!("Failed resizing virtio-mem region: No virtio-mem handler"); 1883 return Err(Error::MissingVirtioMemHandler); 1884 } 1885 1886 return Ok(()); 1887 } 1888 1889 error!("Failed resizing virtio-mem region: Unknown memory zone"); 1890 Err(Error::UnknownMemoryZone) 1891 } 1892 1893 /// In case this function resulted in adding a new memory region to the 1894 /// guest memory, the new region is returned to the caller. The virtio-mem 1895 /// use case never adds a new region as the whole hotpluggable memory has 1896 /// already been allocated at boot time. 1897 pub fn resize(&mut self, desired_ram: u64) -> Result<Option<Arc<GuestRegionMmap>>, Error> { 1898 if self.user_provided_zones { 1899 error!( 1900 "Not allowed to resize guest memory when backed with user \ 1901 defined memory zones." 1902 ); 1903 return Err(Error::InvalidResizeWithMemoryZones); 1904 } 1905 1906 let mut region: Option<Arc<GuestRegionMmap>> = None; 1907 match self.hotplug_method { 1908 HotplugMethod::VirtioMem => { 1909 if desired_ram >= self.boot_ram { 1910 if !self.dynamic { 1911 return Ok(region); 1912 } 1913 1914 self.virtio_mem_resize(DEFAULT_MEMORY_ZONE, desired_ram - self.boot_ram)?; 1915 self.current_ram = desired_ram; 1916 } 1917 } 1918 HotplugMethod::Acpi => { 1919 if desired_ram > self.current_ram { 1920 if !self.dynamic { 1921 return Ok(region); 1922 } 1923 1924 region = 1925 Some(self.hotplug_ram_region((desired_ram - self.current_ram) as usize)?); 1926 self.current_ram = desired_ram; 1927 } 1928 } 1929 } 1930 Ok(region) 1931 } 1932 1933 pub fn resize_zone(&mut self, id: &str, virtio_mem_size: u64) -> Result<(), Error> { 1934 if !self.user_provided_zones { 1935 error!( 1936 "Not allowed to resize guest memory zone when no zone is \ 1937 defined." 1938 ); 1939 return Err(Error::ResizeZone); 1940 } 1941 1942 self.virtio_mem_resize(id, virtio_mem_size) 1943 } 1944 1945 #[cfg(target_arch = "x86_64")] 1946 pub fn setup_sgx(&mut self, sgx_epc_config: Vec<SgxEpcConfig>) -> Result<(), Error> { 1947 let file = OpenOptions::new() 1948 .read(true) 1949 .open("/dev/sgx_provision") 1950 .map_err(Error::SgxProvisionOpen)?; 1951 self.vm 1952 .enable_sgx_attribute(file) 1953 .map_err(Error::SgxEnableProvisioning)?; 1954 1955 // Go over each EPC section and verify its size is a 4k multiple. At 1956 // the same time, calculate the total size needed for the contiguous 1957 // EPC region. 1958 let mut epc_region_size = 0; 1959 for epc_section in sgx_epc_config.iter() { 1960 if epc_section.size == 0 { 1961 return Err(Error::EpcSectionSizeInvalid); 1962 } 1963 if epc_section.size & (SGX_PAGE_SIZE - 1) != 0 { 1964 return Err(Error::EpcSectionSizeInvalid); 1965 } 1966 1967 epc_region_size += epc_section.size; 1968 } 1969 1970 // Place the SGX EPC region on a 4k boundary between the RAM and the device area 1971 let epc_region_start = 1972 GuestAddress(self.start_of_device_area.0.div_ceil(SGX_PAGE_SIZE) * SGX_PAGE_SIZE); 1973 1974 self.start_of_device_area = epc_region_start 1975 .checked_add(epc_region_size) 1976 .ok_or(Error::GuestAddressOverFlow)?; 1977 1978 let mut sgx_epc_region = SgxEpcRegion::new(epc_region_start, epc_region_size as GuestUsize); 1979 info!( 1980 "SGX EPC region: 0x{:x} (0x{:x})", 1981 epc_region_start.0, epc_region_size 1982 ); 1983 1984 // Each section can be memory mapped into the allocated region. 1985 let mut epc_section_start = epc_region_start.raw_value(); 1986 for epc_section in sgx_epc_config.iter() { 1987 let file = OpenOptions::new() 1988 .read(true) 1989 .write(true) 1990 .open("/dev/sgx_vepc") 1991 .map_err(Error::SgxVirtEpcOpen)?; 1992 1993 let prot = PROT_READ | PROT_WRITE; 1994 let mut flags = MAP_NORESERVE | MAP_SHARED; 1995 if epc_section.prefault { 1996 flags |= MAP_POPULATE; 1997 } 1998 1999 // We can't use the vm-memory crate to perform the memory mapping 2000 // here as it would try to ensure the size of the backing file is 2001 // matching the size of the expected mapping. The /dev/sgx_vepc 2002 // device does not work that way, it provides a file descriptor 2003 // which is not matching the mapping size, as it's a just a way to 2004 // let KVM know that an EPC section is being created for the guest. 2005 // SAFETY: FFI call with correct arguments 2006 let host_addr = unsafe { 2007 libc::mmap( 2008 std::ptr::null_mut(), 2009 epc_section.size as usize, 2010 prot, 2011 flags, 2012 file.as_raw_fd(), 2013 0, 2014 ) 2015 } as u64; 2016 2017 info!( 2018 "Adding SGX EPC section: 0x{:x} (0x{:x})", 2019 epc_section_start, epc_section.size 2020 ); 2021 2022 let _mem_slot = self.create_userspace_mapping( 2023 epc_section_start, 2024 epc_section.size, 2025 host_addr, 2026 false, 2027 false, 2028 false, 2029 )?; 2030 2031 sgx_epc_region.insert( 2032 epc_section.id.clone(), 2033 SgxEpcSection::new( 2034 GuestAddress(epc_section_start), 2035 epc_section.size as GuestUsize, 2036 ), 2037 ); 2038 2039 epc_section_start += epc_section.size; 2040 } 2041 2042 self.sgx_epc_region = Some(sgx_epc_region); 2043 2044 Ok(()) 2045 } 2046 2047 #[cfg(target_arch = "x86_64")] 2048 pub fn sgx_epc_region(&self) -> &Option<SgxEpcRegion> { 2049 &self.sgx_epc_region 2050 } 2051 2052 pub fn is_hardlink(f: &File) -> bool { 2053 let mut stat = std::mem::MaybeUninit::<libc::stat>::uninit(); 2054 // SAFETY: FFI call with correct arguments 2055 let ret = unsafe { libc::fstat(f.as_raw_fd(), stat.as_mut_ptr()) }; 2056 if ret != 0 { 2057 error!("Couldn't fstat the backing file"); 2058 return false; 2059 } 2060 2061 // SAFETY: stat is valid 2062 unsafe { (*stat.as_ptr()).st_nlink as usize > 0 } 2063 } 2064 2065 pub fn memory_zones(&self) -> &MemoryZones { 2066 &self.memory_zones 2067 } 2068 2069 pub fn memory_zones_mut(&mut self) -> &mut MemoryZones { 2070 &mut self.memory_zones 2071 } 2072 2073 pub fn memory_range_table( 2074 &self, 2075 snapshot: bool, 2076 ) -> std::result::Result<MemoryRangeTable, MigratableError> { 2077 let mut table = MemoryRangeTable::default(); 2078 2079 for memory_zone in self.memory_zones.values() { 2080 if let Some(virtio_mem_zone) = memory_zone.virtio_mem_zone() { 2081 table.extend(virtio_mem_zone.plugged_ranges()); 2082 } 2083 2084 for region in memory_zone.regions() { 2085 if snapshot { 2086 if let Some(file_offset) = region.file_offset() { 2087 if (region.flags() & libc::MAP_SHARED == libc::MAP_SHARED) 2088 && Self::is_hardlink(file_offset.file()) 2089 { 2090 // In this very specific case, we know the memory 2091 // region is backed by a file on the host filesystem 2092 // that can be accessed by the user, and additionally 2093 // the mapping is shared, which means that modifications 2094 // to the content are written to the actual file. 2095 // When meeting these conditions, we can skip the 2096 // copy of the memory content for this specific region, 2097 // as we can assume the user will have it saved through 2098 // the backing file already. 2099 continue; 2100 } 2101 } 2102 } 2103 2104 table.push(MemoryRange { 2105 gpa: region.start_addr().raw_value(), 2106 length: region.len(), 2107 }); 2108 } 2109 } 2110 2111 Ok(table) 2112 } 2113 2114 pub fn snapshot_data(&self) -> MemoryManagerSnapshotData { 2115 MemoryManagerSnapshotData { 2116 memory_ranges: self.snapshot_memory_ranges.clone(), 2117 guest_ram_mappings: self.guest_ram_mappings.clone(), 2118 start_of_device_area: self.start_of_device_area.0, 2119 boot_ram: self.boot_ram, 2120 current_ram: self.current_ram, 2121 arch_mem_regions: self.arch_mem_regions.clone(), 2122 hotplug_slots: self.hotplug_slots.clone(), 2123 next_memory_slot: self.next_memory_slot.load(Ordering::SeqCst), 2124 selected_slot: self.selected_slot, 2125 next_hotplug_slot: self.next_hotplug_slot, 2126 } 2127 } 2128 2129 pub fn memory_slot_fds(&self) -> HashMap<u32, RawFd> { 2130 let mut memory_slot_fds = HashMap::new(); 2131 for guest_ram_mapping in &self.guest_ram_mappings { 2132 let slot = guest_ram_mapping.slot; 2133 let guest_memory = self.guest_memory.memory(); 2134 let file = guest_memory 2135 .find_region(GuestAddress(guest_ram_mapping.gpa)) 2136 .unwrap() 2137 .file_offset() 2138 .unwrap() 2139 .file(); 2140 memory_slot_fds.insert(slot, file.as_raw_fd()); 2141 } 2142 memory_slot_fds 2143 } 2144 2145 pub fn acpi_address(&self) -> Option<GuestAddress> { 2146 self.acpi_address 2147 } 2148 2149 pub fn num_guest_ram_mappings(&self) -> u32 { 2150 self.guest_ram_mappings.len() as u32 2151 } 2152 2153 #[cfg(target_arch = "aarch64")] 2154 pub fn uefi_flash(&self) -> GuestMemoryAtomic<GuestMemoryMmap> { 2155 self.uefi_flash.as_ref().unwrap().clone() 2156 } 2157 2158 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] 2159 pub fn coredump_memory_regions(&self, mem_offset: u64) -> CoredumpMemoryRegions { 2160 let mut mapping_sorted_by_gpa = self.guest_ram_mappings.clone(); 2161 mapping_sorted_by_gpa.sort_by_key(|m| m.gpa); 2162 2163 let mut mem_offset_in_elf = mem_offset; 2164 let mut ram_maps = BTreeMap::new(); 2165 for mapping in mapping_sorted_by_gpa.iter() { 2166 ram_maps.insert( 2167 mapping.gpa, 2168 CoredumpMemoryRegion { 2169 mem_offset_in_elf, 2170 mem_size: mapping.size, 2171 }, 2172 ); 2173 mem_offset_in_elf += mapping.size; 2174 } 2175 2176 CoredumpMemoryRegions { ram_maps } 2177 } 2178 2179 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] 2180 pub fn coredump_iterate_save_mem( 2181 &mut self, 2182 dump_state: &DumpState, 2183 ) -> std::result::Result<(), GuestDebuggableError> { 2184 let snapshot_memory_ranges = self 2185 .memory_range_table(false) 2186 .map_err(|e| GuestDebuggableError::Coredump(e.into()))?; 2187 2188 if snapshot_memory_ranges.is_empty() { 2189 return Ok(()); 2190 } 2191 2192 let coredump_file = dump_state.file.as_ref().unwrap(); 2193 2194 let guest_memory = self.guest_memory.memory(); 2195 let mut total_bytes: u64 = 0; 2196 2197 for range in snapshot_memory_ranges.regions() { 2198 let mut offset: u64 = 0; 2199 loop { 2200 let bytes_written = guest_memory 2201 .write_volatile_to( 2202 GuestAddress(range.gpa + offset), 2203 &mut coredump_file.as_fd(), 2204 (range.length - offset) as usize, 2205 ) 2206 .map_err(|e| GuestDebuggableError::Coredump(e.into()))?; 2207 offset += bytes_written as u64; 2208 total_bytes += bytes_written as u64; 2209 2210 if offset == range.length { 2211 break; 2212 } 2213 } 2214 } 2215 2216 debug!("coredump total bytes {}", total_bytes); 2217 Ok(()) 2218 } 2219 2220 pub fn receive_memory_regions<F>( 2221 &mut self, 2222 ranges: &MemoryRangeTable, 2223 fd: &mut F, 2224 ) -> std::result::Result<(), MigratableError> 2225 where 2226 F: ReadVolatile, 2227 { 2228 let guest_memory = self.guest_memory(); 2229 let mem = guest_memory.memory(); 2230 2231 for range in ranges.regions() { 2232 let mut offset: u64 = 0; 2233 // Here we are manually handling the retry in case we can't the 2234 // whole region at once because we can't use the implementation 2235 // from vm-memory::GuestMemory of read_exact_from() as it is not 2236 // following the correct behavior. For more info about this issue 2237 // see: https://github.com/rust-vmm/vm-memory/issues/174 2238 loop { 2239 let bytes_read = mem 2240 .read_volatile_from( 2241 GuestAddress(range.gpa + offset), 2242 fd, 2243 (range.length - offset) as usize, 2244 ) 2245 .map_err(|e| { 2246 MigratableError::MigrateReceive(anyhow!( 2247 "Error receiving memory from socket: {}", 2248 e 2249 )) 2250 })?; 2251 offset += bytes_read as u64; 2252 2253 if offset == range.length { 2254 break; 2255 } 2256 } 2257 } 2258 2259 Ok(()) 2260 } 2261 } 2262 2263 struct MemoryNotify { 2264 slot_id: usize, 2265 } 2266 2267 impl Aml for MemoryNotify { 2268 fn to_aml_bytes(&self, sink: &mut dyn acpi_tables::AmlSink) { 2269 let object = aml::Path::new(&format!("M{:03}", self.slot_id)); 2270 aml::If::new( 2271 &aml::Equal::new(&aml::Arg(0), &self.slot_id), 2272 vec![&aml::Notify::new(&object, &aml::Arg(1))], 2273 ) 2274 .to_aml_bytes(sink) 2275 } 2276 } 2277 2278 struct MemorySlot { 2279 slot_id: usize, 2280 } 2281 2282 impl Aml for MemorySlot { 2283 fn to_aml_bytes(&self, sink: &mut dyn acpi_tables::AmlSink) { 2284 aml::Device::new( 2285 format!("M{:03}", self.slot_id).as_str().into(), 2286 vec![ 2287 &aml::Name::new("_HID".into(), &aml::EISAName::new("PNP0C80")), 2288 &aml::Name::new("_UID".into(), &self.slot_id), 2289 /* 2290 _STA return value: 2291 Bit [0] – Set if the device is present. 2292 Bit [1] – Set if the device is enabled and decoding its resources. 2293 Bit [2] – Set if the device should be shown in the UI. 2294 Bit [3] – Set if the device is functioning properly (cleared if device failed its diagnostics). 2295 Bit [4] – Set if the battery is present. 2296 Bits [31:5] – Reserved (must be cleared). 2297 */ 2298 &aml::Method::new( 2299 "_STA".into(), 2300 0, 2301 false, 2302 // Call into MSTA method which will interrogate device 2303 vec![&aml::Return::new(&aml::MethodCall::new( 2304 "MSTA".into(), 2305 vec![&self.slot_id], 2306 ))], 2307 ), 2308 // Get details of memory 2309 &aml::Method::new( 2310 "_CRS".into(), 2311 0, 2312 false, 2313 // Call into MCRS which provides actual memory details 2314 vec![&aml::Return::new(&aml::MethodCall::new( 2315 "MCRS".into(), 2316 vec![&self.slot_id], 2317 ))], 2318 ), 2319 ], 2320 ) 2321 .to_aml_bytes(sink) 2322 } 2323 } 2324 2325 struct MemorySlots { 2326 slots: usize, 2327 } 2328 2329 impl Aml for MemorySlots { 2330 fn to_aml_bytes(&self, sink: &mut dyn acpi_tables::AmlSink) { 2331 for slot_id in 0..self.slots { 2332 MemorySlot { slot_id }.to_aml_bytes(sink); 2333 } 2334 } 2335 } 2336 2337 struct MemoryMethods { 2338 slots: usize, 2339 } 2340 2341 impl Aml for MemoryMethods { 2342 fn to_aml_bytes(&self, sink: &mut dyn acpi_tables::AmlSink) { 2343 // Add "MTFY" notification method 2344 let mut memory_notifies = Vec::new(); 2345 for slot_id in 0..self.slots { 2346 memory_notifies.push(MemoryNotify { slot_id }); 2347 } 2348 2349 let mut memory_notifies_refs: Vec<&dyn Aml> = Vec::new(); 2350 for memory_notifier in memory_notifies.iter() { 2351 memory_notifies_refs.push(memory_notifier); 2352 } 2353 2354 aml::Method::new("MTFY".into(), 2, true, memory_notifies_refs).to_aml_bytes(sink); 2355 2356 // MSCN method 2357 aml::Method::new( 2358 "MSCN".into(), 2359 0, 2360 true, 2361 vec![ 2362 // Take lock defined above 2363 &aml::Acquire::new("MLCK".into(), 0xffff), 2364 &aml::Store::new(&aml::Local(0), &aml::ZERO), 2365 &aml::While::new( 2366 &aml::LessThan::new(&aml::Local(0), &self.slots), 2367 vec![ 2368 // Write slot number (in first argument) to I/O port via field 2369 &aml::Store::new(&aml::Path::new("\\_SB_.MHPC.MSEL"), &aml::Local(0)), 2370 // Check if MINS bit is set (inserting) 2371 &aml::If::new( 2372 &aml::Equal::new(&aml::Path::new("\\_SB_.MHPC.MINS"), &aml::ONE), 2373 // Notify device if it is 2374 vec![ 2375 &aml::MethodCall::new( 2376 "MTFY".into(), 2377 vec![&aml::Local(0), &aml::ONE], 2378 ), 2379 // Reset MINS bit 2380 &aml::Store::new(&aml::Path::new("\\_SB_.MHPC.MINS"), &aml::ONE), 2381 ], 2382 ), 2383 // Check if MRMV bit is set 2384 &aml::If::new( 2385 &aml::Equal::new(&aml::Path::new("\\_SB_.MHPC.MRMV"), &aml::ONE), 2386 // Notify device if it is (with the eject constant 0x3) 2387 vec![ 2388 &aml::MethodCall::new("MTFY".into(), vec![&aml::Local(0), &3u8]), 2389 // Reset MRMV bit 2390 &aml::Store::new(&aml::Path::new("\\_SB_.MHPC.MRMV"), &aml::ONE), 2391 ], 2392 ), 2393 &aml::Add::new(&aml::Local(0), &aml::Local(0), &aml::ONE), 2394 ], 2395 ), 2396 // Release lock 2397 &aml::Release::new("MLCK".into()), 2398 ], 2399 ) 2400 .to_aml_bytes(sink); 2401 2402 // Memory status method 2403 aml::Method::new( 2404 "MSTA".into(), 2405 1, 2406 true, 2407 vec![ 2408 // Take lock defined above 2409 &aml::Acquire::new("MLCK".into(), 0xffff), 2410 // Write slot number (in first argument) to I/O port via field 2411 &aml::Store::new(&aml::Path::new("\\_SB_.MHPC.MSEL"), &aml::Arg(0)), 2412 &aml::Store::new(&aml::Local(0), &aml::ZERO), 2413 // Check if MEN_ bit is set, if so make the local variable 0xf (see _STA for details of meaning) 2414 &aml::If::new( 2415 &aml::Equal::new(&aml::Path::new("\\_SB_.MHPC.MEN_"), &aml::ONE), 2416 vec![&aml::Store::new(&aml::Local(0), &0xfu8)], 2417 ), 2418 // Release lock 2419 &aml::Release::new("MLCK".into()), 2420 // Return 0 or 0xf 2421 &aml::Return::new(&aml::Local(0)), 2422 ], 2423 ) 2424 .to_aml_bytes(sink); 2425 2426 // Memory range method 2427 aml::Method::new( 2428 "MCRS".into(), 2429 1, 2430 true, 2431 vec![ 2432 // Take lock defined above 2433 &aml::Acquire::new("MLCK".into(), 0xffff), 2434 // Write slot number (in first argument) to I/O port via field 2435 &aml::Store::new(&aml::Path::new("\\_SB_.MHPC.MSEL"), &aml::Arg(0)), 2436 &aml::Name::new( 2437 "MR64".into(), 2438 &aml::ResourceTemplate::new(vec![&aml::AddressSpace::new_memory( 2439 aml::AddressSpaceCacheable::Cacheable, 2440 true, 2441 0x0000_0000_0000_0000u64, 2442 0xFFFF_FFFF_FFFF_FFFEu64, 2443 None, 2444 )]), 2445 ), 2446 &aml::CreateQWordField::new( 2447 &aml::Path::new("MINL"), 2448 &aml::Path::new("MR64"), 2449 &14usize, 2450 ), 2451 &aml::CreateDWordField::new( 2452 &aml::Path::new("MINH"), 2453 &aml::Path::new("MR64"), 2454 &18usize, 2455 ), 2456 &aml::CreateQWordField::new( 2457 &aml::Path::new("MAXL"), 2458 &aml::Path::new("MR64"), 2459 &22usize, 2460 ), 2461 &aml::CreateDWordField::new( 2462 &aml::Path::new("MAXH"), 2463 &aml::Path::new("MR64"), 2464 &26usize, 2465 ), 2466 &aml::CreateQWordField::new( 2467 &aml::Path::new("LENL"), 2468 &aml::Path::new("MR64"), 2469 &38usize, 2470 ), 2471 &aml::CreateDWordField::new( 2472 &aml::Path::new("LENH"), 2473 &aml::Path::new("MR64"), 2474 &42usize, 2475 ), 2476 &aml::Store::new(&aml::Path::new("MINL"), &aml::Path::new("\\_SB_.MHPC.MHBL")), 2477 &aml::Store::new(&aml::Path::new("MINH"), &aml::Path::new("\\_SB_.MHPC.MHBH")), 2478 &aml::Store::new(&aml::Path::new("LENL"), &aml::Path::new("\\_SB_.MHPC.MHLL")), 2479 &aml::Store::new(&aml::Path::new("LENH"), &aml::Path::new("\\_SB_.MHPC.MHLH")), 2480 &aml::Add::new( 2481 &aml::Path::new("MAXL"), 2482 &aml::Path::new("MINL"), 2483 &aml::Path::new("LENL"), 2484 ), 2485 &aml::Add::new( 2486 &aml::Path::new("MAXH"), 2487 &aml::Path::new("MINH"), 2488 &aml::Path::new("LENH"), 2489 ), 2490 &aml::If::new( 2491 &aml::LessThan::new(&aml::Path::new("MAXL"), &aml::Path::new("MINL")), 2492 vec![&aml::Add::new( 2493 &aml::Path::new("MAXH"), 2494 &aml::ONE, 2495 &aml::Path::new("MAXH"), 2496 )], 2497 ), 2498 &aml::Subtract::new(&aml::Path::new("MAXL"), &aml::Path::new("MAXL"), &aml::ONE), 2499 // Release lock 2500 &aml::Release::new("MLCK".into()), 2501 &aml::Return::new(&aml::Path::new("MR64")), 2502 ], 2503 ) 2504 .to_aml_bytes(sink) 2505 } 2506 } 2507 2508 impl Aml for MemoryManager { 2509 fn to_aml_bytes(&self, sink: &mut dyn acpi_tables::AmlSink) { 2510 if let Some(acpi_address) = self.acpi_address { 2511 // Memory Hotplug Controller 2512 aml::Device::new( 2513 "_SB_.MHPC".into(), 2514 vec![ 2515 &aml::Name::new("_HID".into(), &aml::EISAName::new("PNP0A06")), 2516 &aml::Name::new("_UID".into(), &"Memory Hotplug Controller"), 2517 // Mutex to protect concurrent access as we write to choose slot and then read back status 2518 &aml::Mutex::new("MLCK".into(), 0), 2519 &aml::Name::new( 2520 "_CRS".into(), 2521 &aml::ResourceTemplate::new(vec![&aml::AddressSpace::new_memory( 2522 aml::AddressSpaceCacheable::NotCacheable, 2523 true, 2524 acpi_address.0, 2525 acpi_address.0 + MEMORY_MANAGER_ACPI_SIZE as u64 - 1, 2526 None, 2527 )]), 2528 ), 2529 // OpRegion and Fields map MMIO range into individual field values 2530 &aml::OpRegion::new( 2531 "MHPR".into(), 2532 aml::OpRegionSpace::SystemMemory, 2533 &(acpi_address.0 as usize), 2534 &MEMORY_MANAGER_ACPI_SIZE, 2535 ), 2536 &aml::Field::new( 2537 "MHPR".into(), 2538 aml::FieldAccessType::DWord, 2539 aml::FieldLockRule::NoLock, 2540 aml::FieldUpdateRule::Preserve, 2541 vec![ 2542 aml::FieldEntry::Named(*b"MHBL", 32), // Base (low 4 bytes) 2543 aml::FieldEntry::Named(*b"MHBH", 32), // Base (high 4 bytes) 2544 aml::FieldEntry::Named(*b"MHLL", 32), // Length (low 4 bytes) 2545 aml::FieldEntry::Named(*b"MHLH", 32), // Length (high 4 bytes) 2546 ], 2547 ), 2548 &aml::Field::new( 2549 "MHPR".into(), 2550 aml::FieldAccessType::DWord, 2551 aml::FieldLockRule::NoLock, 2552 aml::FieldUpdateRule::Preserve, 2553 vec![ 2554 aml::FieldEntry::Reserved(128), 2555 aml::FieldEntry::Named(*b"MHPX", 32), // PXM 2556 ], 2557 ), 2558 &aml::Field::new( 2559 "MHPR".into(), 2560 aml::FieldAccessType::Byte, 2561 aml::FieldLockRule::NoLock, 2562 aml::FieldUpdateRule::WriteAsZeroes, 2563 vec![ 2564 aml::FieldEntry::Reserved(160), 2565 aml::FieldEntry::Named(*b"MEN_", 1), // Enabled 2566 aml::FieldEntry::Named(*b"MINS", 1), // Inserting 2567 aml::FieldEntry::Named(*b"MRMV", 1), // Removing 2568 aml::FieldEntry::Named(*b"MEJ0", 1), // Ejecting 2569 ], 2570 ), 2571 &aml::Field::new( 2572 "MHPR".into(), 2573 aml::FieldAccessType::DWord, 2574 aml::FieldLockRule::NoLock, 2575 aml::FieldUpdateRule::Preserve, 2576 vec![ 2577 aml::FieldEntry::Named(*b"MSEL", 32), // Selector 2578 aml::FieldEntry::Named(*b"MOEV", 32), // Event 2579 aml::FieldEntry::Named(*b"MOSC", 32), // OSC 2580 ], 2581 ), 2582 &MemoryMethods { 2583 slots: self.hotplug_slots.len(), 2584 }, 2585 &MemorySlots { 2586 slots: self.hotplug_slots.len(), 2587 }, 2588 ], 2589 ) 2590 .to_aml_bytes(sink); 2591 } else { 2592 aml::Device::new( 2593 "_SB_.MHPC".into(), 2594 vec![ 2595 &aml::Name::new("_HID".into(), &aml::EISAName::new("PNP0A06")), 2596 &aml::Name::new("_UID".into(), &"Memory Hotplug Controller"), 2597 // Empty MSCN for GED 2598 &aml::Method::new("MSCN".into(), 0, true, vec![]), 2599 ], 2600 ) 2601 .to_aml_bytes(sink); 2602 } 2603 2604 #[cfg(target_arch = "x86_64")] 2605 { 2606 if let Some(sgx_epc_region) = &self.sgx_epc_region { 2607 let min = sgx_epc_region.start().raw_value(); 2608 let max = min + sgx_epc_region.size() - 1; 2609 // SGX EPC region 2610 aml::Device::new( 2611 "_SB_.EPC_".into(), 2612 vec![ 2613 &aml::Name::new("_HID".into(), &aml::EISAName::new("INT0E0C")), 2614 // QWORD describing the EPC region start and size 2615 &aml::Name::new( 2616 "_CRS".into(), 2617 &aml::ResourceTemplate::new(vec![&aml::AddressSpace::new_memory( 2618 aml::AddressSpaceCacheable::NotCacheable, 2619 true, 2620 min, 2621 max, 2622 None, 2623 )]), 2624 ), 2625 &aml::Method::new("_STA".into(), 0, false, vec![&aml::Return::new(&0xfu8)]), 2626 ], 2627 ) 2628 .to_aml_bytes(sink); 2629 } 2630 } 2631 } 2632 } 2633 2634 impl Pausable for MemoryManager {} 2635 2636 #[derive(Clone, Serialize, Deserialize)] 2637 pub struct MemoryManagerSnapshotData { 2638 memory_ranges: MemoryRangeTable, 2639 guest_ram_mappings: Vec<GuestRamMapping>, 2640 start_of_device_area: u64, 2641 boot_ram: u64, 2642 current_ram: u64, 2643 arch_mem_regions: Vec<ArchMemRegion>, 2644 hotplug_slots: Vec<HotPlugState>, 2645 next_memory_slot: u32, 2646 selected_slot: usize, 2647 next_hotplug_slot: usize, 2648 } 2649 2650 impl Snapshottable for MemoryManager { 2651 fn id(&self) -> String { 2652 MEMORY_MANAGER_SNAPSHOT_ID.to_string() 2653 } 2654 2655 fn snapshot(&mut self) -> result::Result<Snapshot, MigratableError> { 2656 let memory_ranges = self.memory_range_table(true)?; 2657 2658 // Store locally this list of ranges as it will be used through the 2659 // Transportable::send() implementation. The point is to avoid the 2660 // duplication of code regarding the creation of the path for each 2661 // region. The 'snapshot' step creates the list of memory regions, 2662 // including information about the need to copy a memory region or 2663 // not. This saves the 'send' step having to go through the same 2664 // process, and instead it can directly proceed with storing the 2665 // memory range content for the ranges requiring it. 2666 self.snapshot_memory_ranges = memory_ranges; 2667 2668 Ok(Snapshot::from_data(SnapshotData::new_from_state( 2669 &self.snapshot_data(), 2670 )?)) 2671 } 2672 } 2673 2674 impl Transportable for MemoryManager { 2675 fn send( 2676 &self, 2677 _snapshot: &Snapshot, 2678 destination_url: &str, 2679 ) -> result::Result<(), MigratableError> { 2680 if self.snapshot_memory_ranges.is_empty() { 2681 return Ok(()); 2682 } 2683 2684 let mut memory_file_path = url_to_path(destination_url)?; 2685 memory_file_path.push(String::from(SNAPSHOT_FILENAME)); 2686 2687 // Create the snapshot file for the entire memory 2688 let mut memory_file = OpenOptions::new() 2689 .read(true) 2690 .write(true) 2691 .create_new(true) 2692 .open(memory_file_path) 2693 .map_err(|e| MigratableError::MigrateSend(e.into()))?; 2694 2695 let guest_memory = self.guest_memory.memory(); 2696 2697 for range in self.snapshot_memory_ranges.regions() { 2698 let mut offset: u64 = 0; 2699 // Here we are manually handling the retry in case we can't read 2700 // the whole region at once because we can't use the implementation 2701 // from vm-memory::GuestMemory of write_all_to() as it is not 2702 // following the correct behavior. For more info about this issue 2703 // see: https://github.com/rust-vmm/vm-memory/issues/174 2704 loop { 2705 let bytes_written = guest_memory 2706 .write_volatile_to( 2707 GuestAddress(range.gpa + offset), 2708 &mut memory_file, 2709 (range.length - offset) as usize, 2710 ) 2711 .map_err(|e| MigratableError::MigrateSend(e.into()))?; 2712 offset += bytes_written as u64; 2713 2714 if offset == range.length { 2715 break; 2716 } 2717 } 2718 } 2719 Ok(()) 2720 } 2721 } 2722 2723 impl Migratable for MemoryManager { 2724 // Start the dirty log in the hypervisor (kvm/mshv). 2725 // Also, reset the dirty bitmap logged by the vmm. 2726 // Just before we do a bulk copy we want to start/clear the dirty log so that 2727 // pages touched during our bulk copy are tracked. 2728 fn start_dirty_log(&mut self) -> std::result::Result<(), MigratableError> { 2729 self.vm.start_dirty_log().map_err(|e| { 2730 MigratableError::MigrateSend(anyhow!("Error starting VM dirty log {}", e)) 2731 })?; 2732 2733 for r in self.guest_memory.memory().iter() { 2734 r.bitmap().reset(); 2735 } 2736 2737 Ok(()) 2738 } 2739 2740 fn stop_dirty_log(&mut self) -> std::result::Result<(), MigratableError> { 2741 self.vm.stop_dirty_log().map_err(|e| { 2742 MigratableError::MigrateSend(anyhow!("Error stopping VM dirty log {}", e)) 2743 })?; 2744 2745 Ok(()) 2746 } 2747 2748 // Generate a table for the pages that are dirty. The dirty pages are collapsed 2749 // together in the table if they are contiguous. 2750 fn dirty_log(&mut self) -> std::result::Result<MemoryRangeTable, MigratableError> { 2751 let mut table = MemoryRangeTable::default(); 2752 for r in &self.guest_ram_mappings { 2753 let vm_dirty_bitmap = self.vm.get_dirty_log(r.slot, r.gpa, r.size).map_err(|e| { 2754 MigratableError::MigrateSend(anyhow!("Error getting VM dirty log {}", e)) 2755 })?; 2756 let vmm_dirty_bitmap = match self.guest_memory.memory().find_region(GuestAddress(r.gpa)) 2757 { 2758 Some(region) => { 2759 assert!(region.start_addr().raw_value() == r.gpa); 2760 assert!(region.len() == r.size); 2761 region.bitmap().get_and_reset() 2762 } 2763 None => { 2764 return Err(MigratableError::MigrateSend(anyhow!( 2765 "Error finding 'guest memory region' with address {:x}", 2766 r.gpa 2767 ))) 2768 } 2769 }; 2770 2771 let dirty_bitmap: Vec<u64> = vm_dirty_bitmap 2772 .iter() 2773 .zip(vmm_dirty_bitmap.iter()) 2774 .map(|(x, y)| x | y) 2775 .collect(); 2776 2777 let sub_table = MemoryRangeTable::from_bitmap(dirty_bitmap, r.gpa, 4096); 2778 2779 if sub_table.regions().is_empty() { 2780 info!("Dirty Memory Range Table is empty"); 2781 } else { 2782 info!("Dirty Memory Range Table:"); 2783 for range in sub_table.regions() { 2784 info!("GPA: {:x} size: {} (KiB)", range.gpa, range.length / 1024); 2785 } 2786 } 2787 2788 table.extend(sub_table); 2789 } 2790 Ok(table) 2791 } 2792 } 2793