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