diff --git a/.rustfmt.toml b/.rustfmt.toml index 754d7badf..394a1065b 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1,4 +1,4 @@ -edition = "2021" +edition = "2024" group_imports="StdExternalCrate" imports_granularity="Module" diff --git a/arch/src/aarch64/mod.rs b/arch/src/aarch64/mod.rs index f7a6c3653..f98942b83 100644 --- a/arch/src/aarch64/mod.rs +++ b/arch/src/aarch64/mod.rs @@ -15,7 +15,7 @@ use std::sync::{Arc, Mutex}; use hypervisor::arch::aarch64::gic::Vgic; use hypervisor::arch::aarch64::regs::MPIDR_EL1; -use log::{log_enabled, Level}; +use log::{Level, log_enabled}; use thiserror::Error; use vm_memory::{Address, GuestAddress, GuestMemory, GuestMemoryAtomic}; diff --git a/arch/src/lib.rs b/arch/src/lib.rs index 2413fe223..36fa20f13 100644 --- a/arch/src/lib.rs +++ b/arch/src/lib.rs @@ -81,9 +81,9 @@ pub mod aarch64; #[cfg(target_arch = "aarch64")] pub use aarch64::{ - arch_memory_regions, configure_system, configure_vcpu, fdt::DeviceInfoForFdt, - get_host_cpu_phys_bits, initramfs_load_addr, layout, layout::CMDLINE_MAX_SIZE, - layout::IRQ_BASE, uefi, EntryPoint, _NSIG, + _NSIG, EntryPoint, arch_memory_regions, configure_system, configure_vcpu, + fdt::DeviceInfoForFdt, get_host_cpu_phys_bits, initramfs_load_addr, layout, + layout::CMDLINE_MAX_SIZE, layout::IRQ_BASE, uefi, }; /// Module for riscv64 related functionality. @@ -92,9 +92,9 @@ pub mod riscv64; #[cfg(target_arch = "riscv64")] pub use riscv64::{ - arch_memory_regions, configure_system, configure_vcpu, fdt::DeviceInfoForFdt, - get_host_cpu_phys_bits, initramfs_load_addr, layout, layout::CMDLINE_MAX_SIZE, - layout::IRQ_BASE, uefi, EntryPoint, _NSIG, + _NSIG, EntryPoint, arch_memory_regions, configure_system, configure_vcpu, + fdt::DeviceInfoForFdt, get_host_cpu_phys_bits, initramfs_load_addr, layout, + layout::CMDLINE_MAX_SIZE, layout::IRQ_BASE, uefi, }; #[cfg(target_arch = "x86_64")] @@ -102,10 +102,9 @@ pub mod x86_64; #[cfg(target_arch = "x86_64")] pub use x86_64::{ - arch_memory_regions, configure_system, configure_vcpu, generate_common_cpuid, - generate_ram_ranges, get_host_cpu_phys_bits, initramfs_load_addr, layout, - layout::CMDLINE_MAX_SIZE, layout::CMDLINE_START, regs, CpuidConfig, CpuidFeatureEntry, - EntryPoint, _NSIG, + _NSIG, CpuidConfig, CpuidFeatureEntry, EntryPoint, arch_memory_regions, configure_system, + configure_vcpu, generate_common_cpuid, generate_ram_ranges, get_host_cpu_phys_bits, + initramfs_load_addr, layout, layout::CMDLINE_MAX_SIZE, layout::CMDLINE_START, regs, }; /// Safe wrapper for `sysconf(_SC_PAGESIZE)`. diff --git a/arch/src/riscv64/mod.rs b/arch/src/riscv64/mod.rs index 62554bd1a..6a0342b3c 100644 --- a/arch/src/riscv64/mod.rs +++ b/arch/src/riscv64/mod.rs @@ -15,7 +15,7 @@ use std::fmt::Debug; use std::sync::{Arc, Mutex}; use hypervisor::arch::riscv64::aia::Vaia; -use log::{log_enabled, Level}; +use log::{Level, log_enabled}; use thiserror::Error; use vm_memory::{Address, GuestAddress, GuestMemory, GuestMemoryAtomic}; diff --git a/arch/src/x86_64/mod.rs b/arch/src/x86_64/mod.rs index 83cb0876c..71edd4508 100644 --- a/arch/src/x86_64/mod.rs +++ b/arch/src/x86_64/mod.rs @@ -14,7 +14,7 @@ mod mptable; pub mod regs; use std::mem; -use hypervisor::arch::x86::{CpuIdEntry, CPUID_FLAG_VALID_INDEX}; +use hypervisor::arch::x86::{CPUID_FLAG_VALID_INDEX, CpuIdEntry}; use hypervisor::{CpuVendor, HypervisorCpuError, HypervisorError}; use linux_loader::loader::bootparam::{boot_params, setup_header}; use linux_loader::loader::elf::start_info::{ @@ -525,9 +525,13 @@ impl CpuidFeatureEntry { error!( "Detected incompatible CPUID entry: leaf={:#02x} (subleaf={:#02x}), register='{:?}', \ compatible_check='{:?}', source VM feature='{:#04x}', destination VM feature'{:#04x}'.", - entry.function, entry.index, entry.feature_reg, - entry.compatible_check, src_vm_feature, dest_vm_feature - ); + entry.function, + entry.index, + entry.feature_reg, + entry.compatible_check, + src_vm_feature, + dest_vm_feature + ); compatible = false; } diff --git a/arch/src/x86_64/mptable.rs b/arch/src/x86_64/mptable.rs index d688e4137..2e2669b38 100644 --- a/arch/src/x86_64/mptable.rs +++ b/arch/src/x86_64/mptable.rs @@ -12,9 +12,9 @@ use thiserror::Error; use vm_memory::{Address, ByteValued, Bytes, GuestAddress, GuestMemory, GuestMemoryError}; use super::MAX_SUPPORTED_CPUS_LEGACY; +use crate::GuestMemoryMmap; 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: diff --git a/arch/src/x86_64/smbios.rs b/arch/src/x86_64/smbios.rs index 55a7df1e7..7d867a43c 100644 --- a/arch/src/x86_64/smbios.rs +++ b/arch/src/x86_64/smbios.rs @@ -12,8 +12,8 @@ use thiserror::Error; use uuid::Uuid; use vm_memory::{Address, ByteValued, Bytes, GuestAddress}; -use crate::layout::SMBIOS_START; use crate::GuestMemoryMmap; +use crate::layout::SMBIOS_START; #[derive(Debug, Error)] pub enum Error { diff --git a/block/src/fixed_vhd.rs b/block/src/fixed_vhd.rs index 22ef4dd80..379005ae2 100644 --- a/block/src/fixed_vhd.rs +++ b/block/src/fixed_vhd.rs @@ -6,8 +6,8 @@ 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; +use crate::vhd::VhdFooter; #[derive(Debug)] pub struct FixedVhd { diff --git a/block/src/fixed_vhd_sync.rs b/block/src/fixed_vhd_sync.rs index b1f2118f1..c12571069 100644 --- a/block/src/fixed_vhd_sync.rs +++ b/block/src/fixed_vhd_sync.rs @@ -7,12 +7,12 @@ use std::os::unix::io::{AsRawFd, RawFd}; use vmm_sys_util::eventfd::EventFd; +use crate::BlockBackend; use crate::async_io::{ AsyncIo, AsyncIoError, AsyncIoResult, BorrowedDiskFd, DiskFile, DiskFileError, DiskFileResult, }; use crate::fixed_vhd::FixedVhd; use crate::raw_sync::RawFileSync; -use crate::BlockBackend; pub struct FixedVhdDiskSync(FixedVhd); diff --git a/block/src/lib.rs b/block/src/lib.rs index 3cca348b3..5599258e3 100644 --- a/block/src/lib.rs +++ b/block/src/lib.rs @@ -31,7 +31,7 @@ pub mod vhd; pub mod vhdx; pub mod vhdx_sync; -use std::alloc::{alloc_zeroed, dealloc, Layout}; +use std::alloc::{Layout, alloc_zeroed, dealloc}; use std::collections::VecDeque; use std::fmt::Debug; use std::fs::File; @@ -44,8 +44,8 @@ use std::time::Instant; use std::{cmp, result}; #[cfg(feature = "io_uring")] -use io_uring::{opcode, IoUring, Probe}; -use libc::{ioctl, S_IFBLK, S_IFMT}; +use io_uring::{IoUring, Probe, opcode}; +use libc::{S_IFBLK, S_IFMT, ioctl}; use serde::{Deserialize, Serialize}; use smallvec::SmallVec; use thiserror::Error; diff --git a/block/src/qcow/mod.rs b/block/src/qcow/mod.rs index 4d84918e9..da6814691 100644 --- a/block/src/qcow/mod.rs +++ b/block/src/qcow/mod.rs @@ -24,11 +24,11 @@ use vmm_sys_util::file_traits::{FileSetLen, FileSync}; use vmm_sys_util::seek_hole::SeekHole; use vmm_sys_util::write_zeroes::{PunchHole, WriteZeroesAt}; +use crate::BlockBackend; use crate::qcow::qcow_raw_file::QcowRawFile; pub use crate::qcow::raw_file::RawFile; use crate::qcow::refcount::RefCount; use crate::qcow::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; diff --git a/block/src/qcow/raw_file.rs b/block/src/qcow/raw_file.rs index 67bc99fca..f0eff54df 100644 --- a/block/src/qcow/raw_file.rs +++ b/block/src/qcow/raw_file.rs @@ -8,7 +8,7 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use std::alloc::{alloc_zeroed, dealloc, Layout}; +use std::alloc::{Layout, alloc_zeroed, dealloc}; use std::fs::{File, Metadata}; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::os::unix::io::{AsRawFd, RawFd}; diff --git a/block/src/qcow/vec_cache.rs b/block/src/qcow/vec_cache.rs index 67068fdde..76e5d4443 100644 --- a/block/src/qcow/vec_cache.rs +++ b/block/src/qcow/vec_cache.rs @@ -4,8 +4,8 @@ // // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause -use std::collections::hash_map::IterMut; use std::collections::HashMap; +use std::collections::hash_map::IterMut; use std::io; use std::ops::{Index, IndexMut}; use std::slice::SliceIndex; diff --git a/block/src/qcow_sync.rs b/block/src/qcow_sync.rs index 332db2486..cd6a1fb77 100644 --- a/block/src/qcow_sync.rs +++ b/block/src/qcow_sync.rs @@ -9,11 +9,11 @@ use std::os::fd::AsRawFd; use vmm_sys_util::eventfd::EventFd; +use crate::AsyncAdaptor; use crate::async_io::{ AsyncIo, AsyncIoResult, BorrowedDiskFd, DiskFile, DiskFileError, DiskFileResult, }; use crate::qcow::{QcowFile, RawFile, Result as QcowResult}; -use crate::AsyncAdaptor; pub struct QcowDiskSync { qcow_file: QcowFile, diff --git a/block/src/raw_async.rs b/block/src/raw_async.rs index b3c9882fb..1a582073b 100644 --- a/block/src/raw_async.rs +++ b/block/src/raw_async.rs @@ -6,7 +6,7 @@ use std::fs::File; use std::io::{Error, Seek, SeekFrom}; use std::os::unix::io::{AsRawFd, RawFd}; -use io_uring::{opcode, types, IoUring}; +use io_uring::{IoUring, opcode, types}; use vmm_sys_util::eventfd::EventFd; use crate::async_io::{ diff --git a/block/src/raw_async_aio.rs b/block/src/raw_async_aio.rs index 9ef0c6261..9a74fa41d 100644 --- a/block/src/raw_async_aio.rs +++ b/block/src/raw_async_aio.rs @@ -12,10 +12,10 @@ use std::os::unix::io::{AsRawFd, RawFd}; use vmm_sys_util::aio; use vmm_sys_util::eventfd::EventFd; +use crate::DiskTopology; use crate::async_io::{ AsyncIo, AsyncIoError, AsyncIoResult, BorrowedDiskFd, DiskFile, DiskFileError, DiskFileResult, }; -use crate::DiskTopology; pub struct RawFileDiskAio { file: File, diff --git a/block/src/raw_sync.rs b/block/src/raw_sync.rs index 54ba1acca..6b98147e1 100644 --- a/block/src/raw_sync.rs +++ b/block/src/raw_sync.rs @@ -9,10 +9,10 @@ use std::os::unix::io::{AsRawFd, RawFd}; use vmm_sys_util::eventfd::EventFd; +use crate::DiskTopology; use crate::async_io::{ AsyncIo, AsyncIoError, AsyncIoResult, BorrowedDiskFd, DiskFile, DiskFileError, DiskFileResult, }; -use crate::DiskTopology; pub struct RawFileDiskSync { file: File, diff --git a/block/src/vhd.rs b/block/src/vhd.rs index 2cc65ca0b..6659ed038 100644 --- a/block/src/vhd.rs +++ b/block/src/vhd.rs @@ -5,7 +5,7 @@ use std::fs::File; use std::io::{Seek, SeekFrom}; -use crate::{read_aligned_block_size, DiskTopology}; +use crate::{DiskTopology, read_aligned_block_size}; #[derive(Clone, Copy)] pub struct VhdFooter { @@ -123,7 +123,7 @@ mod tests { use vmm_sys_util::tempfile::TempFile; - use super::{is_fixed_vhd, VhdFooter}; + use super::{VhdFooter, is_fixed_vhd}; fn valid_fixed_vhd_footer() -> Vec { vec![ diff --git a/block/src/vhdx/mod.rs b/block/src/vhdx/mod.rs index 45974c5a3..d46905d93 100644 --- a/block/src/vhdx/mod.rs +++ b/block/src/vhdx/mod.rs @@ -12,11 +12,11 @@ use remain::sorted; use thiserror::Error; use uuid::Uuid; +use crate::BlockBackend; use crate::vhdx::vhdx_bat::{BatEntry, VhdxBatError}; use crate::vhdx::vhdx_header::{RegionInfo, RegionTableEntry, VhdxHeader, VhdxHeaderError}; use crate::vhdx::vhdx_io::VhdxIoError; use crate::vhdx::vhdx_metadata::{DiskSpec, VhdxMetadataError}; -use crate::BlockBackend; mod vhdx_bat; mod vhdx_header; diff --git a/block/src/vhdx/vhdx_io.rs b/block/src/vhdx/vhdx_io.rs index 30e383787..14feac8d9 100644 --- a/block/src/vhdx/vhdx_io.rs +++ b/block/src/vhdx/vhdx_io.rs @@ -35,9 +35,7 @@ pub enum VhdxIoError { pub type Result = std::result::Result; macro_rules! align { - ($n:expr, $align:expr) => {{ - $n.div_ceil($align) * $align - }}; + ($n:expr, $align:expr) => {{ $n.div_ceil($align) * $align }}; } #[derive(Default)] diff --git a/block/src/vhdx_sync.rs b/block/src/vhdx_sync.rs index fd5888e63..01bcbf5e7 100644 --- a/block/src/vhdx_sync.rs +++ b/block/src/vhdx_sync.rs @@ -8,11 +8,11 @@ use std::os::fd::AsRawFd; use vmm_sys_util::eventfd::EventFd; +use crate::AsyncAdaptor; use crate::async_io::{ AsyncIo, AsyncIoResult, BorrowedDiskFd, DiskFile, DiskFileError, DiskFileResult, }; use crate::vhdx::{Result as VhdxResult, Vhdx}; -use crate::AsyncAdaptor; pub struct VhdxDiskSync { vhdx_file: Vhdx, diff --git a/devices/src/acpi.rs b/devices/src/acpi.rs index 2a38f5974..229b67be5 100644 --- a/devices/src/acpi.rs +++ b/devices/src/acpi.rs @@ -8,9 +8,9 @@ use std::sync::{Arc, Barrier}; use std::thread; use std::time::Instant; -use acpi_tables::{aml, Aml, AmlSink}; -use vm_device::interrupt::InterruptSourceGroup; +use acpi_tables::{Aml, AmlSink, aml}; use vm_device::BusDevice; +use vm_device::interrupt::InterruptSourceGroup; use vm_memory::GuestAddress; use vmm_sys_util::eventfd::EventFd; diff --git a/devices/src/gic.rs b/devices/src/gic.rs index dcae0be37..a157c3f25 100644 --- a/devices/src/gic.rs +++ b/devices/src/gic.rs @@ -9,8 +9,8 @@ use std::sync::{Arc, Mutex}; use anyhow::anyhow; use arch::layout; -use hypervisor::arch::aarch64::gic::{GicState, Vgic, VgicConfig}; use hypervisor::CpuState; +use hypervisor::arch::aarch64::gic::{GicState, Vgic, VgicConfig}; use vm_device::interrupt::{ InterruptIndex, InterruptManager, InterruptSourceConfig, InterruptSourceGroup, LegacyIrqSourceConfig, MsiIrqGroupConfig, diff --git a/devices/src/ioapic.rs b/devices/src/ioapic.rs index 7adbe4f66..97932f016 100644 --- a/devices/src/ioapic.rs +++ b/devices/src/ioapic.rs @@ -14,11 +14,11 @@ use std::sync::{Arc, Barrier}; use byteorder::{ByteOrder, LittleEndian}; use serde::{Deserialize, Serialize}; +use vm_device::BusDevice; use vm_device::interrupt::{ InterruptIndex, InterruptManager, InterruptSourceConfig, InterruptSourceGroup, MsiIrqGroupConfig, MsiIrqSourceConfig, }; -use vm_device::BusDevice; use vm_memory::GuestAddress; use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; use vmm_sys_util::eventfd::EventFd; diff --git a/devices/src/ivshmem.rs b/devices/src/ivshmem.rs index fc7c88de3..50c056edf 100644 --- a/devices/src/ivshmem.rs +++ b/devices/src/ivshmem.rs @@ -12,9 +12,9 @@ use std::sync::{Arc, Barrier, Mutex}; use anyhow::anyhow; use byteorder::{ByteOrder, LittleEndian}; use pci::{ - BarReprogrammingParams, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, - PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciHeaderType, PciSubclass, - PCI_CONFIGURATION_ID, + BarReprogrammingParams, PCI_CONFIGURATION_ID, PciBarConfiguration, PciBarPrefetchable, + PciBarRegionType, PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciHeaderType, + PciSubclass, }; use serde::{Deserialize, Serialize}; use thiserror::Error; diff --git a/devices/src/legacy/cmos.rs b/devices/src/legacy/cmos.rs index 386281c67..b0e140acc 100644 --- a/devices/src/legacy/cmos.rs +++ b/devices/src/legacy/cmos.rs @@ -12,7 +12,7 @@ use std::{mem, thread}; // 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 libc::{CLOCK_REALTIME, clock_gettime, gmtime_r, timespec, tm}; use vm_device::BusDevice; use vmm_sys_util::eventfd::EventFd; diff --git a/devices/src/legacy/fw_cfg.rs b/devices/src/legacy/fw_cfg.rs index 02c52c707..00b5bd745 100644 --- a/devices/src/legacy/fw_cfg.rs +++ b/devices/src/legacy/fw_cfg.rs @@ -20,6 +20,7 @@ use std::{ }; use acpi_tables::rsdp::Rsdp; +use arch::RegionType; #[cfg(target_arch = "aarch64")] use arch::aarch64::layout::{ MEM_32BIT_DEVICES_START, MEM_32BIT_RESERVED_START, RAM_64BIT_START, RAM_START as HIGH_RAM_START, @@ -29,7 +30,6 @@ use arch::layout::{ EBDA_START, HIGH_RAM_START, MEM_32BIT_DEVICES_SIZE, MEM_32BIT_DEVICES_START, MEM_32BIT_RESERVED_START, PCI_MMCONFIG_SIZE, PCI_MMCONFIG_START, RAM_64BIT_START, }; -use arch::RegionType; use bitfield_struct::bitfield; #[cfg(target_arch = "x86_64")] use linux_loader::bootparam::boot_params; @@ -752,7 +752,9 @@ impl BusDevice for FwCfg { data.copy_from_slice(&addr_lo.to_be_bytes()); } _ => { - debug!("fw_cfg: read from unknown port {port:#x}: {size:#x} bytes and offset {offset:#x}."); + debug!( + "fw_cfg: read from unknown port {port:#x}: {size:#x} bytes and offset {offset:#x}." + ); } }; } diff --git a/devices/src/legacy/gpio_pl061.rs b/devices/src/legacy/gpio_pl061.rs index c7c66341a..3a61238dd 100644 --- a/devices/src/legacy/gpio_pl061.rs +++ b/devices/src/legacy/gpio_pl061.rs @@ -12,8 +12,8 @@ use std::{io, result}; use serde::{Deserialize, Serialize}; use thiserror::Error; -use vm_device::interrupt::InterruptSourceGroup; use vm_device::BusDevice; +use vm_device::interrupt::InterruptSourceGroup; use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; use crate::{read_le_u32, write_le_u32}; @@ -28,10 +28,10 @@ const GPIORIE: u64 = 0x414; // Raw Interrupt Status Register const GPIOMIS: u64 = 0x418; // Masked Interrupt Status Register const GPIOIC: u64 = 0x41c; // Interrupt Clear Register const GPIOAFSEL: u64 = 0x420; // Mode Control Select Register - // From 0x424 to 0xFDC => reserved space. - // From 0xFE0 to 0xFFC => Peripheral and PrimeCell Identification Registers which are Read Only registers. - // These registers can conceptually be treated as a 32-bit register, and PartNumber[11:0] is used to identify the peripheral. - // We are putting the expected values (look at 'Reset value' column from above mentioned document) in an array. +// From 0x424 to 0xFDC => reserved space. +// From 0xFE0 to 0xFFC => Peripheral and PrimeCell Identification Registers which are Read Only registers. +// These registers can conceptually be treated as a 32-bit register, and PartNumber[11:0] is used to identify the peripheral. +// We are putting the expected values (look at 'Reset value' column from above mentioned document) in an array. const GPIO_ID: [u8; 8] = [0x61, 0x10, 0x14, 0x00, 0x0d, 0xf0, 0x05, 0xb1]; // ID Margins const GPIO_ID_LOW: u64 = 0xfe0; diff --git a/devices/src/legacy/rtc_pl031.rs b/devices/src/legacy/rtc_pl031.rs index 98bca77af..9ff0c8c1b 100644 --- a/devices/src/legacy/rtc_pl031.rs +++ b/devices/src/legacy/rtc_pl031.rs @@ -31,11 +31,11 @@ const RTCIMSC: u64 = 0x10; // Interrupt Mask Set or Clear Register. const RTCRIS: u64 = 0x14; // Raw Interrupt Status. const RTCMIS: u64 = 0x18; // Masked Interrupt Status. const RTCICR: u64 = 0x1c; // Interrupt Clear Register. - // From 0x020 to 0xFDC => reserved space. - // From 0xFE0 to 0x1000 => Peripheral and PrimeCell Identification Registers which are Read Only registers. - // AMBA standard devices have CIDs (Cell IDs) and PIDs (Peripheral IDs). The linux kernel will look for these in order to assert the identity - // of these devices (i.e look at the `amba_device_try_add` function). - // We are putting the expected values (look at 'Reset value' column from above mentioned document) in an array. +// From 0x020 to 0xFDC => reserved space. +// From 0xFE0 to 0x1000 => Peripheral and PrimeCell Identification Registers which are Read Only registers. +// AMBA standard devices have CIDs (Cell IDs) and PIDs (Peripheral IDs). The linux kernel will look for these in order to assert the identity +// of these devices (i.e look at the `amba_device_try_add` function). +// We are putting the expected values (look at 'Reset value' column from above mentioned document) in an array. const PL031_ID: [u8; 8] = [0x31, 0x10, 0x14, 0x00, 0x0d, 0xf0, 0x05, 0xb1]; // We are only interested in the margins. const AMBA_ID_LOW: u64 = 0xFE0; diff --git a/devices/src/legacy/serial.rs b/devices/src/legacy/serial.rs index 973c96b0c..cbfb2c10b 100644 --- a/devices/src/legacy/serial.rs +++ b/devices/src/legacy/serial.rs @@ -10,8 +10,8 @@ use std::sync::{Arc, Barrier}; use std::{io, result}; use serde::{Deserialize, Serialize}; -use vm_device::interrupt::InterruptSourceGroup; use vm_device::BusDevice; +use vm_device::interrupt::InterruptSourceGroup; use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; use vmm_sys_util::errno::Result; diff --git a/devices/src/legacy/uart_pl011.rs b/devices/src/legacy/uart_pl011.rs index b5603808b..364dd5927 100644 --- a/devices/src/legacy/uart_pl011.rs +++ b/devices/src/legacy/uart_pl011.rs @@ -13,8 +13,8 @@ use std::{io, result}; use serde::{Deserialize, Serialize}; use thiserror::Error; -use vm_device::interrupt::InterruptSourceGroup; use vm_device::BusDevice; +use vm_device::interrupt::InterruptSourceGroup; use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; use crate::{read_le_u32, write_le_u32}; diff --git a/devices/src/lib.rs b/devices/src/lib.rs index d7ac32d9d..0c4bfb8ca 100644 --- a/devices/src/lib.rs +++ b/devices/src/lib.rs @@ -37,7 +37,7 @@ pub mod tpm; pub use self::acpi::{AcpiGedDevice, AcpiPmTimerDevice, AcpiShutdownDevice}; #[cfg(feature = "ivshmem")] pub use self::ivshmem::IvshmemDevice; -pub use self::pvpanic::{PvPanicDevice, PVPANIC_DEVICE_MMIO_SIZE}; +pub use self::pvpanic::{PVPANIC_DEVICE_MMIO_SIZE, PvPanicDevice}; bitflags! { pub struct AcpiNotificationFlags: u8 { diff --git a/devices/src/pvmemcontrol.rs b/devices/src/pvmemcontrol.rs index ff2190933..2977a9a52 100644 --- a/devices/src/pvmemcontrol.rs +++ b/devices/src/pvmemcontrol.rs @@ -520,7 +520,7 @@ impl PvmemcontrolBusDevice { ret_value: get_page_size().into(), arg0: MAJOR_VERSION.into(), arg1: MINOR_VERSION.into(), - }) + }); } FunctionCode::Dontneed => self.madvise(addr, length, libc::MADV_DONTNEED), FunctionCode::Remove => self.madvise(addr, length, libc::MADV_REMOVE), diff --git a/devices/src/pvpanic.rs b/devices/src/pvpanic.rs index 98e7bfa9c..4fd61188b 100644 --- a/devices/src/pvpanic.rs +++ b/devices/src/pvpanic.rs @@ -9,9 +9,9 @@ use std::sync::{Arc, Barrier, Mutex}; use anyhow::anyhow; use pci::{ - BarReprogrammingParams, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, - PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciHeaderType, PciSubclass, - PCI_CONFIGURATION_ID, + BarReprogrammingParams, PCI_CONFIGURATION_ID, PciBarConfiguration, PciBarPrefetchable, + PciBarRegionType, PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciHeaderType, + PciSubclass, }; use serde::{Deserialize, Serialize}; use thiserror::Error; diff --git a/devices/src/tpm.rs b/devices/src/tpm.rs index c6ed5ce0a..4219f5830 100644 --- a/devices/src/tpm.rs +++ b/devices/src/tpm.rs @@ -12,8 +12,8 @@ use arch::aarch64::layout::{TPM_SIZE, TPM_START}; #[cfg(target_arch = "x86_64")] use arch::x86_64::layout::{TPM_SIZE, TPM_START}; use thiserror::Error; -use tpm::emulator::{BackendCmd, Emulator}; use tpm::TPM_CRB_BUFFER_MAX; +use tpm::emulator::{BackendCmd, Emulator}; use vm_device::BusDevice; #[derive(Error, Debug)] diff --git a/hypervisor/src/arch/x86/emulator/instructions/mod.rs b/hypervisor/src/arch/x86/emulator/instructions/mod.rs index c2d39aea0..945ce16ba 100644 --- a/hypervisor/src/arch/x86/emulator/instructions/mod.rs +++ b/hypervisor/src/arch/x86/emulator/instructions/mod.rs @@ -7,8 +7,8 @@ use iced_x86::*; use crate::arch::emulator::{EmulationError, PlatformEmulator, PlatformError}; -use crate::arch::x86::emulator::CpuStateManager; use crate::arch::x86::Exception; +use crate::arch::x86::emulator::CpuStateManager; pub mod cmp; pub mod mov; diff --git a/hypervisor/src/arch/x86/emulator/mod.rs b/hypervisor/src/arch/x86/emulator/mod.rs index 61bbd56fd..9cc8ac472 100644 --- a/hypervisor/src/arch/x86/emulator/mod.rs +++ b/hypervisor/src/arch/x86/emulator/mod.rs @@ -7,13 +7,13 @@ use anyhow::Context; use iced_x86::*; +use crate::StandardRegisters; use crate::arch::emulator::{EmulationError, EmulationResult, PlatformEmulator, PlatformError}; use crate::arch::x86::emulator::instructions::*; use crate::arch::x86::regs::{CR0_PE, EFER_LMA}; use crate::arch::x86::{ - segment_type_expand_down, segment_type_ro, Exception, SegmentRegister, SpecialRegisters, + Exception, SegmentRegister, SpecialRegisters, segment_type_expand_down, segment_type_ro, }; -use crate::StandardRegisters; #[macro_use] mod instructions; @@ -254,7 +254,7 @@ impl CpuStateManager for EmulatorCpuState { return Err(PlatformError::InvalidRegister(anyhow!( "read_reg invalid GPR {:?}", r - ))) + ))); } }; @@ -375,7 +375,7 @@ impl CpuStateManager for EmulatorCpuState { return Err(PlatformError::InvalidRegister(anyhow!( "write_reg invalid register {:?}", reg - ))) + ))); } } @@ -660,9 +660,9 @@ mod mock_vmm { use std::sync::{Arc, Mutex}; use super::*; + use crate::StandardRegisters; use crate::arch::x86::emulator::EmulatorCpuState as CpuState; use crate::arch::x86::gdt::{gdt_entry, segment_from_gdt}; - use crate::StandardRegisters; #[derive(Debug, Clone)] pub struct MockVmm { diff --git a/hypervisor/src/cpu.rs b/hypervisor/src/cpu.rs index 46401cc66..5c377c5d1 100644 --- a/hypervisor/src/cpu.rs +++ b/hypervisor/src/cpu.rs @@ -17,14 +17,14 @@ use thiserror::Error; #[cfg(not(target_arch = "riscv64"))] use vm_memory::GuestAddress; -#[cfg(target_arch = "x86_64")] -use crate::arch::x86::{CpuIdEntry, FpuState, LapicState, MsrEntry, SpecialRegisters}; -#[cfg(feature = "tdx")] -use crate::kvm::{TdxExitDetails, TdxExitStatus}; #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] use crate::RegList; #[cfg(target_arch = "aarch64")] use crate::VcpuInit; +#[cfg(target_arch = "x86_64")] +use crate::arch::x86::{CpuIdEntry, FpuState, LapicState, MsrEntry, SpecialRegisters}; +#[cfg(feature = "tdx")] +use crate::kvm::{TdxExitDetails, TdxExitStatus}; use crate::{CpuState, MpState, StandardRegisters}; #[cfg(target_arch = "x86_64")] diff --git a/hypervisor/src/hypervisor.rs b/hypervisor/src/hypervisor.rs index 4fc98fb8b..13d00fa00 100644 --- a/hypervisor/src/hypervisor.rs +++ b/hypervisor/src/hypervisor.rs @@ -13,6 +13,7 @@ use std::sync::Arc; use thiserror::Error; +use crate::HypervisorType; #[cfg(target_arch = "x86_64")] use crate::arch::x86::CpuIdEntry; #[cfg(target_arch = "x86_64")] @@ -20,7 +21,6 @@ use crate::cpu::CpuVendor; #[cfg(feature = "tdx")] use crate::kvm::TdxCapabilities; use crate::vm::Vm; -use crate::HypervisorType; #[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 0aa3da76d..9a3c719e7 100644 --- a/hypervisor/src/kvm/aarch64/gic/dist_regs.rs +++ b/hypervisor/src/kvm/aarch64/gic/dist_regs.rs @@ -6,7 +6,7 @@ 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, + KVM_DEV_ARM_VGIC_GRP_DIST_REGS, KVM_DEV_ARM_VGIC_GRP_NR_IRQS, kvm_device_attr, }; /* diff --git a/hypervisor/src/kvm/aarch64/gic/icc_regs.rs b/hypervisor/src/kvm/aarch64/gic/icc_regs.rs index f99358184..b084c8989 100644 --- a/hypervisor/src/kvm/aarch64/gic/icc_regs.rs +++ b/hypervisor/src/kvm/aarch64/gic/icc_regs.rs @@ -7,10 +7,11 @@ 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_CPU_SYSREGS, KVM_REG_ARM64_SYSREG_CRM_MASK, + KVM_DEV_ARM_VGIC_GRP_CPU_SYSREGS, KVM_REG_ARM64_SYSREG_CRM_MASK, KVM_REG_ARM64_SYSREG_CRM_SHIFT, KVM_REG_ARM64_SYSREG_CRN_MASK, KVM_REG_ARM64_SYSREG_CRN_SHIFT, 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, + kvm_device_attr, }; const KVM_DEV_ARM_VGIC_V3_MPIDR_SHIFT: u32 = 32; diff --git a/hypervisor/src/kvm/aarch64/gic/redist_regs.rs b/hypervisor/src/kvm/aarch64/gic/redist_regs.rs index 7adc0efef..c06818e04 100644 --- a/hypervisor/src/kvm/aarch64/gic/redist_regs.rs +++ b/hypervisor/src/kvm/aarch64/gic/redist_regs.rs @@ -4,15 +4,15 @@ use kvm_ioctls::DeviceFd; +use crate::CpuState; use crate::arch::aarch64::gic::{Error, Result}; use crate::device::HypervisorDeviceError; -use crate::kvm::kvm_bindings::{ - kvm_device_attr, kvm_one_reg, KVM_DEV_ARM_VGIC_GRP_REDIST_REGS, KVM_REG_ARM64, - KVM_REG_ARM64_SYSREG, KVM_REG_ARM64_SYSREG_OP0_MASK, KVM_REG_ARM64_SYSREG_OP0_SHIFT, - KVM_REG_ARM64_SYSREG_OP2_MASK, KVM_REG_ARM64_SYSREG_OP2_SHIFT, KVM_REG_SIZE_U64, -}; use crate::kvm::VcpuKvmState; -use crate::CpuState; +use crate::kvm::kvm_bindings::{ + KVM_DEV_ARM_VGIC_GRP_REDIST_REGS, KVM_REG_ARM64, KVM_REG_ARM64_SYSREG, + KVM_REG_ARM64_SYSREG_OP0_MASK, KVM_REG_ARM64_SYSREG_OP0_SHIFT, KVM_REG_ARM64_SYSREG_OP2_MASK, + KVM_REG_ARM64_SYSREG_OP2_SHIFT, KVM_REG_SIZE_U64, kvm_device_attr, kvm_one_reg, +}; // 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 20fef7244..a94ed55f1 100644 --- a/hypervisor/src/kvm/aarch64/mod.rs +++ b/hypervisor/src/kvm/aarch64/mod.rs @@ -11,8 +11,8 @@ pub mod gic; 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, + KVM_REG_ARM_COPROC_MASK, KVM_REG_ARM_CORE, KVM_REG_SIZE_MASK, KVM_REG_SIZE_U32, + KVM_REG_SIZE_U64, kvm_mp_state, kvm_one_reg, kvm_regs, }; pub use kvm_ioctls::{Cap, Kvm}; use serde::{Deserialize, Serialize}; diff --git a/hypervisor/src/kvm/mod.rs b/hypervisor/src/kvm/mod.rs index 9aaafd5b0..6becd0e41 100644 --- a/hypervisor/src/kvm/mod.rs +++ b/hypervisor/src/kvm/mod.rs @@ -29,7 +29,7 @@ use vmm_sys_util::eventfd::EventFd; #[cfg(target_arch = "aarch64")] use crate::aarch64::gic::KvmGicV3Its; #[cfg(target_arch = "aarch64")] -pub use crate::aarch64::{check_required_kvm_extensions, is_system_register, VcpuKvmState}; +pub use crate::aarch64::{VcpuKvmState, check_required_kvm_extensions, is_system_register}; #[cfg(target_arch = "aarch64")] use crate::arch::aarch64::gic::{Vgic, VgicConfig}; #[cfg(target_arch = "riscv64")] @@ -40,36 +40,37 @@ use crate::arm64_core_reg_id; use crate::riscv64::aia::KvmAiaImsics; #[cfg(target_arch = "riscv64")] pub use crate::riscv64::{ - aia::AiaImsicsState as AiaState, check_required_kvm_extensions, is_non_core_register, - VcpuKvmState, + VcpuKvmState, aia::AiaImsicsState as AiaState, check_required_kvm_extensions, + is_non_core_register, }; #[cfg(target_arch = "riscv64")] use crate::riscv64_reg_id; use crate::vm::{self, InterruptSourceConfig, VmOps}; -use crate::{cpu, hypervisor, HypervisorType}; +use crate::{HypervisorType, cpu, hypervisor}; // x86_64 dependencies #[cfg(target_arch = "x86_64")] pub mod x86_64; #[cfg(target_arch = "x86_64")] use kvm_bindings::{ - kvm_enable_cap, kvm_msr_entry, MsrList, KVM_CAP_HYPERV_SYNIC, KVM_CAP_SPLIT_IRQCHIP, - KVM_CAP_X2APIC_API, KVM_GUESTDBG_USE_HW_BP, KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK, - KVM_X2APIC_API_USE_32BIT_IDS, + KVM_CAP_HYPERV_SYNIC, KVM_CAP_SPLIT_IRQCHIP, KVM_CAP_X2APIC_API, KVM_GUESTDBG_USE_HW_BP, + KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK, KVM_X2APIC_API_USE_32BIT_IDS, MsrList, kvm_enable_cap, + kvm_msr_entry, }; #[cfg(target_arch = "x86_64")] 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; +#[cfg(target_arch = "x86_64")] +use crate::arch::x86::{ + CpuIdEntry, FpuState, LapicState, MsrEntry, NUM_IOAPIC_PINS, SpecialRegisters, XsaveState, +}; use crate::{ - CpuState, IoEventAddress, IrqRoutingEntry, MpState, StandardRegisters, UserMemoryRegion, + CpuState, IoEventAddress, IrqRoutingEntry, MpState, StandardRegisters, USER_MEMORY_REGION_LOG_DIRTY, USER_MEMORY_REGION_READ, USER_MEMORY_REGION_WRITE, + UserMemoryRegion, }; // aarch64 dependencies #[cfg(target_arch = "aarch64")] @@ -86,23 +87,23 @@ use std::mem; #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] pub use kvm_bindings::kvm_vcpu_events as VcpuEvents; pub use kvm_bindings::{ - kvm_clock_data, kvm_create_device, kvm_create_device as CreateDevice, - kvm_device_attr as DeviceAttr, kvm_device_type_KVM_DEV_TYPE_VFIO, kvm_guest_debug, - kvm_irq_routing, kvm_irq_routing_entry, kvm_mp_state, kvm_run, kvm_userspace_memory_region, KVM_GUESTDBG_ENABLE, KVM_GUESTDBG_SINGLESTEP, KVM_IRQ_ROUTING_IRQCHIP, KVM_IRQ_ROUTING_MSI, - KVM_MEM_LOG_DIRTY_PAGES, KVM_MEM_READONLY, KVM_MSI_VALID_DEVID, + KVM_MEM_LOG_DIRTY_PAGES, KVM_MEM_READONLY, KVM_MSI_VALID_DEVID, kvm_clock_data, + kvm_create_device, kvm_create_device as CreateDevice, kvm_device_attr as DeviceAttr, + kvm_device_type_KVM_DEV_TYPE_VFIO, kvm_guest_debug, kvm_irq_routing, kvm_irq_routing_entry, + kvm_mp_state, kvm_run, kvm_userspace_memory_region, }; #[cfg(target_arch = "aarch64")] use kvm_bindings::{ - kvm_regs, user_pt_regs, KVM_GUESTDBG_USE_HW, KVM_NR_SPSR, KVM_REG_ARM64, KVM_REG_ARM64_SYSREG, + KVM_GUESTDBG_USE_HW, KVM_NR_SPSR, KVM_REG_ARM_CORE, KVM_REG_ARM64, KVM_REG_ARM64_SYSREG, KVM_REG_ARM64_SYSREG_CRM_MASK, KVM_REG_ARM64_SYSREG_CRN_MASK, KVM_REG_ARM64_SYSREG_OP0_MASK, - KVM_REG_ARM64_SYSREG_OP1_MASK, KVM_REG_ARM64_SYSREG_OP2_MASK, KVM_REG_ARM_CORE, - KVM_REG_SIZE_U128, KVM_REG_SIZE_U32, KVM_REG_SIZE_U64, + KVM_REG_ARM64_SYSREG_OP1_MASK, KVM_REG_ARM64_SYSREG_OP2_MASK, KVM_REG_SIZE_U32, + KVM_REG_SIZE_U64, KVM_REG_SIZE_U128, kvm_regs, user_pt_regs, }; #[cfg(target_arch = "riscv64")] -use kvm_bindings::{kvm_riscv_core, KVM_REG_RISCV_CORE}; +use kvm_bindings::{KVM_REG_RISCV_CORE, kvm_riscv_core}; #[cfg(feature = "tdx")] -use kvm_bindings::{kvm_run__bindgen_ty_1, KVMIO}; +use kvm_bindings::{KVMIO, kvm_run__bindgen_ty_1}; pub use kvm_ioctls::{Cap, Kvm, VcpuExit}; use thiserror::Error; use vfio_ioctls::VfioDeviceFd; @@ -112,10 +113,10 @@ use vmm_sys_util::ioctl_io_nr; use vmm_sys_util::{ioctl::ioctl_with_val, ioctl_iowr_nr}; pub use {kvm_bindings, kvm_ioctls}; -#[cfg(target_arch = "aarch64")] -use crate::arch::aarch64::regs; #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] use crate::RegList; +#[cfg(target_arch = "aarch64")] +use crate::arch::aarch64::regs; #[cfg(target_arch = "x86_64")] ioctl_io_nr!(KVM_NMI, kvm_bindings::KVMIO, 0x9a); @@ -2866,7 +2867,7 @@ impl cpu::Vcpu for KvmVcpu { /// Return the list of initial MSR entries for a VCPU /// fn boot_msr_entries(&self) -> Vec { - use crate::arch::x86::{msr_index, MTRR_ENABLE, MTRR_MEM_TYPE_WB}; + use crate::arch::x86::{MTRR_ENABLE, MTRR_MEM_TYPE_WB, msr_index}; [ msr!(msr_index::MSR_IA32_SYSENTER_CS), diff --git a/hypervisor/src/kvm/riscv64/aia.rs b/hypervisor/src/kvm/riscv64/aia.rs index 607c9034c..1aebbafbe 100644 --- a/hypervisor/src/kvm/riscv64/aia.rs +++ b/hypervisor/src/kvm/riscv64/aia.rs @@ -7,10 +7,10 @@ use std::any::Any; use kvm_ioctls::DeviceFd; use serde::{Deserialize, Serialize}; +use crate::Vm; use crate::arch::riscv64::aia::{Error, Result, Vaia, VaiaConfig}; use crate::device::HypervisorDeviceError; use crate::kvm::KvmVm; -use crate::Vm; pub struct KvmAiaImsics { /// The KVM device for the Aia diff --git a/hypervisor/src/kvm/riscv64/mod.rs b/hypervisor/src/kvm/riscv64/mod.rs index c589b488a..07f54efb3 100644 --- a/hypervisor/src/kvm/riscv64/mod.rs +++ b/hypervisor/src/kvm/riscv64/mod.rs @@ -5,8 +5,8 @@ pub mod aia; use kvm_bindings::{ - kvm_mp_state, kvm_one_reg, kvm_riscv_core, KVM_REG_RISCV_CORE, KVM_REG_RISCV_TYPE_MASK, - KVM_REG_SIZE_MASK, KVM_REG_SIZE_U64, + KVM_REG_RISCV_CORE, KVM_REG_RISCV_TYPE_MASK, KVM_REG_SIZE_MASK, KVM_REG_SIZE_U64, kvm_mp_state, + kvm_one_reg, kvm_riscv_core, }; pub use kvm_ioctls::{Cap, Kvm}; use serde::{Deserialize, Serialize}; diff --git a/hypervisor/src/kvm/x86_64/mod.rs b/hypervisor/src/kvm/x86_64/mod.rs index 4cf05a1ac..a01fb9d72 100644 --- a/hypervisor/src/kvm/x86_64/mod.rs +++ b/hypervisor/src/kvm/x86_64/mod.rs @@ -13,18 +13,17 @@ use serde::{Deserialize, Serialize}; /// Export generically-named wrappers of kvm-bindings for Unix-based platforms /// pub use { - kvm_bindings::kvm_cpuid_entry2, kvm_bindings::kvm_dtable, kvm_bindings::kvm_fpu, - kvm_bindings::kvm_lapic_state, kvm_bindings::kvm_mp_state as MpState, + kvm_bindings::CpuId, kvm_bindings::KVM_CPUID_FLAG_SIGNIFCANT_INDEX, kvm_bindings::MsrList, + kvm_bindings::Msrs as MsrEntries, kvm_bindings::kvm_cpuid_entry2, kvm_bindings::kvm_dtable, + kvm_bindings::kvm_fpu, kvm_bindings::kvm_lapic_state, kvm_bindings::kvm_mp_state as MpState, kvm_bindings::kvm_msr_entry, kvm_bindings::kvm_regs, kvm_bindings::kvm_segment, kvm_bindings::kvm_sregs, kvm_bindings::kvm_vcpu_events as VcpuEvents, kvm_bindings::kvm_xcrs as ExtendedControlRegisters, kvm_bindings::kvm_xsave, - kvm_bindings::CpuId, kvm_bindings::MsrList, kvm_bindings::Msrs as MsrEntries, - kvm_bindings::KVM_CPUID_FLAG_SIGNIFCANT_INDEX, }; use crate::arch::x86::{ - CpuIdEntry, DescriptorTable, FpuState, LapicState, MsrEntry, SegmentRegister, SpecialRegisters, - XsaveState, CPUID_FLAG_VALID_INDEX, + CPUID_FLAG_VALID_INDEX, CpuIdEntry, DescriptorTable, FpuState, LapicState, MsrEntry, + SegmentRegister, SpecialRegisters, XsaveState, }; use crate::kvm::{Cap, Kvm, KvmError, KvmResult}; diff --git a/hypervisor/src/lib.rs b/hypervisor/src/lib.rs index af383e3f3..205691a42 100644 --- a/hypervisor/src/lib.rs +++ b/hypervisor/src/lib.rs @@ -61,7 +61,7 @@ pub use device::HypervisorDeviceError; #[cfg(all(feature = "kvm", target_arch = "aarch64"))] pub use kvm::aarch64; #[cfg(all(feature = "kvm", target_arch = "riscv64"))] -pub use kvm::{riscv64, AiaState}; +pub use kvm::{AiaState, riscv64}; pub use vm::{ DataMatch, HypervisorVmError, InterruptSourceConfig, LegacyIrqSourceConfig, MsiIrqSourceConfig, Vm, VmOps, diff --git a/hypervisor/src/mshv/mod.rs b/hypervisor/src/mshv/mod.rs index 93634ada0..bc03c44da 100644 --- a/hypervisor/src/mshv/mod.rs +++ b/hypervisor/src/mshv/mod.rs @@ -14,7 +14,7 @@ use arc_swap::ArcSwap; use mshv_bindings::*; #[cfg(target_arch = "x86_64")] use mshv_ioctls::InterruptRequest; -use mshv_ioctls::{set_registers_64, Mshv, NoDatamatch, VcpuFd, VmFd, VmType}; +use mshv_ioctls::{Mshv, NoDatamatch, VcpuFd, VmFd, VmType, set_registers_64}; use vfio_ioctls::VfioDeviceFd; use vm::DataMatch; #[cfg(feature = "sev_snp")] @@ -32,7 +32,7 @@ use crate::arch::x86::emulator::Emulator; use crate::mshv::aarch64::emulator; use crate::mshv::emulator::MshvEmulatorContext; use crate::vm::{self, InterruptSourceConfig, VmOps}; -use crate::{cpu, hypervisor, vec_with_array_field, HypervisorType}; +use crate::{HypervisorType, cpu, hypervisor, vec_with_array_field}; #[cfg(feature = "sev_snp")] mod snp_constants; // x86_64 dependencies @@ -45,10 +45,10 @@ use std::os::unix::io::AsRawFd; #[cfg(target_arch = "aarch64")] use std::sync::Mutex; -#[cfg(target_arch = "aarch64")] -use aarch64::gic::{MshvGicV2M, BASE_SPI_IRQ}; #[cfg(target_arch = "aarch64")] pub use aarch64::VcpuMshvState; +#[cfg(target_arch = "aarch64")] +use aarch64::gic::{BASE_SPI_IRQ, MshvGicV2M}; #[cfg(feature = "sev_snp")] use igvm_defs::IGVM_VHS_SNP_ID_BLOCK; #[cfg(feature = "sev_snp")] @@ -57,7 +57,7 @@ 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}; +pub use x86_64::{VcpuMshvState, emulator}; /// /// Export generically-named wrappers of mshv-bindings for Unix-based platforms /// @@ -66,18 +66,18 @@ pub use { mshv_bindings::mshv_device_attr as DeviceAttr, mshv_ioctls, mshv_ioctls::DeviceFd, }; +#[cfg(target_arch = "x86_64")] +use crate::ClockData; #[cfg(target_arch = "aarch64")] use crate::arch::aarch64::gic::{Vgic, VgicConfig}; #[cfg(target_arch = "aarch64")] use crate::arch::aarch64::regs; #[cfg(target_arch = "x86_64")] use crate::arch::x86::{CpuIdEntry, FpuState, MsrEntry}; -#[cfg(target_arch = "x86_64")] -use crate::ClockData; use crate::{ - CpuState, IoEventAddress, IrqRoutingEntry, MpState, UserMemoryRegion, - USER_MEMORY_REGION_ADJUSTABLE, USER_MEMORY_REGION_EXECUTE, USER_MEMORY_REGION_READ, - USER_MEMORY_REGION_WRITE, + CpuState, IoEventAddress, IrqRoutingEntry, MpState, USER_MEMORY_REGION_ADJUSTABLE, + USER_MEMORY_REGION_EXECUTE, USER_MEMORY_REGION_READ, USER_MEMORY_REGION_WRITE, + UserMemoryRegion, }; pub const PAGE_SHIFT: usize = 12; @@ -1512,7 +1512,7 @@ impl cpu::Vcpu for MshvVcpu { /// Return the list of initial MSR entries for a VCPU /// fn boot_msr_entries(&self) -> Vec { - use crate::arch::x86::{msr_index, MTRR_ENABLE, MTRR_MEM_TYPE_WB}; + use crate::arch::x86::{MTRR_ENABLE, MTRR_MEM_TYPE_WB, msr_index}; [ msr!(msr_index::MSR_IA32_SYSENTER_CS), diff --git a/hypervisor/src/mshv/x86_64/mod.rs b/hypervisor/src/mshv/x86_64/mod.rs index 1853d234d..a25dcc3ca 100644 --- a/hypervisor/src/mshv/x86_64/mod.rs +++ b/hypervisor/src/mshv/x86_64/mod.rs @@ -21,16 +21,16 @@ pub mod emulator; /// Export generically-named wrappers of mshv_bindings for Unix-based platforms /// pub use { - mshv_bindings::hv_cpuid_entry, mshv_bindings::mshv_user_mem_region as MemoryRegion, - mshv_bindings::msr_entry, mshv_bindings::AllVpStateComponents, mshv_bindings::CpuId, - mshv_bindings::DebugRegisters, mshv_bindings::FloatingPointUnit, - mshv_bindings::LapicState as MshvLapicState, mshv_bindings::MiscRegs as MiscRegisters, - mshv_bindings::MsrList, mshv_bindings::Msrs as MsrEntries, mshv_bindings::Msrs, + mshv_bindings::AllVpStateComponents, mshv_bindings::CpuId, mshv_bindings::DebugRegisters, + mshv_bindings::FloatingPointUnit, mshv_bindings::LapicState as MshvLapicState, + mshv_bindings::MiscRegs as MiscRegisters, mshv_bindings::MsrList, + mshv_bindings::Msrs as MsrEntries, mshv_bindings::Msrs, mshv_bindings::SegmentRegister as MshvSegmentRegister, mshv_bindings::SpecialRegisters as MshvSpecialRegisters, mshv_bindings::StandardRegisters as MshvStandardRegisters, mshv_bindings::SuspendRegisters, mshv_bindings::TableRegister, mshv_bindings::VcpuEvents, mshv_bindings::XSave as Xsave, - mshv_bindings::Xcrs as ExtendedControlRegisters, + mshv_bindings::Xcrs as ExtendedControlRegisters, mshv_bindings::hv_cpuid_entry, + mshv_bindings::mshv_user_mem_region as MemoryRegion, mshv_bindings::msr_entry, }; #[derive(Clone, Serialize, Deserialize)] @@ -60,16 +60,18 @@ impl fmt::Display for VcpuMshvState { msr_entries[i][1] = entry.data; msr_entries[i][0] = entry.index as u64; } - write!(f, "Number of MSRs: {}: MSRs: {:#010X?}, -- VCPU Events: {:?} -- Standard registers: {:?} Special Registers: {:?} ---- Floating Point Unit: {:?} --- Extended Control Register: {:?} --- DBG: {:?} --- VP States: {:?}", - msr_entries.len(), - msr_entries, - self.vcpu_events, - self.regs, - self.sregs, - self.fpu, - self.xcrs, - self.dbg, - self.vp_states, + write!( + f, + "Number of MSRs: {}: MSRs: {:#010X?}, -- VCPU Events: {:?} -- Standard registers: {:?} Special Registers: {:?} ---- Floating Point Unit: {:?} --- Extended Control Register: {:?} --- DBG: {:?} --- VP States: {:?}", + msr_entries.len(), + msr_entries, + self.vcpu_events, + self.regs, + self.sregs, + self.fpu, + self.xcrs, + self.dbg, + self.vp_states, ) } } diff --git a/hypervisor/src/vm.rs b/hypervisor/src/vm.rs index bd9c0e674..a2f792131 100644 --- a/hypervisor/src/vm.rs +++ b/hypervisor/src/vm.rs @@ -20,6 +20,8 @@ use igvm_defs::IGVM_VHS_SNP_ID_BLOCK; use thiserror::Error; use vmm_sys_util::eventfd::EventFd; +#[cfg(target_arch = "x86_64")] +use crate::ClockData; #[cfg(target_arch = "aarch64")] use crate::arch::aarch64::gic::{Vgic, VgicConfig}; #[cfg(target_arch = "riscv64")] @@ -27,8 +29,6 @@ use crate::arch::riscv64::aia::{Vaia, VaiaConfig}; #[cfg(feature = "tdx")] use crate::arch::x86::CpuIdEntry; use crate::cpu::Vcpu; -#[cfg(target_arch = "x86_64")] -use crate::ClockData; use crate::{IoEventAddress, IrqRoutingEntry, UserMemoryRegion}; /// diff --git a/net_util/src/lib.rs b/net_util/src/lib.rs index a28bcc433..4ad7a1c77 100644 --- a/net_util/src/lib.rs +++ b/net_util/src/lib.rs @@ -23,18 +23,18 @@ use std::{io, mem, net}; 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, - VIRTIO_NET_F_GUEST_TSO6, VIRTIO_NET_F_GUEST_UFO, VIRTIO_NET_F_MAC, VIRTIO_NET_F_MQ, + 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, VIRTIO_NET_F_GUEST_TSO6, + VIRTIO_NET_F_GUEST_UFO, VIRTIO_NET_F_MAC, VIRTIO_NET_F_MQ, virtio_net_hdr_v1, }; -use vm_memory::bitmap::AtomicBitmap; use vm_memory::ByteValued; +use vm_memory::bitmap::AtomicBitmap; type GuestMemoryMmap = vm_memory::GuestMemoryMmap; pub use ctrl_queue::{CtrlQueue, Error as CtrlQueueError}; -pub use mac::{MacAddr, MAC_ADDR_LEN}; -pub use open_tap::{open_tap, Error as OpenTapError}; +pub use mac::{MAC_ADDR_LEN, MacAddr}; +pub use open_tap::{Error as OpenTapError, open_tap}; pub use queue_pair::{NetCounters, NetQueuePair, NetQueuePairError, RxVirtio, TxVirtio}; pub use tap::{Error as TapError, Tap}; diff --git a/net_util/src/open_tap.rs b/net_util/src/open_tap.rs index 21c48f839..61e763ba2 100644 --- a/net_util/src/open_tap.rs +++ b/net_util/src/open_tap.rs @@ -8,7 +8,7 @@ use std::{fs, io}; use thiserror::Error; -use super::{vnet_hdr_len, MacAddr, Tap, TapError}; +use super::{MacAddr, Tap, TapError, vnet_hdr_len}; #[derive(Error, Debug)] pub enum Error { diff --git a/net_util/src/queue_pair.rs b/net_util/src/queue_pair.rs index f28d759fe..63fe67750 100644 --- a/net_util/src/queue_pair.rs +++ b/net_util/src/queue_pair.rs @@ -5,8 +5,8 @@ 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 std::sync::atomic::{AtomicU64, Ordering}; use rate_limiter::{RateLimiter, TokenType}; use thiserror::Error; @@ -15,7 +15,7 @@ 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}; +use super::{Tap, register_listener, unregister_listener, vnet_hdr_len}; #[derive(Clone)] pub struct TxVirtio { diff --git a/net_util/src/tap.rs b/net_util/src/tap.rs index 591dbc491..2544b9eee 100644 --- a/net_util/src/tap.rs +++ b/net_util/src/tap.rs @@ -15,8 +15,8 @@ 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, + Error as NetUtilError, MacAddr, create_inet_socket, create_sockaddr, create_unix_socket, + vnet_hdr_len, }; use crate::mac::MAC_ADDR_LEN; @@ -551,7 +551,7 @@ impl AsRawFd for Tap { #[cfg(test)] mod tests { use std::net::Ipv4Addr; - use std::sync::{mpsc, LazyLock, Mutex}; + use std::sync::{LazyLock, Mutex, mpsc}; use std::time::Duration; use std::{str, thread}; @@ -860,15 +860,17 @@ mod tests { // We use a separate thread to wait for the test packet because the API exposed by pnet is // blocking. This thread will be killed when the main thread exits. - let _handle = thread::spawn(move || loop { - let buf = rx.next().unwrap(); - let p = ParsedPkt::new(buf); - p.print(); + let _handle = thread::spawn(move || { + loop { + let buf = rx.next().unwrap(); + let p = ParsedPkt::new(buf); + p.print(); - if let Some(ref udp) = p.udp { - if payload == udp.payload() { - channel_tx.send(true).unwrap(); - break; + if let Some(ref udp) = p.udp { + if payload == udp.payload() { + channel_tx.send(true).unwrap(); + break; + } } } }); diff --git a/pci/src/bus.rs b/pci/src/bus.rs index f6f8ce2d0..fd19321de 100644 --- a/pci/src/bus.rs +++ b/pci/src/bus.rs @@ -13,11 +13,11 @@ use byteorder::{ByteOrder, LittleEndian}; use thiserror::Error; use vm_device::{Bus, BusDevice, BusDeviceSync}; +use crate::PciBarConfiguration; use crate::configuration::{ PciBarRegionType, PciBridgeSubclass, PciClassCode, PciConfiguration, PciHeaderType, }; use crate::device::{BarReprogrammingParams, DeviceRelocation, Error as PciDeviceError, PciDevice}; -use crate::PciBarConfiguration; const VENDOR_ID_INTEL: u16 = 0x8086; const DEVICE_ID_INTEL_VIRT_PCIE_HOST: u16 = 0x0d57; diff --git a/pci/src/device.rs b/pci/src/device.rs index cddb30fce..3c5b3315f 100644 --- a/pci/src/device.rs +++ b/pci/src/device.rs @@ -12,8 +12,8 @@ use thiserror::Error; use vm_allocator::{AddressAllocator, SystemAllocator}; use vm_device::Resource; -use crate::configuration::{self, PciBarRegionType}; use crate::PciBarConfiguration; +use crate::configuration::{self, PciBarRegionType}; #[derive(Error, Debug)] pub enum Error { diff --git a/pci/src/lib.rs b/pci/src/lib.rs index 438a8ce94..c95a38b33 100644 --- a/pci/src/lib.rs +++ b/pci/src/lib.rs @@ -24,16 +24,16 @@ use serde::de::Visitor; pub use self::bus::{PciBus, PciConfigIo, PciConfigMmio, PciRoot, PciRootError}; pub use self::configuration::{ - PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciCapability, PciCapabilityId, - PciClassCode, PciConfiguration, PciExpressCapabilityId, PciHeaderType, PciMassStorageSubclass, - PciNetworkControllerSubclass, PciProgrammingInterface, PciSerialBusSubClass, PciSubclass, - PCI_CONFIGURATION_ID, + PCI_CONFIGURATION_ID, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciCapability, + PciCapabilityId, PciClassCode, PciConfiguration, PciExpressCapabilityId, PciHeaderType, + PciMassStorageSubclass, PciNetworkControllerSubclass, PciProgrammingInterface, + PciSerialBusSubClass, PciSubclass, }; pub use self::device::{ BarReprogrammingParams, DeviceRelocation, Error as PciDeviceError, PciDevice, }; -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::msi::{MsiCap, MsiConfig, msi_num_enabled_vectors}; +pub use self::msix::{MSIX_CONFIG_ID, MSIX_TABLE_ENTRY_SIZE, MsixCap, MsixConfig, MsixTableEntry}; pub use self::vfio::{MmioRegion, VfioDmaMapping, VfioPciDevice, VfioPciError}; pub use self::vfio_user::{VfioUserDmaMapping, VfioUserPciDevice, VfioUserPciDeviceError}; diff --git a/pci/src/vfio.rs b/pci/src/vfio.rs index 42048b8f5..97be4a7bc 100644 --- a/pci/src/vfio.rs +++ b/pci/src/vfio.rs @@ -14,7 +14,7 @@ use std::sync::{Arc, Barrier, Mutex}; use anyhow::anyhow; use byteorder::{ByteOrder, LittleEndian}; use hypervisor::HypervisorVmError; -use libc::{sysconf, _SC_PAGESIZE}; +use libc::{_SC_PAGESIZE, sysconf}; use serde::{Deserialize, Serialize}; use thiserror::Error; use vfio_bindings::bindings::vfio::*; @@ -34,13 +34,13 @@ 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::msi::{MSI_CONFIG_ID, MsiConfigState}; 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, + BarReprogrammingParams, MSIX_CONFIG_ID, MSIX_TABLE_ENTRY_SIZE, MsiCap, MsiConfig, MsixCap, + MsixConfig, PCI_CONFIGURATION_ID, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, + PciBdf, PciCapabilityId, PciClassCode, PciConfiguration, PciDevice, PciDeviceError, + PciExpressCapabilityId, PciHeaderType, PciSubclass, msi_num_enabled_vectors, }; pub(crate) const VFIO_COMMON_ID: &str = "vfio_common"; @@ -1664,9 +1664,8 @@ impl VfioPciDevice { if !is_page_size_aligned(area.size) || !is_page_size_aligned(area.offset) { warn!( "Could not mmap sparse area that is not page size aligned (offset = 0x{:x}, size = 0x{:x})", - area.offset, - area.size, - ); + area.offset, area.size, + ); return Ok(()); } @@ -2040,9 +2039,9 @@ impl ExternalDmaMapping for VfioDmaMapping t as u64, Err(e) => { - return Err(io::Error::other( - format!("unable to retrieve user address for gpa 0x{gpa:x} from guest memory region: {e}") - )); + return Err(io::Error::other(format!( + "unable to retrieve user address for gpa 0x{gpa:x} from guest memory region: {e}" + ))); } } } else if self.mmio_regions.lock().unwrap().check_range(gpa, size) { diff --git a/pci/src/vfio_user.rs b/pci/src/vfio_user.rs index f23259f48..7ca1d2881 100644 --- a/pci/src/vfio_user.rs +++ b/pci/src/vfio_user.rs @@ -24,7 +24,7 @@ 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::vfio::{UserMemoryRegion, VFIO_COMMON_ID, Vfio, VfioCommon, VfioError}; use crate::{ BarReprogrammingParams, PciBarConfiguration, PciBdf, PciDevice, PciDeviceError, PciSubclass, VfioPciError, diff --git a/performance-metrics/src/main.rs b/performance-metrics/src/main.rs index c34815581..220532f6c 100644 --- a/performance-metrics/src/main.rs +++ b/performance-metrics/src/main.rs @@ -9,8 +9,8 @@ extern crate test_infra; mod performance_tests; use std::process::Command; -use std::sync::mpsc::channel; use std::sync::Arc; +use std::sync::mpsc::channel; use std::time::Duration; use std::{env, fmt, thread}; diff --git a/performance-metrics/src/performance_tests.rs b/performance-metrics/src/performance_tests.rs index 46eb090fc..e29dca174 100644 --- a/performance-metrics/src/performance_tests.rs +++ b/performance-metrics/src/performance_tests.rs @@ -12,7 +12,7 @@ use std::{fs, thread}; use test_infra::{Error as InfraError, *}; use thiserror::Error; -use crate::{mean, ImageFormat, PerformanceTestControl, PerformanceTestOverrides}; +use crate::{ImageFormat, PerformanceTestControl, PerformanceTestOverrides, mean}; #[cfg(target_arch = "x86_64")] pub const FOCAL_IMAGE_NAME: &str = "focal-server-cloudimg-amd64-custom-20210609-0.raw"; diff --git a/rate_limiter/src/group.rs b/rate_limiter/src/group.rs index 51e18196a..f88311564 100644 --- a/rate_limiter/src/group.rs +++ b/rate_limiter/src/group.rs @@ -306,7 +306,7 @@ pub(crate) mod tests { use super::RateLimiterGroupHandle; use crate::group::RateLimiterGroup; - use crate::{TokenBucket, TokenType, REFILL_TIMER_INTERVAL_MS}; + use crate::{REFILL_TIMER_INTERVAL_MS, TokenBucket, TokenType}; impl RateLimiterGroupHandle { fn bandwidth(&self) -> Option { diff --git a/rate_limiter/src/lib.rs b/rate_limiter/src/lib.rs index 9d6799338..72221416f 100644 --- a/rate_limiter/src/lib.rs +++ b/rate_limiter/src/lib.rs @@ -48,8 +48,8 @@ extern crate log; use std::io; use std::os::unix::io::{AsRawFd, RawFd}; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; use thiserror::Error; @@ -470,7 +470,7 @@ impl RateLimiter { std::io::ErrorKind::WouldBlock => { return Err(Error::SpuriousRateLimiterEvent( "Rate limiter event handler called without a present timer", - )) + )); } _ => return Err(Error::TimerFdWaitError(err)), } diff --git a/serial_buffer/src/lib.rs b/serial_buffer/src/lib.rs index 6b9182d4c..f914f2ef5 100644 --- a/serial_buffer/src/lib.rs +++ b/serial_buffer/src/lib.rs @@ -5,8 +5,8 @@ use std::collections::VecDeque; use std::io::Write; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; const MAX_BUFFER_SIZE: usize = 1 << 20; diff --git a/src/bin/ch-remote.rs b/src/bin/ch-remote.rs index 904565e5c..803ffc7ee 100644 --- a/src/bin/ch-remote.rs +++ b/src/bin/ch-remote.rs @@ -13,8 +13,8 @@ use std::os::unix::net::UnixStream; use std::process; use api_client::{ - simple_api_command, simple_api_command_with_fds, simple_api_full_command, - Error as ApiClientError, + Error as ApiClientError, simple_api_command, simple_api_command_with_fds, + simple_api_full_command, }; use clap::{Arg, ArgAction, ArgMatches, Command}; use log::error; @@ -1128,7 +1128,9 @@ fn main() { process::exit(1); } _ => { - error!("Please either provide the api-socket option or dbus-service-name and dbus-object-path options"); + error!( + "Please either provide the api-socket option or dbus-service-name and dbus-object-path options" + ); process::exit(1); } }; diff --git a/src/main.rs b/src/main.rs index 8329100b6..3c94f36d8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,22 +8,22 @@ mod test_util; use std::fs::File; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; -use std::sync::mpsc::channel; use std::sync::Mutex; +use std::sync::mpsc::channel; use std::{env, io}; use clap::{Arg, ArgAction, ArgGroup, ArgMatches, Command}; use event_monitor::event; use libc::EFD_NONBLOCK; -use log::{error, warn, LevelFilter}; +use log::{LevelFilter, error, warn}; use option_parser::OptionParser; use seccompiler::SeccompAction; use signal_hook::consts::SIGSYS; use thiserror::Error; -#[cfg(feature = "dbus_api")] -use vmm::api::dbus::{dbus_api_graceful_shutdown, DBusApiOptions}; -use vmm::api::http::http_api_graceful_shutdown; use vmm::api::ApiAction; +#[cfg(feature = "dbus_api")] +use vmm::api::dbus::{DBusApiOptions, dbus_api_graceful_shutdown}; +use vmm::api::http::http_api_graceful_shutdown; use vmm::config::{RestoreConfig, VmParams}; use vmm::landlock::{Landlock, LandlockError}; use vmm::vm_config; diff --git a/test_infra/src/lib.rs b/test_infra/src/lib.rs index 812a3a933..641c5a15a 100644 --- a/test_infra/src/lib.rs +++ b/test_infra/src/lib.rs @@ -1118,10 +1118,12 @@ impl Guest { thread::sleep(std::time::Duration::new(10, 0)); // Write something to vsock from the host - assert!(exec_host_command_status(&format!( - "echo -e \"CONNECT 16\\nHelloWorld!\" | socat - UNIX-CONNECT:{socket}" - )) - .success()); + assert!( + exec_host_command_status(&format!( + "echo -e \"CONNECT 16\\nHelloWorld!\" | socat - UNIX-CONNECT:{socket}" + )) + .success() + ); // Wait for the thread to terminate. listen_socat.join().unwrap(); @@ -1134,10 +1136,11 @@ impl Guest { #[cfg(target_arch = "x86_64")] pub fn check_nvidia_gpu(&self) { - assert!(self - .ssh_command("nvidia-smi") - .unwrap() - .contains("NVIDIA L40S")); + assert!( + self.ssh_command("nvidia-smi") + .unwrap() + .contains("NVIDIA L40S") + ); } pub fn reboot_linux(&self, current_reboot_count: u32, custom_timeout: Option) { @@ -1334,11 +1337,9 @@ impl<'a> GuestCommand<'a> { if pipesize >= PIPE_SIZE && pipesize1 >= PIPE_SIZE { Ok(child) } else { - Err(std::io::Error::other( - format!( - "resizing pipe w/ 'fnctl' failed: stdout pipesize {pipesize}, stderr pipesize {pipesize1}" - ), - )) + Err(std::io::Error::other(format!( + "resizing pipe w/ 'fnctl' failed: stdout pipesize {pipesize}, stderr pipesize {pipesize1}" + ))) } } else { // The caller should call .wait() on the returned child diff --git a/tests/integration.rs b/tests/integration.rs index 255c27adf..bdb258a22 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -20,7 +20,7 @@ use std::path::PathBuf; use std::process::{Child, Command, Stdio}; use std::string::String; use std::sync::mpsc::Receiver; -use std::sync::{mpsc, Mutex}; +use std::sync::{Mutex, mpsc}; use std::time::Duration; use std::{fs, io, thread}; @@ -719,10 +719,12 @@ fn setup_ovs_dpdk() { assert!(exec_host_command_status("service openvswitch-switch restart").success()); // Create OVS-DPDK bridge and ports - assert!(exec_host_command_status( - "ovs-vsctl add-br ovsbr0 -- set bridge ovsbr0 datapath_type=netdev", - ) - .success()); + assert!( + exec_host_command_status( + "ovs-vsctl add-br ovsbr0 -- set bridge ovsbr0 datapath_type=netdev", + ) + .success() + ); assert!(exec_host_command_status("ovs-vsctl add-port ovsbr0 vhost-user1 -- set Interface vhost-user1 type=dpdkvhostuserclient options:vhost-server-path=/tmp/dpdkvhostclient1").success()); assert!(exec_host_command_status("ovs-vsctl add-port ovsbr0 vhost-user2 -- set Interface vhost-user2 type=dpdkvhostuserclient options:vhost-server-path=/tmp/dpdkvhostclient2").success()); assert!(exec_host_command_status("ip link set up dev ovsbr0").success()); @@ -1658,8 +1660,10 @@ fn _test_virtio_fs( "{{\"id\":\"myfs0\",\"bdf\":\"{pci_segment:04x}:00:01.0\"}}" ))); } else { - assert!(String::from_utf8_lossy(&cmd_output) - .contains("{\"id\":\"myfs0\",\"bdf\":\"0000:00:06.0\"}")); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains("{\"id\":\"myfs0\",\"bdf\":\"0000:00:06.0\"}") + ); } thread::sleep(std::time::Duration::new(10, 0)); @@ -1739,8 +1743,10 @@ fn _test_virtio_fs( "{{\"id\":\"myfs0\",\"bdf\":\"{pci_segment:04x}:00:01.0\"}}" ))); } else { - assert!(String::from_utf8_lossy(&cmd_output) - .contains("{\"id\":\"myfs0\",\"bdf\":\"0000:00:06.0\"}")); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains("{\"id\":\"myfs0\",\"bdf\":\"0000:00:06.0\"}") + ); } thread::sleep(std::time::Duration::new(10, 0)); @@ -1894,8 +1900,10 @@ fn _test_virtio_vsock(hotplug: bool) { Some(format!("cid=3,socket={socket},id=test0").as_str()), ); assert!(cmd_success); - assert!(String::from_utf8_lossy(&cmd_output) - .contains("{\"id\":\"test0\",\"bdf\":\"0000:00:06.0\"}")); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains("{\"id\":\"test0\",\"bdf\":\"0000:00:06.0\"}") + ); thread::sleep(std::time::Duration::new(10, 0)); // Check adding a second one fails assert!(!remote_command( @@ -2112,18 +2120,20 @@ fn get_counters(api_socket: &str) -> Counters { fn pty_read(mut pty: std::fs::File) -> Receiver { let (tx, rx) = mpsc::channel::(); - thread::spawn(move || loop { - thread::sleep(std::time::Duration::new(1, 0)); - let mut buf = [0; 512]; - match pty.read(&mut buf) { - Ok(_bytes) => { - let output = std::str::from_utf8(&buf).unwrap().to_string(); - match tx.send(output) { - Ok(_) => (), - Err(_) => break, + thread::spawn(move || { + loop { + thread::sleep(std::time::Duration::new(1, 0)); + let mut buf = [0; 512]; + match pty.read(&mut buf) { + Ok(_bytes) => { + let output = std::str::from_utf8(&buf).unwrap().to_string(); + match tx.send(output) { + Ok(_) => (), + Err(_) => break, + } } + Err(_) => break, } - Err(_) => break, } }); rx @@ -2257,9 +2267,11 @@ fn _test_virtio_iommu(acpi: bool) { guest.wait_vm_boot(None).unwrap(); // Verify the virtio-iommu device is present. - assert!(guest - .does_device_vendor_pair_match("0x1057", "0x1af4") - .unwrap_or_default()); + assert!( + guest + .does_device_vendor_pair_match("0x1057", "0x1af4") + .unwrap_or_default() + ); // On AArch64, if the guest system boots from FDT, the behavior of IOMMU is a bit // different with ACPI. @@ -2319,9 +2331,11 @@ fn get_reboot_count(guest: &Guest) -> u32 { fn enable_guest_watchdog(guest: &Guest, watchdog_sec: u32) { // Check for PCI device - assert!(guest - .does_device_vendor_pair_match("0x1063", "0x1af4") - .unwrap_or_default()); + assert!( + guest + .does_device_vendor_pair_match("0x1063", "0x1af4") + .unwrap_or_default() + ); // Enable systemd watchdog guest @@ -2335,9 +2349,11 @@ fn enable_guest_watchdog(guest: &Guest, watchdog_sec: u32) { fn make_guest_panic(guest: &Guest) { // Check for pvpanic device - assert!(guest - .does_device_vendor_pair_match("0x0011", "0x1b36") - .unwrap_or_default()); + assert!( + guest + .does_device_vendor_pair_match("0x0011", "0x1b36") + .unwrap_or_default() + ); // Trigger guest a panic guest.ssh_command("screen -dmS reboot sh -c \"sleep 5; echo s | tee /proc/sysrq-trigger; echo c | sudo tee /proc/sysrq-trigger\"").unwrap(); @@ -2974,13 +2990,17 @@ mod common_parallel { ), ); assert!(cmd_success); - assert!(String::from_utf8_lossy(&cmd_output) - .contains("{\"id\":\"test0\",\"bdf\":\"0001:00:01.0\"}")); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains("{\"id\":\"test0\",\"bdf\":\"0001:00:01.0\"}") + ); // Check IOMMU setup - assert!(guest - .does_device_vendor_pair_match("0x1057", "0x1af4") - .unwrap_or_default()); + assert!( + guest + .does_device_vendor_pair_match("0x1057", "0x1af4") + .unwrap_or_default() + ); assert_eq!( guest .ssh_command("ls /sys/kernel/iommu_groups/0/devices") @@ -4429,9 +4449,11 @@ mod common_parallel { let r = std::panic::catch_unwind(|| { guest.wait_vm_boot(None).unwrap(); - assert!(guest - .does_device_vendor_pair_match("0x1043", "0x1af4") - .unwrap_or_default()); + assert!( + guest + .does_device_vendor_pair_match("0x1043", "0x1af4") + .unwrap_or_default() + ); guest.ssh_command(&cmd).unwrap(); }); @@ -5407,8 +5429,10 @@ mod common_parallel { ), ); assert!(cmd_success); - assert!(String::from_utf8_lossy(&cmd_output) - .contains("{\"id\":\"test0\",\"bdf\":\"0000:00:06.0\"}")); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains("{\"id\":\"test0\",\"bdf\":\"0000:00:06.0\"}") + ); thread::sleep(std::time::Duration::new(10, 0)); @@ -5454,8 +5478,10 @@ mod common_parallel { ), ); assert!(cmd_success); - assert!(String::from_utf8_lossy(&cmd_output) - .contains("{\"id\":\"test0\",\"bdf\":\"0000:00:06.0\"}")); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains("{\"id\":\"test0\",\"bdf\":\"0000:00:06.0\"}") + ); thread::sleep(std::time::Duration::new(10, 0)); @@ -5953,8 +5979,10 @@ mod common_parallel { "{{\"id\":\"test0\",\"bdf\":\"{pci_segment:04x}:00:01.0\"}}" ))); } else { - assert!(String::from_utf8_lossy(&cmd_output) - .contains("{\"id\":\"test0\",\"bdf\":\"0000:00:06.0\"}")); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains("{\"id\":\"test0\",\"bdf\":\"0000:00:06.0\"}") + ); } // Check that /dev/pmem0 exists and the block size is 128M @@ -6084,8 +6112,10 @@ mod common_parallel { "{{\"id\":\"test0\",\"bdf\":\"{pci_segment:04x}:00:01.0\"}}" ))); } else { - assert!(String::from_utf8_lossy(&cmd_output) - .contains("{\"id\":\"test0\",\"bdf\":\"0000:00:05.0\"}")); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains("{\"id\":\"test0\",\"bdf\":\"0000:00:05.0\"}") + ); } thread::sleep(std::time::Duration::new(5, 0)); @@ -6128,8 +6158,10 @@ mod common_parallel { "{{\"id\":\"test1\",\"bdf\":\"{pci_segment:04x}:00:01.0\"}}" ))); } else { - assert!(String::from_utf8_lossy(&cmd_output) - .contains("{\"id\":\"test1\",\"bdf\":\"0000:00:05.0\"}")); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains("{\"id\":\"test1\",\"bdf\":\"0000:00:05.0\"}") + ); } thread::sleep(std::time::Duration::new(5, 0)); @@ -6566,15 +6598,19 @@ mod common_parallel { let phy_net = "eth0"; // Create a macvtap interface for the guest VM to use - assert!(exec_host_command_status(&format!( - "sudo ip link add link {phy_net} name {guest_macvtap_name} type macvtap mod bridge" - )) - .success()); - assert!(exec_host_command_status(&format!( - "sudo ip link set {} address {} up", - guest_macvtap_name, guest.network.guest_mac - )) - .success()); + assert!( + exec_host_command_status(&format!( + "sudo ip link add link {phy_net} name {guest_macvtap_name} type macvtap mod bridge" + )) + .success() + ); + assert!( + exec_host_command_status(&format!( + "sudo ip link set {} address {} up", + guest_macvtap_name, guest.network.guest_mac + )) + .success() + ); assert!( exec_host_command_status(&format!("sudo ip link show {guest_macvtap_name}")).success() ); @@ -6593,16 +6629,20 @@ mod common_parallel { // Create a macvtap on the same physical net interface for // the host machine to use - assert!(exec_host_command_status(&format!( - "sudo ip link add link {phy_net} name {host_macvtap_name} type macvtap mod bridge" - )) - .success()); + assert!( + exec_host_command_status(&format!( + "sudo ip link add link {phy_net} name {host_macvtap_name} type macvtap mod bridge" + )) + .success() + ); // Use default mask "255.255.255.0" - assert!(exec_host_command_status(&format!( - "sudo ip address add {}/24 dev {}", - guest.network.host_ip, host_macvtap_name - )) - .success()); + assert!( + exec_host_command_status(&format!( + "sudo ip address add {}/24 dev {}", + guest.network.host_ip, host_macvtap_name + )) + .success() + ); assert!( exec_host_command_status(&format!("sudo ip link set dev {host_macvtap_name} up")) .success() @@ -6638,11 +6678,15 @@ mod common_parallel { remote_command_w_output(&api_socket, "add-net", Some(&net_params)); assert!(cmd_success); #[cfg(target_arch = "x86_64")] - assert!(String::from_utf8_lossy(&cmd_output) - .contains("{\"id\":\"_net2\",\"bdf\":\"0000:00:05.0\"}")); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains("{\"id\":\"_net2\",\"bdf\":\"0000:00:05.0\"}") + ); #[cfg(target_arch = "aarch64")] - assert!(String::from_utf8_lossy(&cmd_output) - .contains("{\"id\":\"_net0\",\"bdf\":\"0000:00:05.0\"}")); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains("{\"id\":\"_net0\",\"bdf\":\"0000:00:05.0\"}") + ); } // The functional connectivity provided by the virtio-net device @@ -6818,21 +6862,27 @@ mod common_parallel { fn setup_spdk_nvme(nvme_dir: &std::path::Path) -> Child { cleanup_spdk_nvme(); - assert!(exec_host_command_status(&format!( - "mkdir -p {}", - nvme_dir.join("nvme-vfio-user").to_str().unwrap() - )) - .success()); - assert!(exec_host_command_status(&format!( - "truncate {} -s 128M", - nvme_dir.join("test-disk.raw").to_str().unwrap() - )) - .success()); - assert!(exec_host_command_status(&format!( - "mkfs.ext4 {}", - nvme_dir.join("test-disk.raw").to_str().unwrap() - )) - .success()); + assert!( + exec_host_command_status(&format!( + "mkdir -p {}", + nvme_dir.join("nvme-vfio-user").to_str().unwrap() + )) + .success() + ); + assert!( + exec_host_command_status(&format!( + "truncate {} -s 128M", + nvme_dir.join("test-disk.raw").to_str().unwrap() + )) + .success() + ); + assert!( + exec_host_command_status(&format!( + "mkfs.ext4 {}", + nvme_dir.join("test-disk.raw").to_str().unwrap() + )) + .success() + ); // Start the SPDK nvmf_tgt daemon to present NVMe device as a VFIO user device let child = Command::new("/usr/local/bin/spdk-nvme/nvmf_tgt") @@ -6846,11 +6896,13 @@ mod common_parallel { 3, std::time::Duration::new(5, 0), )); - assert!(exec_host_command_status(&format!( - "/usr/local/bin/spdk-nvme/rpc.py bdev_aio_create {} test 512", - nvme_dir.join("test-disk.raw").to_str().unwrap() - )) - .success()); + assert!( + exec_host_command_status(&format!( + "/usr/local/bin/spdk-nvme/rpc.py bdev_aio_create {} test 512", + nvme_dir.join("test-disk.raw").to_str().unwrap() + )) + .success() + ); assert!(exec_host_command_status( "/usr/local/bin/spdk-nvme/rpc.py nvmf_create_subsystem nqn.2019-07.io.spdk:cnode -a -s test" ) @@ -6911,8 +6963,10 @@ mod common_parallel { )), ); assert!(cmd_success); - assert!(String::from_utf8_lossy(&cmd_output) - .contains("{\"id\":\"vfio_user0\",\"bdf\":\"0000:00:05.0\"}")); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains("{\"id\":\"vfio_user0\",\"bdf\":\"0000:00:05.0\"}") + ); thread::sleep(std::time::Duration::new(10, 0)); @@ -7017,15 +7071,19 @@ mod common_parallel { Some("id=myvdpa0,path=/dev/vhost-vdpa-1,num_queues=1,pci_segment=1,iommu=on"), ); assert!(cmd_success); - assert!(String::from_utf8_lossy(&cmd_output) - .contains("{\"id\":\"myvdpa0\",\"bdf\":\"0001:00:01.0\"}")); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains("{\"id\":\"myvdpa0\",\"bdf\":\"0001:00:01.0\"}") + ); thread::sleep(std::time::Duration::new(10, 0)); // Check IOMMU setup - assert!(guest - .does_device_vendor_pair_match("0x1057", "0x1af4") - .unwrap_or_default()); + assert!( + guest + .does_device_vendor_pair_match("0x1057", "0x1af4") + .unwrap_or_default() + ); assert_eq!( guest .ssh_command("ls /sys/kernel/iommu_groups/0/devices") @@ -7419,7 +7477,7 @@ mod ivshmem { use std::fs::remove_dir_all; use std::process::Command; - use test_infra::{handle_child_output, kill_child, Guest, GuestCommand, UbuntuDiskConfig}; + use test_infra::{Guest, GuestCommand, UbuntuDiskConfig, handle_child_output, kill_child}; use crate::*; @@ -9404,8 +9462,10 @@ mod windows { Some(format!("path={disk},readonly=off").as_str()), ); assert!(cmd_success); - assert!(String::from_utf8_lossy(&cmd_output) - .contains(format!("\"id\":\"{disk_id}\"").as_str())); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains(format!("\"id\":\"{disk_id}\"").as_str()) + ); thread::sleep(std::time::Duration::new(5, 0)); // Online disk devices windows_guest.disks_set_rw(); @@ -9615,8 +9675,10 @@ mod vfio { Some(format!("id=vfio0,path={NVIDIA_VFIO_DEVICE}").as_str()), ); assert!(cmd_success); - assert!(String::from_utf8_lossy(&cmd_output) - .contains("{\"id\":\"vfio0\",\"bdf\":\"0000:00:06.0\"}")); + assert!( + String::from_utf8_lossy(&cmd_output) + .contains("{\"id\":\"vfio0\",\"bdf\":\"0000:00:06.0\"}") + ); thread::sleep(std::time::Duration::new(10, 0)); @@ -9694,10 +9756,12 @@ mod vfio { let r = std::panic::catch_unwind(|| { guest.wait_vm_boot(None).unwrap(); - assert!(guest - .ssh_command("sudo dmesg") - .unwrap() - .contains("input address: 42 bits")); + assert!( + guest + .ssh_command("sudo dmesg") + .unwrap() + .contains("input address: 42 bits") + ); }); let _ = child.kill(); @@ -9818,13 +9882,13 @@ mod live_migration { let _ = dest_vm.kill(); let dest_output = dest_vm.wait_with_output().unwrap(); eprintln!( - "\n\n==== Start 'destination_vm' stdout ====\n\n{}\n\n==== End 'destination_vm' stdout ====", - String::from_utf8_lossy(&dest_output.stdout) - ); + "\n\n==== Start 'destination_vm' stdout ====\n\n{}\n\n==== End 'destination_vm' stdout ====", + String::from_utf8_lossy(&dest_output.stdout) + ); eprintln!( - "\n\n==== Start 'destination_vm' stderr ====\n\n{}\n\n==== End 'destination_vm' stderr ====", - String::from_utf8_lossy(&dest_output.stderr) - ); + "\n\n==== Start 'destination_vm' stderr ====\n\n{}\n\n==== End 'destination_vm' stderr ====", + String::from_utf8_lossy(&dest_output.stderr) + ); if let Some(ovs_vm) = ovs_vm { let mut ovs_vm = ovs_vm; @@ -11382,11 +11446,13 @@ mod rate_limiter { String::from(test_img_dir.as_path().join("blk.img").to_str().unwrap()); // Create the test block image - assert!(exec_host_command_output(&format!( - "dd if=/dev/zero of={blk_rate_limiter_test_img} bs=1M count=1024" - )) - .status - .success()); + assert!( + exec_host_command_output(&format!( + "dd if=/dev/zero of={blk_rate_limiter_test_img} bs=1M count=1024" + )) + .status + .success() + ); let test_blk_params = if bandwidth { format!( @@ -11491,11 +11557,13 @@ mod rate_limiter { .unwrap(), ); - assert!(exec_host_command_output(&format!( - "dd if=/dev/zero of={test_img_path} bs=1M count=1024" - )) - .status - .success()); + assert!( + exec_host_command_output(&format!( + "dd if=/dev/zero of={test_img_path} bs=1M count=1024" + )) + .status + .success() + ); disk_args.push(format!( "path={test_img_path},num_queues={num_queues},rate_limit_group=group0" diff --git a/vhost_user_block/src/lib.rs b/vhost_user_block/src/lib.rs index 5e668c0c5..3977a25ab 100644 --- a/vhost_user_block/src/lib.rs +++ b/vhost_user_block/src/lib.rs @@ -19,13 +19,13 @@ use std::time::Instant; use std::{convert, io, process, result}; use block::qcow::{self, ImageType, QcowFile}; -use block::{build_serial, Request, VirtioBlockConfig}; +use block::{Request, VirtioBlockConfig, build_serial}; use libc::EFD_NONBLOCK; use log::*; use option_parser::{OptionParser, OptionParserError, Toggle}; use thiserror::Error; -use vhost::vhost_user::message::*; use vhost::vhost_user::Listener; +use vhost::vhost_user::message::*; use vhost_user_backend::bitmap::BitmapMmapRegion; use vhost_user_backend::{VhostUserBackendMut, VhostUserDaemon, VringRwLock, VringState, VringT}; use virtio_bindings::virtio_blk::*; diff --git a/vhost_user_net/src/lib.rs b/vhost_user_net/src/lib.rs index de2a416aa..b5c0aa801 100644 --- a/vhost_user_net/src/lib.rs +++ b/vhost_user_net/src/lib.rs @@ -15,12 +15,12 @@ use std::{io, process}; use libc::EFD_NONBLOCK; use log::*; use net_util::{ - open_tap, MacAddr, NetCounters, NetQueuePair, OpenTapError, RxVirtio, Tap, TxVirtio, + MacAddr, NetCounters, NetQueuePair, OpenTapError, RxVirtio, Tap, TxVirtio, open_tap, }; use option_parser::{OptionParser, OptionParserError, Toggle}; use thiserror::Error; -use vhost::vhost_user::message::*; use vhost::vhost_user::Listener; +use vhost::vhost_user::message::*; use vhost_user_backend::bitmap::BitmapMmapRegion; use vhost_user_backend::{VhostUserBackendMut, VhostUserDaemon, VringRwLock, VringT}; use virtio_bindings::virtio_config::{VIRTIO_F_NOTIFY_ON_EMPTY, VIRTIO_F_VERSION_1}; diff --git a/virtio-devices/src/balloon.rs b/virtio-devices/src/balloon.rs index 2a34b6688..1a5e202fd 100644 --- a/virtio-devices/src/balloon.rs +++ b/virtio-devices/src/balloon.rs @@ -37,9 +37,9 @@ use vmm_sys_util::eventfd::EventFd; use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; use crate::{ - ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, GuestMemoryMmap, - VirtioCommon, VirtioDevice, VirtioDeviceType, VirtioInterrupt, VirtioInterruptType, - EPOLL_HELPER_EVENT_LAST, VIRTIO_F_VERSION_1, + ActivateResult, EPOLL_HELPER_EVENT_LAST, EpollHelper, EpollHelperError, EpollHelperHandler, + GuestMemoryMmap, VIRTIO_F_VERSION_1, VirtioCommon, VirtioDevice, VirtioDeviceType, + VirtioInterrupt, VirtioInterruptType, }; const QUEUE_SIZE: u16 = 128; @@ -575,12 +575,12 @@ impl VirtioDevice for Balloon { let data_len = data.len() as u64; if offset + data_len > config_len { error!( - "Out-of-bound access to configuration: config_len = {} offset = {:x} length = {} for {}", - config_len, - offset, - data_len, - self.device_type() - ); + "Out-of-bound access to configuration: config_len = {} offset = {:x} length = {} for {}", + config_len, + offset, + data_len, + self.device_type() + ); return; } diff --git a/virtio-devices/src/block.rs b/virtio-devices/src/block.rs index 415ae3f36..dad4fd215 100644 --- a/virtio-devices/src/block.rs +++ b/virtio-devices/src/block.rs @@ -19,12 +19,12 @@ use std::{io, result}; use anyhow::anyhow; use block::async_io::{AsyncIo, AsyncIoError, DiskFile}; -use block::fcntl::{get_lock_state, LockError, LockType}; +use block::fcntl::{LockError, LockType, get_lock_state}; use block::{ - build_serial, fcntl, ExecuteAsync, ExecuteError, Request, RequestType, VirtioBlockConfig, + ExecuteAsync, ExecuteError, Request, RequestType, VirtioBlockConfig, build_serial, fcntl, }; -use rate_limiter::group::{RateLimiterGroup, RateLimiterGroupHandle}; use rate_limiter::TokenType; +use rate_limiter::group::{RateLimiterGroup, RateLimiterGroupHandle}; use seccompiler::SeccompAction; use serde::{Deserialize, Serialize}; use thiserror::Error; @@ -38,9 +38,9 @@ use vm_virtio::AccessPlatform; use vmm_sys_util::eventfd::EventFd; use super::{ - ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, - Error as DeviceError, VirtioCommon, VirtioDevice, VirtioDeviceType, VirtioInterruptType, - EPOLL_HELPER_EVENT_LAST, + ActivateError, ActivateResult, EPOLL_HELPER_EVENT_LAST, EpollHelper, EpollHelperError, + EpollHelperHandler, Error as DeviceError, VirtioCommon, VirtioDevice, VirtioDeviceType, + VirtioInterruptType, }; use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; diff --git a/virtio-devices/src/console.rs b/virtio-devices/src/console.rs index f05c0c4f4..2c0e250a4 100644 --- a/virtio-devices/src/console.rs +++ b/virtio-devices/src/console.rs @@ -22,9 +22,9 @@ use vm_virtio::{AccessPlatform, Translatable}; use vmm_sys_util::eventfd::EventFd; use super::{ - ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, Error as DeviceError, - VirtioCommon, VirtioDevice, VirtioDeviceType, VirtioInterruptType, EPOLL_HELPER_EVENT_LAST, - VIRTIO_F_IOMMU_PLATFORM, VIRTIO_F_VERSION_1, + ActivateResult, EPOLL_HELPER_EVENT_LAST, EpollHelper, EpollHelperError, EpollHelperHandler, + Error as DeviceError, VIRTIO_F_IOMMU_PLATFORM, VIRTIO_F_VERSION_1, VirtioCommon, VirtioDevice, + VirtioDeviceType, VirtioInterruptType, }; use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; diff --git a/virtio-devices/src/iommu.rs b/virtio-devices/src/iommu.rs index df310823a..71c10c1d0 100644 --- a/virtio-devices/src/iommu.rs +++ b/virtio-devices/src/iommu.rs @@ -24,8 +24,8 @@ use vm_virtio::AccessPlatform; use vmm_sys_util::eventfd::EventFd; use super::{ - ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, Error as DeviceError, - VirtioCommon, VirtioDevice, VirtioDeviceType, EPOLL_HELPER_EVENT_LAST, VIRTIO_F_VERSION_1, + ActivateResult, EPOLL_HELPER_EVENT_LAST, EpollHelper, EpollHelperError, EpollHelperHandler, + Error as DeviceError, VIRTIO_F_VERSION_1, VirtioCommon, VirtioDevice, VirtioDeviceType, }; use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; diff --git a/virtio-devices/src/lib.rs b/virtio-devices/src/lib.rs index a59661eb6..86359da65 100644 --- a/virtio-devices/src/lib.rs +++ b/virtio-devices/src/lib.rs @@ -51,10 +51,10 @@ pub use self::device::{ VirtioSharedMemoryList, }; pub use self::epoll_helper::{ - EpollHelper, EpollHelperError, EpollHelperHandler, EPOLL_HELPER_EVENT_LAST, + EPOLL_HELPER_EVENT_LAST, EpollHelper, EpollHelperError, EpollHelperHandler, }; pub use self::iommu::{AccessPlatformMapping, Iommu, IommuMapping}; -pub use self::mem::{BlocksState, Mem, VirtioMemMappingSource, VIRTIO_MEM_ALIGN_SIZE}; +pub use self::mem::{BlocksState, Mem, VIRTIO_MEM_ALIGN_SIZE, VirtioMemMappingSource}; pub use self::net::{Net, NetCtrlEpollHandler}; pub use self::pmem::Pmem; pub use self::rng::Rng; diff --git a/virtio-devices/src/mem.rs b/virtio-devices/src/mem.rs index 8d5830ac3..6971f0715 100644 --- a/virtio-devices/src/mem.rs +++ b/virtio-devices/src/mem.rs @@ -18,7 +18,7 @@ use std::collections::BTreeMap; use std::mem::size_of; use std::os::unix::io::{AsRawFd, RawFd}; use std::sync::atomic::AtomicBool; -use std::sync::{mpsc, Arc, Barrier, Mutex}; +use std::sync::{Arc, Barrier, Mutex, mpsc}; use std::{io, result}; use anyhow::anyhow; @@ -36,9 +36,9 @@ use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottabl use vmm_sys_util::eventfd::EventFd; use super::{ - ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, - Error as DeviceError, VirtioCommon, VirtioDevice, VirtioDeviceType, EPOLL_HELPER_EVENT_LAST, - VIRTIO_F_VERSION_1, + ActivateError, ActivateResult, EPOLL_HELPER_EVENT_LAST, EpollHelper, EpollHelperError, + EpollHelperHandler, Error as DeviceError, VIRTIO_F_VERSION_1, VirtioCommon, VirtioDevice, + VirtioDeviceType, }; use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; diff --git a/virtio-devices/src/net.rs b/virtio-devices/src/net.rs index 950cedb51..4518321ec 100644 --- a/virtio-devices/src/net.rs +++ b/virtio-devices/src/net.rs @@ -18,8 +18,8 @@ use anyhow::anyhow; #[cfg(not(fuzzing))] use net_util::virtio_features_to_tap_offload; use net_util::{ - build_net_config_space, build_net_config_space_with_mq, open_tap, CtrlQueue, MacAddr, - NetCounters, NetQueuePair, OpenTapError, RxVirtio, Tap, TapError, TxVirtio, VirtioNetConfig, + CtrlQueue, MacAddr, NetCounters, NetQueuePair, OpenTapError, RxVirtio, Tap, TapError, TxVirtio, + VirtioNetConfig, build_net_config_space, build_net_config_space_with_mq, open_tap, }; use seccompiler::SeccompAction; use serde::{Deserialize, Serialize}; @@ -34,9 +34,9 @@ use vm_virtio::AccessPlatform; use vmm_sys_util::eventfd::EventFd; use super::{ - ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, - Error as DeviceError, RateLimiterConfig, VirtioCommon, VirtioDevice, VirtioDeviceType, - VirtioInterruptType, EPOLL_HELPER_EVENT_LAST, + ActivateError, ActivateResult, EPOLL_HELPER_EVENT_LAST, EpollHelper, EpollHelperError, + EpollHelperHandler, Error as DeviceError, RateLimiterConfig, VirtioCommon, VirtioDevice, + VirtioDeviceType, VirtioInterruptType, }; use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; diff --git a/virtio-devices/src/pmem.rs b/virtio-devices/src/pmem.rs index 1e4353477..8e41f0ec0 100644 --- a/virtio-devices/src/pmem.rs +++ b/virtio-devices/src/pmem.rs @@ -28,9 +28,9 @@ use vm_virtio::{AccessPlatform, Translatable}; use vmm_sys_util::eventfd::EventFd; use super::{ - ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, - Error as DeviceError, VirtioCommon, VirtioDevice, VirtioDeviceType, EPOLL_HELPER_EVENT_LAST, - VIRTIO_F_IOMMU_PLATFORM, VIRTIO_F_VERSION_1, + ActivateError, ActivateResult, EPOLL_HELPER_EVENT_LAST, EpollHelper, EpollHelperError, + EpollHelperHandler, Error as DeviceError, VIRTIO_F_IOMMU_PLATFORM, VIRTIO_F_VERSION_1, + VirtioCommon, VirtioDevice, VirtioDeviceType, }; use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; diff --git a/virtio-devices/src/rng.rs b/virtio-devices/src/rng.rs index 8429e3b31..6dccb2de1 100644 --- a/virtio-devices/src/rng.rs +++ b/virtio-devices/src/rng.rs @@ -21,9 +21,9 @@ use vm_virtio::{AccessPlatform, Translatable}; use vmm_sys_util::eventfd::EventFd; use super::{ - ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, - Error as DeviceError, VirtioCommon, VirtioDevice, VirtioDeviceType, EPOLL_HELPER_EVENT_LAST, - VIRTIO_F_IOMMU_PLATFORM, VIRTIO_F_VERSION_1, + ActivateError, ActivateResult, EPOLL_HELPER_EVENT_LAST, EpollHelper, EpollHelperError, + EpollHelperHandler, Error as DeviceError, VIRTIO_F_IOMMU_PLATFORM, VIRTIO_F_VERSION_1, + VirtioCommon, VirtioDevice, VirtioDeviceType, }; use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; diff --git a/virtio-devices/src/seccomp_filters.rs b/virtio-devices/src/seccomp_filters.rs index abad842bb..5986e72ea 100644 --- a/virtio-devices/src/seccomp_filters.rs +++ b/virtio-devices/src/seccomp_filters.rs @@ -53,13 +53,15 @@ const VFIO_IOMMU_UNMAP_DMA: u64 = 0x3b72; #[cfg(feature = "sev_snp")] fn mshv_sev_snp_ioctl_seccomp_rule() -> SeccompRule { - and![Cond::new( - 1, - ArgLen::Dword, - Eq, - mshv_ioctls::MSHV_MODIFY_GPA_HOST_ACCESS() - ) - .unwrap()] + and![ + Cond::new( + 1, + ArgLen::Dword, + Eq, + mshv_ioctls::MSHV_MODIFY_GPA_HOST_ACCESS() + ) + .unwrap() + ] } #[cfg(feature = "sev_snp")] diff --git a/virtio-devices/src/thread_helper.rs b/virtio-devices/src/thread_helper.rs index 41eb99b7c..d4df6c86b 100644 --- a/virtio-devices/src/thread_helper.rs +++ b/virtio-devices/src/thread_helper.rs @@ -6,12 +6,12 @@ use std::panic::AssertUnwindSafe; use std::thread::{self, JoinHandle}; -use seccompiler::{apply_filter, SeccompAction}; +use seccompiler::{SeccompAction, apply_filter}; use vmm_sys_util::eventfd::EventFd; -use crate::epoll_helper::EpollHelperError; -use crate::seccomp_filters::{get_seccomp_filter, Thread}; use crate::ActivateError; +use crate::epoll_helper::EpollHelperError; +use crate::seccomp_filters::{Thread, get_seccomp_filter}; pub(crate) fn spawn_virtio_thread( name: &str, diff --git a/virtio-devices/src/transport/mod.rs b/virtio-devices/src/transport/mod.rs index fae6f166b..9214de5db 100644 --- a/virtio-devices/src/transport/mod.rs +++ b/virtio-devices/src/transport/mod.rs @@ -5,7 +5,7 @@ use vmm_sys_util::eventfd::EventFd; mod pci_common_config; mod pci_device; -pub use pci_common_config::{VirtioPciCommonConfig, VIRTIO_PCI_COMMON_CONFIG_ID}; +pub use pci_common_config::{VIRTIO_PCI_COMMON_CONFIG_ID, VirtioPciCommonConfig}; pub use pci_device::{VirtioPciDevice, VirtioPciDeviceActivator, VirtioPciDeviceError}; pub trait VirtioTransport { diff --git a/virtio-devices/src/transport/pci_device.rs b/virtio-devices/src/transport/pci_device.rs index f493e32ab..a16102218 100644 --- a/virtio-devices/src/transport/pci_device.rs +++ b/virtio-devices/src/transport/pci_device.rs @@ -35,11 +35,11 @@ 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::transport::{VIRTIO_PCI_COMMON_CONFIG_ID, VirtioPciCommonConfig, VirtioTransport}; use crate::{ - ActivateResult, GuestMemoryMmap, VirtioDevice, VirtioDeviceType, VirtioInterrupt, - VirtioInterruptType, DEVICE_ACKNOWLEDGE, DEVICE_DRIVER, DEVICE_DRIVER_OK, DEVICE_FAILED, - DEVICE_FEATURES_OK, DEVICE_INIT, + ActivateResult, DEVICE_ACKNOWLEDGE, DEVICE_DRIVER, DEVICE_DRIVER_OK, DEVICE_FAILED, + DEVICE_FEATURES_OK, DEVICE_INIT, GuestMemoryMmap, VirtioDevice, VirtioDeviceType, + VirtioInterrupt, VirtioInterruptType, }; /// Vector value used to disable MSI for a queue. @@ -973,7 +973,7 @@ impl PciDevice for VirtioPciDevice { settings_bar_addr = Some(GuestAddress(base)); use_64bit_bar = match type_ { PciBarType::Io => { - return Err(PciDeviceError::InvalidResource(resource)) + return Err(PciDeviceError::InvalidResource(resource)); } PciBarType::Mmio32 => false, PciBarType::Mmio64 => true, diff --git a/virtio-devices/src/vdpa.rs b/virtio-devices/src/vdpa.rs index decd6ede6..6ca4f7dda 100644 --- a/virtio-devices/src/vdpa.rs +++ b/virtio-devices/src/vdpa.rs @@ -12,9 +12,9 @@ use anyhow::anyhow; use serde::{Deserialize, Serialize}; use thiserror::Error; use vhost::vdpa::{VhostVdpa, VhostVdpaIovaRange}; +use vhost::vhost_kern::VhostKernFeatures; use vhost::vhost_kern::vdpa::VhostKernVdpa; use vhost::vhost_kern::vhost_binding::VHOST_BACKEND_F_SUSPEND; -use vhost::vhost_kern::VhostKernFeatures; use vhost::{VhostBackend, VringConfigData}; use virtio_queue::desc::RawDescriptor; use virtio_queue::{Queue, QueueT}; @@ -25,9 +25,9 @@ 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, + ActivateError, ActivateResult, DEVICE_ACKNOWLEDGE, DEVICE_DRIVER, DEVICE_DRIVER_OK, + DEVICE_FEATURES_OK, GuestMemoryMmap, VIRTIO_F_IOMMU_PLATFORM, VirtioCommon, VirtioDevice, + VirtioInterrupt, VirtioInterruptType, }; #[derive(Error, Debug)] diff --git a/virtio-devices/src/vhost_user/blk.rs b/virtio-devices/src/vhost_user/blk.rs index 87ca4130a..d009280a8 100644 --- a/virtio-devices/src/vhost_user/blk.rs +++ b/virtio-devices/src/vhost_user/blk.rs @@ -9,8 +9,8 @@ use block::VirtioBlockConfig; use seccompiler::SeccompAction; use serde::{Deserialize, Serialize}; use vhost::vhost_user::message::{ - VhostUserConfigFlags, VhostUserProtocolFeatures, VhostUserVirtioFeatures, - VHOST_USER_CONFIG_OFFSET, + VHOST_USER_CONFIG_OFFSET, VhostUserConfigFlags, VhostUserProtocolFeatures, + VhostUserVirtioFeatures, }; use vhost::vhost_user::{FrontendReqHandler, VhostUserFrontend, VhostUserFrontendReqHandler}; use virtio_bindings::virtio_blk::{ @@ -26,11 +26,11 @@ 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 super::{DEFAULT_VIRTIO_FEATURES, Error, Result}; use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; use crate::vhost_user::VhostUserCommon; -use crate::{GuestMemoryMmap, GuestRegionMmap, VirtioInterrupt, VIRTIO_F_IOMMU_PLATFORM}; +use crate::{GuestMemoryMmap, GuestRegionMmap, VIRTIO_F_IOMMU_PLATFORM, VirtioInterrupt}; const DEFAULT_QUEUE_NUMBER: usize = 1; @@ -134,8 +134,10 @@ impl Blk { }; if num_queues > backend_num_queues { - error!("vhost-user-blk requested too many queues ({}) since the backend only supports {}\n", - num_queues, backend_num_queues); + error!( + "vhost-user-blk requested too many queues ({}) since the backend only supports {}\n", + num_queues, backend_num_queues + ); return Err(Error::BadQueueNum); } diff --git a/virtio-devices/src/vhost_user/fs.rs b/virtio-devices/src/vhost_user/fs.rs index 4aa692047..4c70db2f1 100644 --- a/virtio-devices/src/vhost_user/fs.rs +++ b/virtio-devices/src/vhost_user/fs.rs @@ -7,7 +7,7 @@ use std::{result, thread}; use seccompiler::SeccompAction; use serde::{Deserialize, Serialize}; -use serde_with::{serde_as, Bytes}; +use serde_with::{Bytes, serde_as}; use vhost::vhost_user::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; use vhost::vhost_user::{FrontendReqHandler, VhostUserFrontend, VhostUserFrontendReqHandler}; use virtio_queue::Queue; @@ -18,13 +18,13 @@ use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottabl use vmm_sys_util::eventfd::EventFd; use super::vu_common_ctrl::VhostUserHandle; -use super::{Error, Result, DEFAULT_VIRTIO_FEATURES}; +use super::{DEFAULT_VIRTIO_FEATURES, Error, Result}; use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; use crate::vhost_user::VhostUserCommon; use crate::{ - ActivateResult, GuestMemoryMmap, GuestRegionMmap, MmapRegion, VirtioCommon, VirtioDevice, - VirtioDeviceType, VirtioInterrupt, VirtioSharedMemoryList, VIRTIO_F_IOMMU_PLATFORM, + ActivateResult, GuestMemoryMmap, GuestRegionMmap, MmapRegion, VIRTIO_F_IOMMU_PLATFORM, + VirtioCommon, VirtioDevice, VirtioDeviceType, VirtioInterrupt, VirtioSharedMemoryList, }; const NUM_QUEUE_OFFSET: usize = 1; @@ -148,9 +148,9 @@ impl Fs { if num_queues > backend_num_queues { error!( - "vhost-user-fs requested too many queues ({}) since the backend only supports {}\n", - num_queues, backend_num_queues - ); + "vhost-user-fs requested too many queues ({}) since the backend only supports {}\n", + num_queues, backend_num_queues + ); return Err(Error::BadQueueNum); } diff --git a/virtio-devices/src/vhost_user/mod.rs b/virtio-devices/src/vhost_user/mod.rs index 188942721..14aa173b7 100644 --- a/virtio-devices/src/vhost_user/mod.rs +++ b/virtio-devices/src/vhost_user/mod.rs @@ -10,11 +10,11 @@ use std::sync::{Arc, Barrier, Mutex}; use anyhow::anyhow; use serde::{Deserialize, Serialize}; use thiserror::Error; +use vhost::Error as VhostError; use vhost::vhost_user::message::{ VhostUserInflight, VhostUserProtocolFeatures, VhostUserVirtioFeatures, }; use vhost::vhost_user::{FrontendReqHandler, VhostUserFrontendReqHandler}; -use vhost::Error as VhostError; use virtio_queue::{Error as QueueError, Queue}; use vm_memory::mmap::MmapRegionError; use vm_memory::{Address, Error as MmapError, GuestAddressSpace, GuestMemory, GuestMemoryAtomic}; @@ -24,10 +24,10 @@ 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, + ActivateError, EPOLL_HELPER_EVENT_LAST, EpollHelper, EpollHelperError, EpollHelperHandler, + GuestMemoryMmap, GuestRegionMmap, 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, VirtioInterrupt, }; pub mod blk; diff --git a/virtio-devices/src/vhost_user/net.rs b/virtio-devices/src/vhost_user/net.rs index c52d5ca38..99c0f8155 100644 --- a/virtio-devices/src/vhost_user/net.rs +++ b/virtio-devices/src/vhost_user/net.rs @@ -5,7 +5,7 @@ use std::sync::atomic::AtomicBool; use std::sync::{Arc, Barrier, Mutex}; use std::{result, thread}; -use net_util::{build_net_config_space, CtrlQueue, MacAddr, VirtioNetConfig}; +use net_util::{CtrlQueue, MacAddr, VirtioNetConfig, build_net_config_space}; use seccompiler::SeccompAction; use serde::{Deserialize, Serialize}; use vhost::vhost_user::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; @@ -28,9 +28,9 @@ 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, GuestMemoryMmap, GuestRegionMmap, NetCtrlEpollHandler, VirtioCommon, - VirtioDevice, VirtioDeviceType, VirtioInterrupt, VIRTIO_F_IOMMU_PLATFORM, - VIRTIO_F_RING_EVENT_IDX, VIRTIO_F_VERSION_1, + ActivateResult, GuestMemoryMmap, GuestRegionMmap, NetCtrlEpollHandler, VIRTIO_F_IOMMU_PLATFORM, + VIRTIO_F_RING_EVENT_IDX, VIRTIO_F_VERSION_1, VirtioCommon, VirtioDevice, VirtioDeviceType, + VirtioInterrupt, }; const DEFAULT_QUEUE_NUMBER: usize = 2; @@ -168,8 +168,10 @@ impl Net { }; if num_queues > backend_num_queues { - error!("vhost-user-net requested too many queues ({}) since the backend only supports {}\n", - num_queues, backend_num_queues); + error!( + "vhost-user-net requested too many queues ({}) since the backend only supports {}\n", + num_queues, backend_num_queues + ); return Err(Error::BadQueueNum); } diff --git a/virtio-devices/src/vhost_user/vu_common_ctrl.rs b/virtio-devices/src/vhost_user/vu_common_ctrl.rs index e1204fbd7..91fb55a20 100644 --- a/virtio-devices/src/vhost_user/vu_common_ctrl.rs +++ b/virtio-devices/src/vhost_user/vu_common_ctrl.rs @@ -5,8 +5,8 @@ use std::ffi; use std::fs::File; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::os::unix::net::UnixListener; -use std::sync::atomic::Ordering; use std::sync::Arc; +use std::sync::atomic::Ordering; use std::thread::sleep; use std::time::{Duration, Instant}; @@ -29,8 +29,8 @@ 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, + GuestMemoryMmap, GuestRegionMmap, MmapRegion, VirtioInterrupt, VirtioInterruptType, + get_host_address_range, }; // Size of a dirty page for vhost-user. @@ -399,7 +399,7 @@ impl VhostUserHandle { acked_features: 0, vrings_info: None, queue_indexes: Vec::new(), - }) + }); } Err(e) => e, }; diff --git a/virtio-devices/src/vsock/csm/connection.rs b/virtio-devices/src/vsock/csm/connection.rs index 50f3c3034..e36f58ccb 100644 --- a/virtio-devices/src/vsock/csm/connection.rs +++ b/virtio-devices/src/vsock/csm/connection.rs @@ -89,7 +89,7 @@ use super::super::defs::uapi; use super::super::packet::VsockPacket; use super::super::{Result as VsockResult, VsockChannel, VsockEpollListener, VsockError}; use super::txbuf::TxBuf; -use super::{defs, ConnState, Error, PendingRx, PendingRxSet, Result}; +use super::{ConnState, Error, PendingRx, PendingRxSet, Result, defs}; /// A self-managing connection object, that handles communication between a guest-side AF_VSOCK /// socket and a host-side `Read + Write + AsRawFd` stream. @@ -1158,10 +1158,11 @@ mod tests { // When there's data in the TX buffer, the connection should ask to be notified when it // can write to its backing stream. - assert!(ctx - .conn - .get_polled_evset() - .contains(epoll::Events::EPOLLOUT)); + assert!( + ctx.conn + .get_polled_evset() + .contains(epoll::Events::EPOLLOUT) + ); assert_eq!(ctx.conn.tx_buf.len(), data.len()); // Unlock the write stream and notify the connection it can now write its buffered @@ -1212,10 +1213,11 @@ mod tests { stream.write_state = StreamState::Closed; ctx.set_stream(stream); - assert!(ctx - .conn - .get_polled_evset() - .contains(epoll::Events::EPOLLOUT)); + assert!( + ctx.conn + .get_polled_evset() + .contains(epoll::Events::EPOLLOUT) + ); ctx.notify_epollout(); assert_eq!(ctx.conn.state, ConnState::Killed); } diff --git a/virtio-devices/src/vsock/csm/txbuf.rs b/virtio-devices/src/vsock/csm/txbuf.rs index 4c16913f3..1a8c5dd15 100644 --- a/virtio-devices/src/vsock/csm/txbuf.rs +++ b/virtio-devices/src/vsock/csm/txbuf.rs @@ -5,7 +5,7 @@ use std::io::Write; use std::num::Wrapping; -use super::{defs, Error, Result}; +use super::{Error, Result, defs}; /// A simple ring-buffer implementation, used by vsock connections to buffer TX (guest -> host) /// data. Memory for this buffer is allocated lazily, since buffering will only be needed when diff --git a/virtio-devices/src/vsock/device.rs b/virtio-devices/src/vsock/device.rs index f8c024833..4d073c492 100644 --- a/virtio-devices/src/vsock/device.rs +++ b/virtio-devices/src/vsock/device.rs @@ -47,10 +47,10 @@ use super::{VsockBackend, VsockPacket}; use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; use crate::{ - ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, Error as DeviceError, - GuestMemoryMmap, VirtioCommon, VirtioDevice, VirtioDeviceType, VirtioInterrupt, - VirtioInterruptType, EPOLL_HELPER_EVENT_LAST, VIRTIO_F_IN_ORDER, VIRTIO_F_IOMMU_PLATFORM, - VIRTIO_F_VERSION_1, + ActivateResult, EPOLL_HELPER_EVENT_LAST, EpollHelper, EpollHelperError, EpollHelperHandler, + Error as DeviceError, GuestMemoryMmap, VIRTIO_F_IN_ORDER, VIRTIO_F_IOMMU_PLATFORM, + VIRTIO_F_VERSION_1, VirtioCommon, VirtioDevice, VirtioDeviceType, VirtioInterrupt, + VirtioInterruptType, }; const QUEUE_SIZE: u16 = 256; diff --git a/virtio-devices/src/vsock/mod.rs b/virtio-devices/src/vsock/mod.rs index ecd523d1c..3cd9592a6 100644 --- a/virtio-devices/src/vsock/mod.rs +++ b/virtio-devices/src/vsock/mod.rs @@ -172,7 +172,7 @@ pub mod tests { 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::device::{RX_QUEUE_EVENT, TX_QUEUE_EVENT, VsockEpollHandler}; use super::packet::VSOCK_PKT_HDR_SIZE; use super::*; use crate::device::{VirtioInterrupt, VirtioInterruptType}; diff --git a/virtio-devices/src/vsock/packet.rs b/virtio-devices/src/vsock/packet.rs index 01ee18fbb..a6749381d 100644 --- a/virtio-devices/src/vsock/packet.rs +++ b/virtio-devices/src/vsock/packet.rs @@ -24,7 +24,7 @@ use virtio_queue::DescriptorChain; use vm_memory::{Address, GuestMemory}; use vm_virtio::{AccessPlatform, Translatable}; -use super::{defs, Result, VsockError}; +use super::{Result, VsockError, defs}; use crate::get_host_address_range; // The vsock packet header is defined by the C struct: @@ -427,8 +427,8 @@ mod tests { use super::super::tests::TestContext; use super::*; - use crate::vsock::defs::MAX_PKT_BUF_SIZE; use crate::GuestMemoryMmap; + use crate::vsock::defs::MAX_PKT_BUF_SIZE; macro_rules! create_context { ($test_ctx:ident, $handler_ctx:ident) => { diff --git a/virtio-devices/src/vsock/unix/mod.rs b/virtio-devices/src/vsock/unix/mod.rs index 13c988319..bb4469812 100644 --- a/virtio-devices/src/vsock/unix/mod.rs +++ b/virtio-devices/src/vsock/unix/mod.rs @@ -13,9 +13,9 @@ mod muxer; mod muxer_killq; mod muxer_rxq; +pub use Error as VsockUnixError; pub use muxer::VsockMuxer as VsockUnixBackend; use thiserror::Error; -pub use Error as VsockUnixError; mod defs { /// Maximum number of established connections that we can handle. diff --git a/virtio-devices/src/vsock/unix/muxer.rs b/virtio-devices/src/vsock/unix/muxer.rs index ebe0dc723..58df496e2 100644 --- a/virtio-devices/src/vsock/unix/muxer.rs +++ b/virtio-devices/src/vsock/unix/muxer.rs @@ -52,7 +52,7 @@ use super::super::{ }; use super::muxer_killq::MuxerKillQ; use super::muxer_rxq::MuxerRxQ; -use super::{defs, Error, MuxerConnection, Result}; +use super::{Error, MuxerConnection, Result, defs}; /// A unique identifier of a `MuxerConnection` object. Connections are stored in a hash map, /// keyed by a `ConnMapKey` object. diff --git a/virtio-devices/src/vsock/unix/muxer_killq.rs b/virtio-devices/src/vsock/unix/muxer_killq.rs index 925f4d938..5295ab69e 100644 --- a/virtio-devices/src/vsock/unix/muxer_killq.rs +++ b/virtio-devices/src/vsock/unix/muxer_killq.rs @@ -29,7 +29,7 @@ use std::collections::{HashMap, VecDeque}; use std::time::Instant; use super::muxer::ConnMapKey; -use super::{defs, MuxerConnection}; +use super::{MuxerConnection, defs}; /// A kill queue item, holding the connection key and the scheduled time for termination. /// diff --git a/virtio-devices/src/vsock/unix/muxer_rxq.rs b/virtio-devices/src/vsock/unix/muxer_rxq.rs index 701db3459..077cbc889 100644 --- a/virtio-devices/src/vsock/unix/muxer_rxq.rs +++ b/virtio-devices/src/vsock/unix/muxer_rxq.rs @@ -20,7 +20,7 @@ use std::collections::{HashMap, VecDeque}; use super::super::VsockChannel; use super::muxer::{ConnMapKey, MuxerRx}; -use super::{defs, MuxerConnection}; +use super::{MuxerConnection, defs}; /// The muxer RX queue. /// diff --git a/virtio-devices/src/watchdog.rs b/virtio-devices/src/watchdog.rs index fdfc977d9..23a33a3e5 100644 --- a/virtio-devices/src/watchdog.rs +++ b/virtio-devices/src/watchdog.rs @@ -23,9 +23,9 @@ use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottabl use vmm_sys_util::eventfd::EventFd; use super::{ - ActivateError, ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, - Error as DeviceError, VirtioCommon, VirtioDevice, VirtioDeviceType, EPOLL_HELPER_EVENT_LAST, - VIRTIO_F_VERSION_1, + ActivateError, ActivateResult, EPOLL_HELPER_EVENT_LAST, EpollHelper, EpollHelperError, + EpollHelperHandler, Error as DeviceError, VIRTIO_F_VERSION_1, VirtioCommon, VirtioDevice, + VirtioDeviceType, }; use crate::seccomp_filters::Thread; use crate::thread_helper::spawn_virtio_thread; diff --git a/vm-allocator/src/page_size.rs b/vm-allocator/src/page_size.rs index 96ae01edf..6dedb6847 100644 --- a/vm-allocator/src/page_size.rs +++ b/vm-allocator/src/page_size.rs @@ -1,7 +1,7 @@ // Copyright 2023 Arm Limited (or its affiliates). All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use libc::{sysconf, _SC_PAGESIZE}; +use libc::{_SC_PAGESIZE, sysconf}; /// get host page size pub fn get_page_size() -> u64 { diff --git a/vmm/src/acpi.rs b/vmm/src/acpi.rs index 215deac91..de2f58129 100644 --- a/vmm/src/acpi.rs +++ b/vmm/src/acpi.rs @@ -5,16 +5,16 @@ use std::sync::{Arc, Mutex}; use std::time::Instant; +use acpi_tables::Aml; use acpi_tables::rsdp::Rsdp; #[cfg(target_arch = "aarch64")] use acpi_tables::sdt::GenericAddress; use acpi_tables::sdt::Sdt; -use acpi_tables::Aml; -#[cfg(target_arch = "aarch64")] -use arch::aarch64::DeviceInfoForFdt; #[cfg(target_arch = "aarch64")] use arch::DeviceType; use arch::NumaNodes; +#[cfg(target_arch = "aarch64")] +use arch::aarch64::DeviceInfoForFdt; use bitflags::bitflags; use pci::PciBdf; use tracer::trace_scoped; diff --git a/vmm/src/api/dbus/mod.rs b/vmm/src/api/dbus/mod.rs index 85bd9d54f..f329b86bc 100644 --- a/vmm/src/api/dbus/mod.rs +++ b/vmm/src/api/dbus/mod.rs @@ -3,14 +3,14 @@ // SPDX-License-Identifier: Apache-2.0 // use std::panic::AssertUnwindSafe; -use std::sync::mpsc::Sender; use std::sync::Arc; +use std::sync::mpsc::Sender; use std::thread; use futures::channel::oneshot; -use futures::{executor, FutureExt}; +use futures::{FutureExt, executor}; use hypervisor::HypervisorType; -use seccompiler::{apply_filter, SeccompAction}; +use seccompiler::{SeccompAction, apply_filter}; use vmm_sys_util::eventfd::EventFd; use zbus::connection::Builder; use zbus::fdo::{self, Result}; @@ -26,7 +26,7 @@ use crate::api::{ VmReceiveMigration, VmRemoveDevice, VmResize, VmResizeZone, VmRestore, VmResume, VmSendMigration, VmShutdown, VmSnapshot, VmmPing, VmmShutdown, }; -use crate::seccomp_filters::{get_seccomp_filter, Thread}; +use crate::seccomp_filters::{Thread, get_seccomp_filter}; use crate::{Error as VmmError, NetConfig, Result as VmmResult, VmConfig}; 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 ff1de5629..5a4bf93da 100644 --- a/vmm/src/api/http/http_endpoint.rs +++ b/vmm/src/api/http/http_endpoint.rs @@ -11,9 +11,9 @@ 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; +use crate::api::http::{EndpointHandler, HttpError, error_response}; use crate::api::{ AddDisk, ApiAction, ApiError, ApiRequest, NetConfig, VmAddDevice, VmAddFs, VmAddNet, VmAddPmem, VmAddUserDevice, VmAddVdpa, VmAddVsock, VmBoot, VmConfig, VmCounters, VmDelete, VmNmi, VmPause, diff --git a/vmm/src/api/http/mod.rs b/vmm/src/api/http/mod.rs index 418a4d496..243429154 100644 --- a/vmm/src/api/http/mod.rs +++ b/vmm/src/api/http/mod.rs @@ -10,15 +10,15 @@ 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::sync::LazyLock; +use std::sync::mpsc::Sender; use std::thread; use hypervisor::HypervisorType; use micro_http::{ Body, HttpServer, MediaType, Method, Request, Response, ServerError, StatusCode, Version, }; -use seccompiler::{apply_filter, SeccompAction}; +use seccompiler::{SeccompAction, apply_filter}; use serde_json::Error as SerdeError; use thiserror::Error; use vmm_sys_util::eventfd::EventFd; @@ -33,7 +33,7 @@ use crate::api::{ VmSendMigration, VmShutdown, VmSnapshot, }; use crate::landlock::Landlock; -use crate::seccomp_filters::{get_seccomp_filter, Thread}; +use crate::seccomp_filters::{Thread, get_seccomp_filter}; use crate::{Error as VmmError, Result}; pub mod http_endpoint; diff --git a/vmm/src/api/mod.rs b/vmm/src/api/mod.rs index a856f49f5..5ef63ffa3 100644 --- a/vmm/src/api/mod.rs +++ b/vmm/src/api/mod.rs @@ -34,7 +34,7 @@ pub mod dbus; pub mod http; use std::io; -use std::sync::mpsc::{channel, RecvError, SendError, Sender}; +use std::sync::mpsc::{RecvError, SendError, Sender, channel}; use micro_http::Body; use serde::{Deserialize, Serialize}; @@ -45,6 +45,7 @@ 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, start_http_path_thread}; +use crate::Error as VmmError; use crate::config::RestoreConfig; use crate::device_tree::DeviceTree; use crate::vm::{Error as VmError, VmState}; @@ -52,7 +53,6 @@ use crate::vm_config::{ DeviceConfig, DiskConfig, FsConfig, NetConfig, PmemConfig, UserDeviceConfig, VdpaConfig, VmConfig, VsockConfig, }; -use crate::Error as VmmError; /// API errors are sent back from the VMM API server through the ApiResponse. #[derive(Error, Debug)] diff --git a/vmm/src/clone3.rs b/vmm/src/clone3.rs index fc273680f..eca0d9063 100644 --- a/vmm/src/clone3.rs +++ b/vmm/src/clone3.rs @@ -1,7 +1,7 @@ // Copyright 2021 Alyssa Ross // SPDX-License-Identifier: Apache-2.0 -use libc::{c_long, size_t, syscall, SYS_clone3}; +use libc::{SYS_clone3, c_long, size_t, syscall}; pub const CLONE_CLEAR_SIGHAND: u64 = 0x100000000; diff --git a/vmm/src/config.rs b/vmm/src/config.rs index b66c71b8c..d213b3a2d 100644 --- a/vmm/src/config.rs +++ b/vmm/src/config.rs @@ -270,7 +270,9 @@ pub enum ValidationError { #[error("Invalid PCI segment aperture weight: {0}")] InvalidPciSegmentApertureWeight(u32), /// Invalid IOMMU address width in bits - #[error("IOMMU address width in bits ({0}) should be less than or equal to {MAX_IOMMU_ADDRESS_WIDTH_BITS}")] + #[error( + "IOMMU address width in bits ({0}) should be less than or equal to {MAX_IOMMU_ADDRESS_WIDTH_BITS}" + )] InvalidIommuAddressWidthBits(u8), /// Balloon too big #[error("Ballon size ({0}) greater than RAM ({1})")] @@ -1536,8 +1538,7 @@ impl RngConfig { } impl BalloonConfig { - pub const SYNTAX: &'static str = - "Balloon parameters \"size=,deflate_on_oom=on|off,\ + pub const SYNTAX: &'static str = "Balloon parameters \"size=,deflate_on_oom=on|off,\ free_page_reporting=on|off\""; pub fn parse(balloon: &str) -> Result { @@ -1911,8 +1912,7 @@ impl DebugConsoleConfig { } impl DeviceConfig { - pub const SYNTAX: &'static str = - "Direct device assignment parameters \"path=,iommu=on|off,id=,pci_segment=\""; + pub const SYNTAX: &'static str = "Direct device assignment parameters \"path=,iommu=on|off,id=,pci_segment=\""; pub fn parse(device: &str) -> Result { let mut parser = OptionParser::new(); @@ -2206,7 +2206,9 @@ where S: serde::Serializer, { if let Some(x) = x { - warn!("'RestoredNetConfig' contains FDs that can't be serialized correctly. Serializing them as invalid FDs."); + warn!( + "'RestoredNetConfig' contains FDs that can't be serialized correctly. Serializing them as invalid FDs." + ); let invalid_fds = vec![-1; x.len()]; s.serialize_some(&invalid_fds) } else { @@ -2222,7 +2224,9 @@ where { let invalid_fds: Option> = Option::deserialize(d)?; if let Some(invalid_fds) = invalid_fds { - warn!("'RestoredNetConfig' contains FDs that can't be deserialized correctly. Deserializing them as invalid FDs."); + warn!( + "'RestoredNetConfig' contains FDs that can't be deserialized correctly. Deserializing them as invalid FDs." + ); Ok(Some(vec![-1; invalid_fds.len()])) } else { Ok(None) @@ -3556,7 +3560,9 @@ mod tests { ); assert_eq!( - NetConfig::parse("mac=de:ad:be:ef:12:34,host_mac=12:34:de:ad:be:ef,num_queues=4,queue_size=1024,iommu=on")?, + NetConfig::parse( + "mac=de:ad:be:ef:12:34,host_mac=12:34:de:ad:be:ef,num_queues=4,queue_size=1024,iommu=on" + )?, NetConfig { num_queues: 4, queue_size: 1024, @@ -4814,18 +4820,19 @@ mod tests { )?, FwCfgConfig { items: Some(FwCfgItemList { - item_list: vec![FwCfgItem { - name: "opt/org.test/fw_cfg_test_item".to_string(), - file: PathBuf::from("/tmp/fw_cfg_test_item"), - }, - FwCfgItem { - name: "opt/org.test/fw_cfg_test_item2".to_string(), - file: PathBuf::from("/tmp/fw_cfg_test_item2"), - }] + item_list: vec![ + FwCfgItem { + name: "opt/org.test/fw_cfg_test_item".to_string(), + file: PathBuf::from("/tmp/fw_cfg_test_item"), + }, + FwCfgItem { + name: "opt/org.test/fw_cfg_test_item2".to_string(), + file: PathBuf::from("/tmp/fw_cfg_test_item2"), + } + ] }), ..Default::default() - }, - + }, ); Ok(()) } diff --git a/vmm/src/console_devices.rs b/vmm/src/console_devices.rs index c4137733b..9f8d18ae7 100644 --- a/vmm/src/console_devices.rs +++ b/vmm/src/console_devices.rs @@ -10,7 +10,7 @@ // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause // -use std::fs::{read_link, File, OpenOptions}; +use std::fs::{File, OpenOptions, read_link}; use std::mem::zeroed; use std::os::fd::{AsRawFd, FromRawFd, RawFd}; use std::os::unix::fs::OpenOptionsExt; @@ -19,12 +19,12 @@ use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::{io, result}; -use libc::{cfmakeraw, isatty, tcgetattr, tcsetattr, termios, TCSANOW}; +use libc::{TCSANOW, cfmakeraw, isatty, tcgetattr, tcsetattr, termios}; use thiserror::Error; +use crate::Vmm; 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; @@ -225,7 +225,7 @@ pub(crate) fn pre_create_console_devices(vmm: &mut Vmm) -> ConsoleDeviceResult { - return Err(ConsoleDeviceError::NoSocketOptionSupportForConsoleDevice) + return Err(ConsoleDeviceError::NoSocketOptionSupportForConsoleDevice); } ConsoleOutputMode::Null => ConsoleOutput::Null, ConsoleOutputMode::Off => ConsoleOutput::Off, @@ -288,7 +288,7 @@ pub(crate) fn pre_create_console_devices(vmm: &mut Vmm) -> ConsoleDeviceResult { - return Err(ConsoleDeviceError::NoSocketOptionSupportForConsoleDevice) + return Err(ConsoleDeviceError::NoSocketOptionSupportForConsoleDevice); } ConsoleOutputMode::Null => ConsoleOutput::Null, ConsoleOutputMode::Off => ConsoleOutput::Off, diff --git a/vmm/src/cpu.rs b/vmm/src/cpu.rs index 00d2468f3..5ae2f6da2 100644 --- a/vmm/src/cpu.rs +++ b/vmm/src/cpu.rs @@ -23,7 +23,7 @@ use std::{cmp, io, result, thread}; #[cfg(not(target_arch = "riscv64"))] use acpi_tables::sdt::Sdt; -use acpi_tables::{aml, Aml}; +use acpi_tables::{Aml, aml}; use anyhow::anyhow; #[cfg(target_arch = "x86_64")] use arch::x86_64::get_x2apic_id; @@ -34,30 +34,30 @@ use devices::interrupt_controller::InterruptController; #[cfg(all(target_arch = "aarch64", feature = "guest_debug"))] use gdbstub_arch::aarch64::reg::AArch64CoreRegs as CoreRegs; #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] -use gdbstub_arch::x86::reg::{X86SegmentRegs, X86_64CoreRegs as CoreRegs}; -#[cfg(all(target_arch = "aarch64", feature = "guest_debug"))] -use hypervisor::arch::aarch64::regs::{ID_AA64MMFR0_EL1, TCR_EL1, TTBR1_EL1}; -#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] -use hypervisor::arch::x86::msr_index; -#[cfg(target_arch = "x86_64")] -use hypervisor::arch::x86::CpuIdEntry; -#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] -use hypervisor::arch::x86::MsrEntry; -#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] -use hypervisor::arch::x86::SpecialRegisters; -#[cfg(feature = "tdx")] -use hypervisor::kvm::{TdxExitDetails, TdxExitStatus}; +use gdbstub_arch::x86::reg::{X86_64CoreRegs as CoreRegs, X86SegmentRegs}; #[cfg(target_arch = "x86_64")] use hypervisor::CpuVendor; #[cfg(feature = "kvm")] use hypervisor::HypervisorType; #[cfg(feature = "guest_debug")] use hypervisor::StandardRegisters; +#[cfg(all(target_arch = "aarch64", feature = "guest_debug"))] +use hypervisor::arch::aarch64::regs::{ID_AA64MMFR0_EL1, TCR_EL1, TTBR1_EL1}; +#[cfg(target_arch = "x86_64")] +use hypervisor::arch::x86::CpuIdEntry; +#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] +use hypervisor::arch::x86::MsrEntry; +#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] +use hypervisor::arch::x86::SpecialRegisters; +#[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] +use hypervisor::arch::x86::msr_index; +#[cfg(feature = "tdx")] +use hypervisor::kvm::{TdxExitDetails, TdxExitStatus}; use hypervisor::{CpuState, HypervisorCpuError, VmExit, VmOps}; 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 seccompiler::{SeccompAction, apply_filter}; use thiserror::Error; use tracer::trace_scoped; use vm_device::BusDevice; @@ -67,26 +67,26 @@ use vm_memory::ByteValued; use vm_memory::{Bytes, GuestAddressSpace}; use vm_memory::{GuestAddress, GuestMemoryAtomic}; use vm_migration::{ - snapshot_from_id, Migratable, MigratableError, Pausable, Snapshot, SnapshotData, Snapshottable, - Transportable, + Migratable, MigratableError, Pausable, Snapshot, SnapshotData, Snapshottable, Transportable, + snapshot_from_id, }; use vmm_sys_util::eventfd::EventFd; -use vmm_sys_util::signal::{register_signal_handler, SIGRTMIN}; +use vmm_sys_util::signal::{SIGRTMIN, register_signal_handler}; use zerocopy::{FromBytes, Immutable, IntoBytes}; #[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, + COREDUMP_NAME_SIZE, CpuElf64Writable, CpuSegment, CpuState as DumpCpusState, DumpState, + Elf64Writable, GuestDebuggableError, NT_PRSTATUS, NoteDescType, X86_64ElfPrStatus, + X86_64UserRegs, }; #[cfg(feature = "guest_debug")] -use crate::gdb::{get_raw_tid, Debuggable, DebuggableError}; -use crate::seccomp_filters::{get_seccomp_filter, Thread}; +use crate::gdb::{Debuggable, DebuggableError, get_raw_tid}; +use crate::seccomp_filters::{Thread, get_seccomp_filter}; #[cfg(target_arch = "x86_64")] use crate::vm::physical_bits; use crate::vm_config::CpusConfig; -use crate::{GuestMemoryMmap, CPU_MANAGER_SNAPSHOT_ID}; +use crate::{CPU_MANAGER_SNAPSHOT_ID, GuestMemoryMmap}; #[cfg(all(target_arch = "aarch64", feature = "guest_debug"))] /// Extract the specified bits of a 64-bit integer. @@ -1835,7 +1835,7 @@ impl CpuManager { _ => { return Err(Error::TranslateVirtualAddress(anyhow!(format!( "PA range not supported {pa_range}" - )))) + )))); } }; @@ -2858,8 +2858,8 @@ mod tests { use arch::layout::{BOOT_STACK_POINTER, ZERO_PAGE_START}; use arch::x86_64::interrupts::*; use arch::x86_64::regs::*; - use hypervisor::arch::x86::{FpuState, LapicState}; use hypervisor::StandardRegisters; + use hypervisor::arch::x86::{FpuState, LapicState}; use linux_loader::loader::bootparam::setup_header; #[test] @@ -2912,7 +2912,7 @@ mod tests { #[test] fn test_setup_msrs() { - use hypervisor::arch::x86::{msr_index, MsrEntry}; + use hypervisor::arch::x86::{MsrEntry, msr_index}; let hv = hypervisor::new().unwrap(); let vm = hv.create_vm().expect("new VM fd creation failed"); @@ -2997,6 +2997,7 @@ mod tests { use std::{mem, mem::offset_of}; use arch::layout; + use hypervisor::HypervisorCpuError; use hypervisor::arch::aarch64::regs::MPIDR_EL1; #[cfg(feature = "kvm")] use hypervisor::arm64_core_reg_id; @@ -3004,9 +3005,8 @@ mod tests { use hypervisor::kvm::aarch64::is_system_register; #[cfg(feature = "kvm")] use hypervisor::kvm::kvm_bindings::{ - user_pt_regs, KVM_REG_ARM64, KVM_REG_ARM64_SYSREG, KVM_REG_ARM_CORE, KVM_REG_SIZE_U64, + KVM_REG_ARM_CORE, KVM_REG_ARM64, KVM_REG_ARM64_SYSREG, KVM_REG_SIZE_U64, user_pt_regs, }; - use hypervisor::HypervisorCpuError; #[test] fn test_setup_regs() { diff --git a/vmm/src/device_manager.rs b/vmm/src/device_manager.rs index 256047e87..3bc814fd7 100644 --- a/vmm/src/device_manager.rs +++ b/vmm/src/device_manager.rs @@ -11,7 +11,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::fs::{File, OpenOptions}; -use std::io::{self, stdout, IsTerminal, Seek, SeekFrom}; +use std::io::{self, IsTerminal, Seek, SeekFrom, stdout}; use std::num::Wrapping; use std::os::unix::fs::OpenOptionsExt; use std::os::unix::io::{AsRawFd, FromRawFd}; @@ -23,14 +23,14 @@ use std::time::Instant; use acpi_tables::sdt::GenericAddress; #[cfg(not(target_arch = "riscv64"))] -use acpi_tables::{aml, Aml}; +use acpi_tables::{Aml, aml}; #[cfg(not(target_arch = "riscv64"))] use anyhow::anyhow; #[cfg(target_arch = "x86_64")] use arch::layout::{APIC_START, IOAPIC_SIZE, IOAPIC_START}; -use arch::{layout, NumaNodes}; #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] use arch::{DeviceType, MmioDeviceInfo}; +use arch::{NumaNodes, layout}; use block::async_io::DiskFile; use block::fixed_vhd_sync::FixedVhdDiskSync; use block::qcow_sync::QcowDiskSync; @@ -38,7 +38,7 @@ use block::raw_async_aio::RawFileDiskAio; use block::raw_sync::RawFileDiskSync; use block::vhdx_sync::VhdxDiskSync; use block::{ - block_aio_is_supported, block_io_uring_is_supported, detect_image_type, qcow, vhdx, ImageType, + ImageType, block_aio_is_supported, block_io_uring_is_supported, detect_image_type, qcow, vhdx, }; #[cfg(feature = "io_uring")] use block::{fixed_vhd_async::FixedVhdDiskAsync, raw_async::RawFileDisk}; @@ -55,26 +55,26 @@ use devices::interrupt_controller::InterruptController; use devices::ioapic; #[cfg(feature = "ivshmem")] use devices::ivshmem::{IvshmemError, IvshmemOps}; -#[cfg(all(feature = "fw_cfg", target_arch = "x86_64"))] -use devices::legacy::fw_cfg::FW_CFG_ACPI_ID; #[cfg(target_arch = "aarch64")] use devices::legacy::Pl011; #[cfg(any(target_arch = "x86_64", target_arch = "riscv64"))] use devices::legacy::Serial; +#[cfg(all(feature = "fw_cfg", target_arch = "x86_64"))] +use devices::legacy::fw_cfg::FW_CFG_ACPI_ID; #[cfg(feature = "fw_cfg")] use devices::legacy::{ - fw_cfg::{PORT_FW_CFG_BASE, PORT_FW_CFG_WIDTH}, FwCfg, + fw_cfg::{PORT_FW_CFG_BASE, PORT_FW_CFG_WIDTH}, }; #[cfg(feature = "pvmemcontrol")] use devices::pvmemcontrol::{PvmemcontrolBusDevice, PvmemcontrolPciDevice}; -use devices::{interrupt_controller, AcpiNotificationFlags}; +use devices::{AcpiNotificationFlags, interrupt_controller}; +use hypervisor::IoEventAddress; #[cfg(target_arch = "aarch64")] use hypervisor::arch::aarch64::regs::AARCH64_PMU_IRQ; -use hypervisor::IoEventAddress; use libc::{ - tcsetattr, termios, MAP_NORESERVE, MAP_PRIVATE, MAP_SHARED, O_TMPFILE, PROT_READ, PROT_WRITE, - TCSANOW, + MAP_NORESERVE, MAP_PRIVATE, MAP_SHARED, O_TMPFILE, PROT_READ, PROT_WRITE, TCSANOW, tcsetattr, + termios, }; use pci::{ DeviceRelocation, MmioRegion, PciBarRegionType, PciBdf, PciDevice, VfioDmaMapping, @@ -104,27 +104,27 @@ use vm_memory::{Address, GuestAddress, GuestMemoryRegion, GuestUsize, MmapRegion use vm_memory::{GuestAddressSpace, GuestMemory}; use vm_migration::protocol::MemoryRangeTable; use vm_migration::{ - snapshot_from_id, state_from_id, Migratable, MigratableError, Pausable, Snapshot, SnapshotData, - Snapshottable, Transportable, + Migratable, MigratableError, Pausable, Snapshot, SnapshotData, Snapshottable, Transportable, + snapshot_from_id, state_from_id, }; use vm_virtio::{AccessPlatform, VirtioDeviceType}; use vmm_sys_util::eventfd::EventFd; use crate::console_devices::{ConsoleDeviceError, ConsoleInfo, ConsoleOutput}; -use crate::cpu::{CpuManager, CPU_MANAGER_ACPI_SIZE}; +use crate::cpu::{CPU_MANAGER_ACPI_SIZE, CpuManager}; use crate::device_tree::{DeviceNode, DeviceTree}; use crate::interrupt::{LegacyUserspaceInterruptManager, MsiInterruptManager}; -use crate::memory_manager::{Error as MemoryManagerError, MemoryManager, MEMORY_MANAGER_ACPI_SIZE}; +use crate::memory_manager::{Error as MemoryManagerError, MEMORY_MANAGER_ACPI_SIZE, MemoryManager}; use crate::pci_segment::PciSegment; use crate::serial_manager::{Error as SerialManagerError, SerialManager}; #[cfg(feature = "ivshmem")] use crate::vm_config::IvshmemConfig; use crate::vm_config::{ - ConsoleOutputMode, DeviceConfig, DiskConfig, FsConfig, NetConfig, PmemConfig, UserDeviceConfig, - VdpaConfig, VhostMode, VmConfig, VsockConfig, DEFAULT_IOMMU_ADDRESS_WIDTH_BITS, - DEFAULT_PCI_SEGMENT_APERTURE_WEIGHT, + ConsoleOutputMode, DEFAULT_IOMMU_ADDRESS_WIDTH_BITS, DEFAULT_PCI_SEGMENT_APERTURE_WEIGHT, + DeviceConfig, DiskConfig, FsConfig, NetConfig, PmemConfig, UserDeviceConfig, VdpaConfig, + VhostMode, VmConfig, VsockConfig, }; -use crate::{device_node, GuestRegionMmap, PciDeviceInfo, DEVICE_MANAGER_SNAPSHOT_ID}; +use crate::{DEVICE_MANAGER_SNAPSHOT_ID, GuestRegionMmap, PciDeviceInfo, device_node}; #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] const MMIO_LEN: u64 = 0x1000; diff --git a/vmm/src/gdb.rs b/vmm/src/gdb.rs index 16c9f64d9..ef4f4de8f 100644 --- a/vmm/src/gdb.rs +++ b/vmm/src/gdb.rs @@ -11,24 +11,24 @@ use std::sync::mpsc; use gdbstub::arch::Arch; use gdbstub::common::{Signal, Tid}; use gdbstub::conn::{Connection, ConnectionExt}; -use gdbstub::stub::{run_blocking, DisconnectReason, MultiThreadStopReason}; +use gdbstub::stub::{DisconnectReason, MultiThreadStopReason, run_blocking}; +use gdbstub::target::ext::base::BaseOps; use gdbstub::target::ext::base::multithread::{ MultiThreadBase, MultiThreadResume, MultiThreadResumeOps, MultiThreadSingleStep, MultiThreadSingleStepOps, }; -use gdbstub::target::ext::base::BaseOps; use gdbstub::target::ext::breakpoints::{ Breakpoints, BreakpointsOps, HwBreakpoint, HwBreakpointOps, }; use gdbstub::target::{Target, TargetError, TargetResult}; #[cfg(target_arch = "aarch64")] -use gdbstub_arch::aarch64::reg::AArch64CoreRegs as CoreRegs; -#[cfg(target_arch = "aarch64")] use gdbstub_arch::aarch64::AArch64 as GdbArch; -#[cfg(target_arch = "x86_64")] -use gdbstub_arch::x86::reg::X86_64CoreRegs as CoreRegs; +#[cfg(target_arch = "aarch64")] +use gdbstub_arch::aarch64::reg::AArch64CoreRegs as CoreRegs; #[cfg(target_arch = "x86_64")] use gdbstub_arch::x86::X86_64_SSE as GdbArch; +#[cfg(target_arch = "x86_64")] +use gdbstub_arch::x86::reg::X86_64CoreRegs as CoreRegs; use thiserror::Error; use vm_memory::{GuestAddress, GuestMemoryAtomic, GuestMemoryError}; diff --git a/vmm/src/igvm/igvm_loader.rs b/vmm/src/igvm/igvm_loader.rs index 805bb94b4..97297a092 100644 --- a/vmm/src/igvm/igvm_loader.rs +++ b/vmm/src/igvm/igvm_loader.rs @@ -10,21 +10,21 @@ use std::sync::{Arc, Mutex}; use igvm::snp_defs::SevVmsa; use igvm::{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 igvm_defs::{IGVM_VHS_MEMORY_MAP_ENTRY, MemoryMapEntryType}; +use igvm_defs::{ + IGVM_VHS_PARAMETER, IGVM_VHS_PARAMETER_INSERT, IgvmPageDataType, IgvmPlatformType, +}; use mshv_bindings::*; use thiserror::Error; use zerocopy::IntoBytes; -use crate::cpu::CpuManager; -use crate::igvm::loader::Loader; -use crate::igvm::{BootPageAcceptance, IgvmLoadedInfo, StartupMemoryType, HV_PAGE_SIZE}; -use crate::memory_manager::MemoryManager; #[cfg(feature = "sev_snp")] use crate::GuestMemoryMmap; +use crate::cpu::CpuManager; +use crate::igvm::loader::Loader; +use crate::igvm::{BootPageAcceptance, HV_PAGE_SIZE, IgvmLoadedInfo, StartupMemoryType}; +use crate::memory_manager::MemoryManager; #[derive(Debug, Error)] pub enum Error { diff --git a/vmm/src/igvm/loader.rs b/vmm/src/igvm/loader.rs index 215c84c50..316cadb1a 100644 --- a/vmm/src/igvm/loader.rs +++ b/vmm/src/igvm/loader.rs @@ -10,7 +10,7 @@ use vm_memory::{ GuestMemoryRegion, }; -use crate::igvm::{BootPageAcceptance, StartupMemoryType, HV_PAGE_SIZE}; +use crate::igvm::{BootPageAcceptance, HV_PAGE_SIZE, StartupMemoryType}; /// Structure to hold the guest memory info/layout to check /// the if the memory is accepted within the layout. diff --git a/vmm/src/landlock.rs b/vmm/src/landlock.rs index b7fbf6edb..e7efd9cbc 100644 --- a/vmm/src/landlock.rs +++ b/vmm/src/landlock.rs @@ -9,8 +9,8 @@ use std::path::Path; #[cfg(test)] use landlock::make_bitflags; use landlock::{ - path_beneath_rules, Access, AccessFs, BitFlags, Compatible, Ruleset, RulesetAttr, - RulesetCreated, RulesetCreatedAttr, RulesetError, ABI, + ABI, Access, AccessFs, BitFlags, Compatible, Ruleset, RulesetAttr, RulesetCreated, + RulesetCreatedAttr, RulesetError, path_beneath_rules, }; use thiserror::Error; @@ -59,7 +59,7 @@ impl TryFrom<&str> for LandlockAccess { _ => { return Err(LandlockError::InvalidLandlockAccess( format!("Invalid access: {c}").to_string(), - )) + )); } }; } diff --git a/vmm/src/lib.rs b/vmm/src/lib.rs index cb430728b..ef2379308 100644 --- a/vmm/src/lib.rs +++ b/vmm/src/lib.rs @@ -10,7 +10,7 @@ extern crate log; use std::collections::HashMap; use std::fs::File; -use std::io::{stdout, Read, Write}; +use std::io::{Read, Write, stdout}; use std::net::{TcpListener, TcpStream}; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::os::unix::net::{UnixListener, UnixStream}; @@ -29,12 +29,12 @@ use api::dbus::{DBusApiOptions, DBusApiShutdownChannels}; use api::http::HttpApiHandle; #[cfg(all(feature = "kvm", target_arch = "x86_64"))] use arch::x86_64::MAX_SUPPORTED_CPUS_LEGACY; -use console_devices::{pre_create_console_devices, ConsoleInfo}; +use console_devices::{ConsoleInfo, pre_create_console_devices}; use landlock::LandlockError; -use libc::{tcsetattr, termios, EFD_NONBLOCK, SIGINT, SIGTERM, TCSANOW}; +use libc::{EFD_NONBLOCK, SIGINT, SIGTERM, TCSANOW, tcsetattr, termios}; use memory_manager::MemoryManagerSnapshotData; use pci::PciBdf; -use seccompiler::{apply_filter, SeccompAction}; +use seccompiler::{SeccompAction, apply_filter}; use serde::ser::{SerializeStruct, Serializer}; use serde::{Deserialize, Serialize}; use signal_hook::iterator::{Handle, Signals}; @@ -52,7 +52,7 @@ use crate::api::{ ApiRequest, ApiResponse, RequestHandler, VmInfoResponse, VmReceiveMigrationData, VmSendMigrationData, VmmPingResponse, }; -use crate::config::{add_to_config, RestoreConfig}; +use crate::config::{RestoreConfig, add_to_config}; #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] use crate::coredump::GuestDebuggable; use crate::landlock::Landlock; @@ -60,7 +60,7 @@ use crate::memory_manager::MemoryManager; #[cfg(all(feature = "kvm", target_arch = "x86_64"))] 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::seccomp_filters::{Thread, get_seccomp_filter}; use crate::vm::{Error as VmError, Vm, VmState}; use crate::vm_config::{ DeviceConfig, DiskConfig, FsConfig, NetConfig, PmemConfig, UserDeviceConfig, VdpaConfig, @@ -2469,14 +2469,15 @@ mod unit_tests { )); let _ = vmm.vm_create(create_dummy_vm_config()); - assert!(vmm - .vm_config - .as_ref() - .unwrap() - .lock() - .unwrap() - .devices - .is_none()); + assert!( + vmm.vm_config + .as_ref() + .unwrap() + .lock() + .unwrap() + .devices + .is_none() + ); assert!(vmm.vm_add_device(device_config.clone()).unwrap().is_none()); assert_eq!( @@ -2516,19 +2517,21 @@ mod unit_tests { )); let _ = vmm.vm_create(create_dummy_vm_config()); - assert!(vmm - .vm_config - .as_ref() - .unwrap() - .lock() - .unwrap() - .user_devices - .is_none()); + assert!( + vmm.vm_config + .as_ref() + .unwrap() + .lock() + .unwrap() + .user_devices + .is_none() + ); - assert!(vmm - .vm_add_user_device(user_device_config.clone()) - .unwrap() - .is_none()); + assert!( + vmm.vm_add_user_device(user_device_config.clone()) + .unwrap() + .is_none() + ); assert_eq!( vmm.vm_config .as_ref() @@ -2565,14 +2568,15 @@ mod unit_tests { )); let _ = vmm.vm_create(create_dummy_vm_config()); - assert!(vmm - .vm_config - .as_ref() - .unwrap() - .lock() - .unwrap() - .disks - .is_none()); + assert!( + vmm.vm_config + .as_ref() + .unwrap() + .lock() + .unwrap() + .disks + .is_none() + ); assert!(vmm.vm_add_disk(disk_config.clone()).unwrap().is_none()); assert_eq!( @@ -2650,14 +2654,15 @@ mod unit_tests { )); let _ = vmm.vm_create(create_dummy_vm_config()); - assert!(vmm - .vm_config - .as_ref() - .unwrap() - .lock() - .unwrap() - .pmem - .is_none()); + assert!( + vmm.vm_config + .as_ref() + .unwrap() + .lock() + .unwrap() + .pmem + .is_none() + ); assert!(vmm.vm_add_pmem(pmem_config.clone()).unwrap().is_none()); assert_eq!( @@ -2699,14 +2704,15 @@ mod unit_tests { )); let _ = vmm.vm_create(create_dummy_vm_config()); - assert!(vmm - .vm_config - .as_ref() - .unwrap() - .lock() - .unwrap() - .net - .is_none()); + assert!( + vmm.vm_config + .as_ref() + .unwrap() + .lock() + .unwrap() + .net + .is_none() + ); assert!(vmm.vm_add_net(net_config.clone()).unwrap().is_none()); assert_eq!( @@ -2745,14 +2751,15 @@ mod unit_tests { )); let _ = vmm.vm_create(create_dummy_vm_config()); - assert!(vmm - .vm_config - .as_ref() - .unwrap() - .lock() - .unwrap() - .vdpa - .is_none()); + assert!( + vmm.vm_config + .as_ref() + .unwrap() + .lock() + .unwrap() + .vdpa + .is_none() + ); assert!(vmm.vm_add_vdpa(vdpa_config.clone()).unwrap().is_none()); assert_eq!( @@ -2791,14 +2798,15 @@ mod unit_tests { )); let _ = vmm.vm_create(create_dummy_vm_config()); - assert!(vmm - .vm_config - .as_ref() - .unwrap() - .lock() - .unwrap() - .vsock - .is_none()); + assert!( + vmm.vm_config + .as_ref() + .unwrap() + .lock() + .unwrap() + .vsock + .is_none() + ); assert!(vmm.vm_add_vsock(vsock_config.clone()).unwrap().is_none()); assert_eq!( diff --git a/vmm/src/memory_manager.rs b/vmm/src/memory_manager.rs index 461eb24b9..15225e9dc 100644 --- a/vmm/src/memory_manager.rs +++ b/vmm/src/memory_manager.rs @@ -17,7 +17,7 @@ use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Arc, Barrier, Mutex}; use std::{ffi, result, thread}; -use acpi_tables::{aml, Aml}; +use acpi_tables::{Aml, aml}; use anyhow::anyhow; use arch::RegionType; #[cfg(target_arch = "x86_64")] @@ -278,7 +278,9 @@ pub enum Error { /// It's invalid to try applying a NUMA policy to a memory zone that is /// memory mapped with MAP_SHARED. - #[error("Invalid to try applying a NUMA policy to a memory zone that is memory mapped with MAP_SHARED")] + #[error( + "Invalid to try applying a NUMA policy to a memory zone that is memory mapped with MAP_SHARED" + )] InvalidSharedMemoryZoneWithHostNuma, /// Failed applying NUMA memory policy. @@ -2611,7 +2613,7 @@ impl Migratable for MemoryManager { return Err(MigratableError::MigrateSend(anyhow!( "Error finding 'guest memory region' with address {:x}", r.gpa - ))) + ))); } }; diff --git a/vmm/src/pci_segment.rs b/vmm/src/pci_segment.rs index 010859e05..345869c1d 100644 --- a/vmm/src/pci_segment.rs +++ b/vmm/src/pci_segment.rs @@ -11,11 +11,11 @@ use std::sync::{Arc, Mutex}; -use acpi_tables::{aml, Aml}; +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 pci::{PCI_CONFIG_IO_PORT, PCI_CONFIG_IO_PORT_SIZE, PciConfigIo}; use uuid::Uuid; use vm_allocator::AddressAllocator; use vm_device::BusDeviceSync; @@ -105,7 +105,12 @@ impl PciSegment { info!( "Adding PCI segment: id={}, PCI MMIO config address: 0x{:x}, mem32 area [0x{:x}-0x{:x}, mem64 area [0x{:x}-0x{:x}", - segment.id, segment.mmio_config_address, segment.start_of_mem32_area, segment.end_of_mem32_area, segment.start_of_mem64_area, segment.end_of_mem64_area + segment.id, + segment.mmio_config_address, + segment.start_of_mem32_area, + segment.end_of_mem32_area, + segment.start_of_mem64_area, + segment.end_of_mem64_area ); Ok(segment) } diff --git a/vmm/src/sigwinch_listener.rs b/vmm/src/sigwinch_listener.rs index 104a680a6..b50e93c98 100644 --- a/vmm/src/sigwinch_listener.rs +++ b/vmm/src/sigwinch_listener.rs @@ -3,10 +3,10 @@ use std::cell::RefCell; use std::collections::BTreeSet; -use std::fs::{read_dir, File}; +use std::fs::{File, read_dir}; use std::io::{self, ErrorKind, Read, Write}; use std::iter::once; -use std::mem::{size_of, MaybeUninit}; +use std::mem::{MaybeUninit, size_of}; use std::os::unix::prelude::*; use std::process::exit; use std::ptr::null_mut; @@ -14,15 +14,16 @@ 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, + EINVAL, ENOSYS, ENOTTY, O_CLOEXEC, POLLERR, SIG_DFL, SIG_SETMASK, SIGCHLD, SIGWINCH, + STDERR_FILENO, SYS_close_range, TIOCSCTTY, c_int, c_void, close, fork, getpgrp, ioctl, pipe2, + poll, pollfd, setsid, sigemptyset, siginfo_t, signal, sigprocmask, syscall, tcgetpgrp, + tcsetpgrp, }; -use seccompiler::{apply_filter, BpfProgram, SeccompAction}; +use seccompiler::{BpfProgram, SeccompAction, apply_filter}; 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}; +use crate::clone3::{CLONE_CLEAR_SIGHAND, clone_args, clone3}; +use crate::seccomp_filters::{Thread, get_seccomp_filter}; thread_local! { // The tty file descriptor is stored in a global variable so it diff --git a/vmm/src/vm.rs b/vmm/src/vm.rs index d5e1e808d..0e85b1ddc 100644 --- a/vmm/src/vm.rs +++ b/vmm/src/vm.rs @@ -25,20 +25,20 @@ use std::time::Instant; use std::{cmp, result, str, thread}; use anyhow::anyhow; -#[cfg(target_arch = "x86_64")] -use arch::layout::{KVM_IDENTITY_MAP_START, KVM_TSS_START}; -#[cfg(feature = "tdx")] -use arch::x86_64::tdx::TdvfSection; -#[cfg(all(feature = "kvm", target_arch = "x86_64"))] -use arch::x86_64::MAX_SUPPORTED_CPUS_LEGACY; #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] use arch::PciSpaceInfo; -use arch::{get_host_cpu_phys_bits, EntryPoint, NumaNode, NumaNodes}; +#[cfg(target_arch = "x86_64")] +use arch::layout::{KVM_IDENTITY_MAP_START, KVM_TSS_START}; +#[cfg(all(feature = "kvm", target_arch = "x86_64"))] +use arch::x86_64::MAX_SUPPORTED_CPUS_LEGACY; +#[cfg(feature = "tdx")] +use arch::x86_64::tdx::TdvfSection; +use arch::{EntryPoint, NumaNode, NumaNodes, get_host_cpu_phys_bits}; +use devices::AcpiNotificationFlags; #[cfg(target_arch = "aarch64")] use devices::interrupt_controller; #[cfg(feature = "fw_cfg")] use devices::legacy::fw_cfg::FwCfgItem; -use devices::AcpiNotificationFlags; #[cfg(all(target_arch = "aarch64", feature = "guest_debug"))] use gdbstub_arch::aarch64::reg::AArch64CoreRegs as CoreRegs; #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] @@ -46,17 +46,17 @@ use gdbstub_arch::x86::reg::X86_64CoreRegs as CoreRegs; #[cfg(target_arch = "aarch64")] use hypervisor::arch::aarch64::regs::AARCH64_PMU_IRQ; use hypervisor::{HypervisorVmError, VmOps}; -use libc::{termios, SIGWINCH}; +use libc::{SIGWINCH, termios}; use linux_loader::cmdline::Cmdline; #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] use linux_loader::elf; +use linux_loader::loader::KernelLoader; #[cfg(target_arch = "x86_64")] use linux_loader::loader::bzimage::BzImage; #[cfg(target_arch = "x86_64")] use linux_loader::loader::elf::PvhBootCapability::PvhEntryPresent; #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] use linux_loader::loader::pe::Error::InvalidImageMagicNumber; -use linux_loader::loader::KernelLoader; use seccompiler::SeccompAction; use serde::{Deserialize, Serialize}; use thiserror::Error; @@ -69,12 +69,12 @@ use vm_memory::{ }; use vm_migration::protocol::{MemoryRangeTable, Request, Response}; use vm_migration::{ - snapshot_from_id, Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable, + Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable, snapshot_from_id, }; use vmm_sys_util::eventfd::EventFd; use vmm_sys_util::sock_ctrl_msg::ScmSocket; -use crate::config::{add_to_config, ValidationError}; +use crate::config::{ValidationError, add_to_config}; use crate::console_devices::{ConsoleDeviceError, ConsoleInfo}; #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))] use crate::coredump::{ @@ -94,7 +94,7 @@ use crate::memory_manager::{ 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::migration::{SNAPSHOT_CONFIG_FILE, SNAPSHOT_STATE_FILE, url_to_path}; #[cfg(feature = "fw_cfg")] use crate::vm_config::FwCfgConfig; use crate::vm_config::{ @@ -102,8 +102,8 @@ use crate::vm_config::{ PmemConfig, UserDeviceConfig, VdpaConfig, VmConfig, VsockConfig, }; use crate::{ - cpu, GuestMemoryMmap, PciDeviceInfo, CPU_MANAGER_SNAPSHOT_ID, DEVICE_MANAGER_SNAPSHOT_ID, - MEMORY_MANAGER_SNAPSHOT_ID, + CPU_MANAGER_SNAPSHOT_ID, DEVICE_MANAGER_SNAPSHOT_ID, GuestMemoryMmap, + MEMORY_MANAGER_SNAPSHOT_ID, PciDeviceInfo, cpu, }; /// Errors associated with VM management @@ -1315,10 +1315,7 @@ impl Vm { return Self::load_igvm(igvm, memory_manager, cpu_manager); } } - match ( - &payload.firmware, - &payload.kernel, - ) { + match (&payload.firmware, &payload.kernel) { (Some(firmware), None) => { let firmware = File::open(firmware).map_err(Error::FirmwareFile)?; Self::load_kernel(firmware, None, memory_manager) @@ -1328,7 +1325,9 @@ impl Vm { let cmdline = Self::generate_cmdline(payload)?; Self::load_kernel(kernel, Some(cmdline), memory_manager) } - _ => unreachable!("Unsupported boot configuration: programming error from 'PayloadConfigError::validate()'"), + _ => unreachable!( + "Unsupported boot configuration: programming error from 'PayloadConfigError::validate()'" + ), } } @@ -1346,7 +1345,9 @@ impl Vm { let kernel = File::open(kernel).map_err(Error::KernelFile)?; Self::load_kernel(kernel, memory_manager) } - _ => unreachable!("Unsupported boot configuration: programming error from 'PayloadConfigError::validate()'"), + _ => unreachable!( + "Unsupported boot configuration: programming error from 'PayloadConfigError::validate()'" + ), } } diff --git a/vmm/src/vm_config.rs b/vmm/src/vm_config.rs index 96269bfb2..7a581307e 100644 --- a/vmm/src/vm_config.rs +++ b/vmm/src/vm_config.rs @@ -13,8 +13,8 @@ use serde::{Deserialize, Serialize}; use thiserror::Error; use virtio_devices::RateLimiterConfig; -use crate::landlock::LandlockError; use crate::Landlock; +use crate::landlock::LandlockError; pub type LandlockResult = result::Result; @@ -353,12 +353,16 @@ pub fn default_netconfig_tap() -> Option { } pub fn default_netconfig_ip() -> IpAddr { - warn!("Deprecation warning: No IP address provided. A default IP address is assigned. This behavior will be deprecated soon."); + warn!( + "Deprecation warning: No IP address provided. A default IP address is assigned. This behavior will be deprecated soon." + ); IpAddr::V4(Ipv4Addr::new(192, 168, 249, 1)) } pub fn default_netconfig_mask() -> IpAddr { - warn!("Deprecation warning: No network mask provided. A default network mask is assigned. This behavior will be deprecated soon."); + warn!( + "Deprecation warning: No network mask provided. A default network mask is assigned. This behavior will be deprecated soon." + ); IpAddr::V4(Ipv4Addr::new(255, 255, 255, 0)) } @@ -383,7 +387,9 @@ where S: serde::Serializer, { if let Some(x) = x { - warn!("'NetConfig' contains FDs that can't be serialized correctly. Serializing them as invalid FDs."); + warn!( + "'NetConfig' contains FDs that can't be serialized correctly. Serializing them as invalid FDs." + ); let invalid_fds = vec![-1; x.len()]; s.serialize_some(&invalid_fds) } else { @@ -397,7 +403,9 @@ where { let invalid_fds: Option> = Option::deserialize(d)?; if let Some(invalid_fds) = invalid_fds { - warn!("'NetConfig' contains FDs that can't be deserialized correctly. Deserializing them as invalid FDs."); + warn!( + "'NetConfig' contains FDs that can't be deserialized correctly. Deserializing them as invalid FDs." + ); Ok(Some(vec![-1; invalid_fds.len()])) } else { Ok(None)