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