From 88a9f799449c04180c6b9a21d3b9c0c4b57e2bd6 Mon Sep 17 00:00:00 2001 From: Rob Bradford Date: Sun, 29 Sep 2024 10:48:45 +0100 Subject: [PATCH] misc: Adapt consistent import style formatting Historically the Cloud Hypervisor coding style has been to ensure that all imports are ordered and placed in a single group. Unfortunately cargo fmt has no support for ensuring that all imports are in a single group so if whitespace lines were added as part of the import statements then they would only be odered correctly in the group. By adopting "group_imports="StdExternalCrate" we can enforce a style where imports are placed in at most three groups for std, external crates and the crate itself. Choosing a style enforceable by the tooling reduces the reviewer burden. Signed-off-by: Rob Bradford --- .rustfmt.toml | 3 +- api_client/src/lib.rs | 1 + arch/src/aarch64/fdt.rs | 17 ++-- arch/src/aarch64/mod.rs | 10 ++- arch/src/aarch64/uefi.rs | 1 + arch/src/lib.rs | 8 +- arch/src/x86_64/mod.rs | 15 ++-- arch/src/x86_64/mptable.rs | 15 ++-- arch/src/x86_64/regs.rs | 19 ++-- arch/src/x86_64/smbios.rs | 6 +- arch/src/x86_64/tdx/mod.rs | 4 +- block/src/async_io.rs | 3 +- block/src/fixed_vhd.rs | 5 +- block/src/fixed_vhd_async.rs | 8 +- block/src/fixed_vhd_sync.rs | 8 +- block/src/lib.rs | 20 +++-- block/src/qcow/mod.rs | 23 ++--- block/src/qcow/qcow_raw_file.rs | 6 +- block/src/qcow/raw_file.rs | 6 +- block/src/qcow_sync.rs | 8 +- block/src/raw_async.rs | 12 +-- block/src/raw_async_aio.rs | 12 +-- block/src/raw_sync.rs | 12 +-- block/src/vhd.rs | 7 +- block/src/vhdx/mod.rs | 16 ++-- block/src/vhdx/vhdx_bat.rs | 8 +- block/src/vhdx/vhdx_header.rs | 5 +- block/src/vhdx/vhdx_io.rs | 10 ++- block/src/vhdx/vhdx_metadata.rs | 8 +- block/src/vhdx_sync.rs | 8 +- devices/src/acpi.rs | 6 +- devices/src/debug_console.rs | 1 + devices/src/gic.rs | 5 +- devices/src/interrupt_controller.rs | 1 + devices/src/ioapic.rs | 8 +- devices/src/legacy/cmos.rs | 6 +- devices/src/legacy/debug_port.rs | 1 + devices/src/legacy/fwdebug.rs | 1 + devices/src/legacy/gpio_pl061.rs | 9 +- devices/src/legacy/i8042.rs | 1 + devices/src/legacy/mod.rs | 5 +- devices/src/legacy/rtc_pl031.rs | 9 +- devices/src/legacy/serial.rs | 7 +- devices/src/legacy/uart_pl011.rs | 10 ++- devices/src/pvmemcontrol.rs | 11 +-- devices/src/pvpanic.rs | 7 +- devices/src/tpm.rs | 5 +- event_monitor/src/lib.rs | 5 +- hypervisor/src/arch/aarch64/gic.rs | 4 +- hypervisor/src/arch/emulator/mod.rs | 1 + .../src/arch/x86/emulator/instructions/mod.rs | 3 +- .../src/arch/x86/emulator/instructions/or.rs | 1 - hypervisor/src/arch/x86/emulator/mod.rs | 8 +- hypervisor/src/arch/x86/mod.rs | 6 +- hypervisor/src/cpu.rs | 5 +- hypervisor/src/hypervisor.rs | 10 ++- hypervisor/src/kvm/aarch64/gic/dist_regs.rs | 3 +- hypervisor/src/kvm/aarch64/gic/icc_regs.rs | 3 +- hypervisor/src/kvm/aarch64/gic/mod.rs | 12 +-- hypervisor/src/kvm/aarch64/gic/redist_regs.rs | 3 +- hypervisor/src/kvm/aarch64/mod.rs | 3 +- hypervisor/src/kvm/mod.rs | 61 +++++++------ hypervisor/src/kvm/x86_64/mod.rs | 12 +-- hypervisor/src/lib.rs | 6 +- hypervisor/src/mshv/mod.rs | 57 ++++++------ hypervisor/src/mshv/x86_64/emulator.rs | 5 +- hypervisor/src/mshv/x86_64/mod.rs | 6 +- hypervisor/src/vm.rs | 22 ++--- net_util/src/ctrl_queue.rs | 8 +- net_util/src/lib.rs | 4 +- net_util/src/open_tap.rs | 4 +- net_util/src/queue_pair.rs | 6 +- net_util/src/tap.rs | 13 +-- pci/src/bus.rs | 14 +-- pci/src/configuration.rs | 10 ++- pci/src/device.rs | 6 +- pci/src/lib.rs | 10 ++- pci/src/msi.rs | 5 +- pci/src/msix.rs | 10 ++- pci/src/vfio.rs | 28 +++--- pci/src/vfio_user.rs | 10 ++- performance-metrics/src/main.rs | 7 +- performance-metrics/src/performance_tests.rs | 4 +- rate_limiter/src/group.rs | 10 ++- rate_limiter/src/lib.rs | 4 +- src/bin/ch-remote.rs | 11 +-- src/main.rs | 17 ++-- test_infra/src/lib.rs | 7 +- tests/integration.rs | 6 +- tpm/src/emulator.rs | 14 +-- tpm/src/socket.rs | 3 +- tracer/src/tracer.rs | 5 +- vhost_user_block/src/lib.rs | 17 ++-- vhost_user_net/src/lib.rs | 15 ++-- virtio-devices/src/balloon.rs | 20 +++-- virtio-devices/src/block.rs | 38 ++++---- virtio-devices/src/console.rs | 42 ++++----- virtio-devices/src/device.rs | 12 +-- virtio-devices/src/epoll_helper.rs | 1 + virtio-devices/src/iommu.rs | 26 +++--- virtio-devices/src/lib.rs | 8 +- virtio-devices/src/mem.rs | 26 +++--- virtio-devices/src/net.rs | 58 ++++++------ virtio-devices/src/pmem.rs | 40 +++++---- virtio-devices/src/rng.rs | 32 +++---- virtio-devices/src/thread_helper.rs | 14 +-- .../src/transport/pci_common_config.rs | 13 +-- virtio-devices/src/transport/pci_device.rs | 27 +++--- virtio-devices/src/vdpa.rs | 16 ++-- virtio-devices/src/vhost_user/blk.rs | 23 ++--- virtio-devices/src/vhost_user/fs.rs | 34 +++---- virtio-devices/src/vhost_user/mod.rs | 18 ++-- virtio-devices/src/vhost_user/net.rs | 26 +++--- .../src/vhost_user/vu_common_ctrl.rs | 14 +-- virtio-devices/src/vsock/csm/connection.rs | 10 ++- virtio-devices/src/vsock/csm/txbuf.rs | 3 +- virtio-devices/src/vsock/device.rs | 41 +++++---- virtio-devices/src/vsock/mod.rs | 25 +++--- virtio-devices/src/vsock/packet.rs | 18 ++-- virtio-devices/src/vsock/unix/muxer.rs | 8 +- virtio-devices/src/watchdog.rs | 32 +++---- vm-allocator/src/address.rs | 1 + vm-allocator/src/system.rs | 1 - vm-device/src/interrupt/mod.rs | 3 +- vm-migration/src/lib.rs | 3 +- vm-migration/src/protocol.rs | 6 +- vm-virtio/src/lib.rs | 1 + vm-virtio/src/queue.rs | 1 + vmm/src/acpi.rs | 16 ++-- vmm/src/api/dbus/mod.rs | 26 +++--- vmm/src/api/http/http_endpoint.rs | 12 +-- vmm/src/api/http/mod.rs | 38 ++++---- vmm/src/api/mod.rs | 19 ++-- vmm/src/config.rs | 22 +++-- vmm/src/console_devices.rs | 20 +++-- vmm/src/coredump.rs | 5 +- vmm/src/cpu.rs | 53 +++++------ vmm/src/device_manager.rs | 54 +++++------ vmm/src/device_tree.rs | 8 +- vmm/src/gdb.rs | 6 +- vmm/src/igvm/igvm_loader.rs | 30 +++---- vmm/src/igvm/loader.rs | 3 +- vmm/src/interrupt.rs | 5 +- vmm/src/landlock.rs | 7 +- vmm/src/lib.rs | 81 +++++++++-------- vmm/src/memory_manager.rs | 48 +++++----- vmm/src/migration.rs | 10 ++- vmm/src/pci_segment.rs | 6 +- vmm/src/seccomp_filters.rs | 5 +- vmm/src/serial_manager.rs | 16 ++-- vmm/src/sigwinch_listener.rs | 22 ++--- vmm/src/vm.rs | 89 ++++++++++--------- vmm/src/vm_config.rs | 6 +- 153 files changed, 1185 insertions(+), 924 deletions(-) diff --git a/.rustfmt.toml b/.rustfmt.toml index 36c419bb3..b2477a2f6 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1 +1,2 @@ -edition = "2021" \ No newline at end of file +edition = "2021" +group_imports="StdExternalCrate" diff --git a/api_client/src/lib.rs b/api_client/src/lib.rs index 71ba9e438..12a8089e1 100644 --- a/api_client/src/lib.rs +++ b/api_client/src/lib.rs @@ -5,6 +5,7 @@ use std::io::{Read, Write}; use std::os::unix::io::RawFd; + use thiserror::Error; use vmm_sys_util::sock_ctrl_msg::ScmSocket; diff --git a/arch/src/aarch64/fdt.rs b/arch/src/aarch64/fdt.rs index 1331dcf52..c96ba1365 100644 --- a/arch/src/aarch64/fdt.rs +++ b/arch/src/aarch64/fdt.rs @@ -6,17 +6,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. -use crate::{NumaNodes, PciSpaceInfo}; -use byteorder::{BigEndian, ByteOrder}; -use hypervisor::arch::aarch64::gic::Vgic; use std::cmp; use std::collections::HashMap; use std::ffi::CStr; use std::fmt::Debug; +use std::fs; +use std::path::Path; use std::result; use std::str; use std::sync::{Arc, Mutex}; +use byteorder::{BigEndian, ByteOrder}; +use hypervisor::arch::aarch64::gic::Vgic; +use thiserror::Error; +use vm_fdt::{FdtWriter, FdtWriterResult}; +use vm_memory::{Address, Bytes, GuestMemory, GuestMemoryError, GuestMemoryRegion}; + use super::super::DeviceType; use super::super::GuestMemoryMmap; use super::super::InitramfsConfig; @@ -24,11 +29,7 @@ use super::layout::{ IRQ_BASE, MEM_32BIT_DEVICES_SIZE, MEM_32BIT_DEVICES_START, MEM_PCI_IO_SIZE, MEM_PCI_IO_START, PCI_HIGH_BASE, PCI_MMIO_CONFIG_SIZE_PER_SEGMENT, }; -use std::fs; -use std::path::Path; -use thiserror::Error; -use vm_fdt::{FdtWriter, FdtWriterResult}; -use vm_memory::{Address, Bytes, GuestMemory, GuestMemoryError, GuestMemoryRegion}; +use crate::{NumaNodes, PciSpaceInfo}; // This is a value for uniquely identifying the FDT node declaring the interrupt controller. const GIC_PHANDLE: u32 = 1; diff --git a/arch/src/aarch64/mod.rs b/arch/src/aarch64/mod.rs index ce35956b8..00d3984ce 100644 --- a/arch/src/aarch64/mod.rs +++ b/arch/src/aarch64/mod.rs @@ -11,16 +11,18 @@ pub mod regs; /// Module for loading UEFI binary. pub mod uefi; -pub use self::fdt::DeviceInfoForFdt; -use crate::{DeviceType, GuestMemoryMmap, NumaNodes, PciSpaceInfo, RegionType}; -use hypervisor::arch::aarch64::gic::Vgic; -use log::{log_enabled, Level}; use std::collections::HashMap; use std::fmt::Debug; use std::sync::{Arc, Mutex}; + +use hypervisor::arch::aarch64::gic::Vgic; +use log::{log_enabled, Level}; use thiserror::Error; use vm_memory::{Address, GuestAddress, GuestMemory, GuestMemoryAtomic}; +pub use self::fdt::DeviceInfoForFdt; +use crate::{DeviceType, GuestMemoryMmap, NumaNodes, PciSpaceInfo, RegionType}; + pub const _NSIG: i32 = 65; /// Errors thrown while configuring aarch64 system. diff --git a/arch/src/aarch64/uefi.rs b/arch/src/aarch64/uefi.rs index 60c0e8693..bd40e36ff 100644 --- a/arch/src/aarch64/uefi.rs +++ b/arch/src/aarch64/uefi.rs @@ -5,6 +5,7 @@ use std::io::{Read, Seek, SeekFrom}; use std::os::fd::AsFd; use std::result; + use thiserror::Error; use vm_memory::{GuestAddress, GuestMemory}; diff --git a/arch/src/lib.rs b/arch/src/lib.rs index 04d7c0106..6dab02116 100644 --- a/arch/src/lib.rs +++ b/arch/src/lib.rs @@ -10,15 +10,17 @@ #[macro_use] extern crate log; -#[cfg(target_arch = "x86_64")] -use crate::x86_64::SgxEpcSection; -use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::fmt; use std::result; use std::sync::Arc; + +use serde::{Deserialize, Serialize}; use thiserror::Error; +#[cfg(target_arch = "x86_64")] +use crate::x86_64::SgxEpcSection; + type GuestMemoryMmap = vm_memory::GuestMemoryMmap; type GuestRegionMmap = vm_memory::GuestRegionMmap; diff --git a/arch/src/x86_64/mod.rs b/arch/src/x86_64/mod.rs index aff777f8b..8090f50b4 100644 --- a/arch/src/x86_64/mod.rs +++ b/arch/src/x86_64/mod.rs @@ -12,22 +12,24 @@ pub mod layout; mod mpspec; mod mptable; pub mod regs; -use crate::GuestMemoryMmap; -use crate::InitramfsConfig; -use crate::RegionType; +use std::collections::BTreeMap; +use std::mem; + use hypervisor::arch::x86::{CpuIdEntry, CPUID_FLAG_VALID_INDEX}; use hypervisor::{CpuVendor, HypervisorCpuError, HypervisorError}; use linux_loader::loader::bootparam::{boot_params, setup_header}; use linux_loader::loader::elf::start_info::{ hvm_memmap_table_entry, hvm_modlist_entry, hvm_start_info, }; -use std::collections::BTreeMap; -use std::mem; use thiserror::Error; use vm_memory::{ Address, Bytes, GuestAddress, GuestAddressSpace, GuestMemory, GuestMemoryAtomic, GuestMemoryRegion, GuestUsize, }; + +use crate::GuestMemoryMmap; +use crate::InitramfsConfig; +use crate::RegionType; mod smbios; use std::arch::x86_64; #[cfg(feature = "tdx")] @@ -1551,9 +1553,10 @@ fn update_cpuid_sgx( #[cfg(test)] mod tests { - use super::*; use linux_loader::loader::bootparam::boot_e820_entry; + use super::*; + #[test] fn regions_base_addr() { let regions = arch_memory_regions(); diff --git a/arch/src/x86_64/mptable.rs b/arch/src/x86_64/mptable.rs index 433d90dc8..7ed48d287 100644 --- a/arch/src/x86_64/mptable.rs +++ b/arch/src/x86_64/mptable.rs @@ -5,16 +5,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-BSD-3-Clause file. -use crate::layout::{APIC_START, HIGH_RAM_START, IOAPIC_START}; -use crate::x86_64::{get_x2apic_id, mpspec}; -use crate::GuestMemoryMmap; -use libc::c_uchar; use std::mem; use std::result; use std::slice; + +use libc::c_uchar; use thiserror::Error; use vm_memory::{Address, ByteValued, Bytes, GuestAddress, GuestMemory, GuestMemoryError}; +use crate::layout::{APIC_START, HIGH_RAM_START, IOAPIC_START}; +use crate::x86_64::{get_x2apic_id, mpspec}; +use crate::GuestMemoryMmap; + // This is a workaround to the Rust enforcement specifying that any implementation of a foreign // trait (in this case `ByteValued`) where: // * the type that is implementing the trait is foreign or @@ -304,12 +306,13 @@ pub fn setup_mptable( #[cfg(test)] mod tests { - use super::*; - use crate::layout::MPTABLE_START; use vm_memory::{ bitmap::BitmapSlice, GuestUsize, VolatileMemoryError, VolatileSlice, WriteVolatile, }; + use super::*; + use crate::layout::MPTABLE_START; + fn table_entry_size(type_: u8) -> usize { match type_ as u32 { mpspec::MP_PROCESSOR => mem::size_of::(), diff --git a/arch/src/x86_64/regs.rs b/arch/src/x86_64/regs.rs index 2688c831f..0410cf437 100644 --- a/arch/src/x86_64/regs.rs +++ b/arch/src/x86_64/regs.rs @@ -6,17 +6,19 @@ // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-BSD-3-Clause file. +use std::sync::Arc; +use std::{mem, result}; + +use hypervisor::arch::x86::gdt::{gdt_entry, segment_from_gdt}; +use hypervisor::arch::x86::regs::CR0_PE; +use hypervisor::arch::x86::{FpuState, SpecialRegisters}; +use thiserror::Error; +use vm_memory::{Address, Bytes, GuestMemory, GuestMemoryError}; + use crate::layout::{ BOOT_GDT_START, BOOT_IDT_START, BOOT_STACK_POINTER, PVH_INFO_START, ZERO_PAGE_START, }; use crate::{EntryPoint, GuestMemoryMmap}; -use hypervisor::arch::x86::gdt::{gdt_entry, segment_from_gdt}; -use hypervisor::arch::x86::regs::CR0_PE; -use hypervisor::arch::x86::{FpuState, SpecialRegisters}; -use std::sync::Arc; -use std::{mem, result}; -use thiserror::Error; -use vm_memory::{Address, Bytes, GuestMemory, GuestMemoryError}; #[derive(Debug, Error)] pub enum Error { @@ -186,9 +188,10 @@ pub fn configure_segments_and_sregs( #[cfg(test)] mod tests { - use super::*; use vm_memory::GuestAddress; + use super::*; + fn create_guest_mem() -> GuestMemoryMmap { GuestMemoryMmap::from_ranges(&[(GuestAddress(0), 0x10000)]).unwrap() } diff --git a/arch/src/x86_64/smbios.rs b/arch/src/x86_64/smbios.rs index 7d2e152b1..bc56b02a3 100644 --- a/arch/src/x86_64/smbios.rs +++ b/arch/src/x86_64/smbios.rs @@ -6,16 +6,18 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use crate::layout::SMBIOS_START; -use crate::GuestMemoryMmap; use std::mem; use std::result; use std::slice; + use thiserror::Error; use uuid::Uuid; use vm_memory::ByteValued; use vm_memory::{Address, Bytes, GuestAddress}; +use crate::layout::SMBIOS_START; +use crate::GuestMemoryMmap; + #[derive(Debug, Error)] pub enum Error { /// There was too little guest memory to store the entire SMBIOS table. diff --git a/arch/src/x86_64/tdx/mod.rs b/arch/src/x86_64/tdx/mod.rs index 58a272513..d4c58bfb0 100644 --- a/arch/src/x86_64/tdx/mod.rs +++ b/arch/src/x86_64/tdx/mod.rs @@ -1,14 +1,16 @@ // Copyright © 2021 Intel Corporation // // SPDX-License-Identifier: Apache-2.0 -use crate::GuestMemoryMmap; use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::str::FromStr; + use thiserror::Error; use uuid::Uuid; use vm_memory::{ByteValued, Bytes, GuestAddress, GuestMemoryError}; +use crate::GuestMemoryMmap; + #[derive(Error, Debug)] pub enum TdvfError { #[error("Failed read TDVF descriptor: {0}")] diff --git a/block/src/async_io.rs b/block/src/async_io.rs index a86ad7f26..9242bf038 100644 --- a/block/src/async_io.rs +++ b/block/src/async_io.rs @@ -2,10 +2,11 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use crate::DiskTopology; use thiserror::Error; use vmm_sys_util::eventfd::EventFd; +use crate::DiskTopology; + #[derive(Error, Debug)] pub enum DiskFileError { /// Failed getting disk file size. diff --git a/block/src/fixed_vhd.rs b/block/src/fixed_vhd.rs index 66ef13124..22ef4dd80 100644 --- a/block/src/fixed_vhd.rs +++ b/block/src/fixed_vhd.rs @@ -2,12 +2,13 @@ // // SPDX-License-Identifier: Apache-2.0 -use crate::vhd::VhdFooter; -use crate::BlockBackend; use std::fs::File; use std::io::{Read, Seek, SeekFrom, Write}; use std::os::unix::io::{AsRawFd, RawFd}; +use crate::vhd::VhdFooter; +use crate::BlockBackend; + #[derive(Debug)] pub struct FixedVhd { file: File, diff --git a/block/src/fixed_vhd_async.rs b/block/src/fixed_vhd_async.rs index d8553afaf..d3d897789 100644 --- a/block/src/fixed_vhd_async.rs +++ b/block/src/fixed_vhd_async.rs @@ -2,15 +2,17 @@ // // SPDX-License-Identifier: Apache-2.0 +use std::fs::File; +use std::os::unix::io::{AsRawFd, RawFd}; + +use vmm_sys_util::eventfd::EventFd; + use crate::async_io::{ AsyncIo, AsyncIoError, AsyncIoResult, DiskFile, DiskFileError, DiskFileResult, }; use crate::fixed_vhd::FixedVhd; use crate::raw_async::RawFileAsync; use crate::BlockBackend; -use std::fs::File; -use std::os::unix::io::{AsRawFd, RawFd}; -use vmm_sys_util::eventfd::EventFd; pub struct FixedVhdDiskAsync(FixedVhd); diff --git a/block/src/fixed_vhd_sync.rs b/block/src/fixed_vhd_sync.rs index b435bdd38..089e6bfe7 100644 --- a/block/src/fixed_vhd_sync.rs +++ b/block/src/fixed_vhd_sync.rs @@ -2,15 +2,17 @@ // // SPDX-License-Identifier: Apache-2.0 +use std::fs::File; +use std::os::unix::io::{AsRawFd, RawFd}; + +use vmm_sys_util::eventfd::EventFd; + use crate::async_io::{ AsyncIo, AsyncIoError, AsyncIoResult, DiskFile, DiskFileError, DiskFileResult, }; use crate::fixed_vhd::FixedVhd; use crate::raw_sync::RawFileSync; use crate::BlockBackend; -use std::fs::File; -use std::os::unix::io::{AsRawFd, RawFd}; -use vmm_sys_util::eventfd::EventFd; pub struct FixedVhdDiskSync(FixedVhd); diff --git a/block/src/lib.rs b/block/src/lib.rs index fd1bfbb7f..b7904caf5 100644 --- a/block/src/lib.rs +++ b/block/src/lib.rs @@ -30,15 +30,6 @@ pub mod vhd; pub mod vhdx; pub mod vhdx_sync; -use crate::async_io::{AsyncIo, AsyncIoError, AsyncIoResult}; -use crate::fixed_vhd::FixedVhd; -use crate::qcow::{QcowFile, RawFile}; -use crate::vhdx::{Vhdx, VhdxError}; -#[cfg(feature = "io_uring")] -use io_uring::{opcode, IoUring, Probe}; -use libc::{ioctl, S_IFBLK, S_IFMT}; -use serde::{Deserialize, Serialize}; -use smallvec::SmallVec; use std::alloc::{alloc_zeroed, dealloc, Layout}; use std::cmp; use std::collections::VecDeque; @@ -52,6 +43,12 @@ use std::result; use std::sync::Arc; use std::sync::MutexGuard; use std::time::Instant; + +#[cfg(feature = "io_uring")] +use io_uring::{opcode, IoUring, Probe}; +use libc::{ioctl, S_IFBLK, S_IFMT}; +use serde::{Deserialize, Serialize}; +use smallvec::SmallVec; use thiserror::Error; use virtio_bindings::virtio_blk::*; use virtio_queue::DescriptorChain; @@ -64,6 +61,11 @@ use vmm_sys_util::aio; use vmm_sys_util::eventfd::EventFd; use vmm_sys_util::{ioctl_io_nr, ioctl_ioc_nr}; +use crate::async_io::{AsyncIo, AsyncIoError, AsyncIoResult}; +use crate::fixed_vhd::FixedVhd; +use crate::qcow::{QcowFile, RawFile}; +use crate::vhdx::{Vhdx, VhdxError}; + const SECTOR_SHIFT: u8 = 9; pub const SECTOR_SIZE: u64 = 0x01 << SECTOR_SHIFT; diff --git a/block/src/qcow/mod.rs b/block/src/qcow/mod.rs index abe758f95..a4f0c98a4 100644 --- a/block/src/qcow/mod.rs +++ b/block/src/qcow/mod.rs @@ -9,20 +9,15 @@ mod raw_file; mod refcount; mod vec_cache; -use crate::qcow::{ - qcow_raw_file::QcowRawFile, - refcount::RefCount, - vec_cache::{CacheMap, Cacheable, VecCache}, -}; -use crate::BlockBackend; -use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; -use libc::{EINVAL, ENOSPC, ENOTSUP}; -use remain::sorted; use std::cmp::{max, min}; use std::fs::OpenOptions; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::mem::size_of; use std::str; + +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; +use libc::{EINVAL, ENOSPC, ENOTSUP}; +use remain::sorted; use thiserror::Error; use vmm_sys_util::{ file_traits::FileSetLen, file_traits::FileSync, seek_hole::SeekHole, write_zeroes::PunchHole, @@ -30,6 +25,12 @@ use vmm_sys_util::{ }; pub use crate::qcow::raw_file::RawFile; +use crate::qcow::{ + qcow_raw_file::QcowRawFile, + refcount::RefCount, + vec_cache::{CacheMap, Cacheable, VecCache}, +}; +use crate::BlockBackend; /// Nesting depth limit for disk formats that can open other disk files. const MAX_NESTING_DEPTH: u32 = 10; @@ -1837,13 +1838,15 @@ pub fn detect_image_type(file: &mut RawFile) -> Result { #[cfg(test)] mod tests { - use super::*; use std::fs::File; use std::path::Path; + use vmm_sys_util::tempdir::TempDir; use vmm_sys_util::tempfile::TempFile; use vmm_sys_util::write_zeroes::WriteZeroes; + use super::*; + fn valid_header_v3() -> Vec { vec![ 0x51u8, 0x46, 0x49, 0xfb, // magic diff --git a/block/src/qcow/qcow_raw_file.rs b/block/src/qcow/qcow_raw_file.rs index e789d07b9..4bac118ad 100644 --- a/block/src/qcow/qcow_raw_file.rs +++ b/block/src/qcow/qcow_raw_file.rs @@ -4,12 +4,14 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use super::RawFile; -use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::io::{self, BufWriter, Seek, SeekFrom, Write}; use std::mem::size_of; + +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use vmm_sys_util::write_zeroes::WriteZeroes; +use super::RawFile; + /// A qcow file. Allows reading/writing clusters and appending clusters. #[derive(Debug)] pub struct QcowRawFile { diff --git a/block/src/qcow/raw_file.rs b/block/src/qcow/raw_file.rs index d95ba6f5c..0fa5acd43 100644 --- a/block/src/qcow/raw_file.rs +++ b/block/src/qcow/raw_file.rs @@ -8,15 +8,17 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use crate::BlockBackend; -use libc::c_void; use std::alloc::{alloc_zeroed, dealloc, Layout}; use std::fs::{File, Metadata}; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::os::unix::io::{AsRawFd, RawFd}; use std::slice; + +use libc::c_void; use vmm_sys_util::{seek_hole::SeekHole, write_zeroes::PunchHole, write_zeroes::WriteZeroesAt}; +use crate::BlockBackend; + #[derive(Debug)] pub struct RawFile { file: File, diff --git a/block/src/qcow_sync.rs b/block/src/qcow_sync.rs index 6455be6a0..9cde2a7df 100644 --- a/block/src/qcow_sync.rs +++ b/block/src/qcow_sync.rs @@ -2,15 +2,17 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use crate::async_io::{AsyncIo, AsyncIoResult, DiskFile, DiskFileError, DiskFileResult}; -use crate::qcow::{QcowFile, RawFile, Result as QcowResult}; -use crate::AsyncAdaptor; use std::collections::VecDeque; use std::fs::File; use std::io::{Seek, SeekFrom}; use std::sync::{Arc, Mutex, MutexGuard}; + use vmm_sys_util::eventfd::EventFd; +use crate::async_io::{AsyncIo, AsyncIoResult, DiskFile, DiskFileError, DiskFileResult}; +use crate::qcow::{QcowFile, RawFile, Result as QcowResult}; +use crate::AsyncAdaptor; + pub struct QcowDiskSync { qcow_file: Arc>, } diff --git a/block/src/raw_async.rs b/block/src/raw_async.rs index 0ac3a647e..49bfe0837 100644 --- a/block/src/raw_async.rs +++ b/block/src/raw_async.rs @@ -2,15 +2,17 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause +use std::fs::File; +use std::io::{Seek, SeekFrom}; +use std::os::unix::io::{AsRawFd, RawFd}; + +use io_uring::{opcode, squeue, types, IoUring}; +use vmm_sys_util::eventfd::EventFd; + use crate::async_io::{ AsyncIo, AsyncIoError, AsyncIoResult, DiskFile, DiskFileError, DiskFileResult, }; use crate::DiskTopology; -use io_uring::{opcode, squeue, types, IoUring}; -use std::fs::File; -use std::io::{Seek, SeekFrom}; -use std::os::unix::io::{AsRawFd, RawFd}; -use vmm_sys_util::eventfd::EventFd; pub struct RawFileDisk { file: File, diff --git a/block/src/raw_async_aio.rs b/block/src/raw_async_aio.rs index d0304fbaf..5a5345751 100644 --- a/block/src/raw_async_aio.rs +++ b/block/src/raw_async_aio.rs @@ -5,15 +5,17 @@ // Copyright © 2023 Crusoe Energy Systems LLC // +use std::fs::File; +use std::io::{Seek, SeekFrom}; +use std::os::unix::io::{AsRawFd, RawFd}; + +use vmm_sys_util::aio; +use vmm_sys_util::eventfd::EventFd; + use crate::async_io::{ AsyncIo, AsyncIoError, AsyncIoResult, DiskFile, DiskFileError, DiskFileResult, }; use crate::DiskTopology; -use std::fs::File; -use std::io::{Seek, SeekFrom}; -use std::os::unix::io::{AsRawFd, RawFd}; -use vmm_sys_util::aio; -use vmm_sys_util::eventfd::EventFd; pub struct RawFileDiskAio { file: File, diff --git a/block/src/raw_sync.rs b/block/src/raw_sync.rs index b9415cd9e..20f8aa075 100644 --- a/block/src/raw_sync.rs +++ b/block/src/raw_sync.rs @@ -2,15 +2,17 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause +use std::collections::VecDeque; +use std::fs::File; +use std::io::{Seek, SeekFrom}; +use std::os::unix::io::{AsRawFd, RawFd}; + +use vmm_sys_util::eventfd::EventFd; + use crate::async_io::{ AsyncIo, AsyncIoError, AsyncIoResult, DiskFile, DiskFileError, DiskFileResult, }; use crate::DiskTopology; -use std::collections::VecDeque; -use std::fs::File; -use std::io::{Seek, SeekFrom}; -use std::os::unix::io::{AsRawFd, RawFd}; -use vmm_sys_util::eventfd::EventFd; pub struct RawFileDiskSync { file: File, diff --git a/block/src/vhd.rs b/block/src/vhd.rs index ad9a90dca..2cc65ca0b 100644 --- a/block/src/vhd.rs +++ b/block/src/vhd.rs @@ -2,10 +2,11 @@ // // SPDX-License-Identifier: Apache-2.0 -use crate::{read_aligned_block_size, DiskTopology}; use std::fs::File; use std::io::{Seek, SeekFrom}; +use crate::{read_aligned_block_size, DiskTopology}; + #[derive(Clone, Copy)] pub struct VhdFooter { cookie: u64, @@ -117,11 +118,13 @@ pub fn is_fixed_vhd(f: &mut File) -> std::io::Result { #[cfg(test)] mod tests { - use super::{is_fixed_vhd, VhdFooter}; use std::fs::File; use std::io::{Seek, SeekFrom, Write}; + use vmm_sys_util::tempfile::TempFile; + use super::{is_fixed_vhd, VhdFooter}; + fn valid_fixed_vhd_footer() -> Vec { vec![ 0x63, 0x6f, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x78, // cookie diff --git a/block/src/vhdx/mod.rs b/block/src/vhdx/mod.rs index ccb05d8b0..53e79218e 100644 --- a/block/src/vhdx/mod.rs +++ b/block/src/vhdx/mod.rs @@ -2,6 +2,15 @@ // // SPDX-License-Identifier: Apache-2.0 +use std::collections::btree_map::BTreeMap; +use std::fs::File; +use std::io::{Read, Seek, SeekFrom, Write}; + +use byteorder::{BigEndian, ByteOrder}; +use remain::sorted; +use thiserror::Error; +use uuid::Uuid; + use crate::vhdx::{ vhdx_bat::{BatEntry, VhdxBatError}, vhdx_header::{RegionInfo, RegionTableEntry, VhdxHeader, VhdxHeaderError}, @@ -9,13 +18,6 @@ use crate::vhdx::{ vhdx_metadata::{DiskSpec, VhdxMetadataError}, }; use crate::BlockBackend; -use byteorder::{BigEndian, ByteOrder}; -use remain::sorted; -use std::collections::btree_map::BTreeMap; -use std::fs::File; -use std::io::{Read, Seek, SeekFrom, Write}; -use thiserror::Error; -use uuid::Uuid; macro_rules! div_round_up { ($n:expr,$d:expr) => { diff --git a/block/src/vhdx/vhdx_bat.rs b/block/src/vhdx/vhdx_bat.rs index 22243e147..314adab7e 100644 --- a/block/src/vhdx/vhdx_bat.rs +++ b/block/src/vhdx/vhdx_bat.rs @@ -2,14 +2,16 @@ // // SPDX-License-Identifier: Apache-2.0 -use crate::vhdx::{vhdx_header::RegionTableEntry, vhdx_metadata::DiskSpec}; -use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; -use remain::sorted; use std::fs::File; use std::io::{self, Seek, SeekFrom}; use std::mem::size_of; + +use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; +use remain::sorted; use thiserror::Error; +use crate::vhdx::{vhdx_header::RegionTableEntry, vhdx_metadata::DiskSpec}; + // Payload BAT Entry States pub const PAYLOAD_BLOCK_NOT_PRESENT: u64 = 0; pub const PAYLOAD_BLOCK_UNDEFINED: u64 = 1; diff --git a/block/src/vhdx/vhdx_header.rs b/block/src/vhdx/vhdx_header.rs index 55af64430..b51dab1ce 100644 --- a/block/src/vhdx/vhdx_header.rs +++ b/block/src/vhdx/vhdx_header.rs @@ -4,12 +4,13 @@ extern crate log; -use byteorder::{ByteOrder, LittleEndian, ReadBytesExt}; -use remain::sorted; use std::collections::btree_map::BTreeMap; use std::fs::File; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::mem::size_of; + +use byteorder::{ByteOrder, LittleEndian, ReadBytesExt}; +use remain::sorted; use thiserror::Error; use uuid::Uuid; diff --git a/block/src/vhdx/vhdx_io.rs b/block/src/vhdx/vhdx_io.rs index a67d02124..edb83a844 100644 --- a/block/src/vhdx/vhdx_io.rs +++ b/block/src/vhdx/vhdx_io.rs @@ -2,14 +2,16 @@ // // SPDX-License-Identifier: Apache-2.0 +use std::fs::File; +use std::io::{self, Read, Seek, SeekFrom, Write}; + +use remain::sorted; +use thiserror::Error; + use crate::vhdx::{ vhdx_bat::{self, BatEntry, VhdxBatError}, vhdx_metadata::{self, DiskSpec}, }; -use remain::sorted; -use std::fs::File; -use std::io::{self, Read, Seek, SeekFrom, Write}; -use thiserror::Error; const SECTOR_SIZE: u64 = 512; diff --git a/block/src/vhdx/vhdx_metadata.rs b/block/src/vhdx/vhdx_metadata.rs index f30cb62d6..7c274487a 100644 --- a/block/src/vhdx/vhdx_metadata.rs +++ b/block/src/vhdx/vhdx_metadata.rs @@ -2,15 +2,17 @@ // // SPDX-License-Identifier: Apache-2.0 -use crate::vhdx::vhdx_header::RegionTableEntry; -use byteorder::{LittleEndian, ReadBytesExt}; -use remain::sorted; use std::fs::File; use std::io::{self, Read, Seek, SeekFrom}; use std::mem::size_of; + +use byteorder::{LittleEndian, ReadBytesExt}; +use remain::sorted; use thiserror::Error; use uuid::Uuid; +use crate::vhdx::vhdx_header::RegionTableEntry; + const METADATA_SIGN: u64 = 0x6174_6164_6174_656D; const METADATA_ENTRY_SIZE: usize = 32; const METADATA_MAX_ENTRIES: u16 = 2047; diff --git a/block/src/vhdx_sync.rs b/block/src/vhdx_sync.rs index 037fec069..b6736a990 100644 --- a/block/src/vhdx_sync.rs +++ b/block/src/vhdx_sync.rs @@ -2,14 +2,16 @@ // // SPDX-License-Identifier: Apache-2.0 -use crate::async_io::{AsyncIo, AsyncIoResult, DiskFile, DiskFileError, DiskFileResult}; -use crate::vhdx::{Result as VhdxResult, Vhdx}; -use crate::AsyncAdaptor; use std::collections::VecDeque; use std::fs::File; use std::sync::{Arc, Mutex, MutexGuard}; + use vmm_sys_util::eventfd::EventFd; +use crate::async_io::{AsyncIo, AsyncIoResult, DiskFile, DiskFileError, DiskFileResult}; +use crate::vhdx::{Result as VhdxResult, Vhdx}; +use crate::AsyncAdaptor; + pub struct VhdxDiskSync { vhdx_file: Arc>, } diff --git a/devices/src/acpi.rs b/devices/src/acpi.rs index 57ac8cf9a..2a38f5974 100644 --- a/devices/src/acpi.rs +++ b/devices/src/acpi.rs @@ -3,17 +3,19 @@ // SPDX-License-Identifier: Apache-2.0 // -use super::AcpiNotificationFlags; -use acpi_tables::{aml, Aml, AmlSink}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Barrier}; use std::thread; use std::time::Instant; + +use acpi_tables::{aml, Aml, AmlSink}; use vm_device::interrupt::InterruptSourceGroup; use vm_device::BusDevice; use vm_memory::GuestAddress; use vmm_sys_util::eventfd::EventFd; +use super::AcpiNotificationFlags; + pub const GED_DEVICE_ACPI_SIZE: usize = 0x1; /// A device for handling ACPI shutdown and reboot diff --git a/devices/src/debug_console.rs b/devices/src/debug_console.rs index 799c8a67e..8ec63573b 100644 --- a/devices/src/debug_console.rs +++ b/devices/src/debug_console.rs @@ -8,6 +8,7 @@ use std::io; use std::io::Write; use std::sync::{Arc, Barrier}; + use vm_device::BusDevice; use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; diff --git a/devices/src/gic.rs b/devices/src/gic.rs index c47f2b48d..1f9d23998 100644 --- a/devices/src/gic.rs +++ b/devices/src/gic.rs @@ -4,14 +4,15 @@ use super::interrupt_controller::{Error, InterruptController}; extern crate arch; +use std::result; +use std::sync::{Arc, Mutex}; + use anyhow::anyhow; use arch::layout; use hypervisor::{ arch::aarch64::gic::{Vgic, VgicConfig}, CpuState, GicState, }; -use std::result; -use std::sync::{Arc, Mutex}; use vm_device::interrupt::{ InterruptIndex, InterruptManager, InterruptSourceConfig, InterruptSourceGroup, LegacyIrqSourceConfig, MsiIrqGroupConfig, diff --git a/devices/src/interrupt_controller.rs b/devices/src/interrupt_controller.rs index b3ab8926a..40f842d7d 100644 --- a/devices/src/interrupt_controller.rs +++ b/devices/src/interrupt_controller.rs @@ -4,6 +4,7 @@ use std::io; use std::result; + use thiserror::Error; use vmm_sys_util::eventfd::EventFd; diff --git a/devices/src/ioapic.rs b/devices/src/ioapic.rs index bcfd0a186..dadec0969 100644 --- a/devices/src/ioapic.rs +++ b/devices/src/ioapic.rs @@ -9,11 +9,11 @@ // Implementation of an intel 82093AA Input/Output Advanced Programmable Interrupt Controller // See https://pdos.csail.mit.edu/6.828/2016/readings/ia32/ioapic.pdf for a specification. -use super::interrupt_controller::{Error, InterruptController}; -use byteorder::{ByteOrder, LittleEndian}; -use serde::{Deserialize, Serialize}; use std::result; use std::sync::{Arc, Barrier}; + +use byteorder::{ByteOrder, LittleEndian}; +use serde::{Deserialize, Serialize}; use vm_device::interrupt::{ InterruptIndex, InterruptManager, InterruptSourceConfig, InterruptSourceGroup, MsiIrqGroupConfig, MsiIrqSourceConfig, @@ -23,6 +23,8 @@ use vm_memory::GuestAddress; use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; use vmm_sys_util::eventfd::EventFd; +use super::interrupt_controller::{Error, InterruptController}; + type Result = result::Result; // I/O REDIRECTION TABLE REGISTER diff --git a/devices/src/legacy/cmos.rs b/devices/src/legacy/cmos.rs index d8d20dc37..5f167698a 100644 --- a/devices/src/legacy/cmos.rs +++ b/devices/src/legacy/cmos.rs @@ -4,18 +4,18 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use libc::{clock_gettime, gmtime_r, timespec, tm, CLOCK_REALTIME}; use std::cmp::min; use std::mem; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Barrier}; use std::thread; -use vm_device::BusDevice; -use vmm_sys_util::eventfd::EventFd; // https://github.com/rust-lang/libc/issues/1848 #[cfg_attr(target_env = "musl", allow(deprecated))] use libc::time_t; +use libc::{clock_gettime, gmtime_r, timespec, tm, CLOCK_REALTIME}; +use vm_device::BusDevice; +use vmm_sys_util::eventfd::EventFd; const INDEX_MASK: u8 = 0x7f; const INDEX_OFFSET: u64 = 0x0; diff --git a/devices/src/legacy/debug_port.rs b/devices/src/legacy/debug_port.rs index 14fecfe79..3050e9e61 100644 --- a/devices/src/legacy/debug_port.rs +++ b/devices/src/legacy/debug_port.rs @@ -5,6 +5,7 @@ use std::fmt; use std::time::Instant; + use vm_device::BusDevice; /// Debug I/O port, see: diff --git a/devices/src/legacy/fwdebug.rs b/devices/src/legacy/fwdebug.rs index e28ee7349..0de5b6eea 100644 --- a/devices/src/legacy/fwdebug.rs +++ b/devices/src/legacy/fwdebug.rs @@ -8,6 +8,7 @@ // use std::sync::{Arc, Barrier}; + use vm_device::BusDevice; /// Provides firmware debug output via I/O port controls diff --git a/devices/src/legacy/gpio_pl061.rs b/devices/src/legacy/gpio_pl061.rs index f5e0ea1bc..5f4a3fc0f 100644 --- a/devices/src/legacy/gpio_pl061.rs +++ b/devices/src/legacy/gpio_pl061.rs @@ -7,16 +7,18 @@ //! This module implements an ARM PrimeCell General Purpose Input/Output(PL061) to support gracefully poweroff microvm from external. //! -use crate::{read_le_u32, write_le_u32}; -use serde::{Deserialize, Serialize}; use std::io; use std::result; use std::sync::{Arc, Barrier}; + +use serde::{Deserialize, Serialize}; use thiserror::Error; use vm_device::interrupt::InterruptSourceGroup; use vm_device::BusDevice; use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; +use crate::{read_le_u32, write_le_u32}; + const OFS_DATA: u64 = 0x400; // Data Register const GPIODIR: u64 = 0x400; // Direction Register const GPIOIS: u64 = 0x404; // Interrupt Sense Register @@ -323,10 +325,11 @@ impl Migratable for Gpio {} #[cfg(test)] mod tests { - use super::*; use vm_device::interrupt::{InterruptIndex, InterruptSourceConfig}; use vmm_sys_util::eventfd::EventFd; + use super::*; + const GPIO_NAME: &str = "gpio"; const LEGACY_GPIO_MAPPED_IO_START: u64 = 0x0902_0000; diff --git a/devices/src/legacy/i8042.rs b/devices/src/legacy/i8042.rs index 887fb4d00..b241ce2de 100644 --- a/devices/src/legacy/i8042.rs +++ b/devices/src/legacy/i8042.rs @@ -9,6 +9,7 @@ use std::sync::{ Arc, Barrier, }; use std::thread; + use vm_device::BusDevice; use vmm_sys_util::eventfd::EventFd; diff --git a/devices/src/legacy/mod.rs b/devices/src/legacy/mod.rs index 935ded96b..3f58e5c84 100644 --- a/devices/src/legacy/mod.rs +++ b/devices/src/legacy/mod.rs @@ -24,14 +24,13 @@ pub use self::cmos::Cmos; pub use self::debug_port::DebugPort; #[cfg(target_arch = "x86_64")] pub use self::fwdebug::FwDebugDevice; -pub use self::i8042::I8042Device; -pub use self::serial::Serial; - #[cfg(target_arch = "aarch64")] pub use self::gpio_pl061::Error as GpioDeviceError; #[cfg(target_arch = "aarch64")] pub use self::gpio_pl061::Gpio; +pub use self::i8042::I8042Device; #[cfg(target_arch = "aarch64")] pub use self::rtc_pl031::Rtc; +pub use self::serial::Serial; #[cfg(target_arch = "aarch64")] pub use self::uart_pl011::Pl011; diff --git a/devices/src/legacy/rtc_pl031.rs b/devices/src/legacy/rtc_pl031.rs index f1bb7d3be..0551d7e19 100644 --- a/devices/src/legacy/rtc_pl031.rs +++ b/devices/src/legacy/rtc_pl031.rs @@ -8,14 +8,16 @@ //! This is achieved by generating an interrupt signal after counting for a programmed number of cycles of //! a real-time clock input. //! -use crate::{read_le_u32, write_le_u32}; use std::sync::{Arc, Barrier}; use std::time::Instant; use std::{io, result}; + use thiserror::Error; use vm_device::interrupt::InterruptSourceGroup; use vm_device::BusDevice; +use crate::{read_le_u32, write_le_u32}; + // As you can see in https://static.docs.arm.com/ddi0224/c/real_time_clock_pl031_r1p3_technical_reference_manual_DDI0224C.pdf // at section 3.2 Summary of RTC registers, the total size occupied by this device is 0x000 -> 0xFFC + 4 = 0x1000. // From 0x0 to 0x1C we have following registers: @@ -228,13 +230,14 @@ impl BusDevice for Rtc { #[cfg(test)] mod tests { + use vm_device::interrupt::{InterruptIndex, InterruptSourceConfig}; + use vmm_sys_util::eventfd::EventFd; + use super::*; use crate::{ read_be_u16, read_be_u32, read_le_i32, read_le_u16, read_le_u64, write_be_u16, write_be_u32, write_le_i32, write_le_u16, write_le_u64, }; - use vm_device::interrupt::{InterruptIndex, InterruptSourceConfig}; - use vmm_sys_util::eventfd::EventFd; const LEGACY_RTC_MAPPED_IO_START: u64 = 0x0901_0000; diff --git a/devices/src/legacy/serial.rs b/devices/src/legacy/serial.rs index f97b93f66..143379fd2 100644 --- a/devices/src/legacy/serial.rs +++ b/devices/src/legacy/serial.rs @@ -5,10 +5,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-BSD-3-Clause file. -use serde::{Deserialize, Serialize}; use std::collections::VecDeque; use std::sync::{Arc, Barrier}; use std::{io, result}; + +use serde::{Deserialize, Serialize}; use vm_device::interrupt::InterruptSourceGroup; use vm_device::BusDevice; use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; @@ -340,11 +341,13 @@ impl Migratable for Serial {} #[cfg(test)] mod tests { - use super::*; use std::sync::Mutex; + use vm_device::interrupt::{InterruptIndex, InterruptSourceConfig}; use vmm_sys_util::eventfd::EventFd; + use super::*; + const SERIAL_NAME: &str = "serial"; struct TestInterrupt { diff --git a/devices/src/legacy/uart_pl011.rs b/devices/src/legacy/uart_pl011.rs index d2c4a8f80..19abc29cc 100644 --- a/devices/src/legacy/uart_pl011.rs +++ b/devices/src/legacy/uart_pl011.rs @@ -6,17 +6,19 @@ //! This module implements an ARM PrimeCell UART(PL011). //! -use crate::{read_le_u32, write_le_u32}; -use serde::{Deserialize, Serialize}; use std::collections::VecDeque; use std::sync::{Arc, Barrier}; use std::time::Instant; use std::{io, result}; + +use serde::{Deserialize, Serialize}; use thiserror::Error; use vm_device::interrupt::InterruptSourceGroup; use vm_device::BusDevice; use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; +use crate::{read_le_u32, write_le_u32}; + /* Registers */ const UARTDR: u64 = 0; const UARTRSR_UARTECR: u64 = 1; @@ -452,11 +454,13 @@ impl Migratable for Pl011 {} #[cfg(test)] mod tests { - use super::*; use std::sync::Mutex; + use vm_device::interrupt::{InterruptIndex, InterruptSourceConfig}; use vmm_sys_util::eventfd::EventFd; + use super::*; + const SERIAL_NAME: &str = "serial"; struct TestInterrupt { diff --git a/devices/src/pvmemcontrol.rs b/devices/src/pvmemcontrol.rs index cc7b37fb2..5b95010f5 100644 --- a/devices/src/pvmemcontrol.rs +++ b/devices/src/pvmemcontrol.rs @@ -3,17 +3,18 @@ // SPDX-License-Identifier: Apache-2.0 // -use num_enum::TryFromPrimitive; -use pci::{ - BarReprogrammingParams, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, - PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciHeaderType, PciSubclass, -}; use std::{ collections::HashMap, ffi::CString, io, result, sync::{Arc, Barrier, Mutex, RwLock}, }; + +use num_enum::TryFromPrimitive; +use pci::{ + BarReprogrammingParams, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, + PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciHeaderType, PciSubclass, +}; use thiserror::Error; use vm_allocator::{page_size::get_page_size, AddressAllocator, SystemAllocator}; use vm_device::{BusDeviceSync, Resource}; diff --git a/devices/src/pvpanic.rs b/devices/src/pvpanic.rs index f57e3c963..0142e3725 100644 --- a/devices/src/pvpanic.rs +++ b/devices/src/pvpanic.rs @@ -3,6 +3,10 @@ // SPDX-License-Identifier: Apache-2.0 // +use std::any::Any; +use std::result; +use std::sync::{Arc, Barrier, Mutex}; + use anyhow::anyhow; use pci::{ BarReprogrammingParams, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, @@ -10,9 +14,6 @@ use pci::{ PCI_CONFIGURATION_ID, }; use serde::{Deserialize, Serialize}; -use std::any::Any; -use std::result; -use std::sync::{Arc, Barrier, Mutex}; use thiserror::Error; use vm_allocator::{AddressAllocator, SystemAllocator}; use vm_device::{BusDevice, Resource}; diff --git a/devices/src/tpm.rs b/devices/src/tpm.rs index 0f6c60704..e52887474 100644 --- a/devices/src/tpm.rs +++ b/devices/src/tpm.rs @@ -3,13 +3,14 @@ // SPDX-License-Identifier: Apache-2.0 // +use std::cmp; +use std::sync::{Arc, Barrier}; + use anyhow::anyhow; #[cfg(target_arch = "aarch64")] use arch::aarch64::layout::{TPM_SIZE, TPM_START}; #[cfg(target_arch = "x86_64")] use arch::x86_64::layout::{TPM_SIZE, TPM_START}; -use std::cmp; -use std::sync::{Arc, Barrier}; use thiserror::Error; use tpm::emulator::{BackendCmd, Emulator}; use tpm::TPM_CRB_BUFFER_MAX; diff --git a/event_monitor/src/lib.rs b/event_monitor/src/lib.rs index 482085c21..0e16db9c2 100644 --- a/event_monitor/src/lib.rs +++ b/event_monitor/src/lib.rs @@ -3,8 +3,6 @@ // SPDX-License-Identifier: Apache-2.0 // -use once_cell::sync::OnceCell; -use serde::Serialize; use std::borrow::Cow; use std::collections::HashMap; use std::fs::File; @@ -13,6 +11,9 @@ use std::os::unix::io::AsRawFd; use std::sync::Arc; use std::time::{Duration, Instant}; +use once_cell::sync::OnceCell; +use serde::Serialize; + static MONITOR: OnceCell = OnceCell::new(); #[derive(Serialize)] diff --git a/hypervisor/src/arch/aarch64/gic.rs b/hypervisor/src/arch/aarch64/gic.rs index ecead2dd8..95330d2be 100644 --- a/hypervisor/src/arch/aarch64/gic.rs +++ b/hypervisor/src/arch/aarch64/gic.rs @@ -2,11 +2,13 @@ // // SPDX-License-Identifier: Apache-2.0 -use crate::{CpuState, GicState, HypervisorDeviceError, HypervisorVmError}; use std::any::Any; use std::result; + use thiserror::Error; +use crate::{CpuState, GicState, HypervisorDeviceError, HypervisorVmError}; + /// Errors thrown while setting up the VGIC. #[derive(Debug, Error)] pub enum Error { diff --git a/hypervisor/src/arch/emulator/mod.rs b/hypervisor/src/arch/emulator/mod.rs index c3068d700..e62d5f636 100644 --- a/hypervisor/src/arch/emulator/mod.rs +++ b/hypervisor/src/arch/emulator/mod.rs @@ -6,6 +6,7 @@ use core::fmt::Debug; use std::fmt::{self, Display}; + use thiserror::Error; #[derive(Clone, Copy, Error, Debug)] diff --git a/hypervisor/src/arch/x86/emulator/instructions/mod.rs b/hypervisor/src/arch/x86/emulator/instructions/mod.rs index 5c7d90090..e63986cf6 100644 --- a/hypervisor/src/arch/x86/emulator/instructions/mod.rs +++ b/hypervisor/src/arch/x86/emulator/instructions/mod.rs @@ -4,10 +4,11 @@ // SPDX-License-Identifier: Apache-2.0 // +use iced_x86::*; + use crate::arch::emulator::{EmulationError, PlatformEmulator, PlatformError}; use crate::arch::x86::emulator::CpuStateManager; use crate::arch::x86::Exception; -use iced_x86::*; pub mod cmp; pub mod mov; diff --git a/hypervisor/src/arch/x86/emulator/instructions/or.rs b/hypervisor/src/arch/x86/emulator/instructions/or.rs index 7af356f20..b746354b7 100644 --- a/hypervisor/src/arch/x86/emulator/instructions/or.rs +++ b/hypervisor/src/arch/x86/emulator/instructions/or.rs @@ -51,7 +51,6 @@ impl InstructionHandler for Or_rm8_r8 { #[cfg(test)] mod tests { use super::*; - use crate::arch::x86::emulator::mock_vmm::*; #[test] diff --git a/hypervisor/src/arch/x86/emulator/mod.rs b/hypervisor/src/arch/x86/emulator/mod.rs index 71e375533..ec5f94f0c 100644 --- a/hypervisor/src/arch/x86/emulator/mod.rs +++ b/hypervisor/src/arch/x86/emulator/mod.rs @@ -4,6 +4,9 @@ // SPDX-License-Identifier: Apache-2.0 // +use anyhow::Context; +use iced_x86::*; + use crate::arch::emulator::{EmulationError, EmulationResult, PlatformEmulator, PlatformError}; use crate::arch::x86::emulator::instructions::*; use crate::arch::x86::regs::{CR0_PE, EFER_LMA}; @@ -11,8 +14,6 @@ use crate::arch::x86::{ segment_type_expand_down, segment_type_ro, Exception, SegmentRegister, SpecialRegisters, }; use crate::StandardRegisters; -use anyhow::Context; -use iced_x86::*; #[macro_use] mod instructions; @@ -653,11 +654,12 @@ impl<'a, T: CpuStateManager> Emulator<'a, T> { #[cfg(test)] mod mock_vmm { + use std::sync::{Arc, Mutex}; + use super::*; use crate::arch::x86::emulator::EmulatorCpuState as CpuState; use crate::arch::x86::gdt::{gdt_entry, segment_from_gdt}; use crate::StandardRegisters; - use std::sync::{Arc, Mutex}; #[derive(Debug, Clone)] pub struct MockVmm { diff --git a/hypervisor/src/arch/x86/mod.rs b/hypervisor/src/arch/x86/mod.rs index d9832b296..eb3db34a2 100644 --- a/hypervisor/src/arch/x86/mod.rs +++ b/hypervisor/src/arch/x86/mod.rs @@ -242,10 +242,11 @@ impl Default for LapicState { impl LapicState { pub fn get_klapic_reg(&self, reg_offset: usize) -> u32 { - use byteorder::{LittleEndian, ReadBytesExt}; use std::io::Cursor; use std::mem; + use byteorder::{LittleEndian, ReadBytesExt}; + // SAFETY: plain old data type let sliceu8 = unsafe { // This array is only accessed as parts of a u32 word, so interpret it as a u8 array. @@ -261,10 +262,11 @@ impl LapicState { } pub fn set_klapic_reg(&mut self, reg_offset: usize, value: u32) { - use byteorder::{LittleEndian, WriteBytesExt}; use std::io::Cursor; use std::mem; + use byteorder::{LittleEndian, WriteBytesExt}; + // SAFETY: plain old data type let sliceu8 = unsafe { // This array is only accessed as parts of a u32 word, so interpret it as a u8 array. diff --git a/hypervisor/src/cpu.rs b/hypervisor/src/cpu.rs index e34abe76b..14b562ad6 100644 --- a/hypervisor/src/cpu.rs +++ b/hypervisor/src/cpu.rs @@ -8,6 +8,9 @@ // // +use thiserror::Error; +use vm_memory::GuestAddress; + #[cfg(target_arch = "aarch64")] use crate::aarch64::{RegList, VcpuInit}; #[cfg(target_arch = "x86_64")] @@ -17,8 +20,6 @@ use crate::kvm::{TdxExitDetails, TdxExitStatus}; use crate::CpuState; use crate::MpState; use crate::StandardRegisters; -use thiserror::Error; -use vm_memory::GuestAddress; #[cfg(target_arch = "x86_64")] #[derive(Copy, Clone, Default)] diff --git a/hypervisor/src/hypervisor.rs b/hypervisor/src/hypervisor.rs index a893239be..622d67223 100644 --- a/hypervisor/src/hypervisor.rs +++ b/hypervisor/src/hypervisor.rs @@ -7,6 +7,12 @@ // Copyright 2018-2019 CrowdStrike, Inc. // // +#[cfg(target_arch = "x86_64")] +use std::arch::x86_64; +use std::sync::Arc; + +use thiserror::Error; + #[cfg(target_arch = "x86_64")] use crate::arch::x86::CpuIdEntry; #[cfg(target_arch = "x86_64")] @@ -15,10 +21,6 @@ use crate::cpu::CpuVendor; use crate::kvm::TdxCapabilities; use crate::vm::Vm; use crate::HypervisorType; -#[cfg(target_arch = "x86_64")] -use std::arch::x86_64; -use std::sync::Arc; -use thiserror::Error; #[derive(Error, Debug)] pub enum HypervisorError { diff --git a/hypervisor/src/kvm/aarch64/gic/dist_regs.rs b/hypervisor/src/kvm/aarch64/gic/dist_regs.rs index 2da802032..8c4809476 100644 --- a/hypervisor/src/kvm/aarch64/gic/dist_regs.rs +++ b/hypervisor/src/kvm/aarch64/gic/dist_regs.rs @@ -1,12 +1,13 @@ // Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +use kvm_ioctls::DeviceFd; + use crate::arch::aarch64::gic::{Error, Result}; use crate::device::HypervisorDeviceError; use crate::kvm::kvm_bindings::{ kvm_device_attr, KVM_DEV_ARM_VGIC_GRP_DIST_REGS, KVM_DEV_ARM_VGIC_GRP_NR_IRQS, }; -use kvm_ioctls::DeviceFd; /* Distributor registers as detailed at page 456 from diff --git a/hypervisor/src/kvm/aarch64/gic/icc_regs.rs b/hypervisor/src/kvm/aarch64/gic/icc_regs.rs index a72db6c02..24fba1727 100644 --- a/hypervisor/src/kvm/aarch64/gic/icc_regs.rs +++ b/hypervisor/src/kvm/aarch64/gic/icc_regs.rs @@ -2,6 +2,8 @@ // Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +use kvm_ioctls::DeviceFd; + use crate::arch::aarch64::gic::{Error, Result}; use crate::device::HypervisorDeviceError; use crate::kvm::kvm_bindings::{ @@ -10,7 +12,6 @@ use crate::kvm::kvm_bindings::{ KVM_REG_ARM64_SYSREG_OP0_MASK, KVM_REG_ARM64_SYSREG_OP0_SHIFT, KVM_REG_ARM64_SYSREG_OP1_MASK, KVM_REG_ARM64_SYSREG_OP1_SHIFT, KVM_REG_ARM64_SYSREG_OP2_MASK, KVM_REG_ARM64_SYSREG_OP2_SHIFT, }; -use kvm_ioctls::DeviceFd; const KVM_DEV_ARM_VGIC_V3_MPIDR_SHIFT: u32 = 32; const KVM_DEV_ARM_VGIC_V3_MPIDR_MASK: u64 = 0xffffffff << KVM_DEV_ARM_VGIC_V3_MPIDR_SHIFT as u64; diff --git a/hypervisor/src/kvm/aarch64/gic/mod.rs b/hypervisor/src/kvm/aarch64/gic/mod.rs index 28d67a3e3..a7bef59b6 100644 --- a/hypervisor/src/kvm/aarch64/gic/mod.rs +++ b/hypervisor/src/kvm/aarch64/gic/mod.rs @@ -6,16 +6,18 @@ mod dist_regs; mod icc_regs; mod redist_regs; -use crate::arch::aarch64::gic::{Error, Result, Vgic, VgicConfig}; -use crate::device::HypervisorDeviceError; -use crate::kvm::KvmVm; -use crate::{CpuState, Vm}; +use std::any::Any; + use dist_regs::{get_dist_regs, read_ctlr, set_dist_regs, write_ctlr}; use icc_regs::{get_icc_regs, set_icc_regs}; use kvm_ioctls::DeviceFd; use redist_regs::{construct_gicr_typers, get_redist_regs, set_redist_regs}; use serde::{Deserialize, Serialize}; -use std::any::Any; + +use crate::arch::aarch64::gic::{Error, Result, Vgic, VgicConfig}; +use crate::device::HypervisorDeviceError; +use crate::kvm::KvmVm; +use crate::{CpuState, Vm}; const GITS_CTLR: u32 = 0x0000; const GITS_IIDR: u32 = 0x0004; diff --git a/hypervisor/src/kvm/aarch64/gic/redist_regs.rs b/hypervisor/src/kvm/aarch64/gic/redist_regs.rs index 213a57099..2cc3283cd 100644 --- a/hypervisor/src/kvm/aarch64/gic/redist_regs.rs +++ b/hypervisor/src/kvm/aarch64/gic/redist_regs.rs @@ -2,6 +2,8 @@ // Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +use kvm_ioctls::DeviceFd; + use crate::arch::aarch64::gic::{Error, Result}; use crate::device::HypervisorDeviceError; use crate::kvm::kvm_bindings::{ @@ -12,7 +14,6 @@ use crate::kvm::kvm_bindings::{ use crate::kvm::Register; use crate::kvm::VcpuKvmState; use crate::CpuState; -use kvm_ioctls::DeviceFd; // Relevant redistributor registers that we want to save/restore. const GICR_CTLR: u32 = 0x0000; diff --git a/hypervisor/src/kvm/aarch64/mod.rs b/hypervisor/src/kvm/aarch64/mod.rs index f4ca12f25..1b7f44952 100644 --- a/hypervisor/src/kvm/aarch64/mod.rs +++ b/hypervisor/src/kvm/aarch64/mod.rs @@ -10,7 +10,6 @@ pub mod gic; -use crate::kvm::{KvmError, KvmResult}; use kvm_bindings::{ kvm_mp_state, kvm_one_reg, kvm_regs, KVM_REG_ARM_COPROC_MASK, KVM_REG_ARM_CORE, KVM_REG_SIZE_MASK, KVM_REG_SIZE_U32, KVM_REG_SIZE_U64, @@ -19,6 +18,8 @@ pub use kvm_bindings::{kvm_one_reg as Register, kvm_vcpu_init as VcpuInit, RegLi use serde::{Deserialize, Serialize}; pub use {kvm_ioctls::Cap, kvm_ioctls::Kvm}; +use crate::kvm::{KvmError, KvmResult}; + // This macro gets the offset of a structure (i.e `str`) member (i.e `field`) without having // an instance of that structure. #[macro_export] diff --git a/hypervisor/src/kvm/mod.rs b/hypervisor/src/kvm/mod.rs index ec09b2a07..beda69fc7 100644 --- a/hypervisor/src/kvm/mod.rs +++ b/hypervisor/src/kvm/mod.rs @@ -8,6 +8,23 @@ // // +use std::any::Any; +use std::collections::HashMap; +#[cfg(target_arch = "x86_64")] +use std::fs::File; +#[cfg(target_arch = "x86_64")] +use std::os::unix::io::AsRawFd; +#[cfg(feature = "tdx")] +use std::os::unix::io::RawFd; +use std::result; +#[cfg(target_arch = "x86_64")] +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; +use std::sync::{Arc, RwLock}; + +use kvm_ioctls::{NoDatamatch, VcpuFd, VmFd}; +use vmm_sys_util::eventfd::EventFd; + #[cfg(target_arch = "aarch64")] use crate::aarch64::gic::KvmGicV3Its; #[cfg(target_arch = "aarch64")] @@ -24,35 +41,9 @@ use crate::vm::{self, InterruptSourceConfig, VmOps}; use crate::HypervisorType; #[cfg(target_arch = "aarch64")] use crate::{arm64_core_reg_id, offset_of}; -use kvm_ioctls::{NoDatamatch, VcpuFd, VmFd}; -use std::any::Any; -use std::collections::HashMap; -#[cfg(target_arch = "x86_64")] -use std::fs::File; -#[cfg(target_arch = "x86_64")] -use std::os::unix::io::AsRawFd; -#[cfg(feature = "tdx")] -use std::os::unix::io::RawFd; -use std::result; -#[cfg(target_arch = "x86_64")] -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Mutex; -use std::sync::{Arc, RwLock}; -use vmm_sys_util::eventfd::EventFd; // x86_64 dependencies #[cfg(target_arch = "x86_64")] pub mod x86_64; -#[cfg(target_arch = "x86_64")] -use crate::arch::x86::{ - CpuIdEntry, FpuState, LapicState, MsrEntry, SpecialRegisters, XsaveState, NUM_IOAPIC_PINS, -}; -#[cfg(target_arch = "x86_64")] -use crate::ClockData; -use crate::StandardRegisters; -use crate::{ - CpuState, IoEventAddress, IrqRoutingEntry, MpState, UserMemoryRegion, - USER_MEMORY_REGION_LOG_DIRTY, USER_MEMORY_REGION_READ, USER_MEMORY_REGION_WRITE, -}; #[cfg(target_arch = "aarch64")] use aarch64::{RegList, Register}; #[cfg(target_arch = "x86_64")] @@ -64,9 +55,24 @@ use kvm_bindings::{ use x86_64::check_required_kvm_extensions; #[cfg(target_arch = "x86_64")] pub use x86_64::{CpuId, ExtendedControlRegisters, MsrEntries, VcpuKvmState}; + +#[cfg(target_arch = "x86_64")] +use crate::arch::x86::{ + CpuIdEntry, FpuState, LapicState, MsrEntry, SpecialRegisters, XsaveState, NUM_IOAPIC_PINS, +}; +#[cfg(target_arch = "x86_64")] +use crate::ClockData; +use crate::StandardRegisters; +use crate::{ + CpuState, IoEventAddress, IrqRoutingEntry, MpState, UserMemoryRegion, + USER_MEMORY_REGION_LOG_DIRTY, USER_MEMORY_REGION_READ, USER_MEMORY_REGION_WRITE, +}; // aarch64 dependencies #[cfg(target_arch = "aarch64")] pub mod aarch64; +#[cfg(target_arch = "aarch64")] +use std::mem; + pub use kvm_bindings; pub use kvm_bindings::{ kvm_clock_data, kvm_create_device, kvm_device_type_KVM_DEV_TYPE_VFIO, kvm_guest_debug, @@ -85,8 +91,6 @@ use kvm_bindings::{ use kvm_bindings::{kvm_run__bindgen_ty_1, KVMIO}; pub use kvm_ioctls; pub use kvm_ioctls::{Cap, Kvm}; -#[cfg(target_arch = "aarch64")] -use std::mem; use thiserror::Error; use vfio_ioctls::VfioDeviceFd; #[cfg(feature = "tdx")] @@ -104,7 +108,6 @@ const KVM_CAP_SGX_ATTRIBUTE: u32 = 196; #[cfg(target_arch = "x86_64")] use vmm_sys_util::ioctl_io_nr; - #[cfg(all(not(feature = "tdx"), target_arch = "x86_64"))] use vmm_sys_util::ioctl_ioc_nr; diff --git a/hypervisor/src/kvm/x86_64/mod.rs b/hypervisor/src/kvm/x86_64/mod.rs index 2aecc65c5..4cf05a1ac 100644 --- a/hypervisor/src/kvm/x86_64/mod.rs +++ b/hypervisor/src/kvm/x86_64/mod.rs @@ -8,13 +8,7 @@ // // -use crate::arch::x86::{ - CpuIdEntry, DescriptorTable, FpuState, LapicState, MsrEntry, SegmentRegister, SpecialRegisters, - XsaveState, CPUID_FLAG_VALID_INDEX, -}; -use crate::kvm::{Cap, Kvm, KvmError, KvmResult}; use serde::{Deserialize, Serialize}; - /// /// Export generically-named wrappers of kvm-bindings for Unix-based platforms /// @@ -28,6 +22,12 @@ pub use { kvm_bindings::KVM_CPUID_FLAG_SIGNIFCANT_INDEX, }; +use crate::arch::x86::{ + CpuIdEntry, DescriptorTable, FpuState, LapicState, MsrEntry, SegmentRegister, SpecialRegisters, + XsaveState, CPUID_FLAG_VALID_INDEX, +}; +use crate::kvm::{Cap, Kvm, KvmError, KvmResult}; + /// /// Check KVM extension for Linux /// diff --git a/hypervisor/src/lib.rs b/hypervisor/src/lib.rs index b4e578e5f..f93fd4ffd 100644 --- a/hypervisor/src/lib.rs +++ b/hypervisor/src/lib.rs @@ -48,7 +48,8 @@ mod cpu; /// Device related module mod device; -pub use crate::hypervisor::{Hypervisor, HypervisorError}; +use std::sync::Arc; + use concat_idents::concat_idents; #[cfg(target_arch = "x86_64")] pub use cpu::CpuVendor; @@ -56,12 +57,13 @@ pub use cpu::{HypervisorCpuError, Vcpu, VmExit}; pub use device::HypervisorDeviceError; #[cfg(all(feature = "kvm", target_arch = "aarch64"))] pub use kvm::{aarch64, GicState}; -use std::sync::Arc; pub use vm::{ DataMatch, HypervisorVmError, InterruptSourceConfig, LegacyIrqSourceConfig, MsiIrqSourceConfig, Vm, VmOps, }; +pub use crate::hypervisor::{Hypervisor, HypervisorError}; + #[derive(Debug, Copy, Clone)] pub enum HypervisorType { #[cfg(feature = "kvm")] diff --git a/hypervisor/src/mshv/mod.rs b/hypervisor/src/mshv/mod.rs index ada404391..34c33bb79 100644 --- a/hypervisor/src/mshv/mod.rs +++ b/hypervisor/src/mshv/mod.rs @@ -3,6 +3,15 @@ // Copyright © 2020, Microsoft Corporation // +use std::any::Any; +use std::collections::HashMap; +use std::sync::{Arc, RwLock}; + +use mshv_bindings::*; +use mshv_ioctls::{set_registers_64, InterruptRequest, Mshv, NoDatamatch, VcpuFd, VmFd, VmType}; +use vfio_ioctls::VfioDeviceFd; +use vm::DataMatch; + use crate::arch::emulator::PlatformEmulator; #[cfg(target_arch = "x86_64")] use crate::arch::x86::emulator::Emulator; @@ -12,18 +21,32 @@ use crate::mshv::emulator::MshvEmulatorContext; use crate::vec_with_array_field; use crate::vm::{self, InterruptSourceConfig, VmOps}; use crate::HypervisorType; -use mshv_bindings::*; -use mshv_ioctls::{set_registers_64, InterruptRequest, Mshv, NoDatamatch, VcpuFd, VmFd, VmType}; -use std::any::Any; -use std::collections::HashMap; -use std::sync::{Arc, RwLock}; -use vfio_ioctls::VfioDeviceFd; -use vm::DataMatch; #[cfg(feature = "sev_snp")] mod snp_constants; // x86_64 dependencies #[cfg(target_arch = "x86_64")] pub mod x86_64; +#[cfg(target_arch = "x86_64")] +use std::fs::File; +use std::os::unix::io::AsRawFd; + +#[cfg(feature = "sev_snp")] +use igvm_defs::IGVM_VHS_SNP_ID_BLOCK; +#[cfg(feature = "sev_snp")] +use snp_constants::*; +use vmm_sys_util::eventfd::EventFd; +#[cfg(target_arch = "x86_64")] +pub use x86_64::*; +#[cfg(target_arch = "x86_64")] +pub use x86_64::{emulator, VcpuMshvState}; +/// +/// Export generically-named wrappers of mshv-bindings for Unix-based platforms +/// +pub use { + mshv_bindings::mshv_create_device as CreateDevice, + mshv_bindings::mshv_device_attr as DeviceAttr, mshv_ioctls, mshv_ioctls::DeviceFd, +}; + #[cfg(target_arch = "x86_64")] use crate::arch::x86::{CpuIdEntry, FpuState, MsrEntry}; #[cfg(target_arch = "x86_64")] @@ -33,26 +56,6 @@ use crate::{ USER_MEMORY_REGION_ADJUSTABLE, USER_MEMORY_REGION_EXECUTE, USER_MEMORY_REGION_READ, USER_MEMORY_REGION_WRITE, }; -#[cfg(feature = "sev_snp")] -use igvm_defs::IGVM_VHS_SNP_ID_BLOCK; -#[cfg(feature = "sev_snp")] -use snp_constants::*; -#[cfg(target_arch = "x86_64")] -use std::fs::File; -use std::os::unix::io::AsRawFd; -use vmm_sys_util::eventfd::EventFd; -#[cfg(target_arch = "x86_64")] -pub use x86_64::*; -#[cfg(target_arch = "x86_64")] -pub use x86_64::{emulator, VcpuMshvState}; - -/// -/// Export generically-named wrappers of mshv-bindings for Unix-based platforms -/// -pub use { - mshv_bindings::mshv_create_device as CreateDevice, - mshv_bindings::mshv_device_attr as DeviceAttr, mshv_ioctls, mshv_ioctls::DeviceFd, -}; pub const PAGE_SHIFT: usize = 12; diff --git a/hypervisor/src/mshv/x86_64/emulator.rs b/hypervisor/src/mshv/x86_64/emulator.rs index 104234cc7..6aa74f535 100644 --- a/hypervisor/src/mshv/x86_64/emulator.rs +++ b/hypervisor/src/mshv/x86_64/emulator.rs @@ -3,12 +3,13 @@ // Copyright © 2024, Microsoft Corporation // +use iced_x86::Register; +use mshv_bindings::*; + use crate::arch::emulator::{PlatformEmulator, PlatformError}; use crate::arch::x86::emulator::{CpuStateManager, EmulatorCpuState}; use crate::cpu::Vcpu; use crate::mshv::MshvVcpu; -use iced_x86::Register; -use mshv_bindings::*; pub struct MshvEmulatorContext<'a> { pub vcpu: &'a MshvVcpu, diff --git a/hypervisor/src/mshv/x86_64/mod.rs b/hypervisor/src/mshv/x86_64/mod.rs index 07576004e..1853d234d 100644 --- a/hypervisor/src/mshv/x86_64/mod.rs +++ b/hypervisor/src/mshv/x86_64/mod.rs @@ -7,11 +7,13 @@ // Copyright 2018-2019 CrowdStrike, Inc. // // +use std::fmt; + +use serde::{Deserialize, Serialize}; + use crate::arch::x86::{ CpuIdEntry, DescriptorTable, FpuState, LapicState, MsrEntry, SegmentRegister, SpecialRegisters, }; -use serde::{Deserialize, Serialize}; -use std::fmt; pub mod emulator; diff --git a/hypervisor/src/vm.rs b/hypervisor/src/vm.rs index 19563d0be..712627a63 100644 --- a/hypervisor/src/vm.rs +++ b/hypervisor/src/vm.rs @@ -8,6 +8,18 @@ // // +use std::any::Any; +#[cfg(target_arch = "x86_64")] +use std::fs::File; +use std::sync::Arc; +#[cfg(target_arch = "aarch64")] +use std::sync::Mutex; + +#[cfg(feature = "sev_snp")] +use igvm_defs::IGVM_VHS_SNP_ID_BLOCK; +use thiserror::Error; +use vmm_sys_util::eventfd::EventFd; + #[cfg(target_arch = "aarch64")] use crate::aarch64::VcpuInit; #[cfg(target_arch = "aarch64")] @@ -19,16 +31,6 @@ use crate::cpu::Vcpu; use crate::ClockData; use crate::UserMemoryRegion; use crate::{IoEventAddress, IrqRoutingEntry}; -#[cfg(feature = "sev_snp")] -use igvm_defs::IGVM_VHS_SNP_ID_BLOCK; -use std::any::Any; -#[cfg(target_arch = "x86_64")] -use std::fs::File; -use std::sync::Arc; -#[cfg(target_arch = "aarch64")] -use std::sync::Mutex; -use thiserror::Error; -use vmm_sys_util::eventfd::EventFd; /// /// I/O events data matches (32 or 64 bits). diff --git a/net_util/src/ctrl_queue.rs b/net_util/src/ctrl_queue.rs index dac23c63c..fef1d61f3 100644 --- a/net_util/src/ctrl_queue.rs +++ b/net_util/src/ctrl_queue.rs @@ -2,10 +2,9 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use crate::GuestMemoryMmap; -use crate::Tap; -use libc::c_uint; use std::sync::Arc; + +use libc::c_uint; use virtio_bindings::virtio_net::{ VIRTIO_NET_CTRL_GUEST_OFFLOADS, VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, VIRTIO_NET_CTRL_MQ, VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX, VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN, @@ -17,6 +16,9 @@ use virtio_queue::{Queue, QueueT}; use vm_memory::{ByteValued, Bytes, GuestMemoryError}; use vm_virtio::{AccessPlatform, Translatable}; +use crate::GuestMemoryMmap; +use crate::Tap; + #[derive(Debug)] pub enum Error { /// Read queue failed. diff --git a/net_util/src/lib.rs b/net_util/src/lib.rs index 1cadb7f28..3cdaf6816 100644 --- a/net_util/src/lib.rs +++ b/net_util/src/lib.rs @@ -14,13 +14,13 @@ mod open_tap; mod queue_pair; mod tap; -use serde::{Deserialize, Serialize}; use std::io::Error as IoError; use std::os::raw::c_uint; use std::os::unix::io::{FromRawFd, RawFd}; use std::{io, mem, net}; -use thiserror::Error; +use serde::{Deserialize, Serialize}; +use thiserror::Error; use virtio_bindings::virtio_net::{ virtio_net_hdr_v1, VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX, VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN, VIRTIO_NET_F_GUEST_CSUM, VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_TSO4, diff --git a/net_util/src/open_tap.rs b/net_util/src/open_tap.rs index 4276012d6..f75b92971 100644 --- a/net_util/src/open_tap.rs +++ b/net_util/src/open_tap.rs @@ -2,12 +2,14 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use super::{vnet_hdr_len, MacAddr, Tap, TapError}; use std::net::Ipv4Addr; use std::path::Path; use std::{fs, io}; + use thiserror::Error; +use super::{vnet_hdr_len, MacAddr, Tap, TapError}; + #[derive(Error, Debug)] pub enum Error { #[error("Failed to convert an hexadecimal string into an integer: {0}")] diff --git a/net_util/src/queue_pair.rs b/net_util/src/queue_pair.rs index 96da5bc0a..55e715e5a 100644 --- a/net_util/src/queue_pair.rs +++ b/net_util/src/queue_pair.rs @@ -2,19 +2,21 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use super::{register_listener, unregister_listener, vnet_hdr_len, Tap}; -use rate_limiter::{RateLimiter, TokenType}; use std::io; use std::num::Wrapping; use std::os::unix::io::{AsRawFd, RawFd}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; + +use rate_limiter::{RateLimiter, TokenType}; use thiserror::Error; use virtio_queue::{Queue, QueueOwnedT, QueueT}; use vm_memory::bitmap::Bitmap; use vm_memory::{Bytes, GuestMemory}; use vm_virtio::{AccessPlatform, Translatable}; +use super::{register_listener, unregister_listener, vnet_hdr_len, Tap}; + #[derive(Clone)] pub struct TxVirtio { pub counter_bytes: Wrapping, diff --git a/net_util/src/tap.rs b/net_util/src/tap.rs index 657abe88e..d30e34450 100644 --- a/net_util/src/tap.rs +++ b/net_util/src/tap.rs @@ -5,19 +5,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. -use super::{ - create_inet_socket, create_sockaddr, create_unix_socket, vnet_hdr_len, Error as NetUtilError, - MacAddr, -}; -use crate::mac::MAC_ADDR_LEN; use std::fs::File; use std::io::{Error as IoError, Read, Result as IoResult, Write}; use std::net; use std::os::raw::*; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; + use thiserror::Error; use vmm_sys_util::ioctl::{ioctl_with_mut_ref, ioctl_with_ref, ioctl_with_val}; +use super::{ + create_inet_socket, create_sockaddr, create_unix_socket, vnet_hdr_len, Error as NetUtilError, + MacAddr, +}; +use crate::mac::MAC_ADDR_LEN; + #[derive(Error, Debug)] pub enum Error { #[error("Couldn't open /dev/net/tun: {0}")] @@ -428,7 +430,6 @@ mod tests { use std::time::Duration; use once_cell::sync::Lazy; - use pnet::packet::ethernet::{EtherTypes, EthernetPacket, MutableEthernetPacket}; use pnet::packet::ip::IpNextHeaderProtocols; use pnet::packet::ipv4::{Ipv4Packet, MutableIpv4Packet}; diff --git a/pci/src/bus.rs b/pci/src/bus.rs index 03fbaadf8..906d8f683 100644 --- a/pci/src/bus.rs +++ b/pci/src/bus.rs @@ -4,17 +4,19 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause +use std::any::Any; +use std::collections::HashMap; +use std::ops::DerefMut; +use std::sync::{Arc, Barrier, Mutex}; + +use byteorder::{ByteOrder, LittleEndian}; +use vm_device::{Bus, BusDevice, BusDeviceSync}; + use crate::configuration::{ PciBarRegionType, PciBridgeSubclass, PciClassCode, PciConfiguration, PciHeaderType, }; use crate::device::{DeviceRelocation, Error as PciDeviceError, PciDevice}; use crate::PciBarConfiguration; -use byteorder::{ByteOrder, LittleEndian}; -use std::any::Any; -use std::collections::HashMap; -use std::ops::DerefMut; -use std::sync::{Arc, Barrier, Mutex}; -use vm_device::{Bus, BusDevice, BusDeviceSync}; const VENDOR_ID_INTEL: u16 = 0x8086; const DEVICE_ID_INTEL_VIRT_PCIE_HOST: u16 = 0x0d57; diff --git a/pci/src/configuration.rs b/pci/src/configuration.rs index 030f62cf7..7fb819d21 100644 --- a/pci/src/configuration.rs +++ b/pci/src/configuration.rs @@ -4,15 +4,17 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use crate::device::BarReprogrammingParams; -use crate::{MsixConfig, PciInterruptPin}; -use byteorder::{ByteOrder, LittleEndian}; -use serde::{Deserialize, Serialize}; use std::fmt::{self, Display}; use std::sync::{Arc, Mutex}; + +use byteorder::{ByteOrder, LittleEndian}; +use serde::{Deserialize, Serialize}; use vm_device::PciBarType; use vm_migration::{MigratableError, Pausable, Snapshot, Snapshottable}; +use crate::device::BarReprogrammingParams; +use crate::{MsixConfig, PciInterruptPin}; + // The number of 32bit registers in the config space, 4096 bytes. const NUM_CONFIGURATION_REGISTERS: usize = 1024; diff --git a/pci/src/device.rs b/pci/src/device.rs index f35fbbd19..87dc6da84 100644 --- a/pci/src/device.rs +++ b/pci/src/device.rs @@ -4,15 +4,17 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use crate::configuration::{self, PciBarRegionType}; -use crate::PciBarConfiguration; use std::any::Any; use std::fmt::{self, Display}; use std::sync::{Arc, Barrier, Mutex}; use std::{io, result}; + use vm_allocator::{AddressAllocator, SystemAllocator}; use vm_device::Resource; +use crate::configuration::{self, PciBarRegionType}; +use crate::PciBarConfiguration; + #[derive(Debug)] pub enum Error { /// Setup of the device capabilities failed. diff --git a/pci/src/lib.rs b/pci/src/lib.rs index 3a45d04f0..3b6f9c53f 100644 --- a/pci/src/lib.rs +++ b/pci/src/lib.rs @@ -16,6 +16,12 @@ mod msix; mod vfio; mod vfio_user; +use std::fmt::{self, Display}; +use std::num::ParseIntError; +use std::str::FromStr; + +use serde::de::Visitor; + pub use self::bus::{PciBus, PciConfigIo, PciConfigMmio, PciRoot, PciRootError}; pub use self::configuration::{ PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciCapability, PciCapabilityId, @@ -30,10 +36,6 @@ pub use self::msi::{msi_num_enabled_vectors, MsiCap, MsiConfig}; pub use self::msix::{MsixCap, MsixConfig, MsixTableEntry, MSIX_CONFIG_ID, MSIX_TABLE_ENTRY_SIZE}; pub use self::vfio::{MmioRegion, VfioDmaMapping, VfioPciDevice, VfioPciError}; pub use self::vfio_user::{VfioUserDmaMapping, VfioUserPciDevice, VfioUserPciDeviceError}; -use serde::de::Visitor; -use std::fmt::{self, Display}; -use std::num::ParseIntError; -use std::str::FromStr; /// PCI has four interrupt pins A->D. #[derive(Copy, Clone)] diff --git a/pci/src/msi.rs b/pci/src/msi.rs index c93391d16..042a2a018 100644 --- a/pci/src/msi.rs +++ b/pci/src/msi.rs @@ -3,10 +3,11 @@ // SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause // -use byteorder::{ByteOrder, LittleEndian}; -use serde::{Deserialize, Serialize}; use std::io; use std::sync::Arc; + +use byteorder::{ByteOrder, LittleEndian}; +use serde::{Deserialize, Serialize}; use thiserror::Error; use vm_device::interrupt::{ InterruptIndex, InterruptSourceConfig, InterruptSourceGroup, MsiIrqSourceConfig, diff --git a/pci/src/msix.rs b/pci/src/msix.rs index 821bdfd16..faf87dcfa 100644 --- a/pci/src/msix.rs +++ b/pci/src/msix.rs @@ -3,19 +3,21 @@ // SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause // -use crate::{PciCapability, PciCapabilityId}; -use byteorder::{ByteOrder, LittleEndian}; -use serde::Deserialize; -use serde::Serialize; use std::io; use std::result; use std::sync::Arc; + +use byteorder::{ByteOrder, LittleEndian}; +use serde::Deserialize; +use serde::Serialize; use vm_device::interrupt::{ InterruptIndex, InterruptSourceConfig, InterruptSourceGroup, MsiIrqSourceConfig, }; use vm_memory::ByteValued; use vm_migration::{MigratableError, Pausable, Snapshot, Snapshottable}; +use crate::{PciCapability, PciCapabilityId}; + const MAX_MSIX_VECTORS_PER_DEVICE: u16 = 2048; const MSIX_TABLE_ENTRIES_MODULO: u64 = 16; const MSIX_PBA_ENTRIES_MODULO: u64 = 8; diff --git a/pci/src/vfio.rs b/pci/src/vfio.rs index 07011cc02..ab775ba99 100644 --- a/pci/src/vfio.rs +++ b/pci/src/vfio.rs @@ -3,25 +3,18 @@ // SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause // -use crate::msi::{MsiConfigState, MSI_CONFIG_ID}; -use crate::msix::MsixConfigState; -use crate::{ - msi_num_enabled_vectors, BarReprogrammingParams, MsiCap, MsiConfig, MsixCap, MsixConfig, - PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciBdf, PciCapabilityId, - PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciExpressCapabilityId, - PciHeaderType, PciSubclass, MSIX_CONFIG_ID, MSIX_TABLE_ENTRY_SIZE, PCI_CONFIGURATION_ID, -}; -use anyhow::anyhow; -use byteorder::{ByteOrder, LittleEndian}; -use hypervisor::HypervisorVmError; -use libc::{sysconf, _SC_PAGESIZE}; -use serde::{Deserialize, Serialize}; use std::any::Any; use std::collections::{BTreeMap, HashMap}; use std::io; use std::os::unix::io::AsRawFd; use std::ptr::null_mut; use std::sync::{Arc, Barrier, Mutex}; + +use anyhow::anyhow; +use byteorder::{ByteOrder, LittleEndian}; +use hypervisor::HypervisorVmError; +use libc::{sysconf, _SC_PAGESIZE}; +use serde::{Deserialize, Serialize}; use thiserror::Error; use vfio_bindings::bindings::vfio::*; use vfio_ioctls::{ @@ -40,6 +33,15 @@ use vm_memory::{Address, GuestAddress, GuestAddressSpace, GuestMemory, GuestUsiz use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; use vmm_sys_util::eventfd::EventFd; +use crate::msi::{MsiConfigState, MSI_CONFIG_ID}; +use crate::msix::MsixConfigState; +use crate::{ + msi_num_enabled_vectors, BarReprogrammingParams, MsiCap, MsiConfig, MsixCap, MsixConfig, + PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciBdf, PciCapabilityId, + PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciExpressCapabilityId, + PciHeaderType, PciSubclass, MSIX_CONFIG_ID, MSIX_TABLE_ENTRY_SIZE, PCI_CONFIGURATION_ID, +}; + pub(crate) const VFIO_COMMON_ID: &str = "vfio_common"; #[derive(Debug, Error)] diff --git a/pci/src/vfio_user.rs b/pci/src/vfio_user.rs index b6bd2f2d4..41e491ec6 100644 --- a/pci/src/vfio_user.rs +++ b/pci/src/vfio_user.rs @@ -3,14 +3,12 @@ // SPDX-License-Identifier: Apache-2.0 // -use crate::vfio::{UserMemoryRegion, Vfio, VfioCommon, VfioError, VFIO_COMMON_ID}; -use crate::{BarReprogrammingParams, PciBarConfiguration, VfioPciError}; -use crate::{PciBdf, PciDevice, PciDeviceError, PciSubclass}; -use hypervisor::HypervisorVmError; use std::any::Any; use std::os::unix::prelude::AsRawFd; use std::ptr::null_mut; use std::sync::{Arc, Barrier, Mutex}; + +use hypervisor::HypervisorVmError; use thiserror::Error; use vfio_bindings::bindings::vfio::*; use vfio_ioctls::VfioIrq; @@ -26,6 +24,10 @@ use vm_memory::{ use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; use vmm_sys_util::eventfd::EventFd; +use crate::vfio::{UserMemoryRegion, Vfio, VfioCommon, VfioError, VFIO_COMMON_ID}; +use crate::{BarReprogrammingParams, PciBarConfiguration, VfioPciError}; +use crate::{PciBdf, PciDevice, PciDeviceError, PciSubclass}; + pub struct VfioUserPciDevice { id: String, vm: Arc, diff --git a/performance-metrics/src/main.rs b/performance-metrics/src/main.rs index 89c3f18c1..cc78ed4f7 100644 --- a/performance-metrics/src/main.rs +++ b/performance-metrics/src/main.rs @@ -8,9 +8,6 @@ extern crate test_infra; mod performance_tests; -use clap::{Arg, ArgAction, Command as ClapCommand}; -use performance_tests::*; -use serde::{Deserialize, Serialize}; use std::{ env, fmt, process::Command, @@ -18,6 +15,10 @@ use std::{ thread, time::Duration, }; + +use clap::{Arg, ArgAction, Command as ClapCommand}; +use performance_tests::*; +use serde::{Deserialize, Serialize}; use test_infra::FioOps; use thiserror::Error; diff --git a/performance-metrics/src/performance_tests.rs b/performance-metrics/src/performance_tests.rs index 8d8c34256..2192a2919 100644 --- a/performance-metrics/src/performance_tests.rs +++ b/performance-metrics/src/performance_tests.rs @@ -5,14 +5,16 @@ // Performance tests -use crate::{mean, PerformanceTestControl}; use std::fs; use std::path::PathBuf; use std::thread; use std::time::Duration; + use test_infra::Error as InfraError; use test_infra::*; +use crate::{mean, PerformanceTestControl}; + #[cfg(target_arch = "x86_64")] pub const FOCAL_IMAGE_NAME: &str = "focal-server-cloudimg-amd64-custom-20210609-0.raw"; #[cfg(target_arch = "aarch64")] diff --git a/rate_limiter/src/group.rs b/rate_limiter/src/group.rs index 47d5bc4c8..1b1621ae2 100644 --- a/rate_limiter/src/group.rs +++ b/rate_limiter/src/group.rs @@ -4,7 +4,6 @@ // Copyright 2023 Crusoe Energy Systems LLC // SPDX-License-Identifier: Apache-2.0 -use crate::{RateLimiter, TokenType}; use core::panic::AssertUnwindSafe; use std::fs::File; use std::io; @@ -12,9 +11,12 @@ use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::result; use std::sync::{Arc, Mutex}; use std::thread; + use thiserror::Error; use vmm_sys_util::eventfd::EventFd; +use crate::{RateLimiter, TokenType}; + /// Errors associated with rate-limiter group. #[derive(Debug, Error)] pub enum Error { @@ -298,10 +300,12 @@ impl Drop for RateLimiterGroup { #[cfg(test)] pub(crate) mod tests { + use std::{os::fd::AsRawFd, thread, time::Duration}; + + use vmm_sys_util::eventfd::EventFd; + use super::RateLimiterGroupHandle; use crate::{group::RateLimiterGroup, TokenBucket, TokenType, REFILL_TIMER_INTERVAL_MS}; - use std::{os::fd::AsRawFd, thread, time::Duration}; - use vmm_sys_util::eventfd::EventFd; impl RateLimiterGroupHandle { pub fn bandwidth(&self) -> Option { diff --git a/rate_limiter/src/lib.rs b/rate_limiter/src/lib.rs index 7bfc98a96..646d1fba0 100644 --- a/rate_limiter/src/lib.rs +++ b/rate_limiter/src/lib.rs @@ -51,6 +51,7 @@ use std::os::unix::io::{AsRawFd, RawFd}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; use std::time::{Duration, Instant}; + use vmm_sys_util::timerfd::TimerFd; /// Module for group rate limiting. @@ -519,10 +520,11 @@ impl Default for RateLimiter { #[cfg(test)] pub(crate) mod tests { - use super::*; use std::fmt; use std::thread; + use super::*; + impl TokenBucket { // Resets the token bucket: budget set to max capacity and last-updated set to now. fn reset(&mut self) { diff --git a/src/bin/ch-remote.rs b/src/bin/ch-remote.rs index 05ad2464e..acdfff60a 100644 --- a/src/bin/ch-remote.rs +++ b/src/bin/ch-remote.rs @@ -3,17 +3,18 @@ // SPDX-License-Identifier: Apache-2.0 // +use std::fmt; +use std::io::Read; +use std::marker::PhantomData; +use std::os::unix::net::UnixStream; +use std::process; + use api_client::simple_api_command; use api_client::simple_api_command_with_fds; use api_client::simple_api_full_command; use api_client::Error as ApiClientError; use clap::{Arg, ArgAction, ArgMatches, Command}; use option_parser::{ByteSized, ByteSizedParseError}; -use std::fmt; -use std::io::Read; -use std::marker::PhantomData; -use std::os::unix::net::UnixStream; -use std::process; #[cfg(feature = "dbus_api")] use zbus::{proxy, zvariant::Optional}; diff --git a/src/main.rs b/src/main.rs index f47144150..f2b908f67 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,17 +6,18 @@ #[macro_use] extern crate event_monitor; +use std::fs::File; +use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; +use std::sync::mpsc::channel; +use std::sync::Mutex; +use std::{env, io}; + use clap::{Arg, ArgAction, ArgGroup, ArgMatches, Command}; use libc::EFD_NONBLOCK; use log::{warn, LevelFilter}; use option_parser::OptionParser; use seccompiler::SeccompAction; use signal_hook::consts::SIGSYS; -use std::fs::File; -use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; -use std::sync::mpsc::channel; -use std::sync::Mutex; -use std::{env, io}; use thiserror::Error; #[cfg(feature = "dbus_api")] use vmm::api::dbus::{dbus_api_graceful_shutdown, DBusApiOptions}; @@ -957,9 +958,8 @@ fn main() { #[cfg(test)] mod unit_tests { - use crate::config::HotplugMethod; - use crate::{create_app, prepare_default_values}; use std::path::PathBuf; + use vmm::config::{ ConsoleConfig, ConsoleOutputMode, CpuFeatures, CpusConfig, MemoryConfig, PayloadConfig, RngConfig, VmConfig, VmParams, @@ -967,6 +967,9 @@ mod unit_tests { #[cfg(target_arch = "x86_64")] use vmm::vm_config::DebugConsoleConfig; + use crate::config::HotplugMethod; + use crate::{create_app, prepare_default_values}; + fn get_vm_config_from_vec(args: &[&str]) -> VmConfig { let (default_vcpus, default_memory, default_rng) = prepare_default_values(); let cmd_arguments = diff --git a/test_infra/src/lib.rs b/test_infra/src/lib.rs index d4a511faf..efba7ccaa 100644 --- a/test_infra/src/lib.rs +++ b/test_infra/src/lib.rs @@ -5,9 +5,6 @@ #![allow(clippy::undocumented_unsafe_blocks)] -use once_cell::sync::Lazy; -use serde_json::Value; -use ssh2::Session; use std::env; use std::ffi::OsStr; use std::fmt::Display; @@ -24,6 +21,10 @@ use std::sync::Mutex; use std::thread; use std::time::Duration; use std::{fmt, fs}; + +use once_cell::sync::Lazy; +use serde_json::Value; +use ssh2::Session; use vmm_sys_util::tempdir::TempDir; use wait_timeout::ChildExt; diff --git a/tests/integration.rs b/tests/integration.rs index 62d82e0cc..d05523f2b 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -10,7 +10,6 @@ extern crate test_infra; -use net_util::MacAddr; use std::collections::HashMap; use std::fs; use std::io; @@ -26,6 +25,8 @@ use std::sync::mpsc; use std::sync::mpsc::Receiver; use std::sync::Mutex; use std::thread; + +use net_util::MacAddr; use test_infra::*; use vmm_sys_util::{tempdir::TempDir, tempfile::TempFile}; use wait_timeout::ChildExt; @@ -7955,9 +7956,10 @@ mod common_sequential { } mod windows { - use crate::*; use once_cell::sync::Lazy; + use crate::*; + static NEXT_DISK_ID: Lazy> = Lazy::new(|| Mutex::new(1)); struct WindowsGuest { diff --git a/tpm/src/emulator.rs b/tpm/src/emulator.rs index 53fdc371e..dcd2dc771 100644 --- a/tpm/src/emulator.rs +++ b/tpm/src/emulator.rs @@ -3,17 +3,19 @@ // SPDX-License-Identifier: Apache-2.0 // -use crate::socket::SocketDev; -use crate::{Commands, MemberType, Ptm, PtmCap, PtmEst, PtmInit, PtmResult, PtmSetBufferSize}; -use crate::{TPM_CRB_BUFFER_MAX, TPM_SUCCESS}; -use anyhow::anyhow; -use libc::c_void; -use libc::{sockaddr_storage, socklen_t}; use std::os::unix::io::RawFd; use std::path::Path; use std::{mem, ptr}; + +use anyhow::anyhow; +use libc::c_void; +use libc::{sockaddr_storage, socklen_t}; use thiserror::Error; +use crate::socket::SocketDev; +use crate::{Commands, MemberType, Ptm, PtmCap, PtmEst, PtmInit, PtmResult, PtmSetBufferSize}; +use crate::{TPM_CRB_BUFFER_MAX, TPM_SUCCESS}; + const TPM_REQ_HDR_SIZE: usize = 10; /* capability flags returned by PTM_GET_CAPABILITY */ diff --git a/tpm/src/socket.rs b/tpm/src/socket.rs index 998208dfc..35b058976 100644 --- a/tpm/src/socket.rs +++ b/tpm/src/socket.rs @@ -3,10 +3,11 @@ // SPDX-License-Identifier: Apache-2.0 // -use anyhow::anyhow; use std::io::Read; use std::os::unix::io::{AsRawFd, RawFd}; use std::os::unix::net::UnixStream; + +use anyhow::anyhow; use thiserror::Error; use vmm_sys_util::sock_ctrl_msg::ScmSocket; diff --git a/tracer/src/tracer.rs b/tracer/src/tracer.rs index 0f3bf2cd8..c49077b29 100644 --- a/tracer/src/tracer.rs +++ b/tracer/src/tracer.rs @@ -3,8 +3,6 @@ // SPDX-License-Identifier: Apache-2.0 // -use once_cell::unsync::OnceCell; -use serde::Serialize; use std::collections::HashMap; use std::fs::File; use std::io::Write; @@ -12,6 +10,9 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; +use once_cell::unsync::OnceCell; +use serde::Serialize; + #[derive(Debug)] struct Tracer { events: Arc>>>, diff --git a/vhost_user_block/src/lib.rs b/vhost_user_block/src/lib.rs index f779fb222..09a21d0fc 100644 --- a/vhost_user_block/src/lib.rs +++ b/vhost_user_block/src/lib.rs @@ -8,14 +8,6 @@ // // SPDX-License-Identifier: (Apache-2.0 AND BSD-3-Clause) -use block::{ - build_serial, - qcow::{self, ImageType, QcowFile}, - Request, VirtioBlockConfig, -}; -use libc::EFD_NONBLOCK; -use log::*; -use option_parser::{OptionParser, OptionParserError, Toggle}; use std::fs::File; use std::fs::OpenOptions; use std::io::Read; @@ -30,6 +22,15 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, RwLock, RwLockWriteGuard}; use std::time::Instant; use std::{convert, error, fmt, io}; + +use block::{ + build_serial, + qcow::{self, ImageType, QcowFile}, + Request, VirtioBlockConfig, +}; +use libc::EFD_NONBLOCK; +use log::*; +use option_parser::{OptionParser, OptionParserError, Toggle}; use vhost::vhost_user::message::*; use vhost::vhost_user::Listener; use vhost_user_backend::{ diff --git a/vhost_user_net/src/lib.rs b/vhost_user_net/src/lib.rs index 26e8bce26..85b420cd1 100644 --- a/vhost_user_net/src/lib.rs +++ b/vhost_user_net/src/lib.rs @@ -6,13 +6,6 @@ // // SPDX-License-Identifier: (Apache-2.0 AND BSD-3-Clause) -use libc::EFD_NONBLOCK; -use log::*; -use net_util::{ - open_tap, MacAddr, NetCounters, NetQueuePair, OpenTapError, RxVirtio, Tap, TxVirtio, -}; -use option_parser::Toggle; -use option_parser::{OptionParser, OptionParserError}; use std::fmt; use std::io; use std::net::Ipv4Addr; @@ -20,6 +13,14 @@ use std::ops::Deref; use std::os::unix::io::{AsRawFd, RawFd}; use std::process; use std::sync::{Arc, Mutex, RwLock}; + +use libc::EFD_NONBLOCK; +use log::*; +use net_util::{ + open_tap, MacAddr, NetCounters, NetQueuePair, OpenTapError, RxVirtio, Tap, TxVirtio, +}; +use option_parser::Toggle; +use option_parser::{OptionParser, OptionParserError}; use vhost::vhost_user::message::*; use vhost::vhost_user::Listener; use vhost_user_backend::bitmap::BitmapMmapRegion; diff --git a/virtio-devices/src/balloon.rs b/virtio-devices/src/balloon.rs index 7f6653906..1fd9b7b8c 100644 --- a/virtio-devices/src/balloon.rs +++ b/virtio-devices/src/balloon.rs @@ -14,20 +14,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - seccomp_filters::Thread, thread_helper::spawn_virtio_thread, ActivateResult, EpollHelper, - EpollHelperError, EpollHelperHandler, GuestMemoryMmap, VirtioCommon, VirtioDevice, - VirtioDeviceType, VirtioInterrupt, VirtioInterruptType, EPOLL_HELPER_EVENT_LAST, - VIRTIO_F_VERSION_1, -}; -use anyhow::anyhow; -use seccompiler::SeccompAction; -use serde::{Deserialize, Serialize}; use std::io::{self, Write}; use std::mem::size_of; use std::os::unix::io::AsRawFd; use std::result; use std::sync::{atomic::AtomicBool, Arc, Barrier}; + +use anyhow::anyhow; +use seccompiler::SeccompAction; +use serde::{Deserialize, Serialize}; use thiserror::Error; use virtio_queue::{Queue, QueueT}; use vm_allocator::page_size::{align_page_size_down, get_page_size}; @@ -38,6 +33,13 @@ use vm_memory::{ use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; use vmm_sys_util::eventfd::EventFd; +use crate::{ + seccomp_filters::Thread, thread_helper::spawn_virtio_thread, ActivateResult, EpollHelper, + EpollHelperError, EpollHelperHandler, GuestMemoryMmap, VirtioCommon, VirtioDevice, + VirtioDeviceType, VirtioInterrupt, VirtioInterruptType, EPOLL_HELPER_EVENT_LAST, + VIRTIO_F_VERSION_1, +}; + const QUEUE_SIZE: u16 = 128; const REPORTING_QUEUE_SIZE: u16 = 32; const MIN_NUM_QUEUES: usize = 2; diff --git a/virtio-devices/src/block.rs b/virtio-devices/src/block.rs index 604d6a456..f06b17bbc 100644 --- a/virtio-devices/src/block.rs +++ b/virtio-devices/src/block.rs @@ -8,24 +8,6 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use super::Error as DeviceError; -use super::{ - ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, VirtioCommon, - VirtioDevice, VirtioDeviceType, VirtioInterruptType, EPOLL_HELPER_EVENT_LAST, -}; -use crate::seccomp_filters::Thread; -use crate::thread_helper::spawn_virtio_thread; -use crate::GuestMemoryMmap; -use crate::VirtioInterrupt; -use anyhow::anyhow; -use block::{ - async_io::AsyncIo, async_io::AsyncIoError, async_io::DiskFile, build_serial, Request, - RequestType, VirtioBlockConfig, -}; -use rate_limiter::group::{RateLimiterGroup, RateLimiterGroupHandle}; -use rate_limiter::TokenType; -use seccompiler::SeccompAction; -use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::VecDeque; @@ -37,6 +19,16 @@ use std::path::PathBuf; use std::result; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Barrier}; + +use anyhow::anyhow; +use block::{ + async_io::AsyncIo, async_io::AsyncIoError, async_io::DiskFile, build_serial, Request, + RequestType, VirtioBlockConfig, +}; +use rate_limiter::group::{RateLimiterGroup, RateLimiterGroupHandle}; +use rate_limiter::TokenType; +use seccompiler::SeccompAction; +use serde::{Deserialize, Serialize}; use thiserror::Error; use virtio_bindings::virtio_blk::*; use virtio_bindings::virtio_config::*; @@ -47,6 +39,16 @@ use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottabl use vm_virtio::AccessPlatform; use vmm_sys_util::eventfd::EventFd; +use super::Error as DeviceError; +use super::{ + ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, VirtioCommon, + VirtioDevice, VirtioDeviceType, VirtioInterruptType, EPOLL_HELPER_EVENT_LAST, +}; +use crate::seccomp_filters::Thread; +use crate::thread_helper::spawn_virtio_thread; +use crate::GuestMemoryMmap; +use crate::VirtioInterrupt; + const SECTOR_SHIFT: u8 = 9; pub const SECTOR_SIZE: u64 = 0x01 << SECTOR_SHIFT; diff --git a/virtio-devices/src/console.rs b/virtio-devices/src/console.rs index 06c31b7d4..9fce951ee 100644 --- a/virtio-devices/src/console.rs +++ b/virtio-devices/src/console.rs @@ -1,6 +1,28 @@ // Copyright 2019 Intel Corporation. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +use std::cmp; +use std::collections::VecDeque; +use std::fs::File; +use std::io; +use std::io::{Read, Write}; +use std::os::unix::io::AsRawFd; +use std::result; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Barrier, Mutex}; + +use anyhow::anyhow; +use libc::{EFD_NONBLOCK, TIOCGWINSZ}; +use seccompiler::SeccompAction; +use serde::{Deserialize, Serialize}; +use serial_buffer::SerialBuffer; +use thiserror::Error; +use virtio_queue::{Queue, QueueT}; +use vm_memory::{ByteValued, Bytes, GuestAddressSpace, GuestMemory, GuestMemoryAtomic}; +use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; +use vm_virtio::{AccessPlatform, Translatable}; +use vmm_sys_util::eventfd::EventFd; + use super::Error as DeviceError; use super::{ ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, VirtioCommon, VirtioDevice, @@ -11,26 +33,6 @@ use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; use crate::GuestMemoryMmap; use crate::VirtioInterrupt; -use anyhow::anyhow; -use libc::{EFD_NONBLOCK, TIOCGWINSZ}; -use seccompiler::SeccompAction; -use serde::{Deserialize, Serialize}; -use serial_buffer::SerialBuffer; -use std::cmp; -use std::collections::VecDeque; -use std::fs::File; -use std::io; -use std::io::{Read, Write}; -use std::os::unix::io::AsRawFd; -use std::result; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, Barrier, Mutex}; -use thiserror::Error; -use virtio_queue::{Queue, QueueT}; -use vm_memory::{ByteValued, Bytes, GuestAddressSpace, GuestMemory, GuestMemoryAtomic}; -use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; -use vm_virtio::{AccessPlatform, Translatable}; -use vmm_sys_util::eventfd::EventFd; const QUEUE_SIZE: u16 = 256; const NUM_QUEUES: usize = 2; diff --git a/virtio-devices/src/device.rs b/virtio-devices/src/device.rs index 3f0951373..e2ac65319 100644 --- a/virtio-devices/src/device.rs +++ b/virtio-devices/src/device.rs @@ -6,11 +6,6 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use crate::{ - ActivateError, ActivateResult, Error, GuestMemoryMmap, GuestRegionMmap, - VIRTIO_F_RING_INDIRECT_DESC, -}; -use libc::EFD_NONBLOCK; use std::collections::HashMap; use std::io::Write; use std::num::Wrapping; @@ -19,6 +14,8 @@ use std::sync::{ Arc, Barrier, }; use std::thread; + +use libc::EFD_NONBLOCK; use virtio_queue::Queue; use vm_memory::{GuestAddress, GuestMemoryAtomic, GuestUsize}; use vm_migration::{MigratableError, Pausable}; @@ -26,6 +23,11 @@ use vm_virtio::AccessPlatform; use vm_virtio::VirtioDeviceType; use vmm_sys_util::eventfd::EventFd; +use crate::{ + ActivateError, ActivateResult, Error, GuestMemoryMmap, GuestRegionMmap, + VIRTIO_F_RING_INDIRECT_DESC, +}; + pub enum VirtioInterruptType { Config, Queue(u16), diff --git a/virtio-devices/src/epoll_helper.rs b/virtio-devices/src/epoll_helper.rs index 0de375a3c..3f78768f7 100644 --- a/virtio-devices/src/epoll_helper.rs +++ b/virtio-devices/src/epoll_helper.rs @@ -13,6 +13,7 @@ use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Barrier}; use std::thread; + use thiserror::Error; use vmm_sys_util::eventfd::EventFd; diff --git a/virtio-devices/src/iommu.rs b/virtio-devices/src/iommu.rs index 28594dfe5..ba304f2c5 100644 --- a/virtio-devices/src/iommu.rs +++ b/virtio-devices/src/iommu.rs @@ -2,18 +2,6 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use super::Error as DeviceError; -use super::{ - ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, VirtioCommon, VirtioDevice, - VirtioDeviceType, EPOLL_HELPER_EVENT_LAST, VIRTIO_F_VERSION_1, -}; -use crate::seccomp_filters::Thread; -use crate::thread_helper::spawn_virtio_thread; -use crate::GuestMemoryMmap; -use crate::{DmaRemapping, VirtioInterrupt, VirtioInterruptType}; -use anyhow::anyhow; -use seccompiler::SeccompAction; -use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::io; use std::mem::size_of; @@ -22,6 +10,10 @@ use std::os::unix::io::AsRawFd; use std::result; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Barrier, Mutex, RwLock}; + +use anyhow::anyhow; +use seccompiler::SeccompAction; +use serde::{Deserialize, Serialize}; use thiserror::Error; use virtio_queue::{DescriptorChain, Queue, QueueT}; use vm_device::dma_mapping::ExternalDmaMapping; @@ -33,6 +25,16 @@ use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottabl use vm_virtio::AccessPlatform; use vmm_sys_util::eventfd::EventFd; +use super::Error as DeviceError; +use super::{ + ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, VirtioCommon, VirtioDevice, + VirtioDeviceType, EPOLL_HELPER_EVENT_LAST, VIRTIO_F_VERSION_1, +}; +use crate::seccomp_filters::Thread; +use crate::thread_helper::spawn_virtio_thread; +use crate::GuestMemoryMmap; +use crate::{DmaRemapping, VirtioInterrupt, VirtioInterruptType}; + /// Queues sizes const QUEUE_SIZE: u16 = 256; const NUM_QUEUES: usize = 2; diff --git a/virtio-devices/src/lib.rs b/virtio-devices/src/lib.rs index aaed464cd..28445c3d4 100644 --- a/virtio-devices/src/lib.rs +++ b/virtio-devices/src/lib.rs @@ -15,8 +15,9 @@ extern crate event_monitor; #[macro_use] extern crate log; -use serde::{Deserialize, Serialize}; use std::io; + +use serde::{Deserialize, Serialize}; use thiserror::Error; #[macro_use] @@ -38,6 +39,9 @@ pub mod vhost_user; pub mod vsock; pub mod watchdog; +use vm_memory::{bitmap::AtomicBitmap, GuestAddress, GuestMemory}; +use vm_virtio::VirtioDeviceType; + pub use self::balloon::Balloon; pub use self::block::{Block, BlockState}; pub use self::console::{Console, ConsoleResizer, Endpoint}; @@ -56,8 +60,6 @@ pub use self::rng::Rng; pub use self::vdpa::{Vdpa, VdpaDmaMapping}; pub use self::vsock::Vsock; pub use self::watchdog::Watchdog; -use vm_memory::{bitmap::AtomicBitmap, GuestAddress, GuestMemory}; -use vm_virtio::VirtioDeviceType; type GuestMemoryMmap = vm_memory::GuestMemoryMmap; type GuestRegionMmap = vm_memory::GuestRegionMmap; diff --git a/virtio-devices/src/mem.rs b/virtio-devices/src/mem.rs index 9ad21bd90..d4b01f4a1 100644 --- a/virtio-devices/src/mem.rs +++ b/virtio-devices/src/mem.rs @@ -14,18 +14,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::Error as DeviceError; -use super::{ - ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, VirtioCommon, - VirtioDevice, VirtioDeviceType, EPOLL_HELPER_EVENT_LAST, VIRTIO_F_VERSION_1, -}; -use crate::seccomp_filters::Thread; -use crate::thread_helper::spawn_virtio_thread; -use crate::{GuestMemoryMmap, GuestRegionMmap}; -use crate::{VirtioInterrupt, VirtioInterruptType}; -use anyhow::anyhow; -use seccompiler::SeccompAction; -use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::io; use std::mem::size_of; @@ -34,6 +22,10 @@ use std::result; use std::sync::atomic::AtomicBool; use std::sync::mpsc; use std::sync::{Arc, Barrier, Mutex}; + +use anyhow::anyhow; +use seccompiler::SeccompAction; +use serde::{Deserialize, Serialize}; use thiserror::Error; use virtio_queue::{DescriptorChain, Queue, QueueT}; use vm_device::dma_mapping::ExternalDmaMapping; @@ -45,6 +37,16 @@ use vm_migration::protocol::MemoryRangeTable; use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; use vmm_sys_util::eventfd::EventFd; +use super::Error as DeviceError; +use super::{ + ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, VirtioCommon, + VirtioDevice, VirtioDeviceType, EPOLL_HELPER_EVENT_LAST, VIRTIO_F_VERSION_1, +}; +use crate::seccomp_filters::Thread; +use crate::thread_helper::spawn_virtio_thread; +use crate::{GuestMemoryMmap, GuestRegionMmap}; +use crate::{VirtioInterrupt, VirtioInterruptType}; + const QUEUE_SIZE: u16 = 128; const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE]; diff --git a/virtio-devices/src/net.rs b/virtio-devices/src/net.rs index ce46b9388..2d312d27c 100644 --- a/virtio-devices/src/net.rs +++ b/virtio-devices/src/net.rs @@ -5,6 +5,36 @@ // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. +use std::collections::HashMap; +use std::net::Ipv4Addr; +use std::num::Wrapping; +use std::ops::Deref; +use std::os::unix::io::{AsRawFd, RawFd}; +use std::result; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Barrier}; +use std::thread; + +use anyhow::anyhow; +#[cfg(not(fuzzing))] +use net_util::virtio_features_to_tap_offload; +use net_util::CtrlQueue; +use net_util::{ + build_net_config_space, build_net_config_space_with_mq, open_tap, MacAddr, NetCounters, + NetQueuePair, OpenTapError, RxVirtio, Tap, TapError, TxVirtio, VirtioNetConfig, +}; +use seccompiler::SeccompAction; +use serde::{Deserialize, Serialize}; +use thiserror::Error; +use virtio_bindings::virtio_config::*; +use virtio_bindings::virtio_net::*; +use virtio_bindings::virtio_ring::VIRTIO_RING_F_EVENT_IDX; +use virtio_queue::{Queue, QueueT}; +use vm_memory::{ByteValued, GuestAddressSpace, GuestMemoryAtomic}; +use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; +use vm_virtio::AccessPlatform; +use vmm_sys_util::eventfd::EventFd; + use super::Error as DeviceError; use super::{ ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, @@ -15,34 +45,6 @@ use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; use crate::GuestMemoryMmap; use crate::VirtioInterrupt; -use anyhow::anyhow; -#[cfg(not(fuzzing))] -use net_util::virtio_features_to_tap_offload; -use net_util::CtrlQueue; -use net_util::{ - build_net_config_space, build_net_config_space_with_mq, open_tap, MacAddr, NetCounters, - NetQueuePair, OpenTapError, RxVirtio, Tap, TapError, TxVirtio, VirtioNetConfig, -}; -use seccompiler::SeccompAction; -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::net::Ipv4Addr; -use std::num::Wrapping; -use std::ops::Deref; -use std::os::unix::io::{AsRawFd, RawFd}; -use std::result; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Barrier}; -use std::thread; -use thiserror::Error; -use virtio_bindings::virtio_config::*; -use virtio_bindings::virtio_net::*; -use virtio_bindings::virtio_ring::VIRTIO_RING_F_EVENT_IDX; -use virtio_queue::{Queue, QueueT}; -use vm_memory::{ByteValued, GuestAddressSpace, GuestMemoryAtomic}; -use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; -use vm_virtio::AccessPlatform; -use vmm_sys_util::eventfd::EventFd; /// Control queue // Event available on the control queue. diff --git a/virtio-devices/src/pmem.rs b/virtio-devices/src/pmem.rs index 57ef9c63d..b0507445c 100644 --- a/virtio-devices/src/pmem.rs +++ b/virtio-devices/src/pmem.rs @@ -6,6 +6,27 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause +use std::fs::File; +use std::io; +use std::mem::size_of; +use std::os::unix::io::AsRawFd; +use std::result; +use std::sync::atomic::AtomicBool; +use std::sync::{Arc, Barrier}; + +use anyhow::anyhow; +use seccompiler::SeccompAction; +use serde::{Deserialize, Serialize}; +use thiserror::Error; +use virtio_queue::{DescriptorChain, Queue, QueueT}; +use vm_memory::{ + Address, ByteValued, Bytes, GuestAddress, GuestAddressSpace, GuestMemoryAtomic, + GuestMemoryError, GuestMemoryLoadGuard, +}; +use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; +use vm_virtio::{AccessPlatform, Translatable}; +use vmm_sys_util::eventfd::EventFd; + use super::Error as DeviceError; use super::{ ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, @@ -16,25 +37,6 @@ use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; use crate::{GuestMemoryMmap, MmapRegion}; use crate::{VirtioInterrupt, VirtioInterruptType}; -use anyhow::anyhow; -use seccompiler::SeccompAction; -use serde::{Deserialize, Serialize}; -use std::fs::File; -use std::io; -use std::mem::size_of; -use std::os::unix::io::AsRawFd; -use std::result; -use std::sync::atomic::AtomicBool; -use std::sync::{Arc, Barrier}; -use thiserror::Error; -use virtio_queue::{DescriptorChain, Queue, QueueT}; -use vm_memory::{ - Address, ByteValued, Bytes, GuestAddress, GuestAddressSpace, GuestMemoryAtomic, - GuestMemoryError, GuestMemoryLoadGuard, -}; -use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; -use vm_virtio::{AccessPlatform, Translatable}; -use vmm_sys_util::eventfd::EventFd; const QUEUE_SIZE: u16 = 256; const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE]; diff --git a/virtio-devices/src/rng.rs b/virtio-devices/src/rng.rs index 7c70d1f10..5fde51e88 100644 --- a/virtio-devices/src/rng.rs +++ b/virtio-devices/src/rng.rs @@ -4,6 +4,23 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause +use std::fs::File; +use std::io; +use std::os::unix::io::AsRawFd; +use std::result; +use std::sync::atomic::AtomicBool; +use std::sync::{Arc, Barrier}; + +use anyhow::anyhow; +use seccompiler::SeccompAction; +use serde::{Deserialize, Serialize}; +use thiserror::Error; +use virtio_queue::{Queue, QueueT}; +use vm_memory::{GuestAddressSpace, GuestMemory, GuestMemoryAtomic}; +use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; +use vm_virtio::{AccessPlatform, Translatable}; +use vmm_sys_util::eventfd::EventFd; + use super::Error as DeviceError; use super::{ ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, VirtioCommon, @@ -14,21 +31,6 @@ use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; use crate::GuestMemoryMmap; use crate::{VirtioInterrupt, VirtioInterruptType}; -use anyhow::anyhow; -use seccompiler::SeccompAction; -use serde::{Deserialize, Serialize}; -use std::fs::File; -use std::io; -use std::os::unix::io::AsRawFd; -use std::result; -use std::sync::atomic::AtomicBool; -use std::sync::{Arc, Barrier}; -use thiserror::Error; -use virtio_queue::{Queue, QueueT}; -use vm_memory::{GuestAddressSpace, GuestMemory, GuestMemoryAtomic}; -use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; -use vm_virtio::{AccessPlatform, Translatable}; -use vmm_sys_util::eventfd::EventFd; const QUEUE_SIZE: u16 = 256; const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE]; diff --git a/virtio-devices/src/thread_helper.rs b/virtio-devices/src/thread_helper.rs index 5d6a113b9..114fb1012 100644 --- a/virtio-devices/src/thread_helper.rs +++ b/virtio-devices/src/thread_helper.rs @@ -3,17 +3,19 @@ // SPDX-License-Identifier: Apache-2.0 // +use std::{ + panic::AssertUnwindSafe, + thread::{self, JoinHandle}, +}; + +use seccompiler::{apply_filter, SeccompAction}; +use vmm_sys_util::eventfd::EventFd; + use crate::{ epoll_helper::EpollHelperError, seccomp_filters::{get_seccomp_filter, Thread}, ActivateError, }; -use seccompiler::{apply_filter, SeccompAction}; -use std::{ - panic::AssertUnwindSafe, - thread::{self, JoinHandle}, -}; -use vmm_sys_util::eventfd::EventFd; pub(crate) fn spawn_virtio_thread( name: &str, diff --git a/virtio-devices/src/transport/pci_common_config.rs b/virtio-devices/src/transport/pci_common_config.rs index 04e89d922..79fbb7e13 100644 --- a/virtio-devices/src/transport/pci_common_config.rs +++ b/virtio-devices/src/transport/pci_common_config.rs @@ -6,15 +6,17 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use crate::VirtioDevice; -use byteorder::{ByteOrder, LittleEndian}; -use serde::{Deserialize, Serialize}; use std::sync::atomic::{AtomicU16, Ordering}; use std::sync::{Arc, Mutex}; + +use byteorder::{ByteOrder, LittleEndian}; +use serde::{Deserialize, Serialize}; use virtio_queue::{Queue, QueueT}; use vm_migration::{MigratableError, Pausable, Snapshot, Snapshottable}; use vm_virtio::AccessPlatform; +use crate::VirtioDevice; + pub const VIRTIO_PCI_COMMON_CONFIG_ID: &str = "virtio_pci_common_config"; #[derive(Clone, Serialize, Deserialize)] @@ -404,11 +406,12 @@ impl Snapshottable for VirtioPciCommonConfig { #[cfg(test)] mod tests { + use vm_memory::GuestMemoryAtomic; + use vmm_sys_util::eventfd::EventFd; + use super::*; use crate::GuestMemoryMmap; use crate::{ActivateResult, VirtioInterrupt}; - use vm_memory::GuestMemoryAtomic; - use vmm_sys_util::eventfd::EventFd; struct DummyDevice(u32); const QUEUE_SIZE: u16 = 256; diff --git a/virtio-devices/src/transport/pci_device.rs b/virtio-devices/src/transport/pci_device.rs index 5e5ce3a2d..0551ffc98 100644 --- a/virtio-devices/src/transport/pci_device.rs +++ b/virtio-devices/src/transport/pci_device.rs @@ -6,13 +6,13 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use crate::transport::{VirtioPciCommonConfig, VirtioTransport, VIRTIO_PCI_COMMON_CONFIG_ID}; -use crate::GuestMemoryMmap; -use crate::{ - ActivateResult, VirtioDevice, VirtioDeviceType, VirtioInterrupt, VirtioInterruptType, - DEVICE_ACKNOWLEDGE, DEVICE_DRIVER, DEVICE_DRIVER_OK, DEVICE_FAILED, DEVICE_FEATURES_OK, - DEVICE_INIT, -}; +use std::any::Any; +use std::cmp; +use std::io::Write; +use std::ops::Deref; +use std::sync::atomic::{AtomicBool, AtomicU16, AtomicUsize, Ordering}; +use std::sync::{Arc, Barrier, Mutex}; + use anyhow::anyhow; use libc::EFD_NONBLOCK; use pci::{ @@ -21,12 +21,6 @@ use pci::{ PciHeaderType, PciMassStorageSubclass, PciNetworkControllerSubclass, PciSubclass, }; use serde::{Deserialize, Serialize}; -use std::any::Any; -use std::cmp; -use std::io::Write; -use std::ops::Deref; -use std::sync::atomic::{AtomicBool, AtomicU16, AtomicUsize, Ordering}; -use std::sync::{Arc, Barrier, Mutex}; use thiserror::Error; use virtio_queue::{Queue, QueueT}; use vm_allocator::{AddressAllocator, SystemAllocator}; @@ -41,6 +35,13 @@ use vm_virtio::AccessPlatform; use vmm_sys_util::eventfd::EventFd; use super::pci_common_config::VirtioPciCommonConfigState; +use crate::transport::{VirtioPciCommonConfig, VirtioTransport, VIRTIO_PCI_COMMON_CONFIG_ID}; +use crate::GuestMemoryMmap; +use crate::{ + ActivateResult, VirtioDevice, VirtioDeviceType, VirtioInterrupt, VirtioInterruptType, + DEVICE_ACKNOWLEDGE, DEVICE_DRIVER, DEVICE_DRIVER_OK, DEVICE_FAILED, DEVICE_FEATURES_OK, + DEVICE_INIT, +}; /// Vector value used to disable MSI for a queue. const VIRTQ_MSI_NO_VECTOR: u16 = 0xffff; diff --git a/virtio-devices/src/vdpa.rs b/virtio-devices/src/vdpa.rs index e7884b6fa..f61af9e79 100644 --- a/virtio-devices/src/vdpa.rs +++ b/virtio-devices/src/vdpa.rs @@ -3,13 +3,6 @@ // SPDX-License-Identifier: Apache-2.0 // -use crate::{ - ActivateError, ActivateResult, GuestMemoryMmap, VirtioCommon, VirtioDevice, VirtioInterrupt, - VirtioInterruptType, DEVICE_ACKNOWLEDGE, DEVICE_DRIVER, DEVICE_DRIVER_OK, DEVICE_FEATURES_OK, - VIRTIO_F_IOMMU_PLATFORM, -}; -use anyhow::anyhow; -use serde::{Deserialize, Serialize}; use std::{ collections::BTreeMap, io, result, @@ -18,6 +11,9 @@ use std::{ Arc, Mutex, }, }; + +use anyhow::anyhow; +use serde::{Deserialize, Serialize}; use thiserror::Error; use vhost::{ vdpa::{VhostVdpa, VhostVdpaIovaRange}, @@ -32,6 +28,12 @@ use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottabl use vm_virtio::{AccessPlatform, Translatable}; use vmm_sys_util::eventfd::EventFd; +use crate::{ + ActivateError, ActivateResult, GuestMemoryMmap, VirtioCommon, VirtioDevice, VirtioInterrupt, + VirtioInterruptType, DEVICE_ACKNOWLEDGE, DEVICE_DRIVER, DEVICE_DRIVER_OK, DEVICE_FEATURES_OK, + VIRTIO_F_IOMMU_PLATFORM, +}; + #[derive(Error, Debug)] pub enum Error { #[error("Failed to create vhost-vdpa: {0}")] diff --git a/virtio-devices/src/vhost_user/blk.rs b/virtio-devices/src/vhost_user/blk.rs index 9ed0edc0e..d37f9e7ea 100644 --- a/virtio-devices/src/vhost_user/blk.rs +++ b/virtio-devices/src/vhost_user/blk.rs @@ -1,23 +1,15 @@ // Copyright 2019 Intel Corporation. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -use super::super::{ActivateResult, VirtioCommon, VirtioDevice, VirtioDeviceType}; -use super::vu_common_ctrl::{VhostUserConfig, VhostUserHandle}; -use super::{Error, Result, DEFAULT_VIRTIO_FEATURES}; -use crate::seccomp_filters::Thread; -use crate::thread_helper::spawn_virtio_thread; -use crate::vhost_user::VhostUserCommon; -use crate::{GuestMemoryMmap, GuestRegionMmap}; -use crate::{VirtioInterrupt, VIRTIO_F_IOMMU_PLATFORM}; -use block::VirtioBlockConfig; -use seccompiler::SeccompAction; -use serde::{Deserialize, Serialize}; use std::mem; use std::result; use std::sync::atomic::AtomicBool; use std::sync::{Arc, Barrier, Mutex}; use std::thread; +use block::VirtioBlockConfig; +use seccompiler::SeccompAction; +use serde::{Deserialize, Serialize}; use vhost::vhost_user::message::{ VhostUserConfigFlags, VhostUserProtocolFeatures, VhostUserVirtioFeatures, VHOST_USER_CONFIG_OFFSET, @@ -36,6 +28,15 @@ use vm_migration::{ }; use vmm_sys_util::eventfd::EventFd; +use super::super::{ActivateResult, VirtioCommon, VirtioDevice, VirtioDeviceType}; +use super::vu_common_ctrl::{VhostUserConfig, VhostUserHandle}; +use super::{Error, Result, DEFAULT_VIRTIO_FEATURES}; +use crate::seccomp_filters::Thread; +use crate::thread_helper::spawn_virtio_thread; +use crate::vhost_user::VhostUserCommon; +use crate::{GuestMemoryMmap, GuestRegionMmap}; +use crate::{VirtioInterrupt, VIRTIO_F_IOMMU_PLATFORM}; + const DEFAULT_QUEUE_NUMBER: usize = 1; #[derive(Serialize, Deserialize)] diff --git a/virtio-devices/src/vhost_user/fs.rs b/virtio-devices/src/vhost_user/fs.rs index 6c098ae80..0513d4e1b 100644 --- a/virtio-devices/src/vhost_user/fs.rs +++ b/virtio-devices/src/vhost_user/fs.rs @@ -1,6 +1,24 @@ // Copyright 2019 Intel Corporation. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +use std::result; +use std::sync::atomic::AtomicBool; +use std::sync::{Arc, Barrier, Mutex}; +use std::thread; + +use seccompiler::SeccompAction; +use serde::{Deserialize, Serialize}; +use serde_with::{serde_as, Bytes}; +use vhost::vhost_user::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vhost::vhost_user::{FrontendReqHandler, VhostUserFrontend, VhostUserFrontendReqHandler}; +use virtio_queue::Queue; +use vm_memory::{ByteValued, GuestMemoryAtomic}; +use vm_migration::{ + protocol::MemoryRangeTable, Migratable, MigratableError, Pausable, Snapshot, Snapshottable, + Transportable, +}; +use vmm_sys_util::eventfd::EventFd; + use super::vu_common_ctrl::VhostUserHandle; use super::{Error, Result, DEFAULT_VIRTIO_FEATURES}; use crate::seccomp_filters::Thread; @@ -11,22 +29,6 @@ use crate::{ VirtioInterrupt, VirtioSharedMemoryList, VIRTIO_F_IOMMU_PLATFORM, }; use crate::{GuestMemoryMmap, GuestRegionMmap, MmapRegion}; -use seccompiler::SeccompAction; -use serde::{Deserialize, Serialize}; -use serde_with::{serde_as, Bytes}; -use std::result; -use std::sync::atomic::AtomicBool; -use std::sync::{Arc, Barrier, Mutex}; -use std::thread; -use vhost::vhost_user::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; -use vhost::vhost_user::{FrontendReqHandler, VhostUserFrontend, VhostUserFrontendReqHandler}; -use virtio_queue::Queue; -use vm_memory::{ByteValued, GuestMemoryAtomic}; -use vm_migration::{ - protocol::MemoryRangeTable, Migratable, MigratableError, Pausable, Snapshot, Snapshottable, - Transportable, -}; -use vmm_sys_util::eventfd::EventFd; const NUM_QUEUE_OFFSET: usize = 1; const DEFAULT_QUEUE_NUMBER: usize = 2; diff --git a/virtio-devices/src/vhost_user/mod.rs b/virtio-devices/src/vhost_user/mod.rs index 85d30fee3..bb84d157f 100644 --- a/virtio-devices/src/vhost_user/mod.rs +++ b/virtio-devices/src/vhost_user/mod.rs @@ -1,18 +1,13 @@ // Copyright 2019 Intel Corporation. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -use crate::{ - ActivateError, EpollHelper, EpollHelperError, EpollHelperHandler, GuestMemoryMmap, - GuestRegionMmap, VirtioInterrupt, EPOLL_HELPER_EVENT_LAST, VIRTIO_F_IN_ORDER, - VIRTIO_F_NOTIFICATION_DATA, VIRTIO_F_ORDER_PLATFORM, VIRTIO_F_RING_EVENT_IDX, - VIRTIO_F_RING_INDIRECT_DESC, VIRTIO_F_VERSION_1, -}; -use anyhow::anyhow; -use serde::{Deserialize, Serialize}; use std::io; use std::ops::Deref; use std::os::unix::io::AsRawFd; use std::sync::{atomic::AtomicBool, Arc, Barrier, Mutex}; + +use anyhow::anyhow; +use serde::{Deserialize, Serialize}; use thiserror::Error; use vhost::vhost_user::message::{ VhostUserInflight, VhostUserProtocolFeatures, VhostUserVirtioFeatures, @@ -29,6 +24,13 @@ use vm_migration::{protocol::MemoryRangeTable, MigratableError, Snapshot}; use vmm_sys_util::eventfd::EventFd; use vu_common_ctrl::VhostUserHandle; +use crate::{ + ActivateError, EpollHelper, EpollHelperError, EpollHelperHandler, GuestMemoryMmap, + GuestRegionMmap, VirtioInterrupt, EPOLL_HELPER_EVENT_LAST, VIRTIO_F_IN_ORDER, + VIRTIO_F_NOTIFICATION_DATA, VIRTIO_F_ORDER_PLATFORM, VIRTIO_F_RING_EVENT_IDX, + VIRTIO_F_RING_INDIRECT_DESC, VIRTIO_F_VERSION_1, +}; + pub mod blk; pub mod fs; pub mod net; diff --git a/virtio-devices/src/vhost_user/net.rs b/virtio-devices/src/vhost_user/net.rs index 16cccb6a6..596172fa8 100644 --- a/virtio-devices/src/vhost_user/net.rs +++ b/virtio-devices/src/vhost_user/net.rs @@ -1,22 +1,14 @@ // Copyright 2019 Intel Corporation. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -use crate::seccomp_filters::Thread; -use crate::thread_helper::spawn_virtio_thread; -use crate::vhost_user::vu_common_ctrl::{VhostUserConfig, VhostUserHandle}; -use crate::vhost_user::{Error, Result, VhostUserCommon}; -use crate::{ - ActivateResult, NetCtrlEpollHandler, VirtioCommon, VirtioDevice, VirtioDeviceType, - VirtioInterrupt, VIRTIO_F_IOMMU_PLATFORM, VIRTIO_F_RING_EVENT_IDX, VIRTIO_F_VERSION_1, -}; -use crate::{GuestMemoryMmap, GuestRegionMmap}; -use net_util::{build_net_config_space, CtrlQueue, MacAddr, VirtioNetConfig}; -use seccompiler::SeccompAction; -use serde::{Deserialize, Serialize}; use std::result; use std::sync::atomic::AtomicBool; use std::sync::{Arc, Barrier, Mutex}; use std::thread; + +use net_util::{build_net_config_space, CtrlQueue, MacAddr, VirtioNetConfig}; +use seccompiler::SeccompAction; +use serde::{Deserialize, Serialize}; use vhost::vhost_user::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; use vhost::vhost_user::{FrontendReqHandler, VhostUserFrontend, VhostUserFrontendReqHandler}; use virtio_bindings::virtio_net::{ @@ -34,6 +26,16 @@ use vm_migration::{ }; use vmm_sys_util::eventfd::EventFd; +use crate::seccomp_filters::Thread; +use crate::thread_helper::spawn_virtio_thread; +use crate::vhost_user::vu_common_ctrl::{VhostUserConfig, VhostUserHandle}; +use crate::vhost_user::{Error, Result, VhostUserCommon}; +use crate::{ + ActivateResult, NetCtrlEpollHandler, VirtioCommon, VirtioDevice, VirtioDeviceType, + VirtioInterrupt, VIRTIO_F_IOMMU_PLATFORM, VIRTIO_F_RING_EVENT_IDX, VIRTIO_F_VERSION_1, +}; +use crate::{GuestMemoryMmap, GuestRegionMmap}; + const DEFAULT_QUEUE_NUMBER: usize = 2; #[derive(Serialize, Deserialize)] diff --git a/virtio-devices/src/vhost_user/vu_common_ctrl.rs b/virtio-devices/src/vhost_user/vu_common_ctrl.rs index 9fc6b4d89..60ee6b32d 100644 --- a/virtio-devices/src/vhost_user/vu_common_ctrl.rs +++ b/virtio-devices/src/vhost_user/vu_common_ctrl.rs @@ -1,12 +1,6 @@ // Copyright 2019 Intel Corporation. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -use super::{Error, Result}; -use crate::vhost_user::Inflight; -use crate::{ - get_host_address_range, GuestMemoryMmap, GuestRegionMmap, MmapRegion, VirtioInterrupt, - VirtioInterruptType, -}; use std::ffi; use std::fs::File; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; @@ -15,6 +9,7 @@ use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread::sleep; use std::time::{Duration, Instant}; + use vhost::vhost_kern::vhost_binding::{VHOST_F_LOG_ALL, VHOST_VRING_F_LOG}; use vhost::vhost_user::message::{ VhostUserHeaderFlag, VhostUserInflight, VhostUserProtocolFeatures, VhostUserVirtioFeatures, @@ -30,6 +25,13 @@ use vm_memory::{ use vm_migration::protocol::MemoryRangeTable; use vmm_sys_util::eventfd::EventFd; +use super::{Error, Result}; +use crate::vhost_user::Inflight; +use crate::{ + get_host_address_range, GuestMemoryMmap, GuestRegionMmap, MmapRegion, VirtioInterrupt, + VirtioInterruptType, +}; + // Size of a dirty page for vhost-user. const VHOST_LOG_PAGE: u64 = 0x1000; diff --git a/virtio-devices/src/vsock/csm/connection.rs b/virtio-devices/src/vsock/csm/connection.rs index a5dd6f7c4..c0372ae44 100644 --- a/virtio-devices/src/vsock/csm/connection.rs +++ b/virtio-devices/src/vsock/csm/connection.rs @@ -672,13 +672,15 @@ where #[cfg(test)] mod tests { + use std::io::{Error as IoError, Result as IoResult}; + + use libc::EFD_NONBLOCK; + use virtio_queue::QueueOwnedT; + use vmm_sys_util::eventfd::EventFd; + use super::super::super::tests::TestContext; use super::super::defs as csm_defs; use super::*; - use libc::EFD_NONBLOCK; - use std::io::{Error as IoError, Result as IoResult}; - use virtio_queue::QueueOwnedT; - use vmm_sys_util::eventfd::EventFd; const LOCAL_CID: u64 = 2; const PEER_CID: u64 = 3; diff --git a/virtio-devices/src/vsock/csm/txbuf.rs b/virtio-devices/src/vsock/csm/txbuf.rs index 5f0e7254c..03d668727 100644 --- a/virtio-devices/src/vsock/csm/txbuf.rs +++ b/virtio-devices/src/vsock/csm/txbuf.rs @@ -144,11 +144,12 @@ impl TxBuf { #[cfg(test)] mod tests { - use super::*; use std::io::Error as IoError; use std::io::ErrorKind; use std::io::Result as IoResult; + use super::*; + struct TestSink { data: Vec, err: Option, diff --git a/virtio-devices/src/vsock/device.rs b/virtio-devices/src/vsock/device.rs index 40affae89..3eafd6d55 100644 --- a/virtio-devices/src/vsock/device.rs +++ b/virtio-devices/src/vsock/device.rs @@ -8,6 +8,26 @@ // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. +use std::io; +use std::os::unix::io::AsRawFd; +use std::path::PathBuf; +use std::result; +use std::sync::atomic::AtomicBool; +use std::sync::{Arc, Barrier, RwLock}; + +use anyhow::anyhow; +use byteorder::{ByteOrder, LittleEndian}; +use seccompiler::SeccompAction; +use serde::{Deserialize, Serialize}; +use virtio_queue::Queue; +use virtio_queue::QueueOwnedT; +use virtio_queue::QueueT; +use vm_memory::GuestAddressSpace; +use vm_memory::GuestMemoryAtomic; +use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; +use vm_virtio::AccessPlatform; +use vmm_sys_util::eventfd::EventFd; + /// This is the `VirtioDevice` implementation for our vsock device. It handles the virtio-level /// device logic: feature negotiation, device configuration, and device activation. /// The run-time device logic (i.e. event-driven data handling) is implemented by @@ -37,24 +57,6 @@ use crate::{ EpollHelperHandler, VirtioCommon, VirtioDevice, VirtioDeviceType, VirtioInterruptType, EPOLL_HELPER_EVENT_LAST, VIRTIO_F_IN_ORDER, VIRTIO_F_IOMMU_PLATFORM, VIRTIO_F_VERSION_1, }; -use anyhow::anyhow; -use byteorder::{ByteOrder, LittleEndian}; -use seccompiler::SeccompAction; -use serde::{Deserialize, Serialize}; -use std::io; -use std::os::unix::io::AsRawFd; -use std::path::PathBuf; -use std::result; -use std::sync::atomic::AtomicBool; -use std::sync::{Arc, Barrier, RwLock}; -use virtio_queue::Queue; -use virtio_queue::QueueOwnedT; -use virtio_queue::QueueT; -use vm_memory::GuestAddressSpace; -use vm_memory::GuestMemoryAtomic; -use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; -use vm_virtio::AccessPlatform; -use vmm_sys_util::eventfd::EventFd; const QUEUE_SIZE: u16 = 256; const NUM_QUEUES: usize = 3; @@ -522,11 +524,12 @@ impl Migratable for Vsock where B: VsockBackend + Sync + 'static {} #[cfg(test)] mod tests { + use libc::EFD_NONBLOCK; + use super::super::tests::{NoopVirtioInterrupt, TestContext}; use super::super::*; use super::*; use crate::ActivateError; - use libc::EFD_NONBLOCK; #[test] fn test_virtio_device() { diff --git a/virtio-devices/src/vsock/mod.rs b/virtio-devices/src/vsock/mod.rs index 21c44250e..257032955 100644 --- a/virtio-devices/src/vsock/mod.rs +++ b/virtio-devices/src/vsock/mod.rs @@ -13,13 +13,14 @@ mod device; mod packet; mod unix; +use std::os::unix::io::RawFd; + +use packet::VsockPacket; + pub use self::device::Vsock; pub use self::unix::VsockUnixBackend; pub use self::unix::VsockUnixError; -use packet::VsockPacket; -use std::os::unix::io::RawFd; - mod defs { /// Max vsock packet data/buffer size. @@ -162,6 +163,16 @@ pub trait VsockBackend: VsockChannel + VsockEpollListener + Send {} #[cfg(test)] mod tests { + use std::os::unix::io::AsRawFd; + use std::path::PathBuf; + use std::sync::{Arc, RwLock}; + + use libc::EFD_NONBLOCK; + use virtio_bindings::virtio_ring::{VRING_DESC_F_NEXT, VRING_DESC_F_WRITE}; + use vm_memory::{GuestAddress, GuestMemoryAtomic}; + use vm_virtio::queue::testing::VirtQueue as GuestQ; + use vmm_sys_util::eventfd::EventFd; + use super::device::{VsockEpollHandler, RX_QUEUE_EVENT, TX_QUEUE_EVENT}; use super::packet::VSOCK_PKT_HDR_SIZE; use super::*; @@ -169,14 +180,6 @@ mod tests { use crate::epoll_helper::EpollHelperHandler; use crate::EpollHelper; use crate::GuestMemoryMmap; - use libc::EFD_NONBLOCK; - use std::os::unix::io::AsRawFd; - use std::path::PathBuf; - use std::sync::{Arc, RwLock}; - use virtio_bindings::virtio_ring::{VRING_DESC_F_NEXT, VRING_DESC_F_WRITE}; - use vm_memory::{GuestAddress, GuestMemoryAtomic}; - use vm_virtio::queue::testing::VirtQueue as GuestQ; - use vmm_sys_util::eventfd::EventFd; pub struct NoopVirtioInterrupt {} diff --git a/virtio-devices/src/vsock/packet.rs b/virtio-devices/src/vsock/packet.rs index 852cabf6d..094dd20e9 100644 --- a/virtio-devices/src/vsock/packet.rs +++ b/virtio-devices/src/vsock/packet.rs @@ -16,16 +16,17 @@ //! in guest memory. This is done to avoid unnecessarily copying data from guest memory //! to temporary buffers, before passing it on to the vsock backend. -use byteorder::{ByteOrder, LittleEndian}; use std::ops::Deref; use std::sync::Arc; +use byteorder::{ByteOrder, LittleEndian}; +use virtio_queue::DescriptorChain; +use vm_memory::{Address, GuestMemory}; +use vm_virtio::{AccessPlatform, Translatable}; + use super::defs; use super::{Result, VsockError}; use crate::get_host_address_range; -use virtio_queue::DescriptorChain; -use vm_memory::{Address, GuestMemory}; -use vm_virtio::{AccessPlatform, Translatable}; // The vsock packet header is defined by the C struct: // @@ -420,15 +421,16 @@ impl VsockPacket { #[cfg(test)] #[allow(clippy::undocumented_unsafe_blocks)] mod tests { - use super::super::tests::TestContext; - use super::*; - use crate::vsock::defs::MAX_PKT_BUF_SIZE; - use crate::GuestMemoryMmap; use virtio_bindings::virtio_ring::VRING_DESC_F_WRITE; use virtio_queue::QueueOwnedT; use vm_memory::GuestAddress; use vm_virtio::queue::testing::VirtqDesc as GuestQDesc; + use super::super::tests::TestContext; + use super::*; + use crate::vsock::defs::MAX_PKT_BUF_SIZE; + use crate::GuestMemoryMmap; + macro_rules! create_context { ($test_ctx:ident, $handler_ctx:ident) => { let $test_ctx = TestContext::new(); diff --git a/virtio-devices/src/vsock/unix/muxer.rs b/virtio-devices/src/vsock/unix/muxer.rs index c24b59978..5ff31301c 100644 --- a/virtio-devices/src/vsock/unix/muxer.rs +++ b/virtio-devices/src/vsock/unix/muxer.rs @@ -849,12 +849,14 @@ impl VsockMuxer { #[cfg(test)] mod tests { + use std::io::Write; + use std::path::{Path, PathBuf}; + + use virtio_queue::QueueOwnedT; + use super::super::super::csm::defs as csm_defs; use super::super::super::tests::TestContext as VsockTestContext; use super::*; - use std::io::Write; - use std::path::{Path, PathBuf}; - use virtio_queue::QueueOwnedT; const PEER_CID: u32 = 3; const PEER_BUF_ALLOC: u32 = 64 * 1024; diff --git a/virtio-devices/src/watchdog.rs b/virtio-devices/src/watchdog.rs index 13a8fe279..a45b640c8 100644 --- a/virtio-devices/src/watchdog.rs +++ b/virtio-devices/src/watchdog.rs @@ -5,6 +5,23 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-BSD-3-Clause file. +use std::fs::File; +use std::io::{self, Read}; +use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; +use std::result; +use std::sync::atomic::AtomicBool; +use std::sync::{Arc, Barrier, Mutex}; +use std::time::Instant; + +use anyhow::anyhow; +use seccompiler::SeccompAction; +use serde::{Deserialize, Serialize}; +use thiserror::Error; +use virtio_queue::{Queue, QueueT}; +use vm_memory::{Bytes, GuestAddressSpace, GuestMemoryAtomic}; +use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; +use vmm_sys_util::eventfd::EventFd; + use super::Error as DeviceError; use super::{ ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, VirtioCommon, @@ -14,21 +31,6 @@ use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; use crate::GuestMemoryMmap; use crate::{VirtioInterrupt, VirtioInterruptType}; -use anyhow::anyhow; -use seccompiler::SeccompAction; -use serde::{Deserialize, Serialize}; -use std::fs::File; -use std::io::{self, Read}; -use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; -use std::result; -use std::sync::atomic::AtomicBool; -use std::sync::{Arc, Barrier, Mutex}; -use std::time::Instant; -use thiserror::Error; -use virtio_queue::{Queue, QueueT}; -use vm_memory::{Bytes, GuestAddressSpace, GuestMemoryAtomic}; -use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; -use vmm_sys_util::eventfd::EventFd; const QUEUE_SIZE: u16 = 8; const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE]; diff --git a/vm-allocator/src/address.rs b/vm-allocator/src/address.rs index b48de714f..14e0335cd 100644 --- a/vm-allocator/src/address.rs +++ b/vm-allocator/src/address.rs @@ -9,6 +9,7 @@ use std::collections::btree_map::BTreeMap; use std::result; + use vm_memory::{Address, GuestAddress, GuestUsize}; #[derive(Debug)] diff --git a/vm-allocator/src/system.rs b/vm-allocator/src/system.rs index b6215e404..e4031bfa2 100644 --- a/vm-allocator/src/system.rs +++ b/vm-allocator/src/system.rs @@ -13,7 +13,6 @@ use crate::address::AddressAllocator; use crate::gsi::GsiAllocator; #[cfg(target_arch = "x86_64")] use crate::gsi::GsiApic; - use crate::page_size::get_page_size; /// Manages allocating system resources such as address space and interrupt numbers. diff --git a/vm-device/src/interrupt/mod.rs b/vm-device/src/interrupt/mod.rs index 39e1a3ee3..342cbe063 100644 --- a/vm-device/src/interrupt/mod.rs +++ b/vm-device/src/interrupt/mod.rs @@ -57,8 +57,9 @@ //! * The virtual device backend requests the interrupt manager to create an interrupt group //! according to guest configuration information -pub use hypervisor::{InterruptSourceConfig, LegacyIrqSourceConfig, MsiIrqSourceConfig}; use std::sync::Arc; + +pub use hypervisor::{InterruptSourceConfig, LegacyIrqSourceConfig, MsiIrqSourceConfig}; use vmm_sys_util::eventfd::EventFd; /// Reuse std::io::Result to simplify interoperability among crates. diff --git a/vm-migration/src/lib.rs b/vm-migration/src/lib.rs index 39b16aac7..b32dc9bb9 100644 --- a/vm-migration/src/lib.rs +++ b/vm-migration/src/lib.rs @@ -3,11 +3,12 @@ // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause // -use crate::protocol::MemoryRangeTable; use anyhow::anyhow; use serde::{Deserialize, Serialize}; use thiserror::Error; +use crate::protocol::MemoryRangeTable; + pub mod protocol; #[derive(Error, Debug)] diff --git a/vm-migration/src/protocol.rs b/vm-migration/src/protocol.rs index 4789bdf74..274baf039 100644 --- a/vm-migration/src/protocol.rs +++ b/vm-migration/src/protocol.rs @@ -3,11 +3,13 @@ // SPDX-License-Identifier: Apache-2.0 // -use crate::MigratableError; -use serde::{Deserialize, Serialize}; use std::io::{Read, Write}; + +use serde::{Deserialize, Serialize}; use vm_memory::ByteValued; +use crate::MigratableError; + // Migration protocol // 1: Source establishes communication with destination (file socket or TCP connection.) // (The establishment is out of scope.) diff --git a/vm-virtio/src/lib.rs b/vm-virtio/src/lib.rs index 488a5fd42..87dcd0a8d 100644 --- a/vm-virtio/src/lib.rs +++ b/vm-virtio/src/lib.rs @@ -12,6 +12,7 @@ use std::fmt::{self, Debug}; use std::sync::Arc; + use virtio_queue::{Queue, QueueT}; use vm_memory::GuestAddress; diff --git a/vm-virtio/src/queue.rs b/vm-virtio/src/queue.rs index 7bcc5792f..2789ee053 100644 --- a/vm-virtio/src/queue.rs +++ b/vm-virtio/src/queue.rs @@ -11,6 +11,7 @@ pub mod testing { use std::marker::PhantomData; use std::mem; + use virtio_queue::{Queue, QueueT, VirtqUsedElem}; use vm_memory::{bitmap::AtomicBitmap, Address, Bytes, GuestAddress, GuestUsize}; diff --git a/vmm/src/acpi.rs b/vmm/src/acpi.rs index 42b36b38b..434fd16a5 100644 --- a/vmm/src/acpi.rs +++ b/vmm/src/acpi.rs @@ -2,11 +2,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -use crate::cpu::CpuManager; -use crate::device_manager::DeviceManager; -use crate::memory_manager::MemoryManager; -use crate::pci_segment::PciSegment; -use crate::{GuestMemoryMmap, GuestRegionMmap}; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + #[cfg(target_arch = "aarch64")] use acpi_tables::sdt::GenericAddress; use acpi_tables::{rsdp::Rsdp, sdt::Sdt, Aml}; @@ -17,12 +15,16 @@ use arch::DeviceType; use arch::NumaNodes; use bitflags::bitflags; use pci::PciBdf; -use std::sync::{Arc, Mutex}; -use std::time::Instant; use tracer::trace_scoped; use vm_memory::{Address, Bytes, GuestAddress, GuestMemoryRegion}; use zerocopy::AsBytes; +use crate::cpu::CpuManager; +use crate::device_manager::DeviceManager; +use crate::memory_manager::MemoryManager; +use crate::pci_segment::PciSegment; +use crate::{GuestMemoryMmap, GuestRegionMmap}; + /* Values for Type in APIC sub-headers */ #[cfg(target_arch = "x86_64")] pub const ACPI_X2APIC_PROCESSOR: u8 = 9; diff --git a/vmm/src/api/dbus/mod.rs b/vmm/src/api/dbus/mod.rs index 108fd5d9c..08f140863 100644 --- a/vmm/src/api/dbus/mod.rs +++ b/vmm/src/api/dbus/mod.rs @@ -2,6 +2,20 @@ // // SPDX-License-Identifier: Apache-2.0 // +use std::panic::AssertUnwindSafe; +use std::sync::mpsc::Sender; +use std::sync::Arc; +use std::thread; + +use futures::channel::oneshot; +use futures::{executor, FutureExt}; +use hypervisor::HypervisorType; +use seccompiler::{apply_filter, SeccompAction}; +use vmm_sys_util::eventfd::EventFd; +use zbus::fdo::{self, Result}; +use zbus::zvariant::Optional; +use zbus::{interface, ConnectionBuilder}; + use super::{ApiAction, ApiRequest}; #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] use crate::api::VmCoredump; @@ -14,18 +28,6 @@ use crate::api::{ use crate::seccomp_filters::{get_seccomp_filter, Thread}; use crate::{Error as VmmError, Result as VmmResult}; use crate::{NetConfig, VmConfig}; -use futures::channel::oneshot; -use futures::{executor, FutureExt}; -use hypervisor::HypervisorType; -use seccompiler::{apply_filter, SeccompAction}; -use std::panic::AssertUnwindSafe; -use std::sync::mpsc::Sender; -use std::sync::Arc; -use std::thread; -use vmm_sys_util::eventfd::EventFd; -use zbus::fdo::{self, Result}; -use zbus::zvariant::Optional; -use zbus::{interface, ConnectionBuilder}; pub type DBusApiShutdownChannels = (oneshot::Sender<()>, oneshot::Receiver<()>); diff --git a/vmm/src/api/http/http_endpoint.rs b/vmm/src/api/http/http_endpoint.rs index e310dee05..31ddb40bb 100644 --- a/vmm/src/api/http/http_endpoint.rs +++ b/vmm/src/api/http/http_endpoint.rs @@ -4,6 +4,13 @@ // SPDX-License-Identifier: Apache-2.0 // +use std::fs::File; +use std::os::unix::io::IntoRawFd; +use std::sync::mpsc::Sender; + +use micro_http::{Body, Method, Request, Response, StatusCode, Version}; +use vmm_sys_util::eventfd::EventFd; + use crate::api::http::{error_response, EndpointHandler, HttpError}; #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] use crate::api::VmCoredump; @@ -14,11 +21,6 @@ use crate::api::{ VmSendMigration, VmShutdown, VmSnapshot, }; use crate::config::{NetConfig, RestoreConfig}; -use micro_http::{Body, Method, Request, Response, StatusCode, Version}; -use std::fs::File; -use std::os::unix::io::IntoRawFd; -use std::sync::mpsc::Sender; -use vmm_sys_util::eventfd::EventFd; // /api/v1/vm.create handler pub struct VmCreate {} diff --git a/vmm/src/api/http/mod.rs b/vmm/src/api/http/mod.rs index bfa347d37..a105fc0cf 100644 --- a/vmm/src/api/http/mod.rs +++ b/vmm/src/api/http/mod.rs @@ -3,6 +3,26 @@ // SPDX-License-Identifier: Apache-2.0 // +use core::fmt; +use std::collections::BTreeMap; +use std::fmt::Display; +use std::fs::File; +use std::os::unix::io::{IntoRawFd, RawFd}; +use std::os::unix::net::UnixListener; +use std::panic::AssertUnwindSafe; +use std::path::PathBuf; +use std::sync::mpsc::Sender; +use std::thread; + +use hypervisor::HypervisorType; +use micro_http::{ + Body, HttpServer, MediaType, Method, Request, Response, ServerError, StatusCode, Version, +}; +use once_cell::sync::Lazy; +use seccompiler::{apply_filter, SeccompAction}; +use serde_json::Error as SerdeError; +use vmm_sys_util::eventfd::EventFd; + use self::http_endpoint::{VmActionHandler, VmCreate, VmInfo, VmmPing, VmmShutdown}; #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] use crate::api::VmCoredump; @@ -15,24 +35,6 @@ use crate::api::{ use crate::landlock::Landlock; use crate::seccomp_filters::{get_seccomp_filter, Thread}; use crate::{Error as VmmError, Result}; -use core::fmt; -use hypervisor::HypervisorType; -use micro_http::{ - Body, HttpServer, MediaType, Method, Request, Response, ServerError, StatusCode, Version, -}; -use once_cell::sync::Lazy; -use seccompiler::{apply_filter, SeccompAction}; -use serde_json::Error as SerdeError; -use std::collections::BTreeMap; -use std::fmt::Display; -use std::fs::File; -use std::os::unix::io::{IntoRawFd, RawFd}; -use std::os::unix::net::UnixListener; -use std::panic::AssertUnwindSafe; -use std::path::PathBuf; -use std::sync::mpsc::Sender; -use std::thread; -use vmm_sys_util::eventfd::EventFd; pub mod http_endpoint; diff --git a/vmm/src/api/mod.rs b/vmm/src/api/mod.rs index 6fa973631..8a516ffb0 100644 --- a/vmm/src/api/mod.rs +++ b/vmm/src/api/mod.rs @@ -33,11 +33,20 @@ pub mod dbus; pub mod http; +use core::fmt; +use std::fmt::Display; +use std::io; +use std::sync::mpsc::{channel, RecvError, SendError, Sender}; + +use micro_http::Body; +use serde::{Deserialize, Serialize}; +use vm_migration::MigratableError; +use vmm_sys_util::eventfd::EventFd; + #[cfg(feature = "dbus_api")] pub use self::dbus::start_dbus_thread; pub use self::http::start_http_fd_thread; pub use self::http::start_http_path_thread; - use crate::config::{ DeviceConfig, DiskConfig, FsConfig, NetConfig, PmemConfig, RestoreConfig, UserDeviceConfig, VdpaConfig, VmConfig, VsockConfig, @@ -45,14 +54,6 @@ use crate::config::{ use crate::device_tree::DeviceTree; use crate::vm::{Error as VmError, VmState}; use crate::Error as VmmError; -use core::fmt; -use micro_http::Body; -use serde::{Deserialize, Serialize}; -use std::fmt::Display; -use std::io; -use std::sync::mpsc::{channel, RecvError, SendError, Sender}; -use vm_migration::MigratableError; -use vmm_sys_util::eventfd::EventFd; /// API errors are sent back from the VMM API server through the ApiResponse. #[derive(Debug)] diff --git a/vmm/src/config.rs b/vmm/src/config.rs index 204020c3f..f5f7f9c2a 100644 --- a/vmm/src/config.rs +++ b/vmm/src/config.rs @@ -3,21 +3,23 @@ // SPDX-License-Identifier: Apache-2.0 // -use crate::landlock::LandlockAccess; -pub use crate::vm_config::*; -use clap::ArgMatches; -use option_parser::{ - ByteSized, IntegerList, OptionParser, OptionParserError, StringList, Toggle, Tuple, -}; -use serde::{Deserialize, Serialize}; use std::collections::{BTreeSet, HashMap}; use std::fmt; use std::path::PathBuf; use std::result; use std::str::FromStr; + +use clap::ArgMatches; +use option_parser::{ + ByteSized, IntegerList, OptionParser, OptionParserError, StringList, Toggle, Tuple, +}; +use serde::{Deserialize, Serialize}; use thiserror::Error; use virtio_devices::{RateLimiterConfig, TokenBucketConfig}; +use crate::landlock::LandlockAccess; +pub use crate::vm_config::*; + const MAX_NUM_PCI_SEGMENTS: u16 = 96; /// Errors associated with VM configuration parameters. @@ -3104,12 +3106,14 @@ impl Drop for VmConfig { #[cfg(test)] mod tests { - use super::*; - use net_util::MacAddr; use std::fs::File; use std::net::Ipv4Addr; use std::os::unix::io::AsRawFd; + use net_util::MacAddr; + + use super::*; + #[test] fn test_cpu_parsing() -> Result<()> { assert_eq!(CpusConfig::parse("")?, CpusConfig::default()); diff --git a/vmm/src/console_devices.rs b/vmm/src/console_devices.rs index 4ad49eb62..dbe5813e9 100644 --- a/vmm/src/console_devices.rs +++ b/vmm/src/console_devices.rs @@ -10,15 +10,6 @@ // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause // -use crate::sigwinch_listener::listen_for_sigwinch_on_tty; -use crate::vm_config::ConsoleOutputMode; -use crate::Vmm; -use libc::cfmakeraw; -use libc::isatty; -use libc::tcgetattr; -use libc::tcsetattr; -use libc::termios; -use libc::TCSANOW; use std::fs::read_link; use std::fs::File; use std::fs::OpenOptions; @@ -33,8 +24,19 @@ use std::path::PathBuf; use std::result; use std::sync::Arc; use std::sync::Mutex; + +use libc::cfmakeraw; +use libc::isatty; +use libc::tcgetattr; +use libc::tcsetattr; +use libc::termios; +use libc::TCSANOW; use thiserror::Error; +use crate::sigwinch_listener::listen_for_sigwinch_on_tty; +use crate::vm_config::ConsoleOutputMode; +use crate::Vmm; + const TIOCSPTLCK: libc::c_int = 0x4004_5431; const TIOCGPTPEER: libc::c_int = 0x5441; diff --git a/vmm/src/coredump.rs b/vmm/src/coredump.rs index 08c395286..3b4e4db1b 100644 --- a/vmm/src/coredump.rs +++ b/vmm/src/coredump.rs @@ -3,11 +3,12 @@ // SPDX-License-Identifier: Apache-2.0 // +use std::fs::File; +use std::io::Write; + #[cfg(target_arch = "x86_64")] use hypervisor::arch::x86::{DescriptorTable, SegmentRegister}; use linux_loader::elf; -use std::fs::File; -use std::io::Write; use vm_memory::ByteValued; #[derive(Clone)] diff --git a/vmm/src/cpu.rs b/vmm/src/cpu.rs index 5125aac24..82640c305 100644 --- a/vmm/src/cpu.rs +++ b/vmm/src/cpu.rs @@ -11,22 +11,16 @@ // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause // -use crate::config::CpusConfig; +use std::collections::BTreeMap; #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] -use crate::coredump::{ - CpuElf64Writable, CpuSegment, CpuState as DumpCpusState, DumpState, Elf64Writable, - GuestDebuggableError, NoteDescType, X86_64ElfPrStatus, X86_64UserRegs, COREDUMP_NAME_SIZE, - NT_PRSTATUS, -}; -#[cfg(feature = "guest_debug")] -use crate::gdb::{get_raw_tid, Debuggable, DebuggableError}; -#[cfg(target_arch = "x86_64")] -use crate::memory_manager::MemoryManager; -use crate::seccomp_filters::{get_seccomp_filter, Thread}; -#[cfg(target_arch = "x86_64")] -use crate::vm::physical_bits; -use crate::GuestMemoryMmap; -use crate::CPU_MANAGER_SNAPSHOT_ID; +use std::io::Write; +#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] +use std::mem::size_of; +use std::os::unix::thread::JoinHandleExt; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Barrier, Mutex}; +use std::{cmp, io, result, thread}; + use acpi_tables::{aml, sdt::Sdt, Aml}; use anyhow::anyhow; #[cfg(all(target_arch = "aarch64", feature = "guest_debug"))] @@ -67,15 +61,6 @@ use libc::{c_void, siginfo_t}; #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] use linux_loader::elf::Elf64_Nhdr; use seccompiler::{apply_filter, SeccompAction}; -use std::collections::BTreeMap; -#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] -use std::io::Write; -#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] -use std::mem::size_of; -use std::os::unix::thread::JoinHandleExt; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Barrier, Mutex}; -use std::{cmp, io, result, thread}; use thiserror::Error; use tracer::trace_scoped; use vm_device::BusDevice; @@ -91,6 +76,23 @@ use vm_migration::{ use vmm_sys_util::eventfd::EventFd; use vmm_sys_util::signal::{register_signal_handler, SIGRTMIN}; use zerocopy::AsBytes; + +use crate::config::CpusConfig; +#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] +use crate::coredump::{ + CpuElf64Writable, CpuSegment, CpuState as DumpCpusState, DumpState, Elf64Writable, + GuestDebuggableError, NoteDescType, X86_64ElfPrStatus, X86_64UserRegs, COREDUMP_NAME_SIZE, + NT_PRSTATUS, +}; +#[cfg(feature = "guest_debug")] +use crate::gdb::{get_raw_tid, Debuggable, DebuggableError}; +#[cfg(target_arch = "x86_64")] +use crate::memory_manager::MemoryManager; +use crate::seccomp_filters::{get_seccomp_filter, Thread}; +#[cfg(target_arch = "x86_64")] +use crate::vm::physical_bits; +use crate::GuestMemoryMmap; +use crate::CPU_MANAGER_SNAPSHOT_ID; #[cfg(all(target_arch = "aarch64", feature = "guest_debug"))] /// Extract the specified bits of a 64-bit integer. /// For example, to extrace 2 bits from offset 1 (zero based) of `6u64`, @@ -2943,6 +2945,8 @@ mod tests { #[cfg(target_arch = "aarch64")] #[cfg(test)] mod tests { + use std::mem; + use arch::{aarch64::regs, layout}; use hypervisor::kvm::aarch64::is_system_register; use hypervisor::kvm::kvm_bindings::{ @@ -2950,7 +2954,6 @@ mod tests { KVM_REG_SIZE_U64, }; use hypervisor::{arm64_core_reg_id, offset_of}; - use std::mem; #[test] fn test_setup_regs() { diff --git a/vmm/src/device_manager.rs b/vmm/src/device_manager.rs index 9b5fc31a1..90f19cc6a 100644 --- a/vmm/src/device_manager.rs +++ b/vmm/src/device_manager.rs @@ -9,22 +9,17 @@ // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause // -use crate::config::{ - ConsoleOutputMode, DeviceConfig, DiskConfig, FsConfig, NetConfig, PmemConfig, UserDeviceConfig, - VdpaConfig, VhostMode, VmConfig, VsockConfig, -}; -use crate::console_devices::{ConsoleDeviceError, ConsoleInfo, ConsoleOutput}; -use crate::cpu::{CpuManager, CPU_MANAGER_ACPI_SIZE}; -use crate::device_tree::{DeviceNode, DeviceTree}; -use crate::interrupt::LegacyUserspaceInterruptManager; -use crate::interrupt::MsiInterruptManager; -use crate::memory_manager::{Error as MemoryManagerError, MemoryManager, MEMORY_MANAGER_ACPI_SIZE}; -use crate::pci_segment::PciSegment; -use crate::serial_manager::{Error as SerialManagerError, SerialManager}; -use crate::vm_config::DEFAULT_PCI_SEGMENT_APERTURE_WEIGHT; -use crate::GuestRegionMmap; -use crate::PciDeviceInfo; -use crate::{device_node, DEVICE_MANAGER_SNAPSHOT_ID}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::fs::{File, OpenOptions}; +use std::io::{self, stdout, IsTerminal, Seek, SeekFrom}; +use std::num::Wrapping; +use std::os::unix::fs::OpenOptionsExt; +use std::os::unix::io::{AsRawFd, FromRawFd}; +use std::path::PathBuf; +use std::result; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + use acpi_tables::sdt::GenericAddress; use acpi_tables::{aml, Aml}; use anyhow::anyhow; @@ -66,16 +61,6 @@ use pci::{ use rate_limiter::group::RateLimiterGroup; use seccompiler::SeccompAction; use serde::{Deserialize, Serialize}; -use std::collections::{BTreeMap, BTreeSet, HashMap}; -use std::fs::{File, OpenOptions}; -use std::io::{self, stdout, IsTerminal, Seek, SeekFrom}; -use std::num::Wrapping; -use std::os::unix::fs::OpenOptionsExt; -use std::os::unix::io::{AsRawFd, FromRawFd}; -use std::path::PathBuf; -use std::result; -use std::sync::{Arc, Mutex}; -use std::time::Instant; use tracer::trace_scoped; use vfio_ioctls::{VfioContainer, VfioDevice, VfioDeviceFd}; use virtio_devices::transport::VirtioTransport; @@ -106,6 +91,23 @@ use vmm_sys_util::eventfd::EventFd; #[cfg(target_arch = "x86_64")] use {devices::debug_console, devices::legacy::Serial}; +use crate::config::{ + ConsoleOutputMode, DeviceConfig, DiskConfig, FsConfig, NetConfig, PmemConfig, UserDeviceConfig, + VdpaConfig, VhostMode, VmConfig, VsockConfig, +}; +use crate::console_devices::{ConsoleDeviceError, ConsoleInfo, ConsoleOutput}; +use crate::cpu::{CpuManager, CPU_MANAGER_ACPI_SIZE}; +use crate::device_tree::{DeviceNode, DeviceTree}; +use crate::interrupt::LegacyUserspaceInterruptManager; +use crate::interrupt::MsiInterruptManager; +use crate::memory_manager::{Error as MemoryManagerError, MemoryManager, MEMORY_MANAGER_ACPI_SIZE}; +use crate::pci_segment::PciSegment; +use crate::serial_manager::{Error as SerialManagerError, SerialManager}; +use crate::vm_config::DEFAULT_PCI_SEGMENT_APERTURE_WEIGHT; +use crate::GuestRegionMmap; +use crate::PciDeviceInfo; +use crate::{device_node, DEVICE_MANAGER_SNAPSHOT_ID}; + #[cfg(target_arch = "aarch64")] const MMIO_LEN: u64 = 0x1000; diff --git a/vmm/src/device_tree.rs b/vmm/src/device_tree.rs index 66da13d35..51919f4d7 100644 --- a/vmm/src/device_tree.rs +++ b/vmm/src/device_tree.rs @@ -2,14 +2,16 @@ // // SPDX-License-Identifier: Apache-2.0 -use crate::device_manager::PciDeviceHandle; -use pci::PciBdf; -use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; + +use pci::PciBdf; +use serde::{Deserialize, Serialize}; use vm_device::Resource; use vm_migration::Migratable; +use crate::device_manager::PciDeviceHandle; + #[derive(Clone, Serialize, Deserialize)] pub struct DeviceNode { pub id: String, diff --git a/vmm/src/gdb.rs b/vmm/src/gdb.rs index 2d7cacac2..1b06ec974 100644 --- a/vmm/src/gdb.rs +++ b/vmm/src/gdb.rs @@ -5,7 +5,8 @@ // // SPDX-License-Identifier: BSD-3-Clause -use crate::GuestMemoryMmap; +use std::{os::unix::net::UnixListener, sync::mpsc}; + use gdbstub::{ arch::Arch, common::{Signal, Tid}, @@ -33,9 +34,10 @@ use gdbstub_arch::aarch64::AArch64 as GdbArch; use gdbstub_arch::x86::reg::X86_64CoreRegs as CoreRegs; #[cfg(target_arch = "x86_64")] use gdbstub_arch::x86::X86_64_SSE as GdbArch; -use std::{os::unix::net::UnixListener, sync::mpsc}; use vm_memory::{GuestAddress, GuestMemoryAtomic, GuestMemoryError}; +use crate::GuestMemoryMmap; + type ArchUsize = u64; #[derive(Debug)] diff --git a/vmm/src/igvm/igvm_loader.rs b/vmm/src/igvm/igvm_loader.rs index 90d3aabbf..7ba957c23 100644 --- a/vmm/src/igvm/igvm_loader.rs +++ b/vmm/src/igvm/igvm_loader.rs @@ -2,18 +2,6 @@ // // Copyright © 2023, Microsoft Corporation // -use crate::cpu::CpuManager; -use zerocopy::AsBytes; - -use crate::igvm::{ - loader::Loader, BootPageAcceptance, IgvmLoadedInfo, StartupMemoryType, HV_PAGE_SIZE, -}; -use crate::memory_manager::MemoryManager; -use igvm::{snp_defs::SevVmsa, IgvmDirectiveHeader, IgvmFile, IgvmPlatformHeader, IsolationType}; -use igvm_defs::{ - IgvmPageDataType, IgvmPlatformType, IGVM_VHS_PARAMETER, IGVM_VHS_PARAMETER_INSERT, -}; -use mshv_bindings::*; use std::collections::HashMap; use std::ffi::CString; use std::io::Read; @@ -21,12 +9,24 @@ use std::io::Seek; use std::io::SeekFrom; use std::mem::size_of; use std::sync::{Arc, Mutex}; -use thiserror::Error; -#[cfg(feature = "sev_snp")] -use crate::GuestMemoryMmap; +use igvm::{snp_defs::SevVmsa, IgvmDirectiveHeader, IgvmFile, IgvmPlatformHeader, IsolationType}; +use igvm_defs::{ + IgvmPageDataType, IgvmPlatformType, IGVM_VHS_PARAMETER, IGVM_VHS_PARAMETER_INSERT, +}; #[cfg(feature = "sev_snp")] use igvm_defs::{MemoryMapEntryType, IGVM_VHS_MEMORY_MAP_ENTRY}; +use mshv_bindings::*; +use thiserror::Error; +use zerocopy::AsBytes; + +use crate::cpu::CpuManager; +use crate::igvm::{ + loader::Loader, BootPageAcceptance, IgvmLoadedInfo, StartupMemoryType, HV_PAGE_SIZE, +}; +use crate::memory_manager::MemoryManager; +#[cfg(feature = "sev_snp")] +use crate::GuestMemoryMmap; #[derive(Debug, Error)] pub enum Error { diff --git a/vmm/src/igvm/loader.rs b/vmm/src/igvm/loader.rs index 3050c13c3..215c84c50 100644 --- a/vmm/src/igvm/loader.rs +++ b/vmm/src/igvm/loader.rs @@ -2,7 +2,6 @@ // // Copyright © 2023, Microsoft Corporation // -use crate::igvm::{BootPageAcceptance, StartupMemoryType, HV_PAGE_SIZE}; use range_map_vec::{Entry, RangeMap}; use thiserror::Error; use vm_memory::bitmap::AtomicBitmap; @@ -11,6 +10,8 @@ use vm_memory::{ GuestMemoryRegion, }; +use crate::igvm::{BootPageAcceptance, StartupMemoryType, HV_PAGE_SIZE}; + /// Structure to hold the guest memory info/layout to check /// the if the memory is accepted within the layout. /// Adds up the total bytes written to the guest memory diff --git a/vmm/src/interrupt.rs b/vmm/src/interrupt.rs index 09c50b6dd..1655029c8 100644 --- a/vmm/src/interrupt.rs +++ b/vmm/src/interrupt.rs @@ -3,12 +3,13 @@ // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause // -use devices::interrupt_controller::InterruptController; -use hypervisor::IrqRoutingEntry; use std::collections::HashMap; use std::io; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; + +use devices::interrupt_controller::InterruptController; +use hypervisor::IrqRoutingEntry; use vm_allocator::SystemAllocator; use vm_device::interrupt::{ InterruptIndex, InterruptManager, InterruptSourceConfig, InterruptSourceGroup, diff --git a/vmm/src/landlock.rs b/vmm/src/landlock.rs index 3354bfdda..e0bab1661 100644 --- a/vmm/src/landlock.rs +++ b/vmm/src/landlock.rs @@ -2,15 +2,16 @@ // // SPDX-License-Identifier: Apache-2.0 +use std::convert::TryFrom; +use std::io::Error as IoError; +use std::path::PathBuf; + #[cfg(test)] use landlock::make_bitflags; use landlock::{ path_beneath_rules, Access, AccessFs, BitFlags, Ruleset, RulesetAttr, RulesetCreated, RulesetCreatedAttr, RulesetError, ABI, }; -use std::convert::TryFrom; -use std::io::Error as IoError; -use std::path::PathBuf; use thiserror::Error; #[derive(Debug, Error)] diff --git a/vmm/src/lib.rs b/vmm/src/lib.rs index 113f1a037..6f1c1302d 100644 --- a/vmm/src/lib.rs +++ b/vmm/src/lib.rs @@ -8,6 +8,44 @@ extern crate event_monitor; #[macro_use] extern crate log; +use std::collections::HashMap; +use std::fs::File; +use std::io; +use std::io::{stdout, Read, Write}; +use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; +use std::os::unix::net::UnixListener; +use std::os::unix::net::UnixStream; +use std::panic::AssertUnwindSafe; +use std::path::PathBuf; +use std::rc::Rc; +use std::sync::mpsc::{Receiver, RecvError, SendError, Sender}; +use std::sync::{Arc, Mutex}; +use std::time::Instant; +use std::{result, thread}; + +use anyhow::anyhow; +#[cfg(feature = "dbus_api")] +use api::dbus::{DBusApiOptions, DBusApiShutdownChannels}; +use api::http::HttpApiHandle; +use console_devices::{pre_create_console_devices, ConsoleInfo}; +use landlock::LandlockError; +use libc::{tcsetattr, termios, EFD_NONBLOCK, SIGINT, SIGTERM, TCSANOW}; +use memory_manager::MemoryManagerSnapshotData; +use pci::PciBdf; +use seccompiler::{apply_filter, SeccompAction}; +use serde::ser::{SerializeStruct, Serializer}; +use serde::{Deserialize, Serialize}; +use signal_hook::iterator::{Handle, Signals}; +use thiserror::Error; +use tracer::trace_scoped; +use vm_memory::bitmap::AtomicBitmap; +use vm_memory::{ReadVolatile, WriteVolatile}; +use vm_migration::{protocol::*, Migratable}; +use vm_migration::{MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; +use vmm_sys_util::eventfd::EventFd; +use vmm_sys_util::signal::unblock_signal; +use vmm_sys_util::sock_ctrl_msg::ScmSocket; + use crate::api::{ ApiRequest, ApiResponse, RequestHandler, VmInfoResponse, VmReceiveMigrationData, VmSendMigrationData, VmmPingResponse, @@ -25,42 +63,6 @@ use crate::migration::get_vm_snapshot; use crate::migration::{recv_vm_config, recv_vm_state}; use crate::seccomp_filters::{get_seccomp_filter, Thread}; use crate::vm::{Error as VmError, Vm, VmState}; -use anyhow::anyhow; -#[cfg(feature = "dbus_api")] -use api::dbus::{DBusApiOptions, DBusApiShutdownChannels}; -use api::http::HttpApiHandle; -use console_devices::{pre_create_console_devices, ConsoleInfo}; -use landlock::LandlockError; -use libc::{tcsetattr, termios, EFD_NONBLOCK, SIGINT, SIGTERM, TCSANOW}; -use memory_manager::MemoryManagerSnapshotData; -use pci::PciBdf; -use seccompiler::{apply_filter, SeccompAction}; -use serde::ser::{SerializeStruct, Serializer}; -use serde::{Deserialize, Serialize}; -use signal_hook::iterator::{Handle, Signals}; -use std::collections::HashMap; -use std::fs::File; -use std::io; -use std::io::{stdout, Read, Write}; -use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; -use std::os::unix::net::UnixListener; -use std::os::unix::net::UnixStream; -use std::panic::AssertUnwindSafe; -use std::path::PathBuf; -use std::rc::Rc; -use std::sync::mpsc::{Receiver, RecvError, SendError, Sender}; -use std::sync::{Arc, Mutex}; -use std::time::Instant; -use std::{result, thread}; -use thiserror::Error; -use tracer::trace_scoped; -use vm_memory::bitmap::AtomicBitmap; -use vm_memory::{ReadVolatile, WriteVolatile}; -use vm_migration::{protocol::*, Migratable}; -use vm_migration::{MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; -use vmm_sys_util::eventfd::EventFd; -use vmm_sys_util::signal::unblock_signal; -use vmm_sys_util::sock_ctrl_msg::ScmSocket; mod acpi; pub mod api; @@ -2143,14 +2145,15 @@ const DEVICE_MANAGER_SNAPSHOT_ID: &str = "device-manager"; #[cfg(test)] mod unit_tests { - use super::*; - #[cfg(target_arch = "x86_64")] - use crate::config::DebugConsoleConfig; use config::{ ConsoleConfig, ConsoleOutputMode, CpusConfig, HotplugMethod, MemoryConfig, PayloadConfig, RngConfig, }; + use super::*; + #[cfg(target_arch = "x86_64")] + use crate::config::DebugConsoleConfig; + fn create_dummy_vmm() -> Vmm { Vmm::new( VmmVersionInfo::new("dummy", "dummy"), diff --git a/vmm/src/memory_manager.rs b/vmm/src/memory_manager.rs index 798f641ef..1e94af64d 100644 --- a/vmm/src/memory_manager.rs +++ b/vmm/src/memory_manager.rs @@ -2,29 +2,6 @@ // // SPDX-License-Identifier: Apache-2.0 // -#[cfg(target_arch = "x86_64")] -use crate::config::SgxEpcConfig; -use crate::config::{HotplugMethod, MemoryConfig, MemoryZoneConfig}; -#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] -use crate::coredump::{ - CoredumpMemoryRegion, CoredumpMemoryRegions, DumpState, GuestDebuggableError, -}; -use crate::migration::url_to_path; -use crate::MEMORY_MANAGER_SNAPSHOT_ID; -use crate::{GuestMemoryMmap, GuestRegionMmap}; -use acpi_tables::{aml, Aml}; -use anyhow::anyhow; -#[cfg(target_arch = "x86_64")] -use arch::x86_64::{SgxEpcRegion, SgxEpcSection}; -use arch::RegionType; -#[cfg(target_arch = "x86_64")] -use devices::ioapic; -#[cfg(target_arch = "aarch64")] -use hypervisor::HypervisorVmError; -use libc::_SC_NPROCESSORS_ONLN; -#[cfg(target_arch = "x86_64")] -use libc::{MAP_NORESERVE, MAP_POPULATE, MAP_SHARED, PROT_READ, PROT_WRITE}; -use serde::{Deserialize, Serialize}; #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] use std::collections::BTreeMap; use std::collections::HashMap; @@ -38,6 +15,20 @@ use std::path::PathBuf; use std::result; use std::sync::{Arc, Barrier, Mutex}; use std::{ffi, thread}; + +use acpi_tables::{aml, Aml}; +use anyhow::anyhow; +#[cfg(target_arch = "x86_64")] +use arch::x86_64::{SgxEpcRegion, SgxEpcSection}; +use arch::RegionType; +#[cfg(target_arch = "x86_64")] +use devices::ioapic; +#[cfg(target_arch = "aarch64")] +use hypervisor::HypervisorVmError; +use libc::_SC_NPROCESSORS_ONLN; +#[cfg(target_arch = "x86_64")] +use libc::{MAP_NORESERVE, MAP_POPULATE, MAP_SHARED, PROT_READ, PROT_WRITE}; +use serde::{Deserialize, Serialize}; use tracer::trace_scoped; use virtio_devices::BlocksState; #[cfg(target_arch = "x86_64")] @@ -56,6 +47,17 @@ use vm_migration::{ Snapshot, SnapshotData, Snapshottable, Transportable, }; +#[cfg(target_arch = "x86_64")] +use crate::config::SgxEpcConfig; +use crate::config::{HotplugMethod, MemoryConfig, MemoryZoneConfig}; +#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] +use crate::coredump::{ + CoredumpMemoryRegion, CoredumpMemoryRegions, DumpState, GuestDebuggableError, +}; +use crate::migration::url_to_path; +use crate::MEMORY_MANAGER_SNAPSHOT_ID; +use crate::{GuestMemoryMmap, GuestRegionMmap}; + pub const MEMORY_MANAGER_ACPI_SIZE: usize = 0x18; const DEFAULT_MEMORY_ZONE: &str = "mem0"; diff --git a/vmm/src/migration.rs b/vmm/src/migration.rs index 7e7b53770..4edd71da2 100644 --- a/vmm/src/migration.rs +++ b/vmm/src/migration.rs @@ -2,15 +2,17 @@ // // SPDX-License-Identifier: Apache-2.0 -#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] -use crate::coredump::GuestDebuggableError; -use crate::{config::VmConfig, vm::VmSnapshot}; -use anyhow::anyhow; use std::fs::File; use std::io::Read; use std::path::PathBuf; + +use anyhow::anyhow; use vm_migration::{MigratableError, Snapshot}; +#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] +use crate::coredump::GuestDebuggableError; +use crate::{config::VmConfig, vm::VmSnapshot}; + pub const SNAPSHOT_STATE_FILE: &str = "state.json"; pub const SNAPSHOT_CONFIG_FILE: &str = "config.json"; diff --git a/vmm/src/pci_segment.rs b/vmm/src/pci_segment.rs index 556a44aba..68769178f 100644 --- a/vmm/src/pci_segment.rs +++ b/vmm/src/pci_segment.rs @@ -9,17 +9,19 @@ // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause // -use crate::device_manager::{AddressManager, DeviceManagerError, DeviceManagerResult}; +use std::sync::{Arc, Mutex}; + use acpi_tables::{aml, Aml}; use arch::layout; use pci::{DeviceRelocation, PciBdf, PciBus, PciConfigMmio, PciRoot}; #[cfg(target_arch = "x86_64")] use pci::{PciConfigIo, PCI_CONFIG_IO_PORT, PCI_CONFIG_IO_PORT_SIZE}; -use std::sync::{Arc, Mutex}; use uuid::Uuid; use vm_allocator::AddressAllocator; use vm_device::BusDeviceSync; +use crate::device_manager::{AddressManager, DeviceManagerError, DeviceManagerResult}; + pub(crate) struct PciSegment { pub(crate) id: u16, pub(crate) pci_bus: Arc>, diff --git a/vmm/src/seccomp_filters.rs b/vmm/src/seccomp_filters.rs index 3879c927a..17fc93d14 100644 --- a/vmm/src/seccomp_filters.rs +++ b/vmm/src/seccomp_filters.rs @@ -148,12 +148,11 @@ mod kvm { pub const KVM_NMI: u64 = 0xae9a; } -#[cfg(feature = "kvm")] -use kvm::*; - // MSHV IOCTL code. This is unstable until the kernel code has been declared stable. #[cfg(feature = "mshv")] use hypervisor::mshv::mshv_ioctls::*; +#[cfg(feature = "kvm")] +use kvm::*; #[cfg(feature = "mshv")] fn create_vmm_ioctl_seccomp_rule_common_mshv() -> Result, BackendError> { diff --git a/vmm/src/serial_manager.rs b/vmm/src/serial_manager.rs index 2251c20ab..ac1bbc058 100644 --- a/vmm/src/serial_manager.rs +++ b/vmm/src/serial_manager.rs @@ -3,13 +3,6 @@ // SPDX-License-Identifier: Apache-2.0 // -use crate::console_devices::ConsoleOutput; -#[cfg(target_arch = "aarch64")] -use devices::legacy::Pl011; -#[cfg(target_arch = "x86_64")] -use devices::legacy::Serial; -use libc::EFD_NONBLOCK; -use serial_buffer::SerialBuffer; use std::fs::File; use std::io::Read; use std::net::Shutdown; @@ -20,9 +13,18 @@ use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::{io, result, thread}; + +#[cfg(target_arch = "aarch64")] +use devices::legacy::Pl011; +#[cfg(target_arch = "x86_64")] +use devices::legacy::Serial; +use libc::EFD_NONBLOCK; +use serial_buffer::SerialBuffer; use thiserror::Error; use vmm_sys_util::eventfd::EventFd; +use crate::console_devices::ConsoleOutput; + #[derive(Debug, Error)] pub enum Error { /// Cannot clone File. diff --git a/vmm/src/sigwinch_listener.rs b/vmm/src/sigwinch_listener.rs index 08137aa53..ac87cf27e 100644 --- a/vmm/src/sigwinch_listener.rs +++ b/vmm/src/sigwinch_listener.rs @@ -1,16 +1,6 @@ // Copyright 2021, 2023 Alyssa Ross // SPDX-License-Identifier: Apache-2.0 -use crate::clone3::{clone3, clone_args, CLONE_CLEAR_SIGHAND}; -use crate::seccomp_filters::{get_seccomp_filter, Thread}; -use arch::_NSIG; -use hypervisor::HypervisorType; -use libc::{ - c_int, c_void, close, fork, getpgrp, ioctl, pipe2, poll, pollfd, setsid, sigemptyset, - siginfo_t, signal, sigprocmask, syscall, tcgetpgrp, tcsetpgrp, SYS_close_range, EINVAL, ENOSYS, - ENOTTY, O_CLOEXEC, POLLERR, SIGCHLD, SIGWINCH, SIG_DFL, SIG_SETMASK, STDERR_FILENO, TIOCSCTTY, -}; -use seccompiler::{apply_filter, BpfProgram, SeccompAction}; use std::cell::RefCell; use std::collections::BTreeSet; use std::fs::{read_dir, File}; @@ -21,8 +11,20 @@ use std::mem::MaybeUninit; use std::os::unix::prelude::*; use std::process::exit; use std::ptr::null_mut; + +use arch::_NSIG; +use hypervisor::HypervisorType; +use libc::{ + c_int, c_void, close, fork, getpgrp, ioctl, pipe2, poll, pollfd, setsid, sigemptyset, + siginfo_t, signal, sigprocmask, syscall, tcgetpgrp, tcsetpgrp, SYS_close_range, EINVAL, ENOSYS, + ENOTTY, O_CLOEXEC, POLLERR, SIGCHLD, SIGWINCH, SIG_DFL, SIG_SETMASK, STDERR_FILENO, TIOCSCTTY, +}; +use seccompiler::{apply_filter, BpfProgram, SeccompAction}; use vmm_sys_util::signal::register_signal_handler; +use crate::clone3::{clone3, clone_args, CLONE_CLEAR_SIGHAND}; +use crate::seccomp_filters::{get_seccomp_filter, Thread}; + thread_local! { // The tty file descriptor is stored in a global variable so it // can be accessed by a signal handler. diff --git a/vmm/src/vm.rs b/vmm/src/vm.rs index 2013dda28..00fe42af0 100644 --- a/vmm/src/vm.rs +++ b/vmm/src/vm.rs @@ -11,36 +11,20 @@ // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause // -use crate::config::{ - add_to_config, DeviceConfig, DiskConfig, FsConfig, HotplugMethod, NetConfig, PmemConfig, - UserDeviceConfig, ValidationError, VdpaConfig, VmConfig, VsockConfig, -}; -use crate::config::{NumaConfig, PayloadConfig}; -use crate::console_devices::{ConsoleDeviceError, ConsoleInfo}; +use std::cmp; +use std::collections::BTreeMap; +use std::collections::HashMap; +use std::fs::{File, OpenOptions}; +use std::io::{self, Seek, SeekFrom, Write}; #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] -use crate::coredump::{ - CpuElf64Writable, DumpState, Elf64Writable, GuestDebuggable, GuestDebuggableError, NoteDescType, -}; -use crate::cpu; -use crate::device_manager::{DeviceManager, DeviceManagerError}; -use crate::device_tree::DeviceTree; -#[cfg(feature = "guest_debug")] -use crate::gdb::{Debuggable, DebuggableError, GdbRequestPayload, GdbResponsePayload}; -#[cfg(feature = "igvm")] -use crate::igvm::igvm_loader; -use crate::landlock::LandlockError; -use crate::memory_manager::{ - Error as MemoryManagerError, MemoryManager, MemoryManagerSnapshotData, -}; -#[cfg(target_arch = "x86_64")] -use crate::migration::get_vm_snapshot; -#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] -use crate::migration::url_to_file; -use crate::migration::{url_to_path, SNAPSHOT_CONFIG_FILE, SNAPSHOT_STATE_FILE}; -use crate::GuestMemoryMmap; -use crate::{ - PciDeviceInfo, CPU_MANAGER_SNAPSHOT_ID, DEVICE_MANAGER_SNAPSHOT_ID, MEMORY_MANAGER_SNAPSHOT_ID, -}; +use std::mem::size_of; +use std::num::Wrapping; +use std::ops::Deref; +use std::os::unix::net::UnixStream; +use std::sync::{Arc, Mutex, RwLock}; +use std::time::Instant; +use std::{result, str, thread}; + use anyhow::anyhow; use arch::get_host_cpu_phys_bits; #[cfg(target_arch = "x86_64")] @@ -72,19 +56,6 @@ use linux_loader::loader::pe::Error::InvalidImageMagicNumber; use linux_loader::loader::KernelLoader; use seccompiler::SeccompAction; use serde::{Deserialize, Serialize}; -use std::cmp; -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::fs::{File, OpenOptions}; -use std::io::{self, Seek, SeekFrom, Write}; -#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] -use std::mem::size_of; -use std::num::Wrapping; -use std::ops::Deref; -use std::os::unix::net::UnixStream; -use std::sync::{Arc, Mutex, RwLock}; -use std::time::Instant; -use std::{result, str, thread}; use thiserror::Error; use tracer::trace_scoped; use vm_device::Bus; @@ -101,6 +72,37 @@ use vm_migration::{ use vmm_sys_util::eventfd::EventFd; use vmm_sys_util::sock_ctrl_msg::ScmSocket; +use crate::config::{ + add_to_config, DeviceConfig, DiskConfig, FsConfig, HotplugMethod, NetConfig, PmemConfig, + UserDeviceConfig, ValidationError, VdpaConfig, VmConfig, VsockConfig, +}; +use crate::config::{NumaConfig, PayloadConfig}; +use crate::console_devices::{ConsoleDeviceError, ConsoleInfo}; +#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] +use crate::coredump::{ + CpuElf64Writable, DumpState, Elf64Writable, GuestDebuggable, GuestDebuggableError, NoteDescType, +}; +use crate::cpu; +use crate::device_manager::{DeviceManager, DeviceManagerError}; +use crate::device_tree::DeviceTree; +#[cfg(feature = "guest_debug")] +use crate::gdb::{Debuggable, DebuggableError, GdbRequestPayload, GdbResponsePayload}; +#[cfg(feature = "igvm")] +use crate::igvm::igvm_loader; +use crate::landlock::LandlockError; +use crate::memory_manager::{ + Error as MemoryManagerError, MemoryManager, MemoryManagerSnapshotData, +}; +#[cfg(target_arch = "x86_64")] +use crate::migration::get_vm_snapshot; +#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] +use crate::migration::url_to_file; +use crate::migration::{url_to_path, SNAPSHOT_CONFIG_FILE, SNAPSHOT_STATE_FILE}; +use crate::GuestMemoryMmap; +use crate::{ + PciDeviceInfo, CPU_MANAGER_SNAPSHOT_ID, DEVICE_MANAGER_SNAPSHOT_ID, MEMORY_MANAGER_SNAPSHOT_ID, +}; + /// Errors associated with VM management #[derive(Debug, Error)] pub enum Error { @@ -3124,12 +3126,13 @@ mod tests { #[cfg(target_arch = "aarch64")] #[cfg(test)] mod tests { - use super::*; use arch::aarch64::fdt::create_fdt; use arch::aarch64::layout; use arch::{DeviceType, MmioDeviceInfo}; use devices::gic::Gic; + use super::*; + const LEN: u64 = 4096; #[test] diff --git a/vmm/src/vm_config.rs b/vmm/src/vm_config.rs index e5409496d..408b0ca0b 100644 --- a/vmm/src/vm_config.rs +++ b/vmm/src/vm_config.rs @@ -2,12 +2,14 @@ // // SPDX-License-Identifier: Apache-2.0 // -use crate::{landlock::LandlockError, Landlock}; +use std::{fs, net::Ipv4Addr, path::PathBuf, result}; + use net_util::MacAddr; use serde::{Deserialize, Serialize}; -use std::{fs, net::Ipv4Addr, path::PathBuf, result}; use virtio_devices::RateLimiterConfig; +use crate::{landlock::LandlockError, Landlock}; + pub type LandlockResult = result::Result; /// Trait to apply Landlock on VmConfig elements