diff --git a/aarch64/src/fdt.rs b/aarch64/src/fdt.rs index 24f76846b..2b5f90007 100644 --- a/aarch64/src/fdt.rs +++ b/aarch64/src/fdt.rs @@ -6,14 +6,20 @@ use std::collections::BTreeMap; use std::fs::File; use std::io::Read; -use arch::fdt::{Error, FdtWriter, Result}; +use arch::fdt::Error; +use arch::fdt::FdtWriter; +use arch::fdt::Result; use arch::SERIAL_ADDR; -use devices::{PciAddress, PciInterruptPin}; -use hypervisor::{PsciVersion, PSCI_0_2, PSCI_1_0}; -use vm_memory::{GuestAddress, GuestMemory}; - -// This is the start of DRAM in the physical address space. -use crate::AARCH64_PHYS_MEM_START; +// This is a Battery related constant +use devices::bat::GOLDFISHBAT_MMIO_LEN; +use devices::pl030::PL030_AMBA_ID; +use devices::PciAddress; +use devices::PciInterruptPin; +use hypervisor::PsciVersion; +use hypervisor::PSCI_0_2; +use hypervisor::PSCI_1_0; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; // These are GIC address-space location constants. use crate::AARCH64_GIC_CPUI_BASE; @@ -21,24 +27,19 @@ use crate::AARCH64_GIC_CPUI_SIZE; use crate::AARCH64_GIC_DIST_BASE; use crate::AARCH64_GIC_DIST_SIZE; use crate::AARCH64_GIC_REDIST_SIZE; - +// This is the start of DRAM in the physical address space. +use crate::AARCH64_PHYS_MEM_START; +use crate::AARCH64_PMU_IRQ; // These are RTC related constants use crate::AARCH64_RTC_ADDR; use crate::AARCH64_RTC_IRQ; use crate::AARCH64_RTC_SIZE; -use devices::pl030::PL030_AMBA_ID; - -// This is a Battery related constant -use devices::bat::GOLDFISHBAT_MMIO_LEN; - // These are serial device related constants. use crate::AARCH64_SERIAL_1_3_IRQ; use crate::AARCH64_SERIAL_2_4_IRQ; use crate::AARCH64_SERIAL_SIZE; use crate::AARCH64_SERIAL_SPEED; -use crate::AARCH64_PMU_IRQ; - // This is an arbitrary number to specify the node for the GIC. // If we had a more complex interrupt architecture, then we'd need an enum for // these. diff --git a/aarch64/src/lib.rs b/aarch64/src/lib.rs index 9f0a62225..032efd27f 100644 --- a/aarch64/src/lib.rs +++ b/aarch64/src/lib.rs @@ -10,28 +10,52 @@ use std::collections::BTreeMap; use std::io; use std::sync::Arc; -use arch::{ - get_serial_cmdline, GetSerialCmdlineError, MsrConfig, MsrExitHandlerError, RunnableLinuxVm, - VmComponents, VmImage, -}; -use base::{Event, MemoryMappingBuilder, SendTube}; -use devices::serial_device::{SerialHardware, SerialParameters}; -use devices::vmwdt::{VMWDT_DEFAULT_CLOCK_HZ, VMWDT_DEFAULT_TIMEOUT_SEC}; -use devices::{ - Bus, BusDeviceObj, BusError, IrqChip, IrqChipAArch64, IrqEventSource, PciAddress, - PciConfigMmio, PciDevice, Serial, -}; -use hypervisor::{ - DeviceKind, Hypervisor, HypervisorCap, ProtectionType, VcpuAArch64, VcpuFeature, - VcpuInitAArch64, VcpuRegAArch64, Vm, VmAArch64, -}; +use arch::get_serial_cmdline; +use arch::GetSerialCmdlineError; +use arch::MsrConfig; +use arch::MsrExitHandlerError; +use arch::RunnableLinuxVm; +use arch::VmComponents; +use arch::VmImage; +use base::Event; +use base::MemoryMappingBuilder; +use base::SendTube; +use devices::serial_device::SerialHardware; +use devices::serial_device::SerialParameters; +use devices::vmwdt::VMWDT_DEFAULT_CLOCK_HZ; +use devices::vmwdt::VMWDT_DEFAULT_TIMEOUT_SEC; +use devices::Bus; +use devices::BusDeviceObj; +use devices::BusError; +use devices::IrqChip; +use devices::IrqChipAArch64; +use devices::IrqEventSource; +use devices::PciAddress; +use devices::PciConfigMmio; +use devices::PciDevice; +use devices::Serial; +use hypervisor::DeviceKind; +use hypervisor::Hypervisor; +use hypervisor::HypervisorCap; +use hypervisor::ProtectionType; +use hypervisor::VcpuAArch64; +use hypervisor::VcpuFeature; +use hypervisor::VcpuInitAArch64; +use hypervisor::VcpuRegAArch64; +use hypervisor::Vm; +use hypervisor::VmAArch64; use minijail::Minijail; use remain::sorted; -use resources::{AddressRange, SystemAllocator, SystemAllocatorConfig}; +use resources::AddressRange; +use resources::SystemAllocator; +use resources::SystemAllocatorConfig; use sync::Mutex; use thiserror::Error; -use vm_control::{BatControl, BatteryType}; -use vm_memory::{GuestAddress, GuestMemory, GuestMemoryError}; +use vm_control::BatControl; +use vm_control::BatteryType; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +use vm_memory::GuestMemoryError; mod fdt; diff --git a/acpi_tables/src/rsdp.rs b/acpi_tables/src/rsdp.rs index 6e2befbd9..c96b0860f 100644 --- a/acpi_tables/src/rsdp.rs +++ b/acpi_tables/src/rsdp.rs @@ -47,9 +47,10 @@ impl RSDP { #[cfg(test)] mod tests { - use super::RSDP; use data_model::DataInit; + use super::RSDP; + #[test] fn test_rsdp() { let rsdp = RSDP::new(*b"CHYPER", 0xdead_beef); diff --git a/acpi_tables/src/sdt.rs b/acpi_tables/src/sdt.rs index e1f0f23eb..b695df913 100644 --- a/acpi_tables/src/sdt.rs +++ b/acpi_tables/src/sdt.rs @@ -3,7 +3,9 @@ // found in the LICENSE file. use std::fs::File; -use std::io::{ErrorKind, Read, Result}; +use std::io::ErrorKind; +use std::io::Read; +use std::io::Result; use std::path::Path; use data_model::DataInit; @@ -124,10 +126,12 @@ impl SDT { #[cfg(test)] mod tests { - use super::SDT; use std::io::Write; + use tempfile::NamedTempFile; + use super::SDT; + #[test] fn test_sdt() { let mut sdt = SDT::new(*b"TEST", 40, 1, *b"CROSVM", *b"TESTTEST", 1); diff --git a/arch/src/android.rs b/arch/src/android.rs index 2ddc8fdc0..c033f52fd 100644 --- a/arch/src/android.rs +++ b/arch/src/android.rs @@ -6,7 +6,9 @@ use std::fs::File; use std::io::BufRead; use std::io::BufReader; -use crate::fdt::{Error, FdtWriter, Result}; +use crate::fdt::Error; +use crate::fdt::FdtWriter; +use crate::fdt::Result; fn parse_fstab_line(line: &str) -> Result> { let vec: Vec<&str> = line.split_whitespace().collect(); diff --git a/arch/src/lib.rs b/arch/src/lib.rs index b80cea5a0..f2055598b 100644 --- a/arch/src/lib.rs +++ b/arch/src/lib.rs @@ -14,60 +14,90 @@ pub mod sys; use std::collections::BTreeMap; use std::error::Error as StdError; use std::fs::File; -use std::io::{self, Read, Seek, SeekFrom}; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::{self}; use std::path::PathBuf; use std::sync::Arc; use acpi_tables::sdt::SDT; +use base::syslog; +use base::AsRawDescriptor; +use base::AsRawDescriptors; +use base::Event; +use base::SendTube; #[cfg(all(target_arch = "x86_64", feature = "gdb"))] use base::Tube; -use base::{syslog, AsRawDescriptor, AsRawDescriptors, Event, SendTube}; use devices::virtio::VirtioDevice; +use devices::BarRange; +use devices::Bus; +use devices::BusDevice; +use devices::BusDeviceObj; +use devices::BusError; +use devices::BusResumeDevice; +use devices::HotPlugBus; +use devices::IrqChip; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use devices::IrqChipAArch64 as IrqChipArch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use devices::IrqChipX86_64 as IrqChipArch; +use devices::IrqEventSource; #[cfg(windows)] use devices::Minijail; +use devices::PciAddress; +use devices::PciBus; +use devices::PciDevice; +use devices::PciDeviceError; +use devices::PciInterruptPin; +use devices::PciRoot; #[cfg(unix)] use devices::ProxyDevice; -use devices::{ - BarRange, Bus, BusDevice, BusDeviceObj, BusError, BusResumeDevice, HotPlugBus, IrqChip, - IrqEventSource, PciAddress, PciBus, PciDevice, PciDeviceError, PciInterruptPin, PciRoot, - SerialHardware, SerialParameters, -}; -use hypervisor::{IoEventAddress, ProtectionType, Vm}; +use devices::SerialHardware; +use devices::SerialParameters; +#[cfg(all(target_arch = "x86_64", feature = "gdb"))] +use gdbstub_arch::x86::reg::X86_64CoreRegs as GdbStubRegs; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use hypervisor::Hypervisor as HypervisorArch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use hypervisor::HypervisorX86_64 as HypervisorArch; +use hypervisor::IoEventAddress; +use hypervisor::ProtectionType; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use hypervisor::VcpuAArch64 as VcpuArch; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use hypervisor::VcpuInitAArch64 as VcpuInitArch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use hypervisor::VcpuInitX86_64 as VcpuInitArch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use hypervisor::VcpuX86_64 as VcpuArch; +use hypervisor::Vm; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use hypervisor::VmAArch64 as VmArch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use hypervisor::VmX86_64 as VmArch; #[cfg(unix)] use minijail::Minijail; use remain::sorted; -use resources::{SystemAllocator, SystemAllocatorConfig}; -use serde::{Deserialize, Serialize}; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use resources::AddressRange; +use resources::SystemAllocator; +use resources::SystemAllocatorConfig; +use serde::Deserialize; +use serde::Serialize; +pub use serial::add_serial_devices; +pub use serial::get_serial_cmdline; +pub use serial::set_default_serial_parameters; +pub use serial::GetSerialCmdlineError; +pub use serial::SERIAL_ADDR; use sync::Mutex; use thiserror::Error; -use vm_control::{BatControl, BatteryType, PmResource}; -use vm_memory::{GuestAddress, GuestMemory, GuestMemoryError}; - -#[cfg(all(target_arch = "x86_64", feature = "gdb"))] -use gdbstub_arch::x86::reg::X86_64CoreRegs as GdbStubRegs; - -#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] -use { - devices::IrqChipAArch64 as IrqChipArch, - hypervisor::{ - Hypervisor as HypervisorArch, VcpuAArch64 as VcpuArch, VcpuInitAArch64 as VcpuInitArch, - VmAArch64 as VmArch, - }, -}; -#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use { - devices::IrqChipX86_64 as IrqChipArch, - hypervisor::{ - HypervisorX86_64 as HypervisorArch, VcpuInitX86_64 as VcpuInitArch, VcpuX86_64 as VcpuArch, - VmX86_64 as VmArch, - }, - resources::AddressRange, -}; - -pub use serial::{ - add_serial_devices, get_serial_cmdline, set_default_serial_parameters, GetSerialCmdlineError, - SERIAL_ADDR, -}; +use vm_control::BatControl; +use vm_control::BatteryType; +use vm_control::PmResource; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +use vm_memory::GuestMemoryError; pub enum VmImage { Kernel(File), diff --git a/arch/src/pstore.rs b/arch/src/pstore.rs index 33adbe2e9..c94acb771 100644 --- a/arch/src/pstore.rs +++ b/arch/src/pstore.rs @@ -4,13 +4,16 @@ use std::fs::OpenOptions; -use crate::Pstore; -use anyhow::{bail, Context, Result}; +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; use base::MemoryMappingBuilder; use hypervisor::Vm; use resources::AddressRange; use vm_memory::GuestAddress; +use crate::Pstore; + mod sys; pub struct RamoopsRegion { diff --git a/arch/src/pstore/sys/windows.rs b/arch/src/pstore/sys/windows.rs index 28b517793..71d879f2b 100644 --- a/arch/src/pstore/sys/windows.rs +++ b/arch/src/pstore/sys/windows.rs @@ -4,6 +4,7 @@ use std::fs::OpenOptions; use std::os::windows::fs::OpenOptionsExt; + use winapi::um::winnt::FILE_SHARE_READ; pub fn set_extra_open_opts(opts: &mut OpenOptions) { diff --git a/arch/src/serial.rs b/arch/src/serial.rs index 676e82893..53860e1b1 100644 --- a/arch/src/serial.rs +++ b/arch/src/serial.rs @@ -5,10 +5,13 @@ use std::collections::BTreeMap; use base::Event; -use devices::serial_device::{SerialHardware, SerialParameters, SerialType}; +use devices::serial_device::SerialHardware; +use devices::serial_device::SerialParameters; +use devices::serial_device::SerialType; +use devices::Bus; #[cfg(windows)] use devices::Minijail; -use devices::{Bus, Serial}; +use devices::Serial; use hypervisor::ProtectionType; #[cfg(unix)] use minijail::Minijail; @@ -208,9 +211,10 @@ pub fn get_serial_cmdline( #[cfg(test)] mod tests { - use super::*; use kernel_cmdline::Cmdline; + use super::*; + #[test] fn get_serial_cmdline_default() { let mut cmdline = Cmdline::new(4096); diff --git a/arch/src/serial/sys/unix.rs b/arch/src/serial/sys/unix.rs index b975cd25b..f2ea091ed 100644 --- a/arch/src/serial/sys/unix.rs +++ b/arch/src/serial/sys/unix.rs @@ -6,8 +6,10 @@ use std::sync::Arc; use base::RawDescriptor; use devices::serial_device::SerialParameters; +use devices::Bus; use devices::BusDevice; -use devices::{Bus, ProxyDevice, Serial}; +use devices::ProxyDevice; +use devices::Serial; use minijail::Minijail; use sync::Mutex; diff --git a/arch/src/serial/sys/windows.rs b/arch/src/serial/sys/windows.rs index d9c4c0fec..8d9ebca7f 100644 --- a/arch/src/serial/sys/windows.rs +++ b/arch/src/serial/sys/windows.rs @@ -4,15 +4,18 @@ #![allow(dead_code)] -use std::sync::Arc; - -use devices::serial_device::{SerialParameters, SerialType}; use std::io::Read; +use std::sync::Arc; use std::thread; use std::time::Duration; -use base::{RawDescriptor, Result}; -use devices::{Bus, Minijail, Serial}; +use base::RawDescriptor; +use base::Result; +use devices::serial_device::SerialParameters; +use devices::serial_device::SerialType; +use devices::Bus; +use devices::Minijail; +use devices::Serial; use sync::Mutex; use crate::serial::SERIAL_ADDR; diff --git a/arch/src/sys/unix.rs b/arch/src/sys/unix.rs index 9ad05e655..11315d1bb 100644 --- a/arch/src/sys/unix.rs +++ b/arch/src/sys/unix.rs @@ -2,24 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use acpi_tables::aml::Aml; - +use std::collections::BTreeMap; use std::sync::Arc; +use acpi_tables::aml::Aml; +use base::syslog; +use base::AsRawDescriptors; #[cfg(any(all(target_arch = "x86_64", feature = "gdb"), unix))] use base::Tube; -use base::{syslog, AsRawDescriptors}; -use devices::{Bus, IrqChip, IrqEventSource}; -use devices::{BusDevice, ProxyDevice, VfioPlatformDevice}; +use devices::Bus; +use devices::BusDevice; +use devices::IrqChip; +use devices::IrqEventSource; +use devices::ProxyDevice; +use devices::VfioPlatformDevice; use libc::sched_getcpu; use minijail::Minijail; use resources::MmioType; use resources::SystemAllocator; -use std::collections::BTreeMap; - use sync::Mutex; -use crate::{DeviceRegistrationError, MsrValueFrom}; +use crate::DeviceRegistrationError; +use crate::MsrValueFrom; impl MsrValueFrom { /// Get the physical(host) CPU id from MsrValueFrom type. diff --git a/base/base_event_token_derive/event_token_derive.rs b/base/base_event_token_derive/event_token_derive.rs index c9b0af9f6..1b5823f9c 100644 --- a/base/base_event_token_derive/event_token_derive.rs +++ b/base/base_event_token_derive/event_token_derive.rs @@ -6,9 +6,17 @@ extern crate proc_macro; -use proc_macro2::{Ident, TokenStream}; +use proc_macro2::Ident; +use proc_macro2::TokenStream; use quote::quote; -use syn::{parse_macro_input, Data, DeriveInput, Field, Fields, Index, Member, Variant}; +use syn::parse_macro_input; +use syn::Data; +use syn::DeriveInput; +use syn::Field; +use syn::Fields; +use syn::Index; +use syn::Member; +use syn::Variant; #[cfg(test)] mod tests; diff --git a/base/base_event_token_derive/tests.rs b/base/base_event_token_derive/tests.rs index 569e35206..ea5ad8107 100644 --- a/base/base_event_token_derive/tests.rs +++ b/base/base_event_token_derive/tests.rs @@ -3,7 +3,8 @@ // found in the LICENSE file. use quote::quote; -use syn::{parse_quote, DeriveInput}; +use syn::parse_quote; +use syn::DeriveInput; #[test] fn test_variant_bits() { diff --git a/base/src/alloc.rs b/base/src/alloc.rs index ee8de3801..f3b73a546 100644 --- a/base/src/alloc.rs +++ b/base/src/alloc.rs @@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - alloc::{alloc, alloc_zeroed, dealloc, Layout}, - cmp::min, -}; +use std::alloc::alloc; +use std::alloc::alloc_zeroed; +use std::alloc::dealloc; +use std::alloc::Layout; +use std::cmp::min; /// A contiguous memory allocation with a specified size and alignment, with a /// Drop impl to perform the deallocation. @@ -168,8 +169,10 @@ impl Drop for LayoutAllocation { #[cfg(test)] mod tests { + use std::mem::align_of; + use std::mem::size_of; + use super::*; - use std::mem::{align_of, size_of}; #[test] fn test_as_slice_u32() { diff --git a/base/src/clock.rs b/base/src/clock.rs index b9b2d2a92..b53051d98 100644 --- a/base/src/clock.rs +++ b/base/src/clock.rs @@ -5,9 +5,11 @@ // Utility file to provide a fake clock object representing current time, and a timer driven by // that time. -use std::time::{Duration, Instant}; +use std::time::Duration; +use std::time::Instant; -use crate::{descriptor::AsRawDescriptor, Event}; +use crate::descriptor::AsRawDescriptor; +use crate::Event; #[derive(Debug, Default, Copy, Clone)] pub struct Clock {} diff --git a/base/src/descriptor.rs b/base/src/descriptor.rs index 73f6834d2..09f479169 100644 --- a/base/src/descriptor.rs +++ b/base/src/descriptor.rs @@ -2,12 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{EventToken, RawDescriptor}; -use serde::{Deserialize, Serialize}; -use std::{ - fs::File, - mem::{self, ManuallyDrop}, -}; +use std::fs::File; +use std::mem::ManuallyDrop; +use std::mem::{self}; + +use serde::Deserialize; +use serde::Serialize; + +use crate::EventToken; +use crate::RawDescriptor; /// Wraps a RawDescriptor and safely closes it when self falls out of scope. #[derive(Serialize, Deserialize, Debug, Eq)] diff --git a/base/src/descriptor_reflection.rs b/base/src/descriptor_reflection.rs index 6e857e782..46dde4d9f 100644 --- a/base/src/descriptor_reflection.rs +++ b/base/src/descriptor_reflection.rs @@ -48,21 +48,25 @@ //! .expect("failed to deserialize"); //! ``` -use std::{ - cell::{Cell, RefCell}, - convert::TryInto, - fmt, - fs::File, - ops::{Deref, DerefMut}, - panic::{catch_unwind, resume_unwind, AssertUnwindSafe}, -}; +use std::cell::Cell; +use std::cell::RefCell; +use std::convert::TryInto; +use std::fmt; +use std::fs::File; +use std::ops::Deref; +use std::ops::DerefMut; +use std::panic::catch_unwind; +use std::panic::resume_unwind; +use std::panic::AssertUnwindSafe; -use serde::{ - de::{ - Error, Visitor, {self}, - }, - ser, Deserialize, Deserializer, Serialize, Serializer, -}; +use serde::de::Error; +use serde::de::Visitor; +use serde::de::{self}; +use serde::ser; +use serde::Deserialize; +use serde::Deserializer; +use serde::Serialize; +use serde::Serializer; use super::RawDescriptor; use crate::descriptor::SafeDescriptor; @@ -340,11 +344,11 @@ where /// } /// ``` pub mod with_raw_descriptor { - use super::super::RawDescriptor; - use crate::descriptor::IntoRawDescriptor; use serde::Deserializer; + use super::super::RawDescriptor; pub use super::serialize_descriptor as serialize; + use crate::descriptor::IntoRawDescriptor; pub fn deserialize<'de, D>(de: D) -> std::result::Result where @@ -371,8 +375,12 @@ pub mod with_raw_descriptor { /// } /// ``` pub mod with_as_descriptor { - use crate::descriptor::{AsRawDescriptor, FromRawDescriptor, IntoRawDescriptor}; - use serde::{Deserializer, Serializer}; + use serde::Deserializer; + use serde::Serializer; + + use crate::descriptor::AsRawDescriptor; + use crate::descriptor::FromRawDescriptor; + use crate::descriptor::IntoRawDescriptor; pub fn serialize( rd: &dyn AsRawDescriptor, @@ -432,16 +440,25 @@ impl DerefMut for FileSerdeWrapper { #[cfg(test)] mod tests { - use super::super::{ - deserialize_with_descriptors, with_as_descriptor, with_raw_descriptor, AsRawDescriptor, - FileSerdeWrapper, FromRawDescriptor, RawDescriptor, SafeDescriptor, SerializeDescriptors, - }; + use std::collections::HashMap; + use std::fs::File; + use std::mem::ManuallyDrop; - use std::{collections::HashMap, fs::File, mem::ManuallyDrop}; - - use serde::{de::DeserializeOwned, Deserialize, Serialize}; + use serde::de::DeserializeOwned; + use serde::Deserialize; + use serde::Serialize; use tempfile::tempfile; + use super::super::deserialize_with_descriptors; + use super::super::with_as_descriptor; + use super::super::with_raw_descriptor; + use super::super::AsRawDescriptor; + use super::super::FileSerdeWrapper; + use super::super::FromRawDescriptor; + use super::super::RawDescriptor; + use super::super::SafeDescriptor; + use super::super::SerializeDescriptors; + fn deserialize(json: &str, descriptors: &[RawDescriptor]) -> T { let mut safe_descriptors = descriptors .iter() diff --git a/base/src/errno.rs b/base/src/errno.rs index 231f787ca..9bdbd5f8a 100644 --- a/base/src/errno.rs +++ b/base/src/errno.rs @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - convert::{From, TryInto}, - fmt::{ - Display, {self}, - }, - io, result, -}; +use std::convert::From; +use std::convert::TryInto; +use std::fmt::Display; +use std::fmt::{self}; +use std::io; +use std::result; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; use thiserror::Error; /// A system error diff --git a/base/src/event.rs b/base/src/event.rs index a7885f6c2..6d2913091 100644 --- a/base/src/event.rs +++ b/base/src/event.rs @@ -4,11 +4,16 @@ use std::time::Duration; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; -use crate::descriptor::{AsRawDescriptor, FromRawDescriptor, IntoRawDescriptor}; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::IntoRawDescriptor; +use crate::platform::Event as PlatformEvent; pub use crate::platform::EventReadResult; -use crate::{platform::Event as PlatformEvent, RawDescriptor, Result}; +use crate::RawDescriptor; +use crate::Result; /// See the [platform-specific Event struct](crate::platform::Event) for struct- and method-level /// documentation. diff --git a/base/src/lib.rs b/base/src/lib.rs index 62f605df2..607135a75 100644 --- a/base/src/lib.rs +++ b/base/src/lib.rs @@ -21,27 +21,46 @@ mod wait_context; mod write_zeroes; pub mod sys; -pub use sys::platform; - pub use alloc::LayoutAllocation; -pub use clock::{Clock, FakeClock}; -pub use errno::{errno_result, Error, Result}; -pub use event::{Event, EventReadResult}; -pub use external_mapping::{ - Error as ExternalMappingError, ExternalMapping, Result as ExternalMappingResult, -}; -pub use mmap::{MappedRegion, MemoryMapping, MemoryMappingBuilder}; -pub use notifiers::{CloseNotifier, ReadNotifier}; + +pub use clock::Clock; +pub use clock::FakeClock; +pub use errno::errno_result; +pub use errno::Error; +pub use errno::Result; +pub use event::Event; +pub use event::EventReadResult; +pub use external_mapping::Error as ExternalMappingError; +pub use external_mapping::ExternalMapping; +pub use external_mapping::Result as ExternalMappingResult; +pub use mmap::MappedRegion; +pub use mmap::MemoryMapping; +pub use mmap::MemoryMappingBuilder; +pub use notifiers::CloseNotifier; +pub use notifiers::ReadNotifier; pub use platform::gmtime_secure; -pub use platform::ioctl::{ - ioctl, ioctl_with_mut_ptr, ioctl_with_mut_ref, ioctl_with_ptr, ioctl_with_ref, ioctl_with_val, - IoctlNr, -}; +pub use platform::ioctl::ioctl; +pub use platform::ioctl::ioctl_with_mut_ptr; +pub use platform::ioctl::ioctl_with_mut_ref; +pub use platform::ioctl::ioctl_with_ptr; +pub use platform::ioctl::ioctl_with_ref; +pub use platform::ioctl::ioctl_with_val; +pub use platform::ioctl::IoctlNr; pub use shm::SharedMemory; -pub use timer::{FakeTimer, Timer}; -pub use tube::{Error as TubeError, RecvTube, Result as TubeResult, SendTube, Tube}; -pub use wait_context::{EventToken, EventType, TriggeredEvent, WaitContext}; -pub use write_zeroes::{PunchHole, WriteZeroesAt}; +pub use sys::platform; +pub use timer::FakeTimer; +pub use timer::Timer; +pub use tube::Error as TubeError; +pub use tube::RecvTube; +pub use tube::Result as TubeResult; +pub use tube::SendTube; +pub use tube::Tube; +pub use wait_context::EventToken; +pub use wait_context::EventType; +pub use wait_context::TriggeredEvent; +pub use wait_context::WaitContext; +pub use write_zeroes::PunchHole; +pub use write_zeroes::WriteZeroesAt; // TODO(b/233233301): reorganize platform specific exports under platform // namespaces instead of exposing them directly in base::. @@ -107,33 +126,51 @@ cfg_if::cfg_if! { } } -pub use platform::{BlockingMode, FramingMode, StreamChannel}; - -pub use platform::{ - deserialize_with_descriptors, EventContext, FileAllocate, FileGetLen, FileSerdeWrapper, - SerializeDescriptors, UnsyncMarker, -}; - +pub use log::debug; +pub use log::error; +pub use log::info; +pub use log::trace; +pub use log::warn; +pub use mmap::Protection; +pub use platform::deserialize_with_descriptors; +pub(crate) use platform::file_punch_hole; +pub(crate) use platform::file_write_zeroes_at; +pub use platform::get_cpu_affinity; +pub use platform::get_filesystem_type; +pub use platform::getpid; +pub use platform::number_of_logical_cores; +pub use platform::open_file; +pub use platform::pagesize; +pub use platform::platform_timer_resolution::enable_high_res_timers; +pub use platform::round_up_to_page_size; +pub use platform::set_cpu_affinity; +pub use platform::with_as_descriptor; +pub use platform::with_raw_descriptor; +pub use platform::BlockingMode; +pub use platform::EventContext; +pub use platform::FileAllocate; +pub use platform::FileGetLen; +pub use platform::FileReadWriteAtVolatile; +pub use platform::FileReadWriteVolatile; +pub use platform::FileSerdeWrapper; +pub use platform::FileSetLen; +pub use platform::FileSync; +pub use platform::FramingMode; +pub use platform::MemoryMappingArena; +pub use platform::MmapError; +pub use platform::RawDescriptor; +pub use platform::SerializeDescriptors; +pub use platform::StreamChannel; +pub use platform::UnsyncMarker; +pub use platform::INVALID_DESCRIPTOR; use uuid::Uuid; -pub use mmap::Protection; -pub(crate) use platform::{file_punch_hole, file_write_zeroes_at}; -pub use platform::{get_cpu_affinity, set_cpu_affinity}; -pub use platform::{with_as_descriptor, with_raw_descriptor, RawDescriptor, INVALID_DESCRIPTOR}; - -pub use crate::descriptor::{ - AsRawDescriptor, AsRawDescriptors, Descriptor, FromRawDescriptor, IntoRawDescriptor, - SafeDescriptor, -}; - -pub use platform::getpid; -pub use platform::platform_timer_resolution::enable_high_res_timers; -pub use platform::{get_filesystem_type, open_file}; -pub use platform::{number_of_logical_cores, pagesize, round_up_to_page_size}; -pub use platform::{FileReadWriteAtVolatile, FileReadWriteVolatile, FileSetLen, FileSync}; -pub use platform::{MemoryMappingArena, MmapError}; - -pub use log::{debug, error, info, trace, warn}; +pub use crate::descriptor::AsRawDescriptor; +pub use crate::descriptor::AsRawDescriptors; +pub use crate::descriptor::Descriptor; +pub use crate::descriptor::FromRawDescriptor; +pub use crate::descriptor::IntoRawDescriptor; +pub use crate::descriptor::SafeDescriptor; /// An empty trait that helps reset timer resolution to its previous state. // TODO(b:232103460): Maybe this needs to be thought through. @@ -148,7 +185,8 @@ pub fn generate_uuid() -> String { .to_owned() } -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; #[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq)] pub enum VmEventType { Exit, diff --git a/base/src/mmap.rs b/base/src/mmap.rs index 43f6ecd2a..ebe858050 100644 --- a/base/src/mmap.rs +++ b/base/src/mmap.rs @@ -2,24 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - cmp::min, - fs::File, - intrinsics::copy_nonoverlapping, - mem::size_of, - ptr::{read_unaligned, read_volatile, write_unaligned, write_volatile}, - sync::atomic::{fence, Ordering}, -}; +use std::cmp::min; +use std::fs::File; +use std::intrinsics::copy_nonoverlapping; +use std::mem::size_of; +use std::ptr::read_unaligned; +use std::ptr::read_volatile; +use std::ptr::write_unaligned; +use std::ptr::write_volatile; +use std::sync::atomic::fence; +use std::sync::atomic::Ordering; -use data_model::{volatile_memory::*, DataInit}; +use data_model::volatile_memory::*; +use data_model::DataInit; use libc::c_int; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; -use crate::{ - descriptor::{AsRawDescriptor, SafeDescriptor}, - platform::{MemoryMapping as PlatformMmap, MmapError as Error, PROT_READ, PROT_WRITE}, - SharedMemory, -}; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::SafeDescriptor; +use crate::platform::MemoryMapping as PlatformMmap; +use crate::platform::MmapError as Error; +use crate::platform::PROT_READ; +use crate::platform::PROT_WRITE; +use crate::SharedMemory; pub type Result = std::result::Result; diff --git a/base/src/shm.rs b/base/src/shm.rs index 916be70e4..467f82201 100644 --- a/base/src/shm.rs +++ b/base/src/shm.rs @@ -2,14 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::descriptor::{AsRawDescriptor, FromRawDescriptor, IntoRawDescriptor, SafeDescriptor}; -use crate::{Error, RawDescriptor, Result}; use std::ffi::CString; use libc::EINVAL; +use serde::Deserialize; +use serde::Serialize; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::IntoRawDescriptor; +use crate::descriptor::SafeDescriptor; use crate::platform::SharedMemory as SysUtilSharedMemory; -use serde::{Deserialize, Serialize}; +use crate::Error; +use crate::RawDescriptor; +use crate::Result; /// See [SharedMemory](crate::platform::SharedMemory) for struct- and method-level /// documentation. diff --git a/base/src/sys/unix/acpi_event.rs b/base/src/sys/unix/acpi_event.rs index 39f772c80..37d4bb05c 100644 --- a/base/src/sys/unix/acpi_event.rs +++ b/base/src/sys/unix/acpi_event.rs @@ -4,10 +4,10 @@ use std::str; -use super::netlink::*; +use data_model::DataInit; use thiserror::Error; -use data_model::DataInit; +use super::netlink::*; const ACPI_EVENT_SIZE: usize = std::mem::size_of::(); const GENL_HDRLEN: usize = std::mem::size_of::(); diff --git a/base/src/sys/unix/android/syslog.rs b/base/src/sys/unix/android/syslog.rs index 4396d779d..e8abbc2bd 100644 --- a/base/src/sys/unix/android/syslog.rs +++ b/base/src/sys/unix/android/syslog.rs @@ -6,19 +6,22 @@ extern crate android_log_sys; -use android_log_sys::{ - __android_log_is_loggable, __android_log_message, __android_log_write_log_message, log_id_t, - LogPriority, -}; -use std::{ - ffi::{CString, NulError}, - mem::size_of, -}; +use std::ffi::CString; +use std::ffi::NulError; +use std::mem::size_of; -use crate::{ - syslog::{Error, Facility, Level, Log, Syslog}, - RawDescriptor, -}; +use android_log_sys::__android_log_is_loggable; +use android_log_sys::__android_log_message; +use android_log_sys::__android_log_write_log_message; +use android_log_sys::log_id_t; +use android_log_sys::LogPriority; + +use crate::syslog::Error; +use crate::syslog::Facility; +use crate::syslog::Level; +use crate::syslog::Log; +use crate::syslog::Syslog; +use crate::RawDescriptor; pub struct PlatformSyslog { proc_name: String, diff --git a/base/src/sys/unix/capabilities.rs b/base/src/sys/unix/capabilities.rs index 5d3acd45a..fd962cf98 100644 --- a/base/src/sys/unix/capabilities.rs +++ b/base/src/sys/unix/capabilities.rs @@ -2,9 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use libc::{c_int, c_void}; +use libc::c_int; +use libc::c_void; -use super::{errno_result, Result}; +use super::errno_result; +use super::Result; #[allow(non_camel_case_types)] type cap_t = *mut c_void; diff --git a/base/src/sys/unix/descriptor.rs b/base/src/sys/unix/descriptor.rs index 6fa6fb06d..04ba01754 100644 --- a/base/src/sys/unix/descriptor.rs +++ b/base/src/sys/unix/descriptor.rs @@ -2,26 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - convert::TryFrom, - fs::File, - io::{Stderr, Stdin, Stdout}, - net::UdpSocket, - ops::Drop, - os::unix::{ - io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}, - net::{UnixDatagram, UnixListener, UnixStream}, - }, -}; +use std::convert::TryFrom; +use std::fs::File; +use std::io::Stderr; +use std::io::Stdin; +use std::io::Stdout; +use std::net::UdpSocket; +use std::ops::Drop; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::FromRawFd; +use std::os::unix::io::IntoRawFd; +use std::os::unix::io::RawFd; +use std::os::unix::net::UnixDatagram; +use std::os::unix::net::UnixListener; +use std::os::unix::net::UnixStream; -use super::{ - errno_result, - net::{UnixSeqpacket, UnlinkUnixSeqpacketListener}, - Result, -}; -use crate::descriptor::{ - AsRawDescriptor, Descriptor, FromRawDescriptor, IntoRawDescriptor, SafeDescriptor, -}; +use super::errno_result; +use super::net::UnixSeqpacket; +use super::net::UnlinkUnixSeqpacketListener; +use super::Result; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::Descriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::IntoRawDescriptor; +use crate::descriptor::SafeDescriptor; pub type RawDescriptor = RawFd; diff --git a/base/src/sys/unix/eventfd.rs b/base/src/sys/unix/eventfd.rs index 034ad2f21..4f426f7ae 100644 --- a/base/src/sys/unix/eventfd.rs +++ b/base/src/sys/unix/eventfd.rs @@ -2,18 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - mem, - os::unix::io::{AsRawFd, RawFd}, - ptr, - time::Duration, -}; +use std::mem; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::RawFd; +use std::ptr; +use std::time::Duration; -use libc::{c_void, eventfd, read, write, POLLIN}; -use serde::{Deserialize, Serialize}; +use libc::c_void; +use libc::eventfd; +use libc::read; +use libc::write; +use libc::POLLIN; +use serde::Deserialize; +use serde::Serialize; -use super::{duration_to_timespec, errno_result, RawDescriptor, Result}; -use crate::descriptor::{AsRawDescriptor, FromRawDescriptor, IntoRawDescriptor, SafeDescriptor}; +use super::duration_to_timespec; +use super::errno_result; +use super::RawDescriptor; +use super::Result; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::IntoRawDescriptor; +use crate::descriptor::SafeDescriptor; /// A safe wrapper around a Linux eventfd (man 2 eventfd). /// diff --git a/base/src/sys/unix/file_flags.rs b/base/src/sys/unix/file_flags.rs index 47a03c8f7..8edf5230a 100644 --- a/base/src/sys/unix/file_flags.rs +++ b/base/src/sys/unix/file_flags.rs @@ -4,9 +4,17 @@ use std::os::unix::io::AsRawFd; -use libc::{fcntl, EINVAL, F_GETFL, O_ACCMODE, O_RDONLY, O_RDWR, O_WRONLY}; +use libc::fcntl; +use libc::EINVAL; +use libc::F_GETFL; +use libc::O_ACCMODE; +use libc::O_RDONLY; +use libc::O_RDWR; +use libc::O_WRONLY; -use super::{errno_result, Error, Result}; +use super::errno_result; +use super::Error; +use super::Result; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum FileFlags { @@ -35,10 +43,9 @@ impl FileFlags { #[cfg(test)] mod tests { - use super::{ - super::{pipe, Event}, - *, - }; + use super::super::pipe; + use super::super::Event; + use super::*; #[test] fn pipe_pair() { diff --git a/base/src/sys/unix/file_traits.rs b/base/src/sys/unix/file_traits.rs index a109f2327..e8e57fc8c 100644 --- a/base/src/sys/unix/file_traits.rs +++ b/base/src/sys/unix/file_traits.rs @@ -2,18 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - fs::File, - io::{Error, ErrorKind, Result}, - os::unix::{ - io::{AsRawFd, RawFd}, - net::UnixStream, - }, -}; +use std::fs::File; +use std::io::Error; +use std::io::ErrorKind; +use std::io::Result; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::RawFd; +use std::os::unix::net::UnixStream; use data_model::VolatileSlice; -use super::{fallocate, FallocateMode}; +use super::fallocate; +use super::FallocateMode; /// A trait for flushing the contents of a file to disk. /// This is equivalent to File's `sync_all` method, but @@ -266,12 +266,21 @@ impl<'a, T: FileReadWriteAtVolatile + ?Sized> FileReadWriteAtVolatile for &'a mu // This module allows the below macros to refer to $crate::platform::file_traits::lib::X and ensures other // crates don't need to add additional crates to their Cargo.toml. pub mod lib { - pub use libc::{ - c_int, c_void, iovec, off64_t, pread64, preadv64, pwrite64, pwritev64, read, readv, size_t, - write, writev, - }; - - pub use data_model::{IoBufMut, VolatileSlice}; + pub use data_model::IoBufMut; + pub use data_model::VolatileSlice; + pub use libc::c_int; + pub use libc::c_void; + pub use libc::iovec; + pub use libc::off64_t; + pub use libc::pread64; + pub use libc::preadv64; + pub use libc::pwrite64; + pub use libc::pwritev64; + pub use libc::read; + pub use libc::readv; + pub use libc::size_t; + pub use libc::write; + pub use libc::writev; } #[macro_export] diff --git a/base/src/sys/unix/get_filesystem_type.rs b/base/src/sys/unix/get_filesystem_type.rs index 9025a642e..5febf02b7 100644 --- a/base/src/sys/unix/get_filesystem_type.rs +++ b/base/src/sys/unix/get_filesystem_type.rs @@ -2,10 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::fs::File; +use std::mem::MaybeUninit; +use std::os::unix::io::AsRawFd; + +use libc::fstatfs; + use super::Result; use crate::syscall; -use libc::fstatfs; -use std::{fs::File, mem::MaybeUninit, os::unix::io::AsRawFd}; /// Obtain file system type of the file system that the file is served from. pub fn get_filesystem_type(file: &File) -> Result { diff --git a/base/src/sys/unix/gmtime.rs b/base/src/sys/unix/gmtime.rs index dc402c6f4..077598ab4 100644 --- a/base/src/sys/unix/gmtime.rs +++ b/base/src/sys/unix/gmtime.rs @@ -2,7 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use libc::{gmtime_r, time_t, tm}; +use libc::gmtime_r; +use libc::time_t; +use libc::tm; /// # Safety /// safe because we are passing in the allocated tm struct @@ -13,9 +15,10 @@ pub unsafe fn gmtime_secure(now: *const time_t, result: *mut tm) { #[cfg(test)] mod tests { - use super::*; use std::mem; + use super::*; + #[test] fn gmtime() { // Safe because struct is not used before being initialized diff --git a/base/src/sys/unix/handle_eintr.rs b/base/src/sys/unix/handle_eintr.rs index 7e7f905cd..740305993 100644 --- a/base/src/sys/unix/handle_eintr.rs +++ b/base/src/sys/unix/handle_eintr.rs @@ -171,7 +171,8 @@ macro_rules! handle_eintr_errno { #[cfg(test)] mod tests { - use super::{super::Error as SysError, *}; + use super::super::Error as SysError; + use super::*; // Sets errno to the given error code. fn set_errno(e: i32) { diff --git a/base/src/sys/unix/ioctl.rs b/base/src/sys/unix/ioctl.rs index 58dc48094..b68df8706 100644 --- a/base/src/sys/unix/ioctl.rs +++ b/base/src/sys/unix/ioctl.rs @@ -8,8 +8,12 @@ // `libc::ioctl`. Their safety follows `libc::ioctl`'s safety. #![allow(clippy::missing_safety_doc)] +use std::os::raw::c_int; +use std::os::raw::c_uint; +use std::os::raw::c_ulong; +use std::os::raw::c_void; + use crate::descriptor::AsRawDescriptor; -use std::os::raw::{c_int, c_uint, c_ulong, c_void}; /// Raw macro to declare the expression that calculates an ioctl number #[macro_export] diff --git a/base/src/sys/unix/linux/syslog.rs b/base/src/sys/unix/linux/syslog.rs index 0a87fbe9e..0855e3df0 100644 --- a/base/src/sys/unix/linux/syslog.rs +++ b/base/src/sys/unix/linux/syslog.rs @@ -4,27 +4,34 @@ //! Implementation of the Syslog trait for Linux. -use std::{ - fs::File, - io::{ErrorKind, Write}, - mem, - os::unix::{ - io::{AsRawFd, FromRawFd}, - net::UnixDatagram, - }, - ptr::null, -}; +use std::fs::File; +use std::io::ErrorKind; +use std::io::Write; +use std::mem; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::FromRawFd; +use std::os::unix::net::UnixDatagram; +use std::ptr::null; -use libc::{ - closelog, fcntl, localtime_r, openlog, time, time_t, tm, F_GETFD, LOG_NDELAY, LOG_PERROR, - LOG_PID, LOG_USER, -}; +use libc::closelog; +use libc::fcntl; +use libc::localtime_r; +use libc::openlog; +use libc::time; +use libc::time_t; +use libc::tm; +use libc::F_GETFD; +use libc::LOG_NDELAY; +use libc::LOG_PERROR; +use libc::LOG_PID; +use libc::LOG_USER; use super::super::getpid; -use crate::{ - syslog::{Error, Facility, Priority, Syslog}, - RawDescriptor, -}; +use crate::syslog::Error; +use crate::syslog::Facility; +use crate::syslog::Priority; +use crate::syslog::Syslog; +use crate::RawDescriptor; const SYSLOG_PATH: &str = "/dev/log"; diff --git a/base/src/sys/unix/mmap.rs b/base/src/sys/unix/mmap.rs index a55265616..4e3999048 100644 --- a/base/src/sys/unix/mmap.rs +++ b/base/src/sys/unix/mmap.rs @@ -5,19 +5,28 @@ //! The mmap module provides a safe interface to mmap memory and ensures unmap is called when the //! mmap object leaves scope. -use std::{io, ptr::null_mut}; +use std::io; +use std::ptr::null_mut; -use libc::{self, c_int, c_void, read, write}; +use libc::c_int; +use libc::c_void; +use libc::read; +use libc::write; +use libc::{self}; use log::warn; use remain::sorted; -use crate::{ - external_mapping::ExternalMapping, AsRawDescriptor, Descriptor, MappedRegion, - MemoryMapping as CrateMemoryMapping, MemoryMappingBuilder, Protection, RawDescriptor, - SafeDescriptor, -}; - -use super::{pagesize, Error as ErrnoError}; +use super::pagesize; +use super::Error as ErrnoError; +use crate::external_mapping::ExternalMapping; +use crate::AsRawDescriptor; +use crate::Descriptor; +use crate::MappedRegion; +use crate::MemoryMapping as CrateMemoryMapping; +use crate::MemoryMappingBuilder; +use crate::Protection; +use crate::RawDescriptor; +use crate::SafeDescriptor; #[sorted] #[derive(Debug, thiserror::Error)] @@ -880,10 +889,12 @@ impl<'a> MemoryMappingBuilder<'a> { #[cfg(test)] mod tests { + use data_model::VolatileMemory; + use data_model::VolatileMemoryError; + use tempfile::tempfile; + use super::*; use crate::descriptor::Descriptor; - use data_model::{VolatileMemory, VolatileMemoryError}; - use tempfile::tempfile; #[test] fn basic_map() { diff --git a/base/src/sys/unix/mod.rs b/base/src/sys/unix/mod.rs index 00b6b22cd..a627c8a8e 100644 --- a/base/src/sys/unix/mod.rs +++ b/base/src/sys/unix/mod.rs @@ -46,11 +46,23 @@ mod timer; pub mod vsock; mod write_zeroes; -pub use crate::descriptor_reflection::{ - deserialize_with_descriptors, with_as_descriptor, with_raw_descriptor, FileSerdeWrapper, - SerializeDescriptors, -}; -pub use crate::errno::{Error, Result, *}; +use std::cell::Cell; +use std::convert::TryFrom; +use std::ffi::CStr; +use std::fs::remove_file; +use std::fs::File; +use std::fs::OpenOptions; +use std::mem; +use std::ops::Deref; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::FromRawFd; +use std::os::unix::io::RawFd; +use std::os::unix::net::UnixDatagram; +use std::os::unix::net::UnixListener; +use std::path::Path; +use std::ptr; +use std::time::Duration; + pub use acpi_event::*; pub use capabilities::drop_capabilities; pub use descriptor::*; @@ -59,54 +71,66 @@ pub use descriptor::*; // TODO(b:231344063): Remove EventFd. pub use eventfd::{EventFd as Event, EventFd, EventReadResult}; pub use file_flags::*; +pub use file_traits::AsRawFds; +pub use file_traits::FileAllocate; +pub use file_traits::FileGetLen; +pub use file_traits::FileReadWriteAtVolatile; +pub use file_traits::FileReadWriteVolatile; +pub use file_traits::FileSetLen; +pub use file_traits::FileSync; pub use get_filesystem_type::*; pub use gmtime::*; pub use ioctl::*; +use libc::c_int; +use libc::c_long; +use libc::fcntl; +use libc::pipe2; +use libc::syscall; +use libc::sysconf; +use libc::waitpid; +use libc::SYS_getpid; +use libc::SYS_gettid; +use libc::EINVAL; +use libc::F_GETFL; +use libc::F_SETFL; +use libc::O_CLOEXEC; +pub(crate) use libc::PROT_READ; +pub(crate) use libc::PROT_WRITE; +use libc::SIGKILL; +use libc::WNOHANG; +use libc::_SC_IOV_MAX; +use libc::_SC_PAGESIZE; +pub use mmap::Error as MmapError; pub use mmap::*; pub use netlink::*; pub use poll::EventContext; pub use priority::*; pub use sched::*; pub use scoped_signal_handler::*; -pub use shm::{kernel_has_memfd, MemfdSeals, SharedMemory, Unix as SharedMemoryUnix}; +pub use shm::kernel_has_memfd; +pub use shm::MemfdSeals; +pub use shm::SharedMemory; +pub use shm::Unix as SharedMemoryUnix; pub use signal::*; +pub use signalfd::Error as SignalFdError; pub use signalfd::*; pub use sock_ctrl_msg::*; pub use stream_channel::*; pub use terminal::*; pub use timer::*; +pub(crate) use write_zeroes::file_punch_hole; +pub(crate) use write_zeroes::file_write_zeroes_at; -use crate::descriptor::{FromRawDescriptor, SafeDescriptor}; -pub use file_traits::{ - AsRawFds, FileAllocate, FileGetLen, FileReadWriteAtVolatile, FileReadWriteVolatile, FileSetLen, - FileSync, -}; -pub use mmap::Error as MmapError; -pub use signalfd::Error as SignalFdError; -pub(crate) use write_zeroes::{file_punch_hole, file_write_zeroes_at}; - -use std::{ - cell::Cell, - convert::TryFrom, - ffi::CStr, - fs::{remove_file, File, OpenOptions}, - mem, - ops::Deref, - os::unix::{ - io::{AsRawFd, FromRawFd, RawFd}, - net::{UnixDatagram, UnixListener}, - }, - path::Path, - ptr, - time::Duration, -}; - -use libc::{ - c_int, c_long, fcntl, pipe2, syscall, sysconf, waitpid, SYS_getpid, SYS_gettid, EINVAL, - F_GETFL, F_SETFL, O_CLOEXEC, SIGKILL, WNOHANG, _SC_IOV_MAX, _SC_PAGESIZE, -}; - -pub(crate) use libc::{PROT_READ, PROT_WRITE}; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::SafeDescriptor; +pub use crate::descriptor_reflection::deserialize_with_descriptors; +pub use crate::descriptor_reflection::with_as_descriptor; +pub use crate::descriptor_reflection::with_raw_descriptor; +pub use crate::descriptor_reflection::FileSerdeWrapper; +pub use crate::descriptor_reflection::SerializeDescriptors; +pub use crate::errno::Error; +pub use crate::errno::Result; +pub use crate::errno::*; /// Re-export libc types that are part of the API. pub type Pid = libc::pid_t; @@ -637,9 +661,10 @@ pub fn number_of_logical_cores() -> Result { #[cfg(test)] mod tests { - use libc::EBADF; use std::io::Write; + use libc::EBADF; + use super::*; #[test] diff --git a/base/src/sys/unix/net.rs b/base/src/sys/unix/net.rs index 048d13829..4c74fa0c7 100644 --- a/base/src/sys/unix/net.rs +++ b/base/src/sys/unix/net.rs @@ -2,36 +2,58 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - cmp::Ordering, - convert::TryFrom, - ffi::OsString, - fs::remove_file, - io, - mem::{self, size_of}, - net::{SocketAddr, SocketAddrV4, SocketAddrV6, TcpListener, TcpStream, ToSocketAddrs}, - ops::Deref, - os::unix::{ - ffi::{OsStrExt, OsStringExt}, - io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}, - }, - path::{Path, PathBuf}, - ptr::null_mut, - time::{Duration, Instant}, -}; +use std::cmp::Ordering; +use std::convert::TryFrom; +use std::ffi::OsString; +use std::fs::remove_file; +use std::io; +use std::mem::size_of; +use std::mem::{self}; +use std::net::SocketAddr; +use std::net::SocketAddrV4; +use std::net::SocketAddrV6; +use std::net::TcpListener; +use std::net::TcpStream; +use std::net::ToSocketAddrs; +use std::ops::Deref; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::ffi::OsStringExt; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::FromRawFd; +use std::os::unix::io::IntoRawFd; +use std::os::unix::io::RawFd; +use std::path::Path; +use std::path::PathBuf; +use std::ptr::null_mut; +use std::time::Duration; +use std::time::Instant; -use libc::{ - c_int, in6_addr, in_addr, recvfrom, sa_family_t, sockaddr, sockaddr_in, sockaddr_in6, - socklen_t, AF_INET, AF_INET6, MSG_PEEK, MSG_TRUNC, SOCK_CLOEXEC, SOCK_STREAM, -}; +use libc::c_int; +use libc::in6_addr; +use libc::in_addr; +use libc::recvfrom; +use libc::sa_family_t; +use libc::sockaddr; +use libc::sockaddr_in; +use libc::sockaddr_in6; +use libc::socklen_t; +use libc::AF_INET; +use libc::AF_INET6; +use libc::MSG_PEEK; +use libc::MSG_TRUNC; +use libc::SOCK_CLOEXEC; +use libc::SOCK_STREAM; use log::warn; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; -use super::{ - sock_ctrl_msg::{ScmSocket, SCM_SOCKET_MAX_FD_COUNT}, - Error, RawDescriptor, -}; -use crate::descriptor::{AsRawDescriptor, FromRawDescriptor, IntoRawDescriptor}; +use super::sock_ctrl_msg::ScmSocket; +use super::sock_ctrl_msg::SCM_SOCKET_MAX_FD_COUNT; +use super::Error; +use super::RawDescriptor; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::IntoRawDescriptor; /// Assist in handling both IP version 4 and IP version 6. #[derive(Debug, Copy, Clone, PartialEq, Eq)] @@ -870,8 +892,11 @@ impl Drop for UnlinkUnixSeqpacketListener { #[cfg(test)] mod tests { + use std::env; + use std::io::ErrorKind; + use std::path::PathBuf; + use super::*; - use std::{env, io::ErrorKind, path::PathBuf}; fn tmpdir() -> PathBuf { env::temp_dir() diff --git a/base/src/sys/unix/netlink.rs b/base/src/sys/unix/netlink.rs index 2e6d85e59..d327c0cee 100644 --- a/base/src/sys/unix/netlink.rs +++ b/base/src/sys/unix/netlink.rs @@ -2,16 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{alloc::Layout, mem::MaybeUninit, os::unix::io::AsRawFd, str}; +use std::alloc::Layout; +use std::mem::MaybeUninit; +use std::os::unix::io::AsRawFd; +use std::str; use data_model::DataInit; use libc::EINVAL; use log::error; +use super::errno_result; +use super::getpid; +use super::Error; +use super::RawDescriptor; +use super::Result; use crate::alloc::LayoutAllocation; - -use super::{errno_result, getpid, Error, RawDescriptor, Result}; -use crate::descriptor::{AsRawDescriptor, FromRawDescriptor, SafeDescriptor}; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::SafeDescriptor; macro_rules! debug_pr { // By default debugs are suppressed, to enabled them replace macro body with: diff --git a/base/src/sys/unix/notifiers.rs b/base/src/sys/unix/notifiers.rs index c7e5d1670..d7b5e4d6c 100644 --- a/base/src/sys/unix/notifiers.rs +++ b/base/src/sys/unix/notifiers.rs @@ -5,7 +5,8 @@ use std::os::unix::net::UnixStream; use crate::descriptor::AsRawDescriptor; -use crate::{CloseNotifier, ReadNotifier}; +use crate::CloseNotifier; +use crate::ReadNotifier; impl ReadNotifier for UnixStream { fn get_read_notifier(&self) -> &dyn AsRawDescriptor { diff --git a/base/src/sys/unix/platform_timer_resolution.rs b/base/src/sys/unix/platform_timer_resolution.rs index e8838a746..50ad11030 100644 --- a/base/src/sys/unix/platform_timer_resolution.rs +++ b/base/src/sys/unix/platform_timer_resolution.rs @@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{EnabledHighResTimer, Result}; +use crate::EnabledHighResTimer; +use crate::Result; /// Noop struct on unix. /// On windows, restores the platform timer resolution to its original value on Drop. diff --git a/base/src/sys/unix/poll.rs b/base/src/sys/unix/poll.rs index 5443da46c..a4963b64d 100644 --- a/base/src/sys/unix/poll.rs +++ b/base/src/sys/unix/poll.rs @@ -2,20 +2,36 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - cmp::min, fs::File, marker::PhantomData, mem::MaybeUninit, ptr::null_mut, time::Duration, -}; +use std::cmp::min; +use std::fs::File; +use std::marker::PhantomData; +use std::mem::MaybeUninit; +use std::ptr::null_mut; +use std::time::Duration; -use libc::{ - c_int, epoll_create1, epoll_ctl, epoll_event, epoll_wait, EPOLLHUP, EPOLLIN, EPOLLOUT, - EPOLLRDHUP, EPOLL_CLOEXEC, EPOLL_CTL_ADD, EPOLL_CTL_DEL, EPOLL_CTL_MOD, -}; +use libc::c_int; +use libc::epoll_create1; +use libc::epoll_ctl; +use libc::epoll_event; +use libc::epoll_wait; +use libc::EPOLLHUP; +use libc::EPOLLIN; +use libc::EPOLLOUT; +use libc::EPOLLRDHUP; +use libc::EPOLL_CLOEXEC; +use libc::EPOLL_CTL_ADD; +use libc::EPOLL_CTL_DEL; +use libc::EPOLL_CTL_MOD; use smallvec::SmallVec; -use super::{errno_result, Result}; -use crate::{ - AsRawDescriptor, EventToken, EventType, FromRawDescriptor, RawDescriptor, TriggeredEvent, -}; +use super::errno_result; +use super::Result; +use crate::AsRawDescriptor; +use crate::EventToken; +use crate::EventType; +use crate::FromRawDescriptor; +use crate::RawDescriptor; +use crate::TriggeredEvent; const EVENT_CONTEXT_MAX_EVENTS: usize = 16; @@ -251,10 +267,13 @@ impl AsRawDescriptor for EventContext { #[cfg(test)] mod tests { - use super::{super::Event, *}; - use base_event_token_derive::EventToken; use std::time::Instant; + use base_event_token_derive::EventToken; + + use super::super::Event; + use super::*; + #[test] fn event_context() { let evt1 = Event::new().unwrap(); diff --git a/base/src/sys/unix/priority.rs b/base/src/sys/unix/priority.rs index 491a66b2f..5d1f49983 100644 --- a/base/src/sys/unix/priority.rs +++ b/base/src/sys/unix/priority.rs @@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::{errno_result, Result}; - use std::mem::MaybeUninit; +use super::errno_result; +use super::Result; + /// Enables real time thread priorities in the current thread up to `limit`. pub fn set_rt_prio_limit(limit: u64) -> Result<()> { let rt_limit_arg = libc::rlimit { diff --git a/base/src/sys/unix/sched.rs b/base/src/sys/unix/sched.rs index adec77f11..76a232571 100644 --- a/base/src/sys/unix/sched.rs +++ b/base/src/sys/unix/sched.rs @@ -4,14 +4,22 @@ //! Wrappers for CPU affinity functions. -use std::{iter::FromIterator, mem}; +use std::iter::FromIterator; +use std::mem; -use libc::{ - cpu_set_t, prctl, sched_getaffinity, sched_setaffinity, CPU_ISSET, CPU_SET, CPU_SETSIZE, - CPU_ZERO, EINVAL, -}; +use libc::cpu_set_t; +use libc::prctl; +use libc::sched_getaffinity; +use libc::sched_setaffinity; +use libc::CPU_ISSET; +use libc::CPU_SET; +use libc::CPU_SETSIZE; +use libc::CPU_ZERO; +use libc::EINVAL; -use super::{errno_result, Error, Result}; +use super::errno_result; +use super::Error; +use super::Result; // This is needed because otherwise the compiler will complain that the // impl doesn't reference any types from inside this crate. diff --git a/base/src/sys/unix/scoped_signal_handler.rs b/base/src/sys/unix/scoped_signal_handler.rs index b4d387df9..70b7071b0 100644 --- a/base/src/sys/unix/scoped_signal_handler.rs +++ b/base/src/sys/unix/scoped_signal_handler.rs @@ -4,25 +4,25 @@ //! Provides a struct for registering signal handlers that get cleared on drop. -use std::{ - convert::TryFrom, - fmt, - io::{Cursor, Write}, - panic::catch_unwind, - result, -}; +use std::convert::TryFrom; +use std::fmt; +use std::io::Cursor; +use std::io::Write; +use std::panic::catch_unwind; +use std::result; -use libc::{c_int, c_void, STDERR_FILENO}; +use libc::c_int; +use libc::c_void; +use libc::STDERR_FILENO; use remain::sorted; use thiserror::Error; -use super::{ - signal::{ - clear_signal_handler, has_default_signal_handler, register_signal_handler, wait_for_signal, - Signal, - }, - Error as ErrnoError, -}; +use super::signal::clear_signal_handler; +use super::signal::has_default_signal_handler; +use super::signal::register_signal_handler; +use super::signal::wait_for_signal; +use super::signal::Signal; +use super::Error as ErrnoError; #[sorted] #[derive(Error, Debug)] @@ -179,24 +179,30 @@ pub fn wait_for_interrupt() -> Result<()> { #[cfg(test)] mod tests { - use super::*; - - use std::{ - fs::File, - io::{BufRead, BufReader}, - mem::zeroed, - ptr::{null, null_mut}, - sync::{ - atomic::{AtomicI32, AtomicUsize, Ordering}, - Arc, Mutex, MutexGuard, Once, - }, - thread::{sleep, spawn}, - time::{Duration, Instant}, - }; + use std::fs::File; + use std::io::BufRead; + use std::io::BufReader; + use std::mem::zeroed; + use std::ptr::null; + use std::ptr::null_mut; + use std::sync::atomic::AtomicI32; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + use std::sync::Arc; + use std::sync::Mutex; + use std::sync::MutexGuard; + use std::sync::Once; + use std::thread::sleep; + use std::thread::spawn; + use std::time::Duration; + use std::time::Instant; use libc::sigaction; - use super::super::{gettid, kill, Pid}; + use super::super::gettid; + use super::super::kill; + use super::super::Pid; + use super::*; const TEST_SIGNAL: Signal = Signal::User1; const TEST_SIGNALS: &[Signal] = &[Signal::User1, Signal::User2]; diff --git a/base/src/sys/unix/shm.rs b/base/src/sys/unix/shm.rs index 9fd8d1cc8..2d2094500 100644 --- a/base/src/sys/unix/shm.rs +++ b/base/src/sys/unix/shm.rs @@ -2,24 +2,47 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - ffi::CStr, - fs::{read_link, File}, - io::{ - Read, Seek, SeekFrom, Write, {self}, - }, -}; +use std::ffi::CStr; +use std::fs::read_link; +use std::fs::File; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::Write; +use std::io::{self}; -use libc::{ - c_char, c_int, c_long, c_uint, close, fcntl, ftruncate64, off64_t, syscall, SYS_memfd_create, - EINVAL, F_ADD_SEALS, F_GET_SEALS, F_SEAL_FUTURE_WRITE, F_SEAL_GROW, F_SEAL_SEAL, F_SEAL_SHRINK, - F_SEAL_WRITE, MFD_ALLOW_SEALING, {self}, -}; -use serde::{Deserialize, Serialize}; +use libc::c_char; +use libc::c_int; +use libc::c_long; +use libc::c_uint; +use libc::close; +use libc::fcntl; +use libc::ftruncate64; +use libc::off64_t; +use libc::syscall; +use libc::SYS_memfd_create; +use libc::EINVAL; +use libc::F_ADD_SEALS; +use libc::F_GET_SEALS; +use libc::F_SEAL_FUTURE_WRITE; +use libc::F_SEAL_GROW; +use libc::F_SEAL_SEAL; +use libc::F_SEAL_SHRINK; +use libc::F_SEAL_WRITE; +use libc::MFD_ALLOW_SEALING; +use libc::{self}; +use serde::Deserialize; +use serde::Serialize; -use super::{errno_result, Error, Result}; -use crate::{AsRawDescriptor, IntoRawDescriptor, RawDescriptor, SafeDescriptor}; -use crate::{FromRawDescriptor, SharedMemory as CrateSharedMemory}; +use super::errno_result; +use super::Error; +use super::Result; +use crate::AsRawDescriptor; +use crate::FromRawDescriptor; +use crate::IntoRawDescriptor; +use crate::RawDescriptor; +use crate::SafeDescriptor; +use crate::SharedMemory as CrateSharedMemory; /// A shared memory file descriptor and its size. #[derive(Debug, Serialize, Deserialize)] @@ -327,12 +350,12 @@ impl Unix for CrateSharedMemory { #[cfg(test)] mod tests { - use super::{kernel_has_memfd, SharedMemory}; - use std::ffi::CString; use data_model::VolatileMemory; + use super::kernel_has_memfd; + use super::SharedMemory; use crate::MemoryMappingBuilder; fn create_test_shmem() -> SharedMemory { diff --git a/base/src/sys/unix/signal.rs b/base/src/sys/unix/signal.rs index 02c8ba32b..ee0ecbe02 100644 --- a/base/src/sys/unix/signal.rs +++ b/base/src/sys/unix/signal.rs @@ -2,28 +2,53 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use libc::{ - c_int, pthread_kill, pthread_sigmask, pthread_t, sigaction, sigaddset, sigemptyset, siginfo_t, - sigismember, sigpending, sigset_t, sigtimedwait, sigwait, timespec, waitpid, EAGAIN, EINTR, - EINVAL, SA_RESTART, SIG_BLOCK, SIG_DFL, SIG_UNBLOCK, WNOHANG, -}; +use std::cmp::Ordering; +use std::convert::TryFrom; +use std::io; +use std::mem; +use std::ops::Deref; +use std::ops::DerefMut; +use std::os::unix::thread::JoinHandleExt; +use std::process::Child; +use std::ptr::null; +use std::ptr::null_mut; +use std::result; +use std::thread::JoinHandle; +use std::time::Duration; +use std::time::Instant; + +use libc::c_int; +use libc::pthread_kill; +use libc::pthread_sigmask; +use libc::pthread_t; +use libc::sigaction; +use libc::sigaddset; +use libc::sigemptyset; +use libc::siginfo_t; +use libc::sigismember; +use libc::sigpending; +use libc::sigset_t; +use libc::sigtimedwait; +use libc::sigwait; +use libc::timespec; +use libc::waitpid; +use libc::EAGAIN; +use libc::EINTR; +use libc::EINVAL; +use libc::SA_RESTART; +use libc::SIG_BLOCK; +use libc::SIG_DFL; +use libc::SIG_UNBLOCK; +use libc::WNOHANG; use remain::sorted; use thiserror::Error; -use std::{ - cmp::Ordering, - convert::TryFrom, - io, mem, - os::unix::thread::JoinHandleExt, - process::Child, - ptr::{null, null_mut}, - result, - thread::JoinHandle, - time::{Duration, Instant}, -}; - -use super::{duration_to_timespec, errno_result, getsid, Error as ErrnoError, Pid, Result}; -use std::ops::{Deref, DerefMut}; +use super::duration_to_timespec; +use super::errno_result; +use super::getsid; +use super::Error as ErrnoError; +use super::Pid; +use super::Result; const POLL_RATE: Duration = Duration::from_millis(50); const DEFAULT_KILL_TIMEOUT: Duration = Duration::from_secs(5); diff --git a/base/src/sys/unix/signalfd.rs b/base/src/sys/unix/signalfd.rs index 340755f94..9ae8ccdd7 100644 --- a/base/src/sys/unix/signalfd.rs +++ b/base/src/sys/unix/signalfd.rs @@ -2,22 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - fs::File, - mem, - os::{ - raw::c_int, - unix::io::{AsRawFd, FromRawFd, RawFd}, - }, - result, -}; +use std::fs::File; +use std::mem; +use std::os::raw::c_int; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::FromRawFd; +use std::os::unix::io::RawFd; +use std::result; -use libc::{c_void, read, signalfd, signalfd_siginfo, EAGAIN, SFD_CLOEXEC, SFD_NONBLOCK}; +use libc::c_void; +use libc::read; +use libc::signalfd; +use libc::signalfd_siginfo; +use libc::EAGAIN; +use libc::SFD_CLOEXEC; +use libc::SFD_NONBLOCK; use log::error; use remain::sorted; use thiserror::Error; -use super::{signal, Error as ErrnoError, RawDescriptor}; +use super::signal; +use super::Error as ErrnoError; +use super::RawDescriptor; use crate::descriptor::AsRawDescriptor; #[sorted] @@ -139,11 +145,16 @@ impl Drop for SignalFd { #[cfg(test)] mod tests { - use super::*; + use std::mem; + use std::ptr::null; + + use libc::pthread_sigmask; + use libc::raise; + use libc::sigismember; + use libc::sigset_t; use super::super::signal::SIGRTMIN; - use libc::{pthread_sigmask, raise, sigismember, sigset_t}; - use std::{mem, ptr::null}; + use super::*; #[test] fn new() { diff --git a/base/src/sys/unix/sock_ctrl_msg.rs b/base/src/sys/unix/sock_ctrl_msg.rs index da404831e..da04c9476 100644 --- a/base/src/sys/unix/sock_ctrl_msg.rs +++ b/base/src/sys/unix/sock_ctrl_msg.rs @@ -5,26 +5,37 @@ //! Used to send and receive messages with file descriptors on sockets that accept control messages //! (e.g. Unix domain sockets). -use std::{ - fs::File, - io::{IoSlice, IoSliceMut}, - mem::size_of, - mem::MaybeUninit, - os::unix::{ - io::{AsRawFd, FromRawFd, RawFd}, - net::{UnixDatagram, UnixStream}, - }, - ptr::{copy_nonoverlapping, null_mut, write_unaligned}, - slice, -}; +use std::fs::File; +use std::io::IoSlice; +use std::io::IoSliceMut; +use std::mem::size_of; +use std::mem::MaybeUninit; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::FromRawFd; +use std::os::unix::io::RawFd; +use std::os::unix::net::UnixDatagram; +use std::os::unix::net::UnixStream; +use std::ptr::copy_nonoverlapping; +use std::ptr::null_mut; +use std::ptr::write_unaligned; +use std::slice; -use libc::{ - c_long, c_void, cmsghdr, iovec, msghdr, recvmsg, sendmsg, MSG_NOSIGNAL, SCM_RIGHTS, SOL_SOCKET, -}; +use data_model::IoBufMut; +use data_model::VolatileSlice; +use libc::c_long; +use libc::c_void; +use libc::cmsghdr; +use libc::iovec; +use libc::msghdr; +use libc::recvmsg; +use libc::sendmsg; +use libc::MSG_NOSIGNAL; +use libc::SCM_RIGHTS; +use libc::SOL_SOCKET; -use data_model::{IoBufMut, VolatileSlice}; - -use super::{net::UnixSeqpacket, Error, Result}; +use super::net::UnixSeqpacket; +use super::Error; +use super::Result; // Each of the following macros performs the same function as their C counterparts. They are each // macros because they are used to size statically allocated arrays. @@ -413,18 +424,16 @@ unsafe impl<'a> AsIobuf for VolatileSlice<'a> { #[cfg(test)] mod tests { - use super::*; - - use std::{ - io::Write, - mem::size_of, - os::{raw::c_long, unix::net::UnixDatagram}, - slice::from_raw_parts, - }; + use std::io::Write; + use std::mem::size_of; + use std::os::raw::c_long; + use std::os::unix::net::UnixDatagram; + use std::slice::from_raw_parts; use libc::cmsghdr; use super::super::Event; + use super::*; // Doing this as a macro makes it easier to see the line if it fails macro_rules! CMSG_SPACE_TEST { diff --git a/base/src/sys/unix/stream_channel.rs b/base/src/sys/unix/stream_channel.rs index c24c14510..3a73294bb 100644 --- a/base/src/sys/unix/stream_channel.rs +++ b/base/src/sys/unix/stream_channel.rs @@ -2,18 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::super::{net::UnixSeqpacket, Result}; +use std::io::Read; +use std::io::{self}; +use std::os::unix::net::UnixStream; + +use libc::c_void; +use libc::{self}; + +use super::super::net::UnixSeqpacket; +use super::super::Result; use super::RawDescriptor; -use crate::{descriptor::AsRawDescriptor, ReadNotifier}; -use libc::{ - c_void, {self}, -}; -use std::{ - io::{ - Read, {self}, - }, - os::unix::net::UnixStream, -}; +use crate::descriptor::AsRawDescriptor; +use crate::ReadNotifier; #[derive(Copy, Clone)] pub enum FramingMode { @@ -167,9 +167,13 @@ impl ReadNotifier for StreamChannel { #[cfg(test)] mod test { + use std::io::Read; + use std::io::Write; + use super::*; - use crate::{EventContext, EventToken, ReadNotifier}; - use std::io::{Read, Write}; + use crate::EventContext; + use crate::EventToken; + use crate::ReadNotifier; #[derive(EventToken, Debug, Eq, PartialEq, Copy, Clone)] enum Token { diff --git a/base/src/sys/unix/syslog.rs b/base/src/sys/unix/syslog.rs index 7ca02777a..cad0cd262 100644 --- a/base/src/sys/unix/syslog.rs +++ b/base/src/sys/unix/syslog.rs @@ -2,21 +2,26 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -pub use super::{target_os::syslog::PlatformSyslog, RawDescriptor}; +pub use super::target_os::syslog::PlatformSyslog; +pub use super::RawDescriptor; #[cfg(test)] mod tests { + use std::ffi::CStr; + use std::fs::File; + use std::io::Read; + use std::io::Seek; + use std::io::SeekFrom; + use std::os::unix::io::FromRawFd; + + use libc::shm_open; + use libc::shm_unlink; + use libc::O_CREAT; + use libc::O_EXCL; + use libc::O_RDWR; + use crate::syslog::*; - use libc::{shm_open, shm_unlink, O_CREAT, O_EXCL, O_RDWR}; - - use std::{ - ffi::CStr, - fs::File, - io::{Read, Seek, SeekFrom}, - os::unix::io::FromRawFd, - }; - #[test] fn fds() { ensure_inited().unwrap(); diff --git a/base/src/sys/unix/terminal.rs b/base/src/sys/unix/terminal.rs index caafee3de..8f2c7bfbb 100644 --- a/base/src/sys/unix/terminal.rs +++ b/base/src/sys/unix/terminal.rs @@ -2,14 +2,26 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{io::Stdin, mem::zeroed, os::unix::io::RawFd}; +use std::io::Stdin; +use std::mem::zeroed; +use std::os::unix::io::RawFd; -use libc::{ - isatty, read, tcgetattr, tcsetattr, termios, ECHO, ICANON, ISIG, O_NONBLOCK, STDIN_FILENO, - TCSANOW, -}; +use libc::isatty; +use libc::read; +use libc::tcgetattr; +use libc::tcsetattr; +use libc::termios; +use libc::ECHO; +use libc::ICANON; +use libc::ISIG; +use libc::O_NONBLOCK; +use libc::STDIN_FILENO; +use libc::TCSANOW; -use super::{add_fd_flags, clear_fd_flags, errno_result, Result}; +use super::add_fd_flags; +use super::clear_fd_flags; +use super::errno_result; +use super::Result; fn modify_mode(fd: RawFd, f: F) -> Result<()> { // Safe because we check the return value of isatty. diff --git a/base/src/sys/unix/timer.rs b/base/src/sys/unix/timer.rs index 154aa8d0d..fe1d08dd4 100644 --- a/base/src/sys/unix/timer.rs +++ b/base/src/sys/unix/timer.rs @@ -2,23 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - mem, - os::unix::io::{AsRawFd, RawFd}, - ptr, - time::Duration, -}; +use std::mem; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::RawFd; +use std::ptr; +use std::time::Duration; -use libc::{ - clock_getres, timerfd_create, timerfd_settime, CLOCK_MONOTONIC, EAGAIN, POLLIN, TFD_CLOEXEC, - {self}, -}; +use libc::clock_getres; +use libc::timerfd_create; +use libc::timerfd_settime; +use libc::CLOCK_MONOTONIC; +use libc::EAGAIN; +use libc::POLLIN; +use libc::TFD_CLOEXEC; +use libc::{self}; -use super::super::{errno_result, Error, Result}; +use super::super::errno_result; +use super::super::Error; +use super::super::Result; use super::duration_to_timespec; -use crate::descriptor::{AsRawDescriptor, FromRawDescriptor, SafeDescriptor}; - -use crate::timer::{Timer, WaitResult}; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::SafeDescriptor; +use crate::timer::Timer; +use crate::timer::WaitResult; impl AsRawFd for Timer { fn as_raw_fd(&self) -> RawFd { diff --git a/base/src/sys/unix/tube.rs b/base/src/sys/unix/tube.rs index 17d5d02a0..c324df7ba 100644 --- a/base/src/sys/unix/tube.rs +++ b/base/src/sys/unix/tube.rs @@ -2,21 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - io::IoSlice, - marker::PhantomData, - os::unix::prelude::{AsRawFd, RawFd}, - time::Duration, -}; +use std::io::IoSlice; +use std::marker::PhantomData; +use std::os::unix::prelude::AsRawFd; +use std::os::unix::prelude::RawFd; +use std::time::Duration; -use crate::descriptor::{AsRawDescriptor, FromRawDescriptor, SafeDescriptor}; -use crate::{ - platform::{deserialize_with_descriptors, SerializeDescriptors}, - tube::{Error, RecvTube, Result, SendTube}, - RawDescriptor, ReadNotifier, ScmSocket, UnixSeqpacket, UnsyncMarker, -}; +use serde::de::DeserializeOwned; +use serde::Deserialize; +use serde::Serialize; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::SafeDescriptor; +use crate::platform::deserialize_with_descriptors; +use crate::platform::SerializeDescriptors; +use crate::tube::Error; +use crate::tube::RecvTube; +use crate::tube::Result; +use crate::tube::SendTube; +use crate::RawDescriptor; +use crate::ReadNotifier; +use crate::ScmSocket; +use crate::UnixSeqpacket; +use crate::UnsyncMarker; /// Bidirectional tube that support both send and recv. #[derive(Serialize, Deserialize)] diff --git a/base/src/sys/unix/vsock.rs b/base/src/sys/unix/vsock.rs index 692652258..3b6b0aee1 100644 --- a/base/src/sys/unix/vsock.rs +++ b/base/src/sys/unix/vsock.rs @@ -4,24 +4,31 @@ /// Support for virtual sockets. use std::fmt; -use std::{ - io, - mem::{ - size_of, {self}, - }, - num::ParseIntError, - os::{ - raw::{c_uchar, c_uint, c_ushort}, - unix::io::{AsRawFd, IntoRawFd, RawFd}, - }, - result, - str::FromStr, -}; +use std::io; +use std::mem::size_of; +use std::mem::{self}; +use std::num::ParseIntError; +use std::os::raw::c_uchar; +use std::os::raw::c_uint; +use std::os::raw::c_ushort; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::IntoRawFd; +use std::os::unix::io::RawFd; +use std::result; +use std::str::FromStr; -use libc::{ - c_void, sa_family_t, size_t, sockaddr, socklen_t, F_GETFL, F_SETFL, O_NONBLOCK, VMADDR_CID_ANY, - VMADDR_CID_HOST, VMADDR_CID_HYPERVISOR, {self}, -}; +use libc::c_void; +use libc::sa_family_t; +use libc::size_t; +use libc::sockaddr; +use libc::socklen_t; +use libc::F_GETFL; +use libc::F_SETFL; +use libc::O_NONBLOCK; +use libc::VMADDR_CID_ANY; +use libc::VMADDR_CID_HOST; +use libc::VMADDR_CID_HYPERVISOR; +use libc::{self}; use thiserror::Error; // The domain for vsock sockets. diff --git a/base/src/sys/unix/write_zeroes.rs b/base/src/sys/unix/write_zeroes.rs index 660ceec12..4b6120537 100644 --- a/base/src/sys/unix/write_zeroes.rs +++ b/base/src/sys/unix/write_zeroes.rs @@ -2,9 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{cmp::min, fs::File, io, os::unix::fs::FileExt}; +use std::cmp::min; +use std::fs::File; +use std::io; +use std::os::unix::fs::FileExt; -use super::{fallocate, FallocateMode}; +use super::fallocate; +use super::FallocateMode; pub(crate) fn file_punch_hole(file: &File, offset: u64, length: u64) -> io::Result<()> { fallocate(file, FallocateMode::PunchHole, true, offset, length as u64) diff --git a/base/src/sys/windows/console.rs b/base/src/sys/windows/console.rs index 3808631f5..23895b3e7 100644 --- a/base/src/sys/windows/console.rs +++ b/base/src/sys/windows/console.rs @@ -2,14 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::io::{Error, Read, Result}; +use std::io::Error; +use std::io::Read; +use std::io::Result; -use winapi::{ - shared::{minwindef::LPVOID, ntdef::NULL}, - um::{fileapi::ReadFile, minwinbase::LPOVERLAPPED}, -}; +use winapi::shared::minwindef::LPVOID; +use winapi::shared::ntdef::NULL; +use winapi::um::fileapi::ReadFile; +use winapi::um::minwinbase::LPOVERLAPPED; -use crate::{AsRawDescriptor, ReadNotifier}; +use crate::AsRawDescriptor; +use crate::ReadNotifier; pub struct Console(std::io::Stdin); diff --git a/base/src/sys/windows/descriptor.rs b/base/src/sys/windows/descriptor.rs index a582df710..e00fd3818 100644 --- a/base/src/sys/windows/descriptor.rs +++ b/base/src/sys/windows/descriptor.rs @@ -2,32 +2,37 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::Result; -use std::{ - convert::TryFrom, - fs::File, - io::{Stderr, Stdin, Stdout}, - ops::Drop, -}; +use std::convert::TryFrom; +use std::ffi::CString; +use std::fs::File; +use std::io::Stderr; +use std::io::Stdin; +use std::io::Stdout; +use std::marker::Send; +use std::marker::Sync; +use std::mem::MaybeUninit; +use std::ops::Drop; +use std::os::windows::io::AsRawHandle; +use std::os::windows::io::FromRawHandle; +use std::os::windows::io::IntoRawHandle; +use std::os::windows::io::RawHandle; +use std::sync::Once; -use crate::descriptor::{ - AsRawDescriptor, Descriptor, FromRawDescriptor, IntoRawDescriptor, SafeDescriptor, -}; -use std::{ - ffi::CString, - marker::{Send, Sync}, - mem::MaybeUninit, - os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle}, - sync::Once, -}; -use win_util::{duplicate_handle, win32_wide_string}; -use winapi::{ - shared::minwindef::{BOOL, HMODULE, TRUE}, - um::{ - handleapi::{CloseHandle, INVALID_HANDLE_VALUE}, - libloaderapi, - }, -}; +use win_util::duplicate_handle; +use win_util::win32_wide_string; +use winapi::shared::minwindef::BOOL; +use winapi::shared::minwindef::HMODULE; +use winapi::shared::minwindef::TRUE; +use winapi::um::handleapi::CloseHandle; +use winapi::um::handleapi::INVALID_HANDLE_VALUE; +use winapi::um::libloaderapi; + +use super::Result; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::Descriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::IntoRawDescriptor; +use crate::descriptor::SafeDescriptor; pub type RawDescriptor = RawHandle; diff --git a/base/src/sys/windows/event.rs b/base/src/sys/windows/event.rs index 97aa72e6a..8eb88f92c 100644 --- a/base/src/sys/windows/event.rs +++ b/base/src/sys/windows/event.rs @@ -2,34 +2,42 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use serde::{Deserialize, Serialize}; -use std::{ - ffi::CString, - mem::MaybeUninit, - os::windows::io::{AsRawHandle, RawHandle}, - ptr::null, - time::Duration, -}; -use win_util::{SecurityAttributes, SelfRelativeSecurityDescriptor}; -use winapi::{ - shared::{ - minwindef::{DWORD, FALSE, TRUE}, - winerror::WAIT_TIMEOUT, - }, - um::{ - handleapi::DuplicateHandle, - processthreadsapi::GetCurrentProcess, - synchapi::{CreateEventA, OpenEventA, ResetEvent, SetEvent, WaitForSingleObject}, - winbase::WAIT_FAILED, - winnt::{DUPLICATE_SAME_ACCESS, EVENT_MODIFY_STATE, HANDLE}, - }, -}; +use std::ffi::CString; +use std::mem::MaybeUninit; +use std::os::windows::io::AsRawHandle; +use std::os::windows::io::RawHandle; +use std::ptr::null; +use std::time::Duration; -use super::{errno_result, Error, RawDescriptor, Result}; -use crate::{ - descriptor::{AsRawDescriptor, FromRawDescriptor, IntoRawDescriptor, SafeDescriptor}, - Event as CrateEvent, -}; +use serde::Deserialize; +use serde::Serialize; +use win_util::SecurityAttributes; +use win_util::SelfRelativeSecurityDescriptor; +use winapi::shared::minwindef::DWORD; +use winapi::shared::minwindef::FALSE; +use winapi::shared::minwindef::TRUE; +use winapi::shared::winerror::WAIT_TIMEOUT; +use winapi::um::handleapi::DuplicateHandle; +use winapi::um::processthreadsapi::GetCurrentProcess; +use winapi::um::synchapi::CreateEventA; +use winapi::um::synchapi::OpenEventA; +use winapi::um::synchapi::ResetEvent; +use winapi::um::synchapi::SetEvent; +use winapi::um::synchapi::WaitForSingleObject; +use winapi::um::winbase::WAIT_FAILED; +use winapi::um::winnt::DUPLICATE_SAME_ACCESS; +use winapi::um::winnt::EVENT_MODIFY_STATE; +use winapi::um::winnt::HANDLE; + +use super::errno_result; +use super::Error; +use super::RawDescriptor; +use super::Result; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::IntoRawDescriptor; +use crate::descriptor::SafeDescriptor; +use crate::Event as CrateEvent; /// A safe wrapper around Windows synchapi methods used to mimic Linux eventfd (man 2 eventfd). /// Since the eventfd isn't using "EFD_SEMAPHORE", we don't need to keep count so we can just use @@ -250,11 +258,11 @@ unsafe impl Sync for Event {} #[cfg(test)] mod tests { + use winapi::shared::winerror::WAIT_TIMEOUT; + use winapi::um::winbase::INFINITE; + use winapi::um::winbase::WAIT_OBJECT_0; + use super::*; - use winapi::{ - shared::winerror::WAIT_TIMEOUT, - um::winbase::{INFINITE, WAIT_OBJECT_0}, - }; #[test] fn new() { diff --git a/base/src/sys/windows/events.rs b/base/src/sys/windows/events.rs index dce25ad1c..b4753621c 100644 --- a/base/src/sys/windows/events.rs +++ b/base/src/sys/windows/events.rs @@ -35,9 +35,11 @@ impl Clone for EventTrigger { #[cfg(test)] mod tests { - use super::{super::Event, *}; use std::time::Duration; + use super::super::Event; + use super::*; + #[test] fn event_context() { let evt1 = Event::new().unwrap(); diff --git a/base/src/sys/windows/file_traits.rs b/base/src/sys/windows/file_traits.rs index e9b9302d4..80c292d95 100644 --- a/base/src/sys/windows/file_traits.rs +++ b/base/src/sys/windows/file_traits.rs @@ -2,17 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::fs::File; +use std::io::Error; +use std::io::ErrorKind; +use std::io::Result; + +use data_model::VolatileSlice; + pub use super::win::file_traits::*; use super::RawDescriptor; use crate::descriptor::AsRawDescriptor; -use std::{ - fs::File, - io::{Error, ErrorKind, Result}, -}; - -use data_model::VolatileSlice; - /// A trait for flushing the contents of a file to disk. /// This is equivalent to File's `sync_all` method, but /// wrapped in a trait so that it can be implemented for @@ -279,11 +279,14 @@ crate::volatile_at_impl!(File); #[cfg(test)] mod tests { - use super::*; + use std::io::Read; + use std::io::SeekFrom; + use std::io::Write; - use std::io::{Read, SeekFrom, Write}; use tempfile::tempfile; + use super::*; + #[test] fn read_file() -> Result<()> { let mut f = tempfile()?; diff --git a/base/src/sys/windows/get_filesystem_type.rs b/base/src/sys/windows/get_filesystem_type.rs index 0aec7a4fd..b74b2428c 100644 --- a/base/src/sys/windows/get_filesystem_type.rs +++ b/base/src/sys/windows/get_filesystem_type.rs @@ -2,9 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::Result; use std::fs::File; +use super::Result; + pub fn get_filesystem_type(_file: &File) -> Result { // TODO (b/203574110): create a windows equivalent to get the filesystem type like fstatfs Ok(0) diff --git a/base/src/sys/windows/gmtime.rs b/base/src/sys/windows/gmtime.rs index ea32fac6d..b11a799c3 100644 --- a/base/src/sys/windows/gmtime.rs +++ b/base/src/sys/windows/gmtime.rs @@ -2,7 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use libc::{gmtime_s, time_t, tm}; +use libc::gmtime_s; +use libc::time_t; +use libc::tm; /// # Safety /// safe because we are passing in the allocated tm struct @@ -13,9 +15,10 @@ pub unsafe fn gmtime_secure(now: *const time_t, result: *mut tm) { #[cfg(test)] mod tests { - use super::*; use std::mem; + use super::*; + #[test] fn gmtime() { // Safe because struct is not used before being initialized diff --git a/base/src/sys/windows/ioctl.rs b/base/src/sys/windows/ioctl.rs index b7a96aa69..880fc9c85 100644 --- a/base/src/sys/windows/ioctl.rs +++ b/base/src/sys/windows/ioctl.rs @@ -4,16 +4,19 @@ //! Macros and wrapper functions for dealing with ioctls. -use std::{ - mem::size_of, - os::raw::*, - os::raw::{c_int, c_ulong}, - ptr::null_mut, -}; +use std::mem::size_of; +use std::os::raw::c_int; +use std::os::raw::c_ulong; +use std::os::raw::*; +use std::ptr::null_mut; + +use winapi::um::errhandlingapi::GetLastError; +use winapi::um::ioapiset::DeviceIoControl; +pub use winapi::um::winioctl::CTL_CODE; +pub use winapi::um::winioctl::FILE_ANY_ACCESS; +pub use winapi::um::winioctl::METHOD_BUFFERED; use crate::descriptor::AsRawDescriptor; -pub use winapi::um::winioctl::{CTL_CODE, FILE_ANY_ACCESS, METHOD_BUFFERED}; -use winapi::um::{errhandlingapi::GetLastError, ioapiset::DeviceIoControl}; /// Raw macro to declare the expression that calculates an ioctl number #[macro_export] @@ -321,24 +324,27 @@ pub unsafe fn device_io_control( #[cfg(test)] mod tests { - use winapi::um::winioctl::{FSCTL_GET_COMPRESSION, FSCTL_SET_COMPRESSION}; - - use winapi::um::{ - fileapi::{CreateFileW, OPEN_EXISTING}, - winbase::SECURITY_SQOS_PRESENT, - winnt::{ - COMPRESSION_FORMAT_LZNT1, COMPRESSION_FORMAT_NONE, FILE_SHARE_READ, FILE_SHARE_WRITE, - GENERIC_READ, GENERIC_WRITE, - }, - }; - - use std::{fs::OpenOptions, os::raw::*, ptr::null_mut}; - - use std::{ffi::OsStr, fs::File, io::prelude::*, os::windows::ffi::OsStrExt}; - + use std::ffi::OsStr; + use std::fs::File; + use std::fs::OpenOptions; + use std::io::prelude::*; + use std::os::raw::*; + use std::os::windows::ffi::OsStrExt; use std::os::windows::prelude::*; + use std::ptr::null_mut; use tempfile::tempdir; + use winapi::um::fileapi::CreateFileW; + use winapi::um::fileapi::OPEN_EXISTING; + use winapi::um::winbase::SECURITY_SQOS_PRESENT; + use winapi::um::winioctl::FSCTL_GET_COMPRESSION; + use winapi::um::winioctl::FSCTL_SET_COMPRESSION; + use winapi::um::winnt::COMPRESSION_FORMAT_LZNT1; + use winapi::um::winnt::COMPRESSION_FORMAT_NONE; + use winapi::um::winnt::FILE_SHARE_READ; + use winapi::um::winnt::FILE_SHARE_WRITE; + use winapi::um::winnt::GENERIC_READ; + use winapi::um::winnt::GENERIC_WRITE; // helper func, returns str as Vec fn to_u16s>(s: S) -> std::io::Result> { diff --git a/base/src/sys/windows/mmap.rs b/base/src/sys/windows/mmap.rs index fee679b59..9dcfe1ecf 100644 --- a/base/src/sys/windows/mmap.rs +++ b/base/src/sys/windows/mmap.rs @@ -2,21 +2,29 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::io::{self, Read, Write}; +use std::io::Read; +use std::io::Write; +use std::io::{self}; -use libc::{c_int, c_uint, c_void}; +use libc::c_int; +use libc::c_uint; +use libc::c_void; use remain::sorted; use win_util::create_file_mapping; use win_util::duplicate_handle; use winapi::um::winnt::PAGE_READWRITE; -use crate::{ - external_mapping::ExternalMapping, AsRawDescriptor, Descriptor, FromRawDescriptor, - MappedRegion, MemoryMapping as CrateMemoryMapping, MemoryMappingBuilder, Protection, - RawDescriptor, SafeDescriptor, -}; - pub use super::mmap_platform::MemoryMappingArena; +use crate::external_mapping::ExternalMapping; +use crate::AsRawDescriptor; +use crate::Descriptor; +use crate::FromRawDescriptor; +use crate::MappedRegion; +use crate::MemoryMapping as CrateMemoryMapping; +use crate::MemoryMappingBuilder; +use crate::Protection; +use crate::RawDescriptor; +use crate::SafeDescriptor; #[sorted] #[derive(Debug, thiserror::Error)] @@ -307,10 +315,14 @@ impl<'a> MemoryMappingBuilder<'a> { #[cfg(test)] mod tests { - use super::{super::shm::SharedMemory, *}; - use data_model::{VolatileMemory, VolatileMemoryError}; use std::ffi::CString; + use data_model::VolatileMemory; + use data_model::VolatileMemoryError; + + use super::super::shm::SharedMemory; + use super::*; + // get_slice() and other methods are only available on crate::MemoryMapping. fn to_crate_mmap(mapping: MemoryMapping) -> crate::MemoryMapping { crate::MemoryMapping { diff --git a/base/src/sys/windows/mmap_platform.rs b/base/src/sys/windows/mmap_platform.rs index e3cea6dfb..66931df8a 100644 --- a/base/src/sys/windows/mmap_platform.rs +++ b/base/src/sys/windows/mmap_platform.rs @@ -5,20 +5,32 @@ //! The mmap module provides a safe interface to map memory and ensures UnmapViewOfFile is called when the //! mmap object leaves scope. -use std::{ - io, - slice::{from_raw_parts, from_raw_parts_mut}, -}; +use std::io; +use std::slice::from_raw_parts; +use std::slice::from_raw_parts_mut; -use libc::{self, c_int, c_uint, c_void}; +use libc::c_int; +use libc::c_uint; +use libc::c_void; +use libc::{self}; +use win_util::allocation_granularity; +use win_util::get_high_order; +use win_util::get_low_order; +use winapi::um::memoryapi::FlushViewOfFile; +use winapi::um::memoryapi::MapViewOfFile; +use winapi::um::memoryapi::MapViewOfFileEx; +use winapi::um::memoryapi::UnmapViewOfFile; +use winapi::um::memoryapi::FILE_MAP_READ; +use winapi::um::memoryapi::FILE_MAP_WRITE; -use win_util::{allocation_granularity, get_high_order, get_low_order}; -use winapi::um::memoryapi::{ - FlushViewOfFile, MapViewOfFile, MapViewOfFileEx, UnmapViewOfFile, FILE_MAP_READ, FILE_MAP_WRITE, -}; - -use super::mmap::{Error, MemoryMapping, Result}; -use crate::{descriptor::AsRawDescriptor, warn, MappedRegion, Protection, RawDescriptor}; +use super::mmap::Error; +use super::mmap::MemoryMapping; +use super::mmap::Result; +use crate::descriptor::AsRawDescriptor; +use crate::warn; +use crate::MappedRegion; +use crate::Protection; +use crate::RawDescriptor; pub(crate) const PROT_READ: c_int = FILE_MAP_READ as c_int; pub(crate) const PROT_WRITE: c_int = FILE_MAP_WRITE as c_int; @@ -296,15 +308,18 @@ pub struct MemoryMappingArena(); #[cfg(test)] mod tests { - use super::{ - super::{pagesize, SharedMemory}, - Error, - }; - use crate::descriptor::FromRawDescriptor; - use crate::{MappedRegion, MemoryMappingBuilder}; - use std::{ffi::CString, ptr}; + use std::ffi::CString; + use std::ptr; + use winapi::shared::winerror; + use super::super::pagesize; + use super::super::SharedMemory; + use super::Error; + use crate::descriptor::FromRawDescriptor; + use crate::MappedRegion; + use crate::MemoryMappingBuilder; + #[test] fn map_invalid_fd() { let descriptor = unsafe { std::fs::File::from_raw_descriptor(ptr::null_mut()) }; diff --git a/base/src/sys/windows/mod.rs b/base/src/sys/windows/mod.rs index 4f7250e31..9d9dbaa99 100644 --- a/base/src/sys/windows/mod.rs +++ b/base/src/sys/windows/mod.rs @@ -39,37 +39,44 @@ pub mod thread; mod write_zeroes; -pub use crate::descriptor_reflection::{ - deserialize_with_descriptors, with_as_descriptor, with_raw_descriptor, FileSerdeWrapper, - SerializeDescriptors, -}; -pub use crate::errno::{Error, Result, *}; +use std::cell::Cell; + pub use console::*; pub use descriptor::*; pub use event::*; pub use events::*; +pub use file_traits::AsRawDescriptors; +pub use file_traits::FileAllocate; +pub use file_traits::FileGetLen; +pub use file_traits::FileReadWriteAtVolatile; +pub use file_traits::FileReadWriteVolatile; +pub use file_traits::FileSetLen; +pub use file_traits::FileSync; pub use get_filesystem_type::*; pub use gmtime::*; pub use ioctl::*; +pub use mmap::Error as MmapError; pub use mmap::*; +pub(crate) use mmap_platform::PROT_READ; +pub(crate) use mmap_platform::PROT_WRITE; pub use priority::*; +pub(crate) use punch_hole::file_punch_hole; pub use sched::*; pub use shm::*; pub use shm_platform::*; pub use stream_channel::*; pub use timer::*; pub use win::*; - -pub use file_traits::{ - AsRawDescriptors, FileAllocate, FileGetLen, FileReadWriteAtVolatile, FileReadWriteVolatile, - FileSetLen, FileSync, -}; -pub use mmap::Error as MmapError; -pub(crate) use mmap_platform::{PROT_READ, PROT_WRITE}; -pub(crate) use punch_hole::file_punch_hole; pub(crate) use write_zeroes::file_write_zeroes_at; -use std::cell::Cell; +pub use crate::descriptor_reflection::deserialize_with_descriptors; +pub use crate::descriptor_reflection::with_as_descriptor; +pub use crate::descriptor_reflection::with_raw_descriptor; +pub use crate::descriptor_reflection::FileSerdeWrapper; +pub use crate::descriptor_reflection::SerializeDescriptors; +pub use crate::errno::Error; +pub use crate::errno::Result; +pub use crate::errno::*; // Define libc::* types #[allow(non_camel_case_types)] diff --git a/base/src/sys/windows/named_pipes.rs b/base/src/sys/windows/named_pipes.rs index ad4370201..883bdceda 100644 --- a/base/src/sys/windows/named_pipes.rs +++ b/base/src/sys/windows/named_pipes.rs @@ -2,44 +2,62 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use rand::Rng; -use std::{ - ffi::CString, - fs::OpenOptions, - io, - io::Result, - mem, - os::windows::fs::OpenOptionsExt, - process, ptr, - sync::atomic::{AtomicUsize, Ordering}, -}; +use std::ffi::CString; +use std::fs::OpenOptions; +use std::io; +use std::io::Result; +use std::mem; +use std::os::windows::fs::OpenOptionsExt; +use std::process; +use std::ptr; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; -use super::{Event, RawDescriptor}; -use crate::descriptor::{AsRawDescriptor, FromRawDescriptor, IntoRawDescriptor, SafeDescriptor}; -use serde::{Deserialize, Serialize}; -use win_util::{SecurityAttributes, SelfRelativeSecurityDescriptor}; -use winapi::{ - shared::{ - minwindef::{DWORD, FALSE, LPCVOID, LPVOID, TRUE}, - winerror::{ERROR_IO_INCOMPLETE, ERROR_IO_PENDING, ERROR_NO_DATA, ERROR_PIPE_CONNECTED}, - }, - um::{ - errhandlingapi::GetLastError, - fileapi::{FlushFileBuffers, ReadFile, WriteFile}, - handleapi::INVALID_HANDLE_VALUE, - ioapiset::{CancelIoEx, GetOverlappedResult}, - minwinbase::OVERLAPPED, - namedpipeapi::{ - ConnectNamedPipe, GetNamedPipeInfo, PeekNamedPipe, SetNamedPipeHandleState, - }, - winbase::{ - CreateNamedPipeA, FILE_FLAG_FIRST_PIPE_INSTANCE, FILE_FLAG_OVERLAPPED, - PIPE_ACCESS_DUPLEX, PIPE_NOWAIT, PIPE_READMODE_BYTE, PIPE_READMODE_MESSAGE, - PIPE_REJECT_REMOTE_CLIENTS, PIPE_TYPE_BYTE, PIPE_TYPE_MESSAGE, PIPE_WAIT, - SECURITY_IDENTIFICATION, - }, - }, -}; +use rand::Rng; +use serde::Deserialize; +use serde::Serialize; +use win_util::SecurityAttributes; +use win_util::SelfRelativeSecurityDescriptor; +use winapi::shared::minwindef::DWORD; +use winapi::shared::minwindef::FALSE; +use winapi::shared::minwindef::LPCVOID; +use winapi::shared::minwindef::LPVOID; +use winapi::shared::minwindef::TRUE; +use winapi::shared::winerror::ERROR_IO_INCOMPLETE; +use winapi::shared::winerror::ERROR_IO_PENDING; +use winapi::shared::winerror::ERROR_NO_DATA; +use winapi::shared::winerror::ERROR_PIPE_CONNECTED; +use winapi::um::errhandlingapi::GetLastError; +use winapi::um::fileapi::FlushFileBuffers; +use winapi::um::fileapi::ReadFile; +use winapi::um::fileapi::WriteFile; +use winapi::um::handleapi::INVALID_HANDLE_VALUE; +use winapi::um::ioapiset::CancelIoEx; +use winapi::um::ioapiset::GetOverlappedResult; +use winapi::um::minwinbase::OVERLAPPED; +use winapi::um::namedpipeapi::ConnectNamedPipe; +use winapi::um::namedpipeapi::GetNamedPipeInfo; +use winapi::um::namedpipeapi::PeekNamedPipe; +use winapi::um::namedpipeapi::SetNamedPipeHandleState; +use winapi::um::winbase::CreateNamedPipeA; +use winapi::um::winbase::FILE_FLAG_FIRST_PIPE_INSTANCE; +use winapi::um::winbase::FILE_FLAG_OVERLAPPED; +use winapi::um::winbase::PIPE_ACCESS_DUPLEX; +use winapi::um::winbase::PIPE_NOWAIT; +use winapi::um::winbase::PIPE_READMODE_BYTE; +use winapi::um::winbase::PIPE_READMODE_MESSAGE; +use winapi::um::winbase::PIPE_REJECT_REMOTE_CLIENTS; +use winapi::um::winbase::PIPE_TYPE_BYTE; +use winapi::um::winbase::PIPE_TYPE_MESSAGE; +use winapi::um::winbase::PIPE_WAIT; +use winapi::um::winbase::SECURITY_IDENTIFICATION; + +use super::Event; +use super::RawDescriptor; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::IntoRawDescriptor; +use crate::descriptor::SafeDescriptor; /// The default buffer size for all named pipes in the system. If this size is too small, writers /// on named pipes that expect not to block *can* block until the reading side empties the buffer. diff --git a/base/src/sys/windows/platform_timer_resolution.rs b/base/src/sys/windows/platform_timer_resolution.rs index c81e9e4cd..a10968b12 100644 --- a/base/src/sys/windows/platform_timer_resolution.rs +++ b/base/src/sys/windows/platform_timer_resolution.rs @@ -2,12 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{ - info, measure_timer_resolution, nt_query_timer_resolution, nt_set_timer_resolution, - set_time_period, warn, EnabledHighResTimer, Result, -}; use std::time::Duration; +use crate::info; +use crate::measure_timer_resolution; +use crate::nt_query_timer_resolution; +use crate::nt_set_timer_resolution; +use crate::set_time_period; +use crate::warn; +use crate::EnabledHighResTimer; +use crate::Result; + /// Restores the Windows platform timer resolution to its original value on Drop. struct NtSetTimerResolution { previous_duration: Duration, diff --git a/base/src/sys/windows/priority.rs b/base/src/sys/windows/priority.rs index fcdaa3f89..043c7883b 100644 --- a/base/src/sys/windows/priority.rs +++ b/base/src/sys/windows/priority.rs @@ -2,17 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::{errno_result, Result}; -use log::warn; use std::os::windows::raw::HANDLE; -use winapi::{ - shared::minwindef::FALSE, - um::{ - avrt::{AvRevertMmThreadCharacteristics, AvSetMmThreadCharacteristicsA}, - errhandlingapi::GetLastError, - processthreadsapi::{GetCurrentThread, SetThreadPriority}, - }, -}; + +use log::warn; +use winapi::shared::minwindef::FALSE; +use winapi::um::avrt::AvRevertMmThreadCharacteristics; +use winapi::um::avrt::AvSetMmThreadCharacteristicsA; +use winapi::um::errhandlingapi::GetLastError; +use winapi::um::processthreadsapi::GetCurrentThread; +use winapi::um::processthreadsapi::SetThreadPriority; + +use super::errno_result; +use super::Result; pub fn set_audio_thread_priorities() -> Result { // Safe because we know Pro Audio is part of windows and we down task_index. @@ -65,11 +66,12 @@ impl Drop for SafeMultimediaHandle { #[cfg(test)] mod test { + use winapi::um::processthreadsapi::GetCurrentThread; + use winapi::um::processthreadsapi::GetThreadPriority; + use winapi::um::winbase::THREAD_PRIORITY_NORMAL; + use winapi::um::winbase::THREAD_PRIORITY_TIME_CRITICAL; + use super::*; - use winapi::um::{ - processthreadsapi::{GetCurrentThread, GetThreadPriority}, - winbase::{THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_TIME_CRITICAL}, - }; // TODO(b/223733375): Enable ignored flaky tests. #[test] diff --git a/base/src/sys/windows/punch_hole.rs b/base/src/sys/windows/punch_hole.rs index 4750e27ce..56ebdfb95 100644 --- a/base/src/sys/windows/punch_hole.rs +++ b/base/src/sys/windows/punch_hole.rs @@ -3,7 +3,8 @@ // found in the LICENSE file. use std::fs::File; -use std::io::{self, Error}; +use std::io::Error; +use std::io::{self}; use win_util::LargeInteger; pub use winapi::um::winioctl::FSCTL_SET_ZERO_DATA; diff --git a/base/src/sys/windows/sched.rs b/base/src/sys/windows/sched.rs index be4282db4..b86681384 100644 --- a/base/src/sys/windows/sched.rs +++ b/base/src/sys/windows/sched.rs @@ -3,9 +3,12 @@ // found in the LICENSE file. use libc::EINVAL; -use winapi::um::{processthreadsapi::GetCurrentThread, winbase::SetThreadAffinityMask}; +use winapi::um::processthreadsapi::GetCurrentThread; +use winapi::um::winbase::SetThreadAffinityMask; -use super::{errno_result, Error, Result}; +use super::errno_result; +use super::Error; +use super::Result; /// Set the CPU affinity of the current thread to a given set of CPUs. /// The cpus must be a subset of those in the process affinity mask. @@ -49,8 +52,10 @@ pub fn get_cpu_affinity() -> Result> { #[cfg(test)] mod tests { + use winapi::um::processthreadsapi::GetCurrentProcess; + use winapi::um::winbase::GetProcessAffinityMask; + use super::super::sched::*; - use winapi::um::{processthreadsapi::GetCurrentProcess, winbase::GetProcessAffinityMask}; #[test] fn cpu_affinity() { let mut process_affinity_mask: usize = 0; diff --git a/base/src/sys/windows/shm.rs b/base/src/sys/windows/shm.rs index d81f742d0..3a2d68ca6 100644 --- a/base/src/sys/windows/shm.rs +++ b/base/src/sys/windows/shm.rs @@ -2,13 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::{RawDescriptor, Result}; -use crate::descriptor::{AsRawDescriptor, IntoRawDescriptor, SafeDescriptor}; +use std::io::Error; +use std::io::ErrorKind; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::Write; +use std::io::{self}; + +use serde::ser; +use serde::Deserialize; +use serde::Serialize; +use serde::Serializer; + +use super::RawDescriptor; +use super::Result; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::IntoRawDescriptor; +use crate::descriptor::SafeDescriptor; use crate::MemoryMapping; -use serde::{ser, Deserialize, Serialize, Serializer}; -use std::io::{ - Error, ErrorKind, Read, Seek, SeekFrom, Write, {self}, -}; /// A shared memory file descriptor and its size. #[derive(Debug, Deserialize)] @@ -155,9 +167,10 @@ impl Seek for SharedMemory { #[cfg(test)] mod tests { - use super::*; use std::ffi::CString; + use super::*; + #[test] fn new() { let shm = SharedMemory::new(&CString::new("name").unwrap(), 1028) diff --git a/base/src/sys/windows/shm_platform.rs b/base/src/sys/windows/shm_platform.rs index 125873349..714832e8c 100644 --- a/base/src/sys/windows/shm_platform.rs +++ b/base/src/sys/windows/shm_platform.rs @@ -3,12 +3,18 @@ // found in the LICENSE file. use std::ffi::CStr; + use win_util::create_file_mapping; use winapi::um::winnt::PAGE_EXECUTE_READWRITE; -use super::{shm::SharedMemory, MemoryMapping, Result}; -use crate::descriptor::{AsRawDescriptor, FromRawDescriptor, SafeDescriptor}; -use crate::{MemoryMapping as CrateMemoryMapping, MmapError}; +use super::shm::SharedMemory; +use super::MemoryMapping; +use super::Result; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::SafeDescriptor; +use crate::MemoryMapping as CrateMemoryMapping; +use crate::MmapError; impl SharedMemory { /// Creates a new shared memory file mapping with zero size. @@ -56,10 +62,12 @@ impl SharedMemory { #[cfg(test)] mod test { - use super::*; use std::ffi::CString; + use winapi::shared::winerror::ERROR_NOT_ENOUGH_MEMORY; + use super::*; + #[cfg_attr(all(target_os = "windows", target_env = "gnu"), ignore)] #[test] fn new_too_huge() { diff --git a/base/src/sys/windows/stream_channel.rs b/base/src/sys/windows/stream_channel.rs index f31af9d41..e57f3936c 100644 --- a/base/src/sys/windows/stream_channel.rs +++ b/base/src/sys/windows/stream_channel.rs @@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::io; + pub use super::stream_channel_platform::*; use super::RawDescriptor; use crate::descriptor::AsRawDescriptor; -use std::io; #[derive(Copy, Clone)] pub enum FramingMode { @@ -39,13 +40,14 @@ impl AsRawDescriptor for StreamChannel { #[cfg(test)] mod test { - use super::{ - super::{EventContext, EventTrigger}, - *, - }; + use std::io::Read; + use std::io::Write; - use crate::{EventToken, ReadNotifier}; - use std::io::{Read, Write}; + use super::super::EventContext; + use super::super::EventTrigger; + use super::*; + use crate::EventToken; + use crate::ReadNotifier; #[derive(EventToken, Debug, Eq, PartialEq, Copy, Clone)] enum Token { diff --git a/base/src/sys/windows/stream_channel_platform.rs b/base/src/sys/windows/stream_channel_platform.rs index 5193d7742..6b95ed311 100644 --- a/base/src/sys/windows/stream_channel_platform.rs +++ b/base/src/sys/windows/stream_channel_platform.rs @@ -2,18 +2,29 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{cell::RefCell, io, sync::Arc}; +use std::cell::RefCell; +use std::io; +use std::sync::Arc; -use log::{error, warn}; -use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer}; +use log::error; +use log::warn; +use serde::ser::SerializeStruct; +use serde::Deserialize; +use serde::Serialize; +use serde::Serializer; use sync::Mutex; -use super::{ - named_pipes::{self, PipeConnection}, - stream_channel::{BlockingMode, FramingMode}, - Event, MultiProcessMutex, RawDescriptor, Result, -}; -use crate::{descriptor::AsRawDescriptor, CloseNotifier, ReadNotifier}; +use super::named_pipes::PipeConnection; +use super::named_pipes::{self}; +use super::stream_channel::BlockingMode; +use super::stream_channel::FramingMode; +use super::Event; +use super::MultiProcessMutex; +use super::RawDescriptor; +use super::Result; +use crate::descriptor::AsRawDescriptor; +use crate::CloseNotifier; +use crate::ReadNotifier; impl From for named_pipes::FramingMode { fn from(framing_mode: FramingMode) -> Self { @@ -396,15 +407,15 @@ impl CloseNotifier for StreamChannel { #[cfg(test)] mod test { - use super::{ - super::{EventContext, EventTrigger}, - *, - }; - use crate::{EventToken, ReadNotifier}; - use std::{ - io::{Read, Write}, - time::Duration, - }; + use std::io::Read; + use std::io::Write; + use std::time::Duration; + + use super::super::EventContext; + use super::super::EventTrigger; + use super::*; + use crate::EventToken; + use crate::ReadNotifier; #[derive(EventToken, Debug, Eq, PartialEq, Copy, Clone)] enum Token { diff --git a/base/src/sys/windows/thread.rs b/base/src/sys/windows/thread.rs index 71e9c5a72..1d9fdf48a 100644 --- a/base/src/sys/windows/thread.rs +++ b/base/src/sys/windows/thread.rs @@ -2,15 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - any::Any, - panic, - panic::UnwindSafe, - sync::mpsc::{channel, Receiver}, - thread, - thread::JoinHandle, - time::Duration, -}; +use std::any::Any; +use std::panic; +use std::panic::UnwindSafe; +use std::sync::mpsc::channel; +use std::sync::mpsc::Receiver; +use std::thread; +use std::thread::JoinHandle; +use std::time::Duration; /// Spawns a thread that can be joined with a timeout. pub fn spawn_with_timeout(f: F) -> JoinHandleWithTimeout diff --git a/base/src/sys/windows/timer.rs b/base/src/sys/windows/timer.rs index 390033e78..729d9f0ec 100644 --- a/base/src/sys/windows/timer.rs +++ b/base/src/sys/windows/timer.rs @@ -2,26 +2,31 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - os::windows::io::{AsRawHandle, RawHandle}, - ptr, - time::Duration, -}; +use std::os::windows::io::AsRawHandle; +use std::os::windows::io::RawHandle; +use std::ptr; +use std::time::Duration; -use win_util::{LargeInteger, SecurityAttributes, SelfRelativeSecurityDescriptor}; -use winapi::{ - shared::{minwindef::FALSE, winerror::WAIT_TIMEOUT}, - um::{ - synchapi::{CancelWaitableTimer, SetWaitableTimer, WaitForSingleObject}, - winbase::{CreateWaitableTimerA, INFINITE, WAIT_OBJECT_0}, - }, -}; +use win_util::LargeInteger; +use win_util::SecurityAttributes; +use win_util::SelfRelativeSecurityDescriptor; +use winapi::shared::minwindef::FALSE; +use winapi::shared::winerror::WAIT_TIMEOUT; +use winapi::um::synchapi::CancelWaitableTimer; +use winapi::um::synchapi::SetWaitableTimer; +use winapi::um::synchapi::WaitForSingleObject; +use winapi::um::winbase::CreateWaitableTimerA; +use winapi::um::winbase::INFINITE; +use winapi::um::winbase::WAIT_OBJECT_0; -use super::{errno_result, win::nt_query_timer_resolution, Result}; -use crate::{ - descriptor::{AsRawDescriptor, FromRawDescriptor, SafeDescriptor}, - timer::{Timer, WaitResult}, -}; +use super::errno_result; +use super::win::nt_query_timer_resolution; +use super::Result; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::SafeDescriptor; +use crate::timer::Timer; +use crate::timer::WaitResult; impl AsRawHandle for Timer { fn as_raw_handle(&self) -> RawHandle { diff --git a/base/src/sys/windows/tube.rs b/base/src/sys/windows/tube.rs index ed622cc92..d3ddd5931 100644 --- a/base/src/sys/windows/tube.rs +++ b/base/src/sys/windows/tube.rs @@ -2,28 +2,40 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - io::{ - Cursor, Read, Write, {self}, - }, - time::Duration, -}; +use std::io::Cursor; +use std::io::Read; +use std::io::Write; +use std::io::{self}; +use std::mem; +use std::os::windows::io::AsRawHandle; +use std::os::windows::io::RawHandle; +use std::time::Duration; -use crate::descriptor::{AsRawDescriptor, FromRawDescriptor, SafeDescriptor}; -use crate::{ - platform::{deserialize_with_descriptors, RawDescriptor, SerializeDescriptors}, - tube::{Error, RecvTube, Result, SendTube}, - BlockingMode, CloseNotifier, EventToken, FramingMode, ReadNotifier, StreamChannel, -}; use data_model::DataInit; use once_cell::sync::Lazy; -use serde::{de::DeserializeOwned, Deserialize, Serialize, Serializer}; -use std::{ - mem, - os::windows::io::{AsRawHandle, RawHandle}, -}; +use serde::de::DeserializeOwned; +use serde::Deserialize; +use serde::Serialize; +use serde::Serializer; use winapi::shared::winerror::ERROR_MORE_DATA; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::SafeDescriptor; +use crate::platform::deserialize_with_descriptors; +use crate::platform::RawDescriptor; +use crate::platform::SerializeDescriptors; +use crate::tube::Error; +use crate::tube::RecvTube; +use crate::tube::Result; +use crate::tube::SendTube; +use crate::BlockingMode; +use crate::CloseNotifier; +use crate::EventToken; +use crate::FramingMode; +use crate::ReadNotifier; +use crate::StreamChannel; + /// Bidirectional tube that support both send and recv. /// /// NOTE: serializing this type across processes is slightly involved. Suppose there is a Tube pair @@ -402,10 +414,14 @@ impl DuplicateHandleTube { #[cfg(test)] mod tests { - use super::*; - use crate::{EventContext, EventToken, EventTrigger, ReadNotifier}; use std::time; + use super::*; + use crate::EventContext; + use crate::EventToken; + use crate::EventTrigger; + use crate::ReadNotifier; + const EVENT_WAIT_TIME: time::Duration = time::Duration::from_secs(10); #[derive(EventToken, Debug, Eq, PartialEq, Copy, Clone)] diff --git a/base/src/sys/windows/wait.rs b/base/src/sys/windows/wait.rs index 7d3eb70b0..00163df57 100644 --- a/base/src/sys/windows/wait.rs +++ b/base/src/sys/windows/wait.rs @@ -2,21 +2,34 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{cmp::min, collections::HashMap, os::windows::io::RawHandle, sync::Arc, time::Duration}; +use std::cmp::min; +use std::collections::HashMap; +use std::os::windows::io::RawHandle; +use std::sync::Arc; +use std::time::Duration; use smallvec::SmallVec; use sync::Mutex; -use winapi::{ - shared::{ - minwindef::{DWORD, FALSE}, - winerror::{ERROR_INVALID_PARAMETER, WAIT_TIMEOUT}, - }, - um::{synchapi::WaitForMultipleObjects, winbase::WAIT_OBJECT_0}, -}; +use winapi::shared::minwindef::DWORD; +use winapi::shared::minwindef::FALSE; +use winapi::shared::winerror::ERROR_INVALID_PARAMETER; +use winapi::shared::winerror::WAIT_TIMEOUT; +use winapi::um::synchapi::WaitForMultipleObjects; +use winapi::um::winbase::WAIT_OBJECT_0; -use super::{errno_result, Error, Event, EventTrigger, Result}; -use crate::descriptor::{AsRawDescriptor, Descriptor}; -use crate::{error, EventToken, EventType, RawDescriptor, TriggeredEvent, WaitContext}; +use super::errno_result; +use super::Error; +use super::Event; +use super::EventTrigger; +use super::Result; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::Descriptor; +use crate::error; +use crate::EventToken; +use crate::EventType; +use crate::RawDescriptor; +use crate::TriggeredEvent; +use crate::WaitContext; // MAXIMUM_WAIT_OBJECTS = 64 pub const MAXIMUM_WAIT_OBJECTS: usize = winapi::um::winnt::MAXIMUM_WAIT_OBJECTS as usize; diff --git a/base/src/sys/windows/win/file_traits.rs b/base/src/sys/windows/win/file_traits.rs index fdb6cad79..9b195fa64 100644 --- a/base/src/sys/windows/win/file_traits.rs +++ b/base/src/sys/windows/win/file_traits.rs @@ -2,8 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{FileAllocate, WriteZeroesAt}; -use std::{fs::File, io}; +use std::fs::File; +use std::io; + +use crate::FileAllocate; +use crate::WriteZeroesAt; #[macro_export] macro_rules! volatile_impl { @@ -11,11 +14,12 @@ macro_rules! volatile_impl { // Unused imports are "unneeded" because the only usage of this macro already has those // names in scope. #[allow(unused_imports)] - use crate::AsRawDescriptor as _; - #[allow(unused_imports)] use std::convert::TryInto as _; #[allow(unused_imports)] use std::io::Seek as _; + + #[allow(unused_imports)] + use crate::AsRawDescriptor as _; impl FileReadWriteVolatile for $ty { fn read_volatile(&mut self, slice: VolatileSlice) -> Result { // Safe because only bytes inside the slice are accessed and the kernel is expected diff --git a/base/src/sys/windows/win/file_util.rs b/base/src/sys/windows/win/file_util.rs index eed42bb24..905e9a52b 100644 --- a/base/src/sys/windows/win/file_util.rs +++ b/base/src/sys/windows/win/file_util.rs @@ -2,10 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::descriptor::AsRawDescriptor; -use std::{ffi::c_void, io}; +use std::ffi::c_void; +use std::io; + pub use winapi::um::winioctl::FSCTL_SET_SPARSE; +use crate::descriptor::AsRawDescriptor; + /// Marks the given file as sparse. Required if we want hole punching to be performant. /// (If a file is not marked as sparse, a hole punch will just write zeros.) /// # Safety diff --git a/base/src/sys/windows/win/mod.rs b/base/src/sys/windows/win/mod.rs index 77c9577f8..49d72281e 100644 --- a/base/src/sys/windows/win/mod.rs +++ b/base/src/sys/windows/win/mod.rs @@ -12,26 +12,33 @@ mod platform_timer_utils; pub use platform_timer_utils::*; mod file_util; -pub use file_util::*; +use std::fs::File; +use std::fs::OpenOptions; +use std::path::Path; +use std::ptr::null_mut; -use super::{errno_result, pid_t, Error, Result}; -use crate::descriptor::{AsRawDescriptor, FromRawDescriptor, SafeDescriptor}; -use serde::{Deserialize, Serialize}; -use std::{ - fs::{File, OpenOptions}, - path::Path, - ptr::null_mut, -}; -use winapi::{ - shared::{minwindef::DWORD, winerror::WAIT_TIMEOUT}, - um::{ - handleapi::INVALID_HANDLE_VALUE, - processthreadsapi::GetCurrentProcessId, - synchapi::{CreateMutexA, ReleaseMutex, WaitForSingleObject}, - winbase::{INFINITE, WAIT_ABANDONED, WAIT_OBJECT_0}, - winuser::AllowSetForegroundWindow, - }, -}; +pub use file_util::*; +use serde::Deserialize; +use serde::Serialize; +use winapi::shared::minwindef::DWORD; +use winapi::shared::winerror::WAIT_TIMEOUT; +use winapi::um::handleapi::INVALID_HANDLE_VALUE; +use winapi::um::processthreadsapi::GetCurrentProcessId; +use winapi::um::synchapi::CreateMutexA; +use winapi::um::synchapi::ReleaseMutex; +use winapi::um::synchapi::WaitForSingleObject; +use winapi::um::winbase::INFINITE; +use winapi::um::winbase::WAIT_ABANDONED; +use winapi::um::winbase::WAIT_OBJECT_0; +use winapi::um::winuser::AllowSetForegroundWindow; + +use super::errno_result; +use super::pid_t; +use super::Error; +use super::Result; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::SafeDescriptor; #[inline(always)] pub fn pagesize() -> usize { diff --git a/base/src/sys/windows/win/platform_timer_utils.rs b/base/src/sys/windows/win/platform_timer_utils.rs index 1fd558980..cccd92408 100644 --- a/base/src/sys/windows/win/platform_timer_utils.rs +++ b/base/src/sys/windows/win/platform_timer_utils.rs @@ -2,33 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - io, - mem::MaybeUninit, - sync::Once, - time::{Duration, Instant}, -}; - -use winapi::shared::minwindef::{ - HINSTANCE, HMODULE, PULONG, {self}, -}; - -use winapi::{ - shared::{ - ntdef::{NTSTATUS, ULONG}, - ntstatus::STATUS_SUCCESS, - }, - um::{libloaderapi, mmsystem::TIMERR_NOERROR}, -}; - +use std::io; +use std::mem::MaybeUninit; +use std::sync::Once; use std::thread::sleep; -use win_util::{win32_string, win32_wide_string}; -use winapi::um::{ - timeapi::{timeBeginPeriod, timeEndPeriod}, - winnt::BOOLEAN, -}; +use std::time::Duration; +use std::time::Instant; -use super::super::{Error, Result}; +use win_util::win32_string; +use win_util::win32_wide_string; +use winapi::shared::minwindef::HINSTANCE; +use winapi::shared::minwindef::HMODULE; +use winapi::shared::minwindef::PULONG; +use winapi::shared::minwindef::{self}; +use winapi::shared::ntdef::NTSTATUS; +use winapi::shared::ntdef::ULONG; +use winapi::shared::ntstatus::STATUS_SUCCESS; +use winapi::um::libloaderapi; +use winapi::um::mmsystem::TIMERR_NOERROR; +use winapi::um::timeapi::timeBeginPeriod; +use winapi::um::timeapi::timeEndPeriod; +use winapi::um::winnt::BOOLEAN; + +use super::super::Error; +use super::super::Result; use crate::warn; static NT_INIT: Once = Once::new(); diff --git a/base/src/sys/windows/win/syslog.rs b/base/src/sys/windows/win/syslog.rs index f0dc79386..2dd5a2d6f 100644 --- a/base/src/sys/windows/win/syslog.rs +++ b/base/src/sys/windows/win/syslog.rs @@ -4,7 +4,10 @@ //! Implementation of the Syslog trait as a wrapper around Window's events -use crate::syslog::{Error, Facility, Log, Syslog}; +use crate::syslog::Error; +use crate::syslog::Facility; +use crate::syslog::Log; +use crate::syslog::Syslog; use crate::RawDescriptor; pub struct PlatformSyslog {} diff --git a/base/src/sys/windows/write_zeroes.rs b/base/src/sys/windows/write_zeroes.rs index 3f32d728d..797968825 100644 --- a/base/src/sys/windows/write_zeroes.rs +++ b/base/src/sys/windows/write_zeroes.rs @@ -2,8 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::cmp::min; +use std::fs::File; +use std::io; +use std::os::windows::fs::FileExt; + use crate::PunchHole; -use std::{cmp::min, fs::File, io, os::windows::fs::FileExt}; // TODO(b/195151495): Fix so that this will extend a file size if needed. pub(crate) fn file_write_zeroes_at( diff --git a/base/src/syslog.rs b/base/src/syslog.rs index cbdd36cf7..73eecf92b 100644 --- a/base/src/syslog.rs +++ b/base/src/syslog.rs @@ -49,21 +49,23 @@ //! //! [log-crate-url]: https://docs.rs/log/ -use std::{fmt::Display, io, io::Write}; +use std::fmt::Display; +use std::io; +use std::io::Write; use chrono::Local; +// Reexports +pub use env_logger::{self, fmt}; +pub use log::*; use once_cell::sync::OnceCell; use remain::sorted; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; use thiserror::Error as ThisError; use crate::platform::syslog::PlatformSyslog; use crate::platform::RawDescriptor; -// Reexports -pub use env_logger::{self, fmt}; -pub use log::*; - /// The priority (i.e. severity) of a syslog message. /// /// See syslog man pages for information on their semantics. @@ -468,16 +470,18 @@ impl io::Write for Syslogger { #[cfg(test)] mod tests { #![allow(clippy::field_reassign_with_default)] - use super::*; use std::io::Write; + use super::*; + impl Default for State { fn default() -> Self { Self::new(Default::default()).unwrap() } } - use std::sync::{Arc, Mutex}; + use std::sync::Arc; + use std::sync::Mutex; #[derive(Clone)] struct MockWrite { buffer: Arc>>, diff --git a/base/src/timer.rs b/base/src/timer.rs index ceef45931..7160e8ccc 100644 --- a/base/src/timer.rs +++ b/base/src/timer.rs @@ -2,14 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - sync::Arc, - time::{Duration, Instant}, -}; +use std::sync::Arc; +use std::time::Duration; +use std::time::Instant; + use sync::Mutex; -use super::{Event, EventReadResult, FakeClock, RawDescriptor, Result}; -use crate::descriptor::{AsRawDescriptor, FromRawDescriptor, IntoRawDescriptor, SafeDescriptor}; +use super::Event; +use super::EventReadResult; +use super::FakeClock; +use super::RawDescriptor; +use super::Result; +use crate::descriptor::AsRawDescriptor; +use crate::descriptor::FromRawDescriptor; +use crate::descriptor::IntoRawDescriptor; +use crate::descriptor::SafeDescriptor; pub struct Timer { pub(crate) handle: SafeDescriptor, @@ -182,8 +189,10 @@ impl IntoRawDescriptor for FakeTimer { #[cfg(test)] mod tests { + use std::time::Duration; + use std::time::Instant; + use super::*; - use std::time::{Duration, Instant}; // clock error is 2*clock_resolution + 100 microseconds to handle // time change from calling now() to arming timer diff --git a/base/src/tube.rs b/base/src/tube.rs index 3a7f20fec..7c6be5409 100644 --- a/base/src/tube.rs +++ b/base/src/tube.rs @@ -2,16 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use remain::sorted; use std::io; +use remain::sorted; use thiserror::Error as ThisError; #[cfg_attr(windows, path = "sys/windows/tube.rs")] #[cfg_attr(not(windows), path = "sys/unix/tube.rs")] mod tube; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; use std::time::Duration; + +use serde::de::DeserializeOwned; +use serde::Deserialize; +use serde::Serialize; pub use tube::*; impl Tube { @@ -122,17 +125,18 @@ pub type Result = std::result::Result; #[cfg(test)] mod tests { + use std::collections::HashMap; + use std::sync::Arc; + use std::sync::Barrier; + use std::thread; + use std::time::Duration; + + use serde::Deserialize; + use serde::Serialize; + use super::*; use crate::Event; - use std::{collections::HashMap, time::Duration}; - - use serde::{Deserialize, Serialize}; - use std::{ - sync::{Arc, Barrier}, - thread, - }; - #[derive(Serialize, Deserialize)] struct DataStruct { x: u32, diff --git a/base/src/wait_context.rs b/base/src/wait_context.rs index b4540f565..80b419e0f 100644 --- a/base/src/wait_context.rs +++ b/base/src/wait_context.rs @@ -4,11 +4,13 @@ use std::time::Duration; -use crate::descriptor::AsRawDescriptor; -use crate::{platform::EventContext, RawDescriptor, Result}; +pub use base_event_token_derive::*; use smallvec::SmallVec; -pub use base_event_token_derive::*; +use crate::descriptor::AsRawDescriptor; +use crate::platform::EventContext; +use crate::RawDescriptor; +use crate::Result; /// Trait that can be used to associate events with arbitrary enums when using /// `WaitContext`. @@ -232,9 +234,10 @@ impl AsRawDescriptor for WaitContext { #[cfg(test)] mod tests { - use super::*; use base_event_token_derive::EventToken; + use super::*; + #[test] #[allow(dead_code)] fn event_token_derive() { diff --git a/base/src/write_zeroes.rs b/base/src/write_zeroes.rs index 6bb12335d..d3169cb00 100644 --- a/base/src/write_zeroes.rs +++ b/base/src/write_zeroes.rs @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - fs::File, - io::{self, Error, ErrorKind}, -}; +use std::fs::File; +use std::io::Error; +use std::io::ErrorKind; +use std::io::{self}; /// A trait for deallocating space in a file. pub trait PunchHole { @@ -60,10 +60,15 @@ impl WriteZeroesAt for File { #[cfg(test)] mod tests { - use super::*; - use std::io::{Read, Seek, SeekFrom, Write}; + use std::io::Read; + use std::io::Seek; + use std::io::SeekFrom; + use std::io::Write; + use tempfile::tempfile; + use super::*; + #[test] fn simple_test() { let mut f = tempfile().unwrap(); diff --git a/bit_field/bit_field_derive/bit_field_derive.rs b/bit_field/bit_field_derive/bit_field_derive.rs index e8a536709..596f4db77 100644 --- a/bit_field/bit_field_derive/bit_field_derive.rs +++ b/bit_field/bit_field_derive/bit_field_derive.rs @@ -6,13 +6,26 @@ extern crate proc_macro; -use proc_macro2::{Span, TokenStream}; -use quote::{quote, quote_spanned}; -use syn::parse::{Error, Result}; -use syn::{ - parse_macro_input, Attribute, Data, DataEnum, DeriveInput, Fields, FieldsNamed, FieldsUnnamed, - Ident, Lit, LitInt, Meta, Type, Visibility, -}; +use proc_macro2::Span; +use proc_macro2::TokenStream; +use quote::quote; +use quote::quote_spanned; +use syn::parse::Error; +use syn::parse::Result; +use syn::parse_macro_input; +use syn::Attribute; +use syn::Data; +use syn::DataEnum; +use syn::DeriveInput; +use syn::Fields; +use syn::FieldsNamed; +use syn::FieldsUnnamed; +use syn::Ident; +use syn::Lit; +use syn::LitInt; +use syn::Meta; +use syn::Type; +use syn::Visibility; /// The function that derives the actual implementation. #[proc_macro_attribute] @@ -641,9 +654,10 @@ pub fn define_bit_field_specifiers(_input: proc_macro::TokenStream) -> proc_macr #[cfg(test)] mod tests { - use super::*; use syn::parse_quote; + use super::*; + #[test] fn end_to_end() { let input: DeriveInput = parse_quote! { diff --git a/bit_field/src/lib.rs b/bit_field/src/lib.rs index 1455430b9..02a8c0757 100644 --- a/bit_field/src/lib.rs +++ b/bit_field/src/lib.rs @@ -267,7 +267,8 @@ //! } //! ``` -use std::fmt::{self, Display}; +use std::fmt::Display; +use std::fmt::{self}; pub use bit_field_derive::bitfield; diff --git a/broker_ipc/src/generic.rs b/broker_ipc/src/generic.rs index b39820169..0553a8dca 100644 --- a/broker_ipc/src/generic.rs +++ b/broker_ipc/src/generic.rs @@ -5,11 +5,15 @@ //! Generic implementation of product specific functions that are called on child process //! initialization. -use crate::{log_file_from_path, CommonChildStartupArgs}; -use base::Tube; -use serde::{Deserialize, Serialize}; use std::path::PathBuf; +use base::Tube; +use serde::Deserialize; +use serde::Serialize; + +use crate::log_file_from_path; +use crate::CommonChildStartupArgs; + #[derive(Serialize, Deserialize)] pub struct ProductAttributes {} diff --git a/broker_ipc/src/lib.rs b/broker_ipc/src/lib.rs index b43ff637c..872a96b8e 100644 --- a/broker_ipc/src/lib.rs +++ b/broker_ipc/src/lib.rs @@ -5,19 +5,28 @@ //! Contains shared code between the broker & its children, specifically any IPC messages or common //! bootstrapping code. +use std::fs::File; +use std::fs::OpenOptions; + use anyhow::Context; -use base::{enable_high_res_timers, syslog, FromRawDescriptor, IntoRawDescriptor, SafeDescriptor}; -use base::{EnabledHighResTimer, Tube}; -use serde::{Deserialize, Serialize}; -use std::fs::{File, OpenOptions}; +use base::enable_high_res_timers; +use base::syslog; +use base::EnabledHighResTimer; +use base::FromRawDescriptor; +use base::IntoRawDescriptor; +use base::SafeDescriptor; +use base::Tube; +use serde::Deserialize; +use serde::Serialize; mod generic; -use generic as product; - -use product::{init_child_crash_reporting, product_child_setup, ProductAttributes}; - use std::path::PathBuf; +use generic as product; +use product::init_child_crash_reporting; +use product::product_child_setup; +use product::ProductAttributes; + /// Arguments that are common to all devices & helper processes. #[derive(Serialize, Deserialize)] pub struct CommonChildStartupArgs { diff --git a/common/audio_streams/src/async_api.rs b/common/audio_streams/src/async_api.rs index 8e94a009d..8f6112bda 100644 --- a/common/audio_streams/src/async_api.rs +++ b/common/audio_streams/src/async_api.rs @@ -12,12 +12,12 @@ //! //! The implementation is provided in `cros_async::audio_streams_async`. +use std::io::Result; #[cfg(unix)] use std::os::unix::net::UnixStream; +use std::time::Duration; use async_trait::async_trait; -use std::io::Result; -use std::time::Duration; #[async_trait(?Send)] pub trait ReadAsync { diff --git a/common/audio_streams/src/audio_streams.rs b/common/audio_streams/src/audio_streams.rs index ec47ddfaa..62843b3b2 100644 --- a/common/audio_streams/src/audio_streams.rs +++ b/common/audio_streams/src/audio_streams.rs @@ -41,20 +41,25 @@ //! ``` pub mod async_api; -use async_trait::async_trait; use std::cmp::min; use std::error; -use std::fmt::{self, Display}; -use std::io::{self, Read, Write}; +use std::fmt::Display; +use std::fmt::{self}; +use std::io::Read; +use std::io::Write; +use std::io::{self}; #[cfg(unix)] use std::os::unix::io::RawFd as RawDescriptor; #[cfg(windows)] use std::os::windows::io::RawHandle as RawDescriptor; use std::result::Result; use std::str::FromStr; -use std::time::{Duration, Instant}; +use std::time::Duration; +use std::time::Instant; -pub use async_api::{AsyncStream, AudioStreamsExecutor}; +pub use async_api::AsyncStream; +pub use async_api::AudioStreamsExecutor; +use async_trait::async_trait; use remain::sorted; use thiserror::Error; @@ -731,10 +736,12 @@ impl StreamSourceGenerator for NoopStreamSourceGenerator { #[cfg(test)] mod tests { + use futures::FutureExt; + use io::Write; + use io::{self}; + use super::async_api::test::TestExecutor; use super::*; - use futures::FutureExt; - use io::{self, Write}; #[test] fn invalid_buffer_length() { diff --git a/common/audio_streams/src/capture.rs b/common/audio_streams/src/capture.rs index ab1d4efe2..b112572a6 100644 --- a/common/audio_streams/src/capture.rs +++ b/common/audio_streams/src/capture.rs @@ -30,19 +30,24 @@ //! # } //! ``` -use async_trait::async_trait; -use std::{ - io::{self, Read, Write}, - time::{Duration, Instant}, -}; +use std::io::Read; +use std::io::Write; +use std::io::{self}; +use std::time::Duration; +use std::time::Instant; -use super::async_api::AudioStreamsExecutor; -use super::{ - AsyncBufferCommit, AudioBuffer, BoxError, BufferCommit, NoopBufferCommit, SampleFormat, -}; +use async_trait::async_trait; use remain::sorted; use thiserror::Error; +use super::async_api::AudioStreamsExecutor; +use super::AsyncBufferCommit; +use super::AudioBuffer; +use super::BoxError; +use super::BufferCommit; +use super::NoopBufferCommit; +use super::SampleFormat; + /// `CaptureBufferStream` provides `CaptureBuffer`s to read with audio samples from capture. pub trait CaptureBufferStream: Send { fn next_capture_buffer<'b, 's: 'b>(&'s mut self) -> Result, BoxError>; @@ -308,10 +313,11 @@ where #[cfg(test)] mod tests { + use futures::FutureExt; + use super::super::async_api::test::TestExecutor; use super::super::*; use super::*; - use futures::FutureExt; #[test] fn invalid_buffer_length() { diff --git a/common/audio_streams/src/shm_streams.rs b/common/audio_streams/src/shm_streams.rs index a801a5057..dc846b530 100644 --- a/common/audio_streams/src/shm_streams.rs +++ b/common/audio_streams/src/shm_streams.rs @@ -5,13 +5,18 @@ #[cfg(unix)] use std::os::unix::io::RawFd; use std::sync::Arc; -use std::time::{Duration, Instant}; +use std::sync::Condvar; +use std::sync::Mutex; +use std::time::Duration; +use std::time::Instant; use remain::sorted; -use std::sync::{Condvar, Mutex}; use thiserror::Error; -use crate::{BoxError, SampleFormat, StreamDirection, StreamEffect}; +use crate::BoxError; +use crate::SampleFormat; +use crate::StreamDirection; +use crate::StreamEffect; type GenericResult = std::result::Result; diff --git a/common/balloon_control/src/lib.rs b/common/balloon_control/src/lib.rs index 0ea428302..b5209db3d 100644 --- a/common/balloon_control/src/lib.rs +++ b/common/balloon_control/src/lib.rs @@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; // Balloon commands that are send on the balloon command tube. #[derive(Serialize, Deserialize, Debug)] diff --git a/common/cros-fuzz/src/rand.rs b/common/cros-fuzz/src/rand.rs index b52ddbf05..2823b5c17 100644 --- a/common/cros-fuzz/src/rand.rs +++ b/common/cros-fuzz/src/rand.rs @@ -7,7 +7,8 @@ use std::fmt; use std::mem::size_of; use std::result::Result; -use rand_core::{Error, RngCore}; +use rand_core::Error; +use rand_core::RngCore; /// A random number generator that uses fuzzer input as the source of its /// randomness. When run on the same input, it provides the same output, as diff --git a/common/cros_asyncv2/src/blocking/block_on.rs b/common/cros_asyncv2/src/blocking/block_on.rs index bbd5110fc..de4292c76 100644 --- a/common/cros_asyncv2/src/blocking/block_on.rs +++ b/common/cros_asyncv2/src/blocking/block_on.rs @@ -2,18 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - future::Future, - ptr, - sync::atomic::{AtomicI32, Ordering}, - sync::Arc, - task::{Context, Poll}, -}; +use std::future::Future; +use std::ptr; +use std::sync::atomic::AtomicI32; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::task::Context; +use std::task::Poll; -use futures::{ - pin_mut, - task::{waker_ref, ArcWake}, -}; +use futures::pin_mut; +use futures::task::waker_ref; +use futures::task::ArcWake; // Randomly generated values to indicate the state of the current thread. const WAITING: i32 = 0x25de_74d1; @@ -109,16 +108,18 @@ pub fn block_on(f: F) -> F::Output { #[cfg(test)] mod test { - use super::*; - use std::future::Future; use std::pin::Pin; - use std::sync::mpsc::{channel, Sender}; + use std::sync::mpsc::channel; + use std::sync::mpsc::Sender; use std::sync::Arc; - use std::task::{Context, Poll, Waker}; + use std::task::Context; + use std::task::Poll; + use std::task::Waker; use std::thread; use std::time::Duration; + use super::*; use crate::sync::SpinLock; struct TimerState { diff --git a/common/cros_asyncv2/src/blocking/pool.rs b/common/cros_asyncv2/src/blocking/pool.rs index fbf4bc0f9..4efe5bffa 100644 --- a/common/cros_asyncv2/src/blocking/pool.rs +++ b/common/cros_asyncv2/src/blocking/pool.rs @@ -2,21 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - collections::VecDeque, - mem, - sync::{ - mpsc::{channel, Receiver, Sender}, - Arc, - }, - thread::{self, JoinHandle}, - time::{Duration, Instant}, -}; +use std::collections::VecDeque; +use std::mem; +use std::sync::mpsc::channel; +use std::sync::mpsc::Receiver; +use std::sync::mpsc::Sender; +use std::sync::Arc; +use std::thread::JoinHandle; +use std::thread::{self}; +use std::time::Duration; +use std::time::Instant; -use async_task::{Runnable, Task}; -use base::{error, warn}; +use async_task::Runnable; +use async_task::Task; +use base::error; +use base::warn; use slab::Slab; -use sync::{Condvar, Mutex}; +use sync::Condvar; +use sync::Mutex; const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10); @@ -332,16 +335,19 @@ impl Drop for BlockingPool { #[cfg(test)] mod test { - use std::{ - sync::{Arc, Barrier}, - thread, - time::{Duration, Instant}, - }; + use std::sync::Arc; + use std::sync::Barrier; + use std::thread; + use std::time::Duration; + use std::time::Instant; - use futures::{stream::FuturesUnordered, StreamExt}; - use sync::{Condvar, Mutex}; + use futures::stream::FuturesUnordered; + use futures::StreamExt; + use sync::Condvar; + use sync::Mutex; - use crate::{block_on, BlockingPool}; + use crate::block_on; + use crate::BlockingPool; #[test] fn blocking_sleep() { diff --git a/common/cros_asyncv2/src/enter.rs b/common/cros_asyncv2/src/enter.rs index e243ea5f9..68b8e5d43 100644 --- a/common/cros_asyncv2/src/enter.rs +++ b/common/cros_asyncv2/src/enter.rs @@ -38,9 +38,8 @@ pub fn enter() -> anyhow::Result { #[cfg(test)] mod test { - use crate::Executor; - use super::NestedExecutionNotSupported; + use crate::Executor; #[test] fn nested_execution() { diff --git a/common/cros_asyncv2/src/event.rs b/common/cros_asyncv2/src/event.rs index 8cf650b10..5d0057858 100644 --- a/common/cros_asyncv2/src/event.rs +++ b/common/cros_asyncv2/src/event.rs @@ -51,12 +51,13 @@ impl TryFrom for Event { #[cfg(test)] mod tests { - use super::*; - use std::convert::TryInto; - use futures::channel::oneshot::{channel, Receiver, Sender}; + use futures::channel::oneshot::channel; + use futures::channel::oneshot::Receiver; + use futures::channel::oneshot::Sender; + use super::*; use crate::Executor; #[test] diff --git a/common/cros_asyncv2/src/executor.rs b/common/cros_asyncv2/src/executor.rs index 88f7c1617..cae975edf 100644 --- a/common/cros_asyncv2/src/executor.rs +++ b/common/cros_asyncv2/src/executor.rs @@ -2,25 +2,33 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - cmp::Reverse, - collections::{BTreeMap, VecDeque}, - future::{pending, Future}, - num::Wrapping, - sync::Arc, - task::{self, Poll, Waker}, - thread::{self, ThreadId}, - time::{Duration, Instant}, -}; +use std::cmp::Reverse; +use std::collections::BTreeMap; +use std::collections::VecDeque; +use std::future::pending; +use std::future::Future; +use std::num::Wrapping; +use std::sync::Arc; +use std::task::Poll; +use std::task::Waker; +use std::task::{self}; +use std::thread::ThreadId; +use std::thread::{self}; +use std::time::Duration; +use std::time::Instant; use anyhow::Result; -use async_task::{Runnable, Task}; -use futures::{pin_mut, task::WakerRef}; +use async_task::Runnable; +use async_task::Task; +use futures::pin_mut; +use futures::task::WakerRef; use once_cell::unsync::Lazy; use smallvec::SmallVec; use sync::Mutex; -use crate::{enter::enter, sys, BlockingPool}; +use crate::enter::enter; +use crate::sys; +use crate::BlockingPool; thread_local! (static LOCAL_CONTEXT: Lazy>> = Lazy::new(Default::default)); @@ -499,25 +507,27 @@ pub(crate) trait PlatformState { #[cfg(test)] mod test { + use std::convert::TryFrom; + use std::fs::OpenOptions; + use std::mem; + use std::pin::Pin; + use std::thread::JoinHandle; + use std::thread::{self}; + use std::time::Instant; + + use futures::channel::mpsc; + use futures::channel::oneshot; + use futures::future::join3; + use futures::future::select; + use futures::future::Either; + use futures::sink::SinkExt; + use futures::stream::FuturesUnordered; + use futures::stream::StreamExt; + use futures::stream::{self}; + use super::*; - - use std::{ - convert::TryFrom, - fs::OpenOptions, - mem, - pin::Pin, - thread::{self, JoinHandle}, - time::Instant, - }; - - use futures::{ - channel::{mpsc, oneshot}, - future::{join3, select, Either}, - sink::SinkExt, - stream::{self, FuturesUnordered, StreamExt}, - }; - - use crate::{File, OwnedIoBuf}; + use crate::File; + use crate::OwnedIoBuf; #[test] fn basic() { diff --git a/common/cros_asyncv2/src/file.rs b/common/cros_asyncv2/src/file.rs index a663300e8..6bd55976a 100644 --- a/common/cros_asyncv2/src/file.rs +++ b/common/cros_asyncv2/src/file.rs @@ -2,16 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - convert::{TryFrom, TryInto}, - fs::File as StdFile, - io, - path::Path, -}; +use std::convert::TryFrom; +use std::convert::TryInto; +use std::fs::File as StdFile; +use std::io; +use std::path::Path; use base::AsRawDescriptor; -use crate::{sys, AsIoBufs}; +use crate::sys; +use crate::AsIoBufs; static DOWNCAST_ERROR: &str = "inner error not downcastable to `io::Error`"; @@ -356,18 +356,17 @@ impl AsRawDescriptor for File { #[cfg(test)] mod test { - use super::*; - - use std::{ - fs::{File as StdFile, OpenOptions}, - path::PathBuf, - thread, - }; + use std::fs::File as StdFile; + use std::fs::OpenOptions; + use std::path::PathBuf; + use std::thread; use anyhow::Context; use futures::channel::oneshot::channel; - use crate::{Executor, OwnedIoBuf}; + use super::*; + use crate::Executor; + use crate::OwnedIoBuf; #[test] fn readvec() { diff --git a/common/cros_asyncv2/src/iobuf.rs b/common/cros_asyncv2/src/iobuf.rs index 16afa899f..d9e39a260 100644 --- a/common/cros_asyncv2/src/iobuf.rs +++ b/common/cros_asyncv2/src/iobuf.rs @@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::ops::{Deref, DerefMut}; +use std::ops::Deref; +use std::ops::DerefMut; use data_model::IoBufMut; diff --git a/common/cros_asyncv2/src/lib.rs b/common/cros_asyncv2/src/lib.rs index 711d1ca99..14143d590 100644 --- a/common/cros_asyncv2/src/lib.rs +++ b/common/cros_asyncv2/src/lib.rs @@ -98,11 +98,19 @@ mod timer; #[cfg_attr(unix, path = "unix/mod.rs")] mod sys; -pub use blocking::{block_on, BlockingPool}; +pub use blocking::block_on; +pub use blocking::BlockingPool; pub use event::Event; pub use executor::Executor; pub use file::File; -pub use iobuf::{AsIoBufs, OwnedIoBuf}; +pub use iobuf::AsIoBufs; +pub use iobuf::OwnedIoBuf; #[cfg(unix)] -pub use sys::{Descriptor, SeqPacket as UnixSeqPacket, SeqPacketListener as UnixSeqPacketListener}; -pub use timer::{with_deadline, TimedOut, Timer}; +pub use sys::Descriptor; +#[cfg(unix)] +pub use sys::SeqPacket as UnixSeqPacket; +#[cfg(unix)] +pub use sys::SeqPacketListener as UnixSeqPacketListener; +pub use timer::with_deadline; +pub use timer::TimedOut; +pub use timer::Timer; diff --git a/common/cros_asyncv2/src/sync/cv.rs b/common/cros_asyncv2/src/sync/cv.rs index cc7512129..9afedb6f4 100644 --- a/common/cros_asyncv2/src/sync/cv.rs +++ b/common/cros_asyncv2/src/sync/cv.rs @@ -5,11 +5,18 @@ use std::cell::UnsafeCell; use std::hint; use std::mem; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; use std::sync::Arc; -use crate::sync::mu::{MutexGuard, MutexReadGuard, RawMutex}; -use crate::sync::waiter::{Kind as WaiterKind, Waiter, WaiterAdapter, WaiterList, WaitingFor}; +use crate::sync::mu::MutexGuard; +use crate::sync::mu::MutexReadGuard; +use crate::sync::mu::RawMutex; +use crate::sync::waiter::Kind as WaiterKind; +use crate::sync::waiter::Waiter; +use crate::sync::waiter::WaiterAdapter; +use crate::sync::waiter::WaiterList; +use crate::sync::waiter::WaitingFor; const SPINLOCK: usize = 1 << 0; const HAS_WAITERS: usize = 1 << 1; @@ -446,25 +453,32 @@ fn cancel_waiter(cv: usize, waiter: &Waiter, wake_next: bool) { #[cfg(test)] mod test { - use super::*; - use std::future::Future; use std::mem; use std::ptr; use std::rc::Rc; - use std::sync::mpsc::{channel, Sender}; + use std::sync::mpsc::channel; + use std::sync::mpsc::Sender; use std::sync::Arc; - use std::task::{Context, Poll}; - use std::thread::{self, JoinHandle}; + use std::task::Context; + use std::task::Poll; + use std::thread::JoinHandle; + use std::thread::{self}; use std::time::Duration; use futures::channel::oneshot; - use futures::task::{waker_ref, ArcWake}; - use futures::{select, FutureExt}; - use futures_executor::{LocalPool, LocalSpawner, ThreadPool}; + use futures::select; + use futures::task::waker_ref; + use futures::task::ArcWake; + use futures::FutureExt; + use futures_executor::LocalPool; + use futures_executor::LocalSpawner; + use futures_executor::ThreadPool; use futures_util::task::LocalSpawnExt; - use crate::{block_on, sync::Mutex}; + use super::*; + use crate::block_on; + use crate::sync::Mutex; // Dummy waker used when we want to manually drive futures. struct TestWaker; diff --git a/common/cros_asyncv2/src/sync/mu.rs b/common/cros_asyncv2/src/sync/mu.rs index b4e41f77f..150b22602 100644 --- a/common/cros_asyncv2/src/sync/mu.rs +++ b/common/cros_asyncv2/src/sync/mu.rs @@ -5,12 +5,18 @@ use std::cell::UnsafeCell; use std::hint; use std::mem; -use std::ops::{Deref, DerefMut}; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::ops::Deref; +use std::ops::DerefMut; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread::yield_now; -use crate::sync::waiter::{Kind as WaiterKind, Waiter, WaiterAdapter, WaiterList, WaitingFor}; +use crate::sync::waiter::Kind as WaiterKind; +use crate::sync::waiter::Waiter; +use crate::sync::waiter::WaiterAdapter; +use crate::sync::waiter::WaiterList; +use crate::sync::waiter::WaitingFor; // Set when the mutex is exclusively locked. const LOCKED: usize = 1 << 0; @@ -880,29 +886,35 @@ impl<'a, T: ?Sized> Drop for MutexReadGuard<'a, T> { #[cfg(test)] mod test { - use super::*; - use std::future::Future; use std::mem; use std::pin::Pin; use std::rc::Rc; - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::sync::mpsc::{channel, Sender}; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + use std::sync::mpsc::channel; + use std::sync::mpsc::Sender; use std::sync::Arc; - use std::task::{Context, Poll, Waker}; + use std::task::Context; + use std::task::Poll; + use std::task::Waker; use std::thread; use std::time::Duration; use futures::channel::oneshot; - use futures::task::{waker_ref, ArcWake}; - use futures::{pending, select, FutureExt}; - use futures_executor::{LocalPool, ThreadPool}; + use futures::pending; + use futures::select; + use futures::task::waker_ref; + use futures::task::ArcWake; + use futures::FutureExt; + use futures_executor::LocalPool; + use futures_executor::ThreadPool; use futures_util::task::LocalSpawnExt; - use crate::{ - block_on, - sync::{Condvar, SpinLock}, - }; + use super::*; + use crate::block_on; + use crate::sync::Condvar; + use crate::sync::SpinLock; #[derive(Debug, Eq, PartialEq)] struct NonCopy(u32); diff --git a/common/cros_asyncv2/src/sync/spin.rs b/common/cros_asyncv2/src/sync/spin.rs index f313721f8..de1740722 100644 --- a/common/cros_asyncv2/src/sync/spin.rs +++ b/common/cros_asyncv2/src/sync/spin.rs @@ -4,8 +4,10 @@ use std::cell::UnsafeCell; use std::hint; -use std::ops::{Deref, DerefMut}; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::ops::Deref; +use std::ops::DerefMut; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; const UNLOCKED: bool = false; const LOCKED: bool = true; @@ -132,13 +134,14 @@ impl<'a, T: ?Sized> Drop for SpinLockGuard<'a, T> { #[cfg(test)] mod test { - use super::*; - use std::mem; - use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread; + use super::*; + #[derive(PartialEq, Eq, Debug)] struct NonCopy(u32); diff --git a/common/cros_asyncv2/src/sync/waiter.rs b/common/cros_asyncv2/src/sync/waiter.rs index 072a0f506..1a3a9c61e 100644 --- a/common/cros_asyncv2/src/sync/waiter.rs +++ b/common/cros_asyncv2/src/sync/waiter.rs @@ -7,12 +7,19 @@ use std::future::Future; use std::mem; use std::pin::Pin; use std::ptr::NonNull; -use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicU8; +use std::sync::atomic::Ordering; use std::sync::Arc; -use std::task::{Context, Poll, Waker}; +use std::task::Context; +use std::task::Poll; +use std::task::Waker; -use intrusive_collections::linked_list::{LinkedList, LinkedListOps}; -use intrusive_collections::{intrusive_adapter, DefaultLinkOps, LinkOps}; +use intrusive_collections::intrusive_adapter; +use intrusive_collections::linked_list::LinkedList; +use intrusive_collections::linked_list::LinkedListOps; +use intrusive_collections::DefaultLinkOps; +use intrusive_collections::LinkOps; use crate::sync::SpinLock; diff --git a/common/cros_asyncv2/src/timer.rs b/common/cros_asyncv2/src/timer.rs index 69d9ffc1a..447537951 100644 --- a/common/cros_asyncv2/src/timer.rs +++ b/common/cros_asyncv2/src/timer.rs @@ -2,18 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - future::Future, - io, - pin::Pin, - task::{Context, Poll}, - time::Instant, -}; +use std::future::Future; +use std::io; +use std::pin::Pin; +use std::task::Context; +use std::task::Poll; +use std::time::Instant; -use futures::{ - future::{select, Either}, - pin_mut, -}; +use futures::future::select; +use futures::future::Either; +use futures::pin_mut; use thiserror::Error as ThisError; use crate::executor; @@ -164,13 +162,18 @@ pub async fn with_deadline(deadline: Instant, f: F) -> Result VolatileRef<'a, T> { #[cfg(test)] mod tests { - use super::*; - - use std::sync::{Arc, Barrier}; + use std::sync::Arc; + use std::sync::Barrier; use std::thread::spawn; + use super::*; + #[derive(Clone)] struct VecMem { mem: Arc>, diff --git a/common/p9/src/fuzzing.rs b/common/p9/src/fuzzing.rs index 47aa07057..65e878df6 100644 --- a/common/p9/src/fuzzing.rs +++ b/common/p9/src/fuzzing.rs @@ -4,7 +4,8 @@ use std::io::Cursor; -use crate::protocol::{Tframe, WireFormat}; +use crate::protocol::Tframe; +use crate::protocol::WireFormat; pub fn tframe_decode(bytes: &[u8]) { let mut cursor = Cursor::new(bytes); diff --git a/common/p9/src/protocol/messages.rs b/common/p9/src/protocol/messages.rs index 6b36dcc30..99d231ace 100644 --- a/common/p9/src/protocol/messages.rs +++ b/common/p9/src/protocol/messages.rs @@ -2,12 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::io::{self, ErrorKind, Read, Write}; +use std::io::ErrorKind; +use std::io::Read; +use std::io::Write; +use std::io::{self}; use std::mem; use std::string::String; use std::vec::Vec; -use crate::protocol::wire_format::{Data, WireFormat}; +use crate::protocol::wire_format::Data; +use crate::protocol::wire_format::WireFormat; // Message type constants. Taken from "include/net/9p/9p.h" in the linux kernel // tree. The protocol specifies each R* message to be the corresponding T* diff --git a/common/p9/src/protocol/mod.rs b/common/p9/src/protocol/mod.rs index 9c278ee89..0af46b9e1 100644 --- a/common/p9/src/protocol/mod.rs +++ b/common/p9/src/protocol/mod.rs @@ -6,4 +6,5 @@ mod messages; mod wire_format; pub use self::messages::*; -pub use self::wire_format::{Data, WireFormat}; +pub use self::wire_format::Data; +pub use self::wire_format::WireFormat; diff --git a/common/p9/src/protocol/wire_format.rs b/common/p9/src/protocol/wire_format.rs index 1576bde43..e3c348af2 100644 --- a/common/p9/src/protocol/wire_format.rs +++ b/common/p9/src/protocol/wire_format.rs @@ -4,9 +4,12 @@ use std::fmt; use std::io; -use std::io::{ErrorKind, Read, Write}; +use std::io::ErrorKind; +use std::io::Read; +use std::io::Write; use std::mem; -use std::ops::{Deref, DerefMut}; +use std::ops::Deref; +use std::ops::DerefMut; use std::string::String; use std::vec::Vec; @@ -202,11 +205,12 @@ impl WireFormat for Data { #[cfg(test)] mod test { - use super::*; use std::io::Cursor; use std::mem; use std::string::String; + use super::*; + #[test] fn integer_byte_size() { assert_eq!(1, 0u8.byte_size()); diff --git a/common/p9/src/server/mod.rs b/common/p9/src/server/mod.rs index c39bc9063..5d356afe5 100644 --- a/common/p9/src/server/mod.rs +++ b/common/p9/src/server/mod.rs @@ -5,22 +5,31 @@ mod read_dir; use std::cmp::min; -use std::collections::{btree_map, BTreeMap}; -use std::ffi::{CStr, CString}; +use std::collections::btree_map; +use std::collections::BTreeMap; +use std::ffi::CStr; +use std::ffi::CString; use std::fs::File; -use std::io::{self, Cursor, Read, Write}; -use std::mem::{self, MaybeUninit}; +use std::io::Cursor; +use std::io::Read; +use std::io::Write; +use std::io::{self}; +use std::mem::MaybeUninit; +use std::mem::{self}; use std::ops::Deref; use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::FileExt; -use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::FromRawFd; +use std::os::unix::io::RawFd; use std::path::Path; -use serde::{Deserialize, Serialize}; +use read_dir::read_dir; +use serde::Deserialize; +use serde::Serialize; use crate::protocol::*; use crate::syscall; -use read_dir::read_dir; // Tlopen and Tlcreate flags. Taken from "include/net/9p/9p.h" in the linux tree. const P9_RDONLY: u32 = 0o00000000; diff --git a/common/p9/src/server/read_dir.rs b/common/p9/src/server/read_dir.rs index fe5d74f42..9b3f12db4 100644 --- a/common/p9/src/server/read_dir.rs +++ b/common/p9/src/server/read_dir.rs @@ -2,7 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ffi::CStr, io::Result, mem::size_of, os::unix::io::AsRawFd}; +use std::ffi::CStr; +use std::io::Result; +use std::mem::size_of; +use std::os::unix::io::AsRawFd; use crate::syscall; diff --git a/common/p9/src/server/tests.rs b/common/p9/src/server/tests.rs index 1cd07484c..05a791e21 100644 --- a/common/p9/src/server/tests.rs +++ b/common/p9/src/server/tests.rs @@ -2,21 +2,27 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::*; - use std::borrow::Cow; -use std::collections::{HashSet, VecDeque}; +use std::collections::HashSet; +use std::collections::VecDeque; use std::env; -use std::ffi::{CString, OsString}; -use std::fs::{self, File}; -use std::io::{self, Cursor}; +use std::ffi::CString; +use std::ffi::OsString; +use std::fs::File; +use std::fs::{self}; +use std::io::Cursor; +use std::io::{self}; use std::mem; use std::ops::Deref; use std::os::unix::ffi::OsStringExt; use std::os::unix::fs::MetadataExt; -use std::path::{Component, Path, PathBuf}; +use std::path::Component; +use std::path::Path; +use std::path::PathBuf; use std::u32; +use super::*; + // Used to indicate that there is no fid associated with this message. const P9_NOFID: u32 = u32::MAX; diff --git a/common/p9/wire_format_derive/wire_format_derive.rs b/common/p9/wire_format_derive/wire_format_derive.rs index 290ffc5f1..f2e24e301 100644 --- a/common/p9/wire_format_derive/wire_format_derive.rs +++ b/common/p9/wire_format_derive/wire_format_derive.rs @@ -17,9 +17,13 @@ extern crate quote; #[macro_use] extern crate syn; -use proc_macro2::{Span, TokenStream}; +use proc_macro2::Span; +use proc_macro2::TokenStream; use syn::spanned::Spanned; -use syn::{Data, DeriveInput, Fields, Ident}; +use syn::Data; +use syn::DeriveInput; +use syn::Fields; +use syn::Ident; /// The function that derives the actual implementation. #[proc_macro_derive(P9WireFormat)] diff --git a/common/sync/src/condvar.rs b/common/sync/src/condvar.rs index 508a04d2c..115492381 100644 --- a/common/sync/src/condvar.rs +++ b/common/sync/src/condvar.rs @@ -2,8 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::fmt::{self, Debug}; -use std::sync::{Condvar as StdCondvar, MutexGuard, WaitTimeoutResult}; +use std::fmt::Debug; +use std::fmt::{self}; +use std::sync::Condvar as StdCondvar; +use std::sync::MutexGuard; +use std::sync::WaitTimeoutResult; use std::time::Duration; static CONDVAR_POISONED: &str = "condvar is poisoned"; diff --git a/common/sync/src/lib.rs b/common/sync/src/lib.rs index 5a1e88318..58e3cd922 100644 --- a/common/sync/src/lib.rs +++ b/common/sync/src/lib.rs @@ -25,4 +25,5 @@ mod condvar; mod mutex; pub use crate::condvar::Condvar; -pub use crate::mutex::{Mutex, WouldBlock}; +pub use crate::mutex::Mutex; +pub use crate::mutex::WouldBlock; diff --git a/common/sync/src/mutex.rs b/common/sync/src/mutex.rs index c479a2e56..88885421e 100644 --- a/common/sync/src/mutex.rs +++ b/common/sync/src/mutex.rs @@ -24,8 +24,12 @@ //! Developers should feel free to use sync::Mutex anywhere in crosvm that they //! would otherwise be using std::sync::Mutex. -use std::fmt::{self, Debug, Display}; -use std::sync::{Mutex as StdMutex, MutexGuard, TryLockError}; +use std::fmt::Debug; +use std::fmt::Display; +use std::fmt::{self}; +use std::sync::Mutex as StdMutex; +use std::sync::MutexGuard; +use std::sync::TryLockError; /// A mutual exclusion primitive useful for protecting shared data. #[derive(Default)] diff --git a/cros_async/src/async_types.rs b/cros_async/src/async_types.rs index aa971d164..7827ff651 100644 --- a/cros_async/src/async_types.rs +++ b/cros_async/src/async_types.rs @@ -2,12 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{Executor, IntoAsync}; -use base::{RecvTube, SendTube, Tube, TubeResult}; -use serde::{de::DeserializeOwned, Serialize}; use std::io; +use base::RecvTube; +use base::SendTube; +use base::Tube; +use base::TubeResult; +use serde::de::DeserializeOwned; +use serde::Serialize; + pub use crate::sys::async_types::*; +use crate::Executor; +use crate::IntoAsync; // NOTE: A StreamChannel can either be used fully in async mode, or not in async // mode. Mixing modes will break StreamChannel's internal read/write diff --git a/cros_async/src/audio_streams_async.rs b/cros_async/src/audio_streams_async.rs index 2816b136b..cba88e28c 100644 --- a/cros_async/src/audio_streams_async.rs +++ b/cros_async/src/audio_streams_async.rs @@ -6,19 +6,24 @@ //! //! It implements the `AudioStreamsExecutor` trait for `Executor`, so it can be passed into //! the audio_streams API. +use std::io::Result; #[cfg(unix)] use std::os::unix::net::UnixStream; +use std::time::Duration; -use std::{io::Result, time::Duration}; - -use crate::{IntoAsync, IoSourceExt, TimerAsync}; use async_trait::async_trait; -use audio_streams::async_api::{AudioStreamsExecutor, ReadAsync, ReadWriteAsync, WriteAsync}; +#[cfg(unix)] +use audio_streams::async_api::AsyncStream; +use audio_streams::async_api::AudioStreamsExecutor; +use audio_streams::async_api::ReadAsync; +use audio_streams::async_api::ReadWriteAsync; +use audio_streams::async_api::WriteAsync; #[cfg(unix)] use super::AsyncWrapper; -#[cfg(unix)] -use audio_streams::async_api::AsyncStream; +use crate::IntoAsync; +use crate::IoSourceExt; +use crate::TimerAsync; /// A wrapper around IoSourceExt that is compatible with the audio_streams traits. pub struct IoSourceWrapper { diff --git a/cros_async/src/blocking/cancellable_pool.rs b/cros_async/src/blocking/cancellable_pool.rs index 53f594a9d..99fb33349 100644 --- a/cros_async/src/blocking/cancellable_pool.rs +++ b/cros_async/src/blocking/cancellable_pool.rs @@ -4,18 +4,19 @@ //! Provides an async blocking pool whose tasks can be cancelled. -use std::{ - collections::HashMap, - sync::Arc, - time::{Duration, Instant}, -}; +use std::collections::HashMap; +use std::sync::Arc; +use std::time::Duration; +use std::time::Instant; -use crate::BlockingPool; use async_task::Task; use once_cell::sync::Lazy; -use sync::{Condvar, Mutex}; +use sync::Condvar; +use sync::Mutex; use thiserror::Error as ThisError; +use crate::BlockingPool; + /// Global executor. /// /// This is convenient, though not preferred. Pros/cons: @@ -347,13 +348,17 @@ pub fn unblock_disarm() { #[cfg(test)] mod test { - use std::{sync::Arc, thread, time::Duration}; + use std::sync::Arc; + use std::sync::Barrier; + use std::thread; + use std::time::Duration; use futures::executor::block_on; - use sync::{Condvar, Mutex}; + use sync::Condvar; + use sync::Mutex; - use crate::{blocking::Error, CancellableBlockingPool}; - use std::sync::Barrier; + use crate::blocking::Error; + use crate::CancellableBlockingPool; #[test] fn disarm_with_pending_work() { diff --git a/cros_async/src/blocking/pool.rs b/cros_async/src/blocking/pool.rs index 0d940756b..6c11c113c 100644 --- a/cros_async/src/blocking/pool.rs +++ b/cros_async/src/blocking/pool.rs @@ -2,23 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - collections::VecDeque, - mem, - sync::{ - mpsc::{channel, Receiver, Sender}, - Arc, - }, - thread::{ - JoinHandle, {self}, - }, - time::{Duration, Instant}, -}; +use std::collections::VecDeque; +use std::mem; +use std::sync::mpsc::channel; +use std::sync::mpsc::Receiver; +use std::sync::mpsc::Sender; +use std::sync::Arc; +use std::thread::JoinHandle; +use std::thread::{self}; +use std::time::Duration; +use std::time::Instant; -use async_task::{Runnable, Task}; -use base::{error, warn}; +use async_task::Runnable; +use async_task::Task; +use base::error; +use base::warn; use slab::Slab; -use sync::{Condvar, Mutex}; +use sync::Condvar; +use sync::Mutex; const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10); @@ -347,14 +348,17 @@ impl Drop for BlockingPool { #[cfg(test)] mod test { - use std::{ - sync::{Arc, Barrier}, - thread, - time::{Duration, Instant}, - }; + use std::sync::Arc; + use std::sync::Barrier; + use std::thread; + use std::time::Duration; + use std::time::Instant; - use futures::{executor::block_on, stream::FuturesUnordered, StreamExt}; - use sync::{Condvar, Mutex}; + use futures::executor::block_on; + use futures::stream::FuturesUnordered; + use futures::StreamExt; + use sync::Condvar; + use sync::Mutex; use super::super::super::BlockingPool; diff --git a/cros_async/src/blocking/sys/unix/block_on.rs b/cros_async/src/blocking/sys/unix/block_on.rs index e422fbfe4..de4292c76 100644 --- a/cros_async/src/blocking/sys/unix/block_on.rs +++ b/cros_async/src/blocking/sys/unix/block_on.rs @@ -2,20 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - future::Future, - ptr, - sync::{ - atomic::{AtomicI32, Ordering}, - Arc, - }, - task::{Context, Poll}, -}; +use std::future::Future; +use std::ptr; +use std::sync::atomic::AtomicI32; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::task::Context; +use std::task::Poll; -use futures::{ - pin_mut, - task::{waker_ref, ArcWake}, -}; +use futures::pin_mut; +use futures::task::waker_ref; +use futures::task::ArcWake; // Randomly generated values to indicate the state of the current thread. const WAITING: i32 = 0x25de_74d1; @@ -111,20 +108,18 @@ pub fn block_on(f: F) -> F::Output { #[cfg(test)] mod test { + use std::future::Future; + use std::pin::Pin; + use std::sync::mpsc::channel; + use std::sync::mpsc::Sender; + use std::sync::Arc; + use std::task::Context; + use std::task::Poll; + use std::task::Waker; + use std::thread; + use std::time::Duration; + use super::*; - - use std::{ - future::Future, - pin::Pin, - sync::{ - mpsc::{channel, Sender}, - Arc, - }, - task::{Context, Poll, Waker}, - thread, - time::Duration, - }; - use crate::sync::SpinLock; struct TimerState { diff --git a/cros_async/src/complete.rs b/cros_async/src/complete.rs index 9fb9273f4..cb0c7092c 100644 --- a/cros_async/src/complete.rs +++ b/cros_async/src/complete.rs @@ -5,13 +5,13 @@ // Need non-snake case so the macro can re-use type names for variables. #![allow(non_snake_case)] -use std::{ - future::Future, - pin::Pin, - task::{Context, Poll}, -}; +use std::future::Future; +use std::pin::Pin; +use std::task::Context; +use std::task::Poll; -use futures::future::{maybe_done, MaybeDone}; +use futures::future::maybe_done; +use futures::future::MaybeDone; use pin_utils::unsafe_pinned; // Macro-generate future combinators to allow for running different numbers of top-level futures in diff --git a/cros_async/src/event.rs b/cros_async/src/event.rs index 11a3c4293..1e091babe 100644 --- a/cros_async/src/event.rs +++ b/cros_async/src/event.rs @@ -2,9 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{IntoAsync, IoSourceExt}; use base::Event; +use crate::IntoAsync; +use crate::IoSourceExt; + /// An async version of `base::Event`. pub struct EventAsync { pub(crate) io_source: Box>, diff --git a/cros_async/src/io_ext.rs b/cros_async/src/io_ext.rs index 12e77e9ee..6ed6381ec 100644 --- a/cros_async/src/io_ext.rs +++ b/cros_async/src/io_ext.rs @@ -15,22 +15,22 @@ //! Operations can only access memory in a `Vec` or an implementor of `BackingMemory`. See the //! `URingExecutor` documentation for an explaination of why. -use std::{ - fs::File, - io, - ops::{Deref, DerefMut}, - sync::Arc, -}; +use std::fs::File; +use std::io; +use std::ops::Deref; +use std::ops::DerefMut; +use std::sync::Arc; use async_trait::async_trait; -use base::{AsRawDescriptor, RawDescriptor}; +use base::AsRawDescriptor; +use base::RawDescriptor; +#[cfg(unix)] +use base::UnixSeqpacket; use remain::sorted; use thiserror::Error as ThisError; -use super::{BackingMemory, MemRegion}; - -#[cfg(unix)] -use base::UnixSeqpacket; +use super::BackingMemory; +use super::MemRegion; #[cfg(unix)] #[sorted] @@ -252,29 +252,32 @@ impl IntoAsync for AsyncWrapper {} #[cfg(all(test, unix))] mod tests { + use std::fs::File; + use std::fs::OpenOptions; + use std::future::Future; + use std::pin::Pin; + use std::sync::Arc; + use std::task::Context; + use std::task::Poll; + use std::task::Waker; + use std::thread; + use base::Event; - use std::{ - fs::{File, OpenOptions}, - future::Future, - pin::Pin, - sync::Arc, - task::{Context, Poll, Waker}, - thread, - }; use sync::Mutex; use super::*; - use crate::{ - mem::VecIoWrapper, - sys::unix::{ - executor::{ - async_poll_from, async_poll_from_local, async_uring_from, async_uring_from_local, - }, - uring_executor::use_uring, - FdExecutor, PollSource, URingExecutor, UringSource, - }, - Executor, MemRegion, - }; + use crate::mem::VecIoWrapper; + use crate::sys::unix::executor::async_poll_from; + use crate::sys::unix::executor::async_poll_from_local; + use crate::sys::unix::executor::async_uring_from; + use crate::sys::unix::executor::async_uring_from_local; + use crate::sys::unix::uring_executor::use_uring; + use crate::sys::unix::FdExecutor; + use crate::sys::unix::PollSource; + use crate::sys::unix::URingExecutor; + use crate::sys::unix::UringSource; + use crate::Executor; + use crate::MemRegion; struct State { should_quit: bool, diff --git a/cros_async/src/lib.rs b/cros_async/src/lib.rs index bb668a620..805e75dde 100644 --- a/cros_async/src/lib.rs +++ b/cros_async/src/lib.rs @@ -73,33 +73,39 @@ pub use sys::Executor; mod timer; mod waker; +use std::future::Future; +use std::marker::PhantomData; +use std::pin::Pin; +use std::task::Context; +use std::task::Poll; + pub use async_types::*; pub use base::Event; #[cfg(unix)] pub use blocking::sys::unix::block_on::block_on; +pub use blocking::unblock; +pub use blocking::unblock_disarm; pub use blocking::BlockingPool; +pub use blocking::CancellableBlockingPool; +pub use blocking::TimeoutAction; pub use event::EventAsync; #[cfg(windows)] pub use futures::executor::block_on; -pub use io_ext::{ - AllocateMode, AsyncWrapper, Error as AsyncError, IntoAsync, IoSourceExt, ReadAsync, - Result as AsyncResult, WriteAsync, -}; -pub use mem::{BackingMemory, MemRegion}; +pub use io_ext::AllocateMode; +pub use io_ext::AsyncWrapper; +pub use io_ext::Error as AsyncError; +pub use io_ext::IntoAsync; +pub use io_ext::IoSourceExt; +pub use io_ext::ReadAsync; +pub use io_ext::Result as AsyncResult; +pub use io_ext::WriteAsync; +pub use mem::BackingMemory; +pub use mem::MemRegion; +use remain::sorted; pub use select::SelectResult; pub use sys::run_one; -pub use timer::TimerAsync; - -use std::{ - future::Future, - marker::PhantomData, - pin::Pin, - task::{Context, Poll}, -}; - -pub use blocking::{unblock, unblock_disarm, CancellableBlockingPool, TimeoutAction}; -use remain::sorted; use thiserror::Error as ThisError; +pub use timer::TimerAsync; #[sorted] #[derive(ThisError, Debug)] diff --git a/cros_async/src/select.rs b/cros_async/src/select.rs index a78a0d92b..34a69f4f5 100644 --- a/cros_async/src/select.rs +++ b/cros_async/src/select.rs @@ -5,13 +5,14 @@ // Need non-snake case so the macro can re-use type names for variables. #![allow(non_snake_case)] -use std::{ - future::Future, - pin::Pin, - task::{Context, Poll}, -}; +use std::future::Future; +use std::pin::Pin; +use std::task::Context; +use std::task::Poll; -use futures::future::{maybe_done, FutureExt, MaybeDone}; +use futures::future::maybe_done; +use futures::future::FutureExt; +use futures::future::MaybeDone; pub enum SelectResult { Pending(F), diff --git a/cros_async/src/sync/cv.rs b/cros_async/src/sync/cv.rs index b5455833f..0d57f5d23 100644 --- a/cros_async/src/sync/cv.rs +++ b/cros_async/src/sync/cv.rs @@ -2,19 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - cell::UnsafeCell, - hint, mem, - sync::{ - atomic::{AtomicUsize, Ordering}, - Arc, - }, -}; +use std::cell::UnsafeCell; +use std::hint; +use std::mem; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; +use std::sync::Arc; -use super::super::sync::{ - mu::{MutexGuard, MutexReadGuard, RawMutex}, - waiter::{Kind as WaiterKind, Waiter, WaiterAdapter, WaiterList, WaitingFor}, -}; +use super::super::sync::mu::MutexGuard; +use super::super::sync::mu::MutexReadGuard; +use super::super::sync::mu::RawMutex; +use super::super::sync::waiter::Kind as WaiterKind; +use super::super::sync::waiter::Waiter; +use super::super::sync::waiter::WaiterAdapter; +use super::super::sync::waiter::WaiterList; +use super::super::sync::waiter::WaitingFor; const SPINLOCK: usize = 1 << 0; const HAS_WAITERS: usize = 1 << 1; @@ -453,33 +455,32 @@ fn cancel_waiter(cv: usize, waiter: &Waiter, wake_next: bool) { #[cfg(unix)] #[cfg(test)] mod test { - use super::*; + use std::future::Future; + use std::mem; + use std::ptr; + use std::rc::Rc; + use std::sync::mpsc::channel; + use std::sync::mpsc::Sender; + use std::sync::Arc; + use std::task::Context; + use std::task::Poll; + use std::thread::JoinHandle; + use std::thread::{self}; + use std::time::Duration; - use std::{ - future::Future, - mem, ptr, - rc::Rc, - sync::{ - mpsc::{channel, Sender}, - Arc, - }, - task::{Context, Poll}, - thread::{ - JoinHandle, {self}, - }, - time::Duration, - }; - - use futures::{ - channel::oneshot, - select, - task::{waker_ref, ArcWake}, - FutureExt, - }; - use futures_executor::{LocalPool, LocalSpawner, ThreadPool}; + use futures::channel::oneshot; + use futures::select; + use futures::task::waker_ref; + use futures::task::ArcWake; + use futures::FutureExt; + use futures_executor::LocalPool; + use futures_executor::LocalSpawner; + use futures_executor::ThreadPool; use futures_util::task::LocalSpawnExt; - use super::super::super::{block_on, sync::Mutex}; + use super::super::super::block_on; + use super::super::super::sync::Mutex; + use super::*; // Dummy waker used when we want to manually drive futures. struct TestWaker; diff --git a/cros_async/src/sync/mu.rs b/cros_async/src/sync/mu.rs index 0aead01c2..b1a7d9e2a 100644 --- a/cros_async/src/sync/mu.rs +++ b/cros_async/src/sync/mu.rs @@ -2,20 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - cell::UnsafeCell, - hint, mem, - ops::{Deref, DerefMut}, - sync::{ - atomic::{AtomicUsize, Ordering}, - Arc, - }, - thread::yield_now, -}; +use std::cell::UnsafeCell; +use std::hint; +use std::mem; +use std::ops::Deref; +use std::ops::DerefMut; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::thread::yield_now; -use super::super::sync::waiter::{ - Kind as WaiterKind, Waiter, WaiterAdapter, WaiterList, WaitingFor, -}; +use super::super::sync::waiter::Kind as WaiterKind; +use super::super::sync::waiter::Waiter; +use super::super::sync::waiter::WaiterAdapter; +use super::super::sync::waiter::WaiterList; +use super::super::sync::waiter::WaitingFor; // Set when the mutex is exclusively locked. const LOCKED: usize = 1 << 0; @@ -887,36 +888,35 @@ impl<'a, T: ?Sized> Drop for MutexReadGuard<'a, T> { #[cfg(unix)] #[cfg(test)] mod test { - use super::*; + use std::future::Future; + use std::mem; + use std::pin::Pin; + use std::rc::Rc; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + use std::sync::mpsc::channel; + use std::sync::mpsc::Sender; + use std::sync::Arc; + use std::task::Context; + use std::task::Poll; + use std::task::Waker; + use std::thread; + use std::time::Duration; - use std::{ - future::Future, - mem, - pin::Pin, - rc::Rc, - sync::{ - atomic::{AtomicUsize, Ordering}, - mpsc::{channel, Sender}, - Arc, - }, - task::{Context, Poll, Waker}, - thread, - time::Duration, - }; - - use futures::{ - channel::oneshot, - pending, select, - task::{waker_ref, ArcWake}, - FutureExt, - }; - use futures_executor::{LocalPool, ThreadPool}; + use futures::channel::oneshot; + use futures::pending; + use futures::select; + use futures::task::waker_ref; + use futures::task::ArcWake; + use futures::FutureExt; + use futures_executor::LocalPool; + use futures_executor::ThreadPool; use futures_util::task::LocalSpawnExt; - use super::super::super::{ - block_on, - sync::{Condvar, SpinLock}, - }; + use super::super::super::block_on; + use super::super::super::sync::Condvar; + use super::super::super::sync::SpinLock; + use super::*; #[derive(Debug, Eq, PartialEq)] struct NonCopy(u32); diff --git a/cros_async/src/sync/spin.rs b/cros_async/src/sync/spin.rs index 7faec6dc2..de1740722 100644 --- a/cros_async/src/sync/spin.rs +++ b/cros_async/src/sync/spin.rs @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - cell::UnsafeCell, - hint, - ops::{Deref, DerefMut}, - sync::atomic::{AtomicBool, Ordering}, -}; +use std::cell::UnsafeCell; +use std::hint; +use std::ops::Deref; +use std::ops::DerefMut; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; const UNLOCKED: bool = false; const LOCKED: bool = true; @@ -134,16 +134,13 @@ impl<'a, T: ?Sized> Drop for SpinLockGuard<'a, T> { #[cfg(test)] mod test { - use super::*; + use std::mem; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + use std::sync::Arc; + use std::thread; - use std::{ - mem, - sync::{ - atomic::{AtomicUsize, Ordering}, - Arc, - }, - thread, - }; + use super::*; #[derive(PartialEq, Eq, Debug)] struct NonCopy(u32); diff --git a/cros_async/src/sync/waiter.rs b/cros_async/src/sync/waiter.rs index e161c623d..95e07917c 100644 --- a/cros_async/src/sync/waiter.rs +++ b/cros_async/src/sync/waiter.rs @@ -2,24 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - cell::UnsafeCell, - future::Future, - mem, - pin::Pin, - ptr::NonNull, - sync::{ - atomic::{AtomicBool, AtomicU8, Ordering}, - Arc, - }, - task::{Context, Poll, Waker}, -}; +use std::cell::UnsafeCell; +use std::future::Future; +use std::mem; +use std::pin::Pin; +use std::ptr::NonNull; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicU8; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::task::Context; +use std::task::Poll; +use std::task::Waker; -use intrusive_collections::{ - intrusive_adapter, - linked_list::{LinkedList, LinkedListOps}, - DefaultLinkOps, LinkOps, -}; +use intrusive_collections::intrusive_adapter; +use intrusive_collections::linked_list::LinkedList; +use intrusive_collections::linked_list::LinkedListOps; +use intrusive_collections::DefaultLinkOps; +use intrusive_collections::LinkOps; use super::super::sync::SpinLock; diff --git a/cros_async/src/sys/unix.rs b/cros_async/src/sys/unix.rs index 04bfb2662..e0c2c7881 100644 --- a/cros_async/src/sys/unix.rs +++ b/cros_async/src/sys/unix.rs @@ -15,9 +15,11 @@ pub use uring_executor::URingExecutor; pub use uring_source::UringSource; mod timer; -use crate::{Error, Result}; use std::future::Future; +use crate::Error; +use crate::Result; + /// Creates a URingExecutor that runs one future to completion. /// /// # Example diff --git a/cros_async/src/sys/unix/async_types.rs b/cros_async/src/sys/unix/async_types.rs index bb7ee88dc..6b12d271b 100644 --- a/cros_async/src/sys/unix/async_types.rs +++ b/cros_async/src/sys/unix/async_types.rs @@ -2,12 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{Executor, IoSourceExt}; -use base::{Tube, TubeResult}; -use serde::{de::DeserializeOwned, Serialize}; use std::io; use std::ops::Deref; +use base::Tube; +use base::TubeResult; +use serde::de::DeserializeOwned; +use serde::Serialize; + +use crate::Executor; +use crate::IoSourceExt; + pub struct AsyncTube { inner: Box>, } diff --git a/cros_async/src/sys/unix/event.rs b/cros_async/src/sys/unix/event.rs index 9a95dbe16..165aa62b0 100644 --- a/cros_async/src/sys/unix/event.rs +++ b/cros_async/src/sys/unix/event.rs @@ -2,11 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#[cfg(test)] -use super::{FdExecutor, URingExecutor}; -use crate::{AsyncResult, EventAsync, Executor}; use base::Event; +#[cfg(test)] +use super::FdExecutor; +#[cfg(test)] +use super::URingExecutor; +use crate::AsyncResult; +use crate::EventAsync; +use crate::Executor; + impl EventAsync { pub fn new(event: Event, ex: &Executor) -> AsyncResult { ex.async_from(event) @@ -32,7 +37,6 @@ impl EventAsync { #[cfg(test)] mod tests { use super::*; - use crate::sys::unix::uring_executor::use_uring; #[test] diff --git a/cros_async/src/sys/unix/executor.rs b/cros_async/src/sys/unix/executor.rs index 7816a9edc..112793730 100644 --- a/cros_async/src/sys/unix/executor.rs +++ b/cros_async/src/sys/unix/executor.rs @@ -5,15 +5,18 @@ use std::future::Future; use async_task::Task; +use base::AsRawDescriptors; +use base::RawDescriptor; -use base::{AsRawDescriptors, RawDescriptor}; - -use super::{ - poll_source::Error as PollError, uring_executor::use_uring, FdExecutor, PollSource, - URingExecutor, UringSource, -}; - -use crate::{AsyncResult, IntoAsync, IoSourceExt}; +use super::poll_source::Error as PollError; +use super::uring_executor::use_uring; +use super::FdExecutor; +use super::PollSource; +use super::URingExecutor; +use super::UringSource; +use crate::AsyncResult; +use crate::IntoAsync; +use crate::IoSourceExt; pub(crate) fn async_uring_from<'a, F: IntoAsync + Send + 'a>( f: F, diff --git a/cros_async/src/sys/unix/fd_executor.rs b/cros_async/src/sys/unix/fd_executor.rs index 53db34e68..03c79eaf8 100644 --- a/cros_async/src/sys/unix/fd_executor.rs +++ b/cros_async/src/sys/unix/fd_executor.rs @@ -9,24 +9,30 @@ //! `FdExecutor` is meant to be used with the `futures-rs` crate that provides combinators and //! utility functions to combine futures. -use std::{ - fs::File, - future::Future, - io, mem, - os::unix::io::{FromRawFd, RawFd}, - pin::Pin, - sync::{ - atomic::{AtomicI32, Ordering}, - Arc, Weak, - }, - task::{Context, Poll, Waker}, -}; +use std::fs::File; +use std::future::Future; +use std::io; +use std::mem; +use std::os::unix::io::FromRawFd; +use std::os::unix::io::RawFd; +use std::pin::Pin; +use std::sync::atomic::AtomicI32; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::sync::Weak; +use std::task::Context; +use std::task::Poll; +use std::task::Waker; use async_task::Task; -use base::{ - add_fd_flags, warn, AsRawDescriptor, AsRawDescriptors, Event, EventType, RawDescriptor, - WaitContext, -}; +use base::add_fd_flags; +use base::warn; +use base::AsRawDescriptor; +use base::AsRawDescriptors; +use base::Event; +use base::EventType; +use base::RawDescriptor; +use base::WaitContext; use futures::task::noop_waker; use pin_utils::pin_mut; use remain::sorted; @@ -34,11 +40,11 @@ use slab::Slab; use sync::Mutex; use thiserror::Error as ThisError; -use crate::{ - queue::RunnableQueue, - waker::{new_waker, WakerToken, WeakWake}, - BlockingPool, -}; +use crate::queue::RunnableQueue; +use crate::waker::new_waker; +use crate::waker::WakerToken; +use crate::waker::WeakWake; +use crate::BlockingPool; #[sorted] #[derive(Debug, ThisError)] @@ -576,11 +582,10 @@ unsafe fn dup_fd(fd: RawFd) -> Result { #[cfg(test)] mod test { - use std::{ - cell::RefCell, - io::{Read, Write}, - rc::Rc, - }; + use std::cell::RefCell; + use std::io::Read; + use std::io::Write; + use std::rc::Rc; use futures::future::Either; diff --git a/cros_async/src/sys/unix/poll_source.rs b/cros_async/src/sys/unix/poll_source.rs index fcfbbbffa..6699d0684 100644 --- a/cros_async/src/sys/unix/poll_source.rs +++ b/cros_async/src/sys/unix/poll_source.rs @@ -5,25 +5,28 @@ //! A wrapped IO source that uses FdExecutor to drive asynchronous completion. Used from //! `IoSourceExt::new` when uring isn't available in the kernel. -use std::{ - io, - ops::{Deref, DerefMut}, - sync::Arc, -}; +use std::io; +use std::ops::Deref; +use std::ops::DerefMut; +use std::sync::Arc; use async_trait::async_trait; +use base::AsRawDescriptor; use data_model::VolatileSlice; use remain::sorted; use thiserror::Error as ThisError; -use super::fd_executor::{ - FdExecutor, RegisteredSource, {self}, -}; -use crate::{ - mem::{BackingMemory, MemRegion}, - AllocateMode, AsyncError, AsyncResult, IoSourceExt, ReadAsync, WriteAsync, -}; -use base::AsRawDescriptor; +use super::fd_executor::FdExecutor; +use super::fd_executor::RegisteredSource; +use super::fd_executor::{self}; +use crate::mem::BackingMemory; +use crate::mem::MemRegion; +use crate::AllocateMode; +use crate::AsyncError; +use crate::AsyncResult; +use crate::IoSourceExt; +use crate::ReadAsync; +use crate::WriteAsync; #[sorted] #[derive(ThisError, Debug)] @@ -369,10 +372,9 @@ impl IoSourceExt for PollSource { #[cfg(test)] mod tests { - use std::{ - fs::{File, OpenOptions}, - path::PathBuf, - }; + use std::fs::File; + use std::fs::OpenOptions; + use std::path::PathBuf; use super::*; diff --git a/cros_async/src/sys/unix/timer.rs b/cros_async/src/sys/unix/timer.rs index 22457de4b..c563033cd 100644 --- a/cros_async/src/sys/unix/timer.rs +++ b/cros_async/src/sys/unix/timer.rs @@ -5,10 +5,14 @@ // For the moment, the only platform specific code is related to tests. #![cfg(test)] -use super::{FdExecutor, URingExecutor}; -use crate::{sys::unix::executor, AsyncResult, TimerAsync}; use base::Timer; +use super::FdExecutor; +use super::URingExecutor; +use crate::sys::unix::executor; +use crate::AsyncResult; +use crate::TimerAsync; + impl TimerAsync { pub(crate) fn new_poll(timer: Timer, ex: &FdExecutor) -> AsyncResult { executor::async_poll_from(timer, ex).map(|io_source| TimerAsync { io_source }) @@ -20,9 +24,12 @@ impl TimerAsync { } mod tests { + use std::time::Duration; + use std::time::Instant; + use super::*; - use crate::{sys::unix::uring_executor::use_uring, Executor}; - use std::time::{Duration, Instant}; + use crate::sys::unix::uring_executor::use_uring; + use crate::Executor; #[test] fn timer() { diff --git a/cros_async/src/sys/unix/uring_executor.rs b/cros_async/src/sys/unix/uring_executor.rs index 3f6b306a9..355499302 100644 --- a/cros_async/src/sys/unix/uring_executor.rs +++ b/cros_async/src/sys/unix/uring_executor.rs @@ -51,25 +51,32 @@ //! ensures that only the kernel is allowed to access the `Vec` and wraps the the `Vec` in an Arc to //! ensure it lives long enough. -use std::{ - convert::TryInto, - ffi::CStr, - fs::File, - future::Future, - io, - mem::{self, MaybeUninit}, - os::unix::io::{FromRawFd, RawFd}, - pin::Pin, - sync::{ - atomic::{AtomicI32, Ordering}, - Arc, Weak, - }, - task::{Context, Poll, Waker}, - thread::{self, ThreadId}, -}; +use std::convert::TryInto; +use std::ffi::CStr; +use std::fs::File; +use std::future::Future; +use std::io; +use std::mem::MaybeUninit; +use std::mem::{self}; +use std::os::unix::io::FromRawFd; +use std::os::unix::io::RawFd; +use std::pin::Pin; +use std::sync::atomic::AtomicI32; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::sync::Weak; +use std::task::Context; +use std::task::Poll; +use std::task::Waker; +use std::thread::ThreadId; +use std::thread::{self}; use async_task::Task; -use base::{trace, warn, AsRawDescriptor, EventType, RawDescriptor}; +use base::trace; +use base::warn; +use base::AsRawDescriptor; +use base::EventType; +use base::RawDescriptor; use futures::task::noop_waker; use io_uring::URingContext; use once_cell::sync::Lazy; @@ -79,12 +86,13 @@ use slab::Slab; use sync::Mutex; use thiserror::Error as ThisError; -use crate::{ - mem::{BackingMemory, MemRegion}, - queue::RunnableQueue, - waker::{new_waker, WakerToken, WeakWake}, - BlockingPool, -}; +use crate::mem::BackingMemory; +use crate::mem::MemRegion; +use crate::queue::RunnableQueue; +use crate::waker::new_waker; +use crate::waker::WakerToken; +use crate::waker::WeakWake; +use crate::BlockingPool; #[sorted] #[derive(Debug, ThisError)] @@ -950,17 +958,20 @@ impl Drop for PendingOperation { #[cfg(test)] mod tests { - use std::{ - future::Future, - io::{Read, Write}, - mem, - pin::Pin, - task::{Context, Poll}, - }; + use std::future::Future; + use std::io::Read; + use std::io::Write; + use std::mem; + use std::pin::Pin; + use std::task::Context; + use std::task::Poll; + + use futures::executor::block_on; use super::*; - use crate::mem::{BackingMemory, MemRegion, VecIoWrapper}; - use futures::executor::block_on; + use crate::mem::BackingMemory; + use crate::mem::MemRegion; + use crate::mem::VecIoWrapper; // A future that returns ready when the uring queue is empty. struct UringQueueEmpty<'a> { diff --git a/cros_async/src/sys/unix/uring_source.rs b/cros_async/src/sys/unix/uring_source.rs index 6186c2fef..ea537e14b 100644 --- a/cros_async/src/sys/unix/uring_source.rs +++ b/cros_async/src/sys/unix/uring_source.rs @@ -2,22 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - convert::TryInto, - io, - ops::{Deref, DerefMut}, - sync::Arc, -}; +use std::convert::TryInto; +use std::io; +use std::ops::Deref; +use std::ops::DerefMut; +use std::sync::Arc; use async_trait::async_trait; - -use super::uring_executor::{Error, RegisteredSource, Result, URingExecutor}; -use crate::{ - mem::{BackingMemory, MemRegion, VecIoWrapper}, - AllocateMode, AsyncError, AsyncResult, ReadAsync, WriteAsync, -}; use base::AsRawDescriptor; +use super::uring_executor::Error; +use super::uring_executor::RegisteredSource; +use super::uring_executor::Result; +use super::uring_executor::URingExecutor; +use crate::mem::BackingMemory; +use crate::mem::MemRegion; +use crate::mem::VecIoWrapper; +use crate::AllocateMode; +use crate::AsyncError; +use crate::AsyncResult; +use crate::ReadAsync; +use crate::WriteAsync; + /// `UringSource` wraps FD backed IO sources for use with io_uring. It is a thin wrapper around /// registering an IO source with the uring that provides an `IoSource` implementation. /// Most useful functions are provided by 'IoSourceExt'. @@ -220,15 +226,15 @@ impl DerefMut for UringSource { #[cfg(test)] mod tests { - use std::{ - fs::{File, OpenOptions}, - path::PathBuf, - }; - - use super::super::{uring_executor::use_uring, UringSource}; - use crate::io_ext::{ReadAsync, WriteAsync}; + use std::fs::File; + use std::fs::OpenOptions; + use std::path::PathBuf; + use super::super::uring_executor::use_uring; + use super::super::UringSource; use super::*; + use crate::io_ext::ReadAsync; + use crate::io_ext::WriteAsync; #[test] fn read_to_mem() { @@ -236,10 +242,12 @@ mod tests { return; } - use crate::mem::VecIoWrapper; use std::io::Write; + use tempfile::tempfile; + use crate::mem::VecIoWrapper; + let ex = URingExecutor::new().unwrap(); // Use guest memory as a test file, it implements AsRawDescriptor. let mut source = tempfile().unwrap(); diff --git a/cros_async/src/sys/windows.rs b/cros_async/src/sys/windows.rs index 8fe7ef672..ae87c1c82 100644 --- a/cros_async/src/sys/windows.rs +++ b/cros_async/src/sys/windows.rs @@ -9,15 +9,16 @@ pub mod handle_executor; pub mod handle_source; mod timer; pub mod wait_for_handle; -pub(crate) use wait_for_handle::WaitForHandle; -pub use { - handle_executor::HandleExecutor, - handle_source::{HandleSource, HandleWrapper}, -}; - -use crate::{Error, Result}; use std::future::Future; +pub use handle_executor::HandleExecutor; +pub use handle_source::HandleSource; +pub use handle_source::HandleWrapper; +pub(crate) use wait_for_handle::WaitForHandle; + +use crate::Error; +use crate::Result; + pub fn run_one_handle(fut: F) -> Result { let ex = HandleExecutor::new(); ex.run_until(fut).map_err(Error::HandleExecutor) diff --git a/cros_async/src/sys/windows/async_types.rs b/cros_async/src/sys/windows/async_types.rs index ca306dd57..bd41f6faa 100644 --- a/cros_async/src/sys/windows/async_types.rs +++ b/cros_async/src/sys/windows/async_types.rs @@ -2,12 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::HandleWrapper; -use crate::{unblock, Executor}; -use base::{AsRawDescriptor, Descriptor, Tube, TubeError, TubeResult}; -use serde::{de::DeserializeOwned, Serialize}; use std::io; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; +use std::sync::Mutex; + +use base::AsRawDescriptor; +use base::Descriptor; +use base::Tube; +use base::TubeError; +use base::TubeResult; +use serde::de::DeserializeOwned; +use serde::Serialize; + +use super::HandleWrapper; +use crate::unblock; +use crate::Executor; pub struct AsyncTube { inner: Arc>, diff --git a/cros_async/src/sys/windows/event.rs b/cros_async/src/sys/windows/event.rs index c44b5357c..4e4e50a8a 100644 --- a/cros_async/src/sys/windows/event.rs +++ b/cros_async/src/sys/windows/event.rs @@ -2,8 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{AsyncError, AsyncResult, EventAsync, Executor}; -use base::{Event, EventExt}; +use base::Event; +use base::EventExt; + +use crate::AsyncError; +use crate::AsyncResult; +use crate::EventAsync; +use crate::Executor; impl EventAsync { pub fn new(event: Event, ex: &Executor) -> AsyncResult { diff --git a/cros_async/src/sys/windows/executor.rs b/cros_async/src/sys/windows/executor.rs index 8534bbdbc..66f02f930 100644 --- a/cros_async/src/sys/windows/executor.rs +++ b/cros_async/src/sys/windows/executor.rs @@ -6,8 +6,11 @@ use std::future::Future; use async_task::Task; -use super::{HandleExecutor, HandleSource}; -use crate::{AsyncResult, IntoAsync, IoSourceExt}; +use super::HandleExecutor; +use super::HandleSource; +use crate::AsyncResult; +use crate::IntoAsync; +use crate::IoSourceExt; /// Creates a concrete `IoSourceExt` using the handle_executor. pub(crate) fn async_handle_from<'a, F: IntoAsync + 'a + Send>( diff --git a/cros_async/src/sys/windows/handle_executor.rs b/cros_async/src/sys/windows/handle_executor.rs index 0afa62629..f876b687a 100644 --- a/cros_async/src/sys/windows/handle_executor.rs +++ b/cros_async/src/sys/windows/handle_executor.rs @@ -2,21 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{ - queue::RunnableQueue, - waker::{new_waker, WeakWake}, -}; -use async_task::{Runnable, Task}; -use futures::task::{Context, Poll}; +use std::future::Future; +use std::io; +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Weak; + +use async_task::Runnable; +use async_task::Task; +use futures::task::Context; +use futures::task::Poll; use pin_utils::pin_mut; -use std::{ - future::Future, - io, - sync::{mpsc, Arc, Weak}, -}; -use sync::{Condvar, Mutex}; +use sync::Condvar; +use sync::Mutex; use thiserror::Error as ThisError; +use crate::queue::RunnableQueue; +use crate::waker::new_waker; +use crate::waker::WeakWake; + #[derive(Debug, ThisError)] pub enum Error { #[error("Failed to get future from executor run.")] @@ -161,7 +165,9 @@ impl WeakWake for RawExecutor { mod test { use super::*; const FUT_MSG: i32 = 5; - use futures::{channel::mpsc as fut_mpsc, SinkExt, StreamExt}; + use futures::channel::mpsc as fut_mpsc; + use futures::SinkExt; + use futures::StreamExt; #[test] fn run_future() { diff --git a/cros_async/src/sys/windows/handle_source.rs b/cros_async/src/sys/windows/handle_source.rs index 61aebeae8..8c39ec242 100644 --- a/cros_async/src/sys/windows/handle_source.rs +++ b/cros_async/src/sys/windows/handle_source.rs @@ -2,31 +2,44 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{ - io_ext::AllocateMode, - mem::{BackingMemory, MemRegion}, - AsyncError, AsyncResult, CancellableBlockingPool, IoSourceExt, ReadAsync, WriteAsync, -}; +use std::fs::File; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::Write; +use std::io::{self}; +use std::mem::ManuallyDrop; +use std::ptr::null_mut; +use std::sync::Arc; +use std::time::Duration; + use async_trait::async_trait; -use base::{ - error, warn, AsRawDescriptor, Descriptor, Error as SysUtilError, FileReadWriteAtVolatile, - FileReadWriteVolatile, FromRawDescriptor, PunchHole, WriteZeroesAt, -}; +use base::error; +use base::warn; +use base::AsRawDescriptor; +use base::Descriptor; +use base::Error as SysUtilError; +use base::FileReadWriteAtVolatile; +use base::FileReadWriteVolatile; +use base::FromRawDescriptor; +use base::PunchHole; +use base::WriteZeroesAt; use data_model::VolatileSlice; use smallvec::SmallVec; -use std::{ - fs::File, - io::{ - Read, Seek, SeekFrom, Write, {self}, - }, - mem::ManuallyDrop, - ptr::null_mut, - sync::Arc, - time::Duration, -}; use sync::Mutex; use thiserror::Error as ThisError; -use winapi::um::{ioapiset::CancelIoEx, processthreadsapi::GetCurrentThreadId}; +use winapi::um::ioapiset::CancelIoEx; +use winapi::um::processthreadsapi::GetCurrentThreadId; + +use crate::io_ext::AllocateMode; +use crate::mem::BackingMemory; +use crate::mem::MemRegion; +use crate::AsyncError; +use crate::AsyncResult; +use crate::CancellableBlockingPool; +use crate::IoSourceExt; +use crate::ReadAsync; +use crate::WriteAsync; #[derive(ThisError, Debug)] pub enum Error { @@ -413,11 +426,14 @@ impl IoSourceExt for HandleSource { #[cfg(test)] mod tests { + use std::fs; + + use tempfile::tempfile; + use tempfile::NamedTempFile; + use super::super::HandleExecutor; use super::*; use crate::mem::VecIoWrapper; - use std::fs; - use tempfile::{tempfile, NamedTempFile}; #[test] fn test_read_vec() { diff --git a/cros_async/src/sys/windows/timer.rs b/cros_async/src/sys/windows/timer.rs index 403bd8300..680e38b97 100644 --- a/cros_async/src/sys/windows/timer.rs +++ b/cros_async/src/sys/windows/timer.rs @@ -4,8 +4,11 @@ #[cfg(test)] mod test { - use crate::{Executor, TimerAsync}; - use std::time::{Duration, Instant}; + use std::time::Duration; + use std::time::Instant; + + use crate::Executor; + use crate::TimerAsync; #[test] fn timer() { diff --git a/cros_async/src/sys/windows/wait_for_handle.rs b/cros_async/src/sys/windows/wait_for_handle.rs index 6b95e68fa..8333917ab 100644 --- a/cros_async/src/sys/windows/wait_for_handle.rs +++ b/cros_async/src/sys/windows/wait_for_handle.rs @@ -2,34 +2,35 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::{error, warn, AsRawDescriptor, Descriptor}; -use std::{ - ffi::c_void, - future::Future, - marker::{PhantomData, PhantomPinned}, - pin::Pin, - ptr::null_mut, - sync::MutexGuard, - task::{Context, Poll, Waker}, -}; -use sync::Mutex; -use winapi::{ - shared::ntdef::FALSE, - um::{ - handleapi::INVALID_HANDLE_VALUE, - threadpoollegacyapiset::UnregisterWaitEx, - winbase::{RegisterWaitForSingleObject, INFINITE}, - winnt::{BOOLEAN, PVOID, WT_EXECUTEONLYONCE}, - }, -}; +use std::ffi::c_void; +use std::future::Future; +use std::marker::PhantomData; +use std::marker::PhantomPinned; +use std::pin::Pin; +use std::ptr::null_mut; +use std::sync::MutexGuard; +use std::task::Context; +use std::task::Poll; +use std::task::Waker; -use crate::{ - sys::windows::{ - handle_source::{Error, Result}, - HandleSource, - }, - IoSourceExt, -}; +use base::error; +use base::warn; +use base::AsRawDescriptor; +use base::Descriptor; +use sync::Mutex; +use winapi::shared::ntdef::FALSE; +use winapi::um::handleapi::INVALID_HANDLE_VALUE; +use winapi::um::threadpoollegacyapiset::UnregisterWaitEx; +use winapi::um::winbase::RegisterWaitForSingleObject; +use winapi::um::winbase::INFINITE; +use winapi::um::winnt::BOOLEAN; +use winapi::um::winnt::PVOID; +use winapi::um::winnt::WT_EXECUTEONLYONCE; + +use crate::sys::windows::handle_source::Error; +use crate::sys::windows::handle_source::Result; +use crate::sys::windows::HandleSource; +use crate::IoSourceExt; /// Inner state shared between the future struct & the kernel invoked waiter callback. struct WaitForHandleInner { @@ -241,17 +242,19 @@ unsafe fn unregister_wait(desc: Descriptor) { #[cfg(test)] mod tests { - use super::*; - use crate::{ - waker::{new_waker, WeakWake}, - EventAsync, Executor, - }; - use base::{thread::spawn_with_timeout, Event}; + use std::sync::Arc; + use std::sync::Weak; + use std::time::Duration; + + use base::thread::spawn_with_timeout; + use base::Event; use futures::pin_mut; - use std::{ - sync::{Arc, Weak}, - time::Duration, - }; + + use super::*; + use crate::waker::new_waker; + use crate::waker::WeakWake; + use crate::EventAsync; + use crate::Executor; struct FakeWaker {} impl WeakWake for FakeWaker { diff --git a/cros_async/src/timer.rs b/cros_async/src/timer.rs index dd688a63f..09955f89a 100644 --- a/cros_async/src/timer.rs +++ b/cros_async/src/timer.rs @@ -2,10 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{AsyncResult, Error, Executor, IntoAsync, IoSourceExt}; -use base::{Result as SysResult, Timer}; use std::time::Duration; +use base::Result as SysResult; +use base::Timer; + +use crate::AsyncResult; +use crate::Error; +use crate::Executor; +use crate::IntoAsync; +use crate::IoSourceExt; + /// An async version of base::Timer. pub struct TimerAsync { pub(crate) io_source: Box>, diff --git a/cros_async/src/waker.rs b/cros_async/src/waker.rs index 5daeb5771..02c9a5a2c 100644 --- a/cros_async/src/waker.rs +++ b/cros_async/src/waker.rs @@ -2,11 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - mem::{drop, ManuallyDrop}, - sync::Weak, - task::{RawWaker, RawWakerVTable, Waker}, -}; +use std::mem::drop; +use std::mem::ManuallyDrop; +use std::sync::Weak; +use std::task::RawWaker; +use std::task::RawWakerVTable; +use std::task::Waker; /// Wrapper around a usize used as a token to uniquely identify a pending waker. #[derive(Debug)] diff --git a/crosvm-fuzz/block_fuzzer.rs b/crosvm-fuzz/block_fuzzer.rs index 7fdee5159..ee39b228e 100644 --- a/crosvm-fuzz/block_fuzzer.rs +++ b/crosvm-fuzz/block_fuzzer.rs @@ -4,17 +4,25 @@ #![no_main] -use std::io::{Cursor, Read, Seek, SeekFrom}; +use std::io::Cursor; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; use std::mem::size_of; use std::sync::atomic::AtomicUsize; use std::sync::Arc; use base::Event; use cros_fuzz::fuzz_target; -use devices::virtio::{base_features, Block, Interrupt, Queue, VirtioDevice}; +use devices::virtio::base_features; +use devices::virtio::Block; +use devices::virtio::Interrupt; +use devices::virtio::Queue; +use devices::virtio::VirtioDevice; use devices::IrqLevelEvent; use hypervisor::ProtectionType; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; const MEM_SIZE: u64 = 256 * 1024 * 1024; const DESC_SIZE: u64 = 16; // Bytes in one virtio descriptor. diff --git a/crosvm-fuzz/fs_server_fuzzer.rs b/crosvm-fuzz/fs_server_fuzzer.rs index 5421dee3c..15630690d 100644 --- a/crosvm-fuzz/fs_server_fuzzer.rs +++ b/crosvm-fuzz/fs_server_fuzzer.rs @@ -9,9 +9,13 @@ mod fs_server_fuzzer { use std::convert::TryInto; use cros_fuzz::fuzz_target; - use devices::virtio::{create_descriptor_chain, DescriptorType, Reader, Writer}; + use devices::virtio::create_descriptor_chain; + use devices::virtio::DescriptorType; + use devices::virtio::Reader; + use devices::virtio::Writer; use fuse::fuzzing::fuzz_server; - use vm_memory::{GuestAddress, GuestMemory}; + use vm_memory::GuestAddress; + use vm_memory::GuestMemory; const MEM_SIZE: u64 = 256 * 1024 * 1024; const BUFFER_ADDR: GuestAddress = GuestAddress(0x100); diff --git a/crosvm-fuzz/qcow_fuzzer.rs b/crosvm-fuzz/qcow_fuzzer.rs index 23cba4e48..a86410702 100644 --- a/crosvm-fuzz/qcow_fuzzer.rs +++ b/crosvm-fuzz/qcow_fuzzer.rs @@ -4,14 +4,18 @@ #![no_main] +use std::io::Cursor; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::Write; +use std::mem::size_of; + use base::FileReadWriteAtVolatile; use cros_fuzz::fuzz_target; use data_model::VolatileSlice; use disk::QcowFile; -use std::io::{Cursor, Read, Seek, SeekFrom, Write}; -use std::mem::size_of; - // Take the first 64 bits of data as an address and the next 64 bits as data to // store there. The rest of the data is used as a qcow image. fuzz_target!(|bytes| { diff --git a/crosvm-fuzz/usb_descriptor_fuzzer.rs b/crosvm-fuzz/usb_descriptor_fuzzer.rs index a33e7c752..39e8c186a 100644 --- a/crosvm-fuzz/usb_descriptor_fuzzer.rs +++ b/crosvm-fuzz/usb_descriptor_fuzzer.rs @@ -5,7 +5,6 @@ #![no_main] use cros_fuzz::fuzz_target; - use usb_util::parse_usbfs_descriptors; fuzz_target!(|data| { diff --git a/crosvm-fuzz/virtqueue_fuzzer.rs b/crosvm-fuzz/virtqueue_fuzzer.rs index cf4f6cae7..480d30dc3 100644 --- a/crosvm-fuzz/virtqueue_fuzzer.rs +++ b/crosvm-fuzz/virtqueue_fuzzer.rs @@ -8,9 +8,12 @@ use std::mem::size_of; use cros_fuzz::fuzz_target; use cros_fuzz::rand::FuzzRng; -use devices::virtio::{DescriptorChain, Queue}; -use rand::{Rng, RngCore}; -use vm_memory::{GuestAddress, GuestMemory}; +use devices::virtio::DescriptorChain; +use devices::virtio::Queue; +use rand::Rng; +use rand::RngCore; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; const MAX_QUEUE_SIZE: u16 = 256; const MEM_SIZE: u64 = 1024 * 1024; diff --git a/crosvm-fuzz/zimage_fuzzer.rs b/crosvm-fuzz/zimage_fuzzer.rs index 79d011034..f895e08b1 100644 --- a/crosvm-fuzz/zimage_fuzzer.rs +++ b/crosvm-fuzz/zimage_fuzzer.rs @@ -4,12 +4,13 @@ #![no_main] -use cros_fuzz::fuzz_target; -use vm_memory::{GuestAddress, GuestMemory}; - use std::fs::File; use std::io::Write; +use cros_fuzz::fuzz_target; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; + const MEM_SIZE: u64 = 256 * 1024 * 1024; fn make_elf_bin(elf_bytes: &[u8]) -> File { diff --git a/crosvm_control/build.rs b/crosvm_control/build.rs index f21100099..19a023f31 100644 --- a/crosvm_control/build.rs +++ b/crosvm_control/build.rs @@ -2,12 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use cbindgen::Config; -use cbindgen::Language; use std::env; use std::path::PathBuf; -use anyhow::{Context, Result}; +use anyhow::Context; +use anyhow::Result; +use cbindgen::Config; +use cbindgen::Language; static COPYRIGHT_CLAUSE: &str = "// Copyright 2022 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be diff --git a/crosvm_control/src/lib.rs b/crosvm_control/src/lib.rs index 98631a9fc..64049670b 100644 --- a/crosvm_control/src/lib.rs +++ b/crosvm_control/src/lib.rs @@ -13,17 +13,24 @@ //! For more information see: //! -use std::convert::{TryFrom, TryInto}; +use std::convert::TryFrom; +use std::convert::TryInto; use std::ffi::CStr; use std::panic::catch_unwind; -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::path::PathBuf; -use libc::{c_char, ssize_t}; - -use vm_control::{ - client::*, BalloonControlCommand, BalloonStats, DiskControlCommand, UsbControlAttachedDevice, - UsbControlResult, VmRequest, VmResponse, USB_CONTROL_MAX_PORTS, -}; +use libc::c_char; +use libc::ssize_t; +use vm_control::client::*; +use vm_control::BalloonControlCommand; +use vm_control::BalloonStats; +use vm_control::DiskControlCommand; +use vm_control::UsbControlAttachedDevice; +use vm_control::UsbControlResult; +use vm_control::VmRequest; +use vm_control::VmResponse; +use vm_control::USB_CONTROL_MAX_PORTS; fn validate_socket_path(socket_path: *const c_char) -> Option { if !socket_path.is_null() { diff --git a/crosvm_plugin/src/lib.rs b/crosvm_plugin/src/lib.rs index 4a074506d..8b5e6dc33 100644 --- a/crosvm_plugin/src/lib.rs +++ b/crosvm_plugin/src/lib.rs @@ -18,32 +18,53 @@ use std::env; use std::fs::File; -use std::io::{IoSlice, IoSliceMut, Read, Write}; -use std::mem::{size_of, swap}; -use std::os::raw::{c_int, c_void}; -use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; +use std::io::IoSlice; +use std::io::IoSliceMut; +use std::io::Read; +use std::io::Write; +use std::mem::size_of; +use std::mem::swap; +use std::os::raw::c_int; +use std::os::raw::c_void; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::FromRawFd; +use std::os::unix::io::IntoRawFd; +use std::os::unix::io::RawFd; use std::os::unix::net::UnixDatagram; -use std::ptr::{self, null_mut}; +use std::ptr::null_mut; +use std::ptr::{self}; use std::result; use std::slice; -use std::slice::{from_raw_parts, from_raw_parts_mut}; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::slice::from_raw_parts; +use std::slice::from_raw_parts_mut; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; use std::sync::Arc; -use libc::{E2BIG, EINVAL, ENOENT, ENOTCONN, EPROTO}; - -use protobuf::{Message, ProtobufEnum, RepeatedField}; - use base::ScmSocket; - use kvm::dirty_log_bitmap_size; - -use kvm_sys::{ - kvm_clock_data, kvm_cpuid_entry2, kvm_debugregs, kvm_fpu, kvm_ioapic_state, kvm_lapic_state, - kvm_mp_state, kvm_msr_entry, kvm_pic_state, kvm_pit_state2, kvm_regs, kvm_sregs, - kvm_vcpu_events, kvm_xcrs, -}; - +use kvm_sys::kvm_clock_data; +use kvm_sys::kvm_cpuid_entry2; +use kvm_sys::kvm_debugregs; +use kvm_sys::kvm_fpu; +use kvm_sys::kvm_ioapic_state; +use kvm_sys::kvm_lapic_state; +use kvm_sys::kvm_mp_state; +use kvm_sys::kvm_msr_entry; +use kvm_sys::kvm_pic_state; +use kvm_sys::kvm_pit_state2; +use kvm_sys::kvm_regs; +use kvm_sys::kvm_sregs; +use kvm_sys::kvm_vcpu_events; +use kvm_sys::kvm_xcrs; +use libc::E2BIG; +use libc::EINVAL; +use libc::ENOENT; +use libc::ENOTCONN; +use libc::EPROTO; +use protobuf::Message; +use protobuf::ProtobufEnum; +use protobuf::RepeatedField; use protos::plugin::*; #[cfg(feature = "stats")] diff --git a/crosvm_plugin/src/stats.rs b/crosvm_plugin/src/stats.rs index 0406e2fc2..832f21169 100644 --- a/crosvm_plugin/src/stats.rs +++ b/crosvm_plugin/src/stats.rs @@ -2,9 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::Stat; use std::time::Instant; +use crate::Stat; + #[derive(Clone, Copy)] struct StatEntry { count: u64, diff --git a/devices/src/acpi.rs b/devices/src/acpi.rs index 2ecffe478..1eccf59c2 100644 --- a/devices/src/acpi.rs +++ b/devices/src/acpi.rs @@ -2,19 +2,37 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::pci::CrosvmDeviceId; -use crate::{BusAccessInfo, BusDevice, BusResumeDevice, DeviceId, IrqLevelEvent}; -use acpi_tables::{aml, aml::Aml}; -use base::{error, warn, Error as SysError, Event, EventToken, SendTube, VmEventType, WaitContext}; use std::collections::BTreeMap; +#[cfg(feature = "direct")] +use std::fs; +#[cfg(feature = "direct")] +use std::io::Error as IoError; +#[cfg(feature = "direct")] +use std::path::PathBuf; use std::sync::Arc; use std::thread; + +use acpi_tables::aml; +use acpi_tables::aml::Aml; +use base::error; +use base::warn; +use base::Error as SysError; +use base::Event; +use base::EventToken; +use base::SendTube; +use base::VmEventType; +use base::WaitContext; use sync::Mutex; use thiserror::Error; -use vm_control::{GpeNotify, PmResource}; +use vm_control::GpeNotify; +use vm_control::PmResource; -#[cfg(feature = "direct")] -use {std::fs, std::io::Error as IoError, std::path::PathBuf}; +use crate::pci::CrosvmDeviceId; +use crate::BusAccessInfo; +use crate::BusDevice; +use crate::BusResumeDevice; +use crate::DeviceId; +use crate::IrqLevelEvent; #[derive(Error, Debug)] pub enum ACPIPMError { diff --git a/devices/src/bat.rs b/devices/src/bat.rs index a321a0c96..c93cc617c 100644 --- a/devices/src/bat.rs +++ b/devices/src/bat.rs @@ -2,17 +2,32 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{pci::CrosvmDeviceId, BusAccessInfo, BusDevice, DeviceId, IrqLevelEvent}; -use acpi_tables::{aml, aml::Aml}; -use base::{error, warn, AsRawDescriptor, Event, EventToken, RawDescriptor, Tube, WaitContext}; +use std::sync::Arc; +use std::thread; + +use acpi_tables::aml; +use acpi_tables::aml::Aml; +use base::error; +use base::warn; +use base::AsRawDescriptor; +use base::Event; +use base::EventToken; +use base::RawDescriptor; +use base::Tube; +use base::WaitContext; #[cfg(unix)] use power_monitor::CreatePowerMonitorFn; use remain::sorted; -use std::sync::Arc; -use std::thread; use sync::Mutex; use thiserror::Error; -use vm_control::{BatControlCommand, BatControlResult}; +use vm_control::BatControlCommand; +use vm_control::BatControlResult; + +use crate::pci::CrosvmDeviceId; +use crate::BusAccessInfo; +use crate::BusDevice; +use crate::DeviceId; +use crate::IrqLevelEvent; /// Errors for battery devices. #[sorted] diff --git a/devices/src/bus.rs b/devices/src/bus.rs index e937efff5..f0f6a71e0 100644 --- a/devices/src/bus.rs +++ b/devices/src/bus.rs @@ -4,22 +4,30 @@ //! Handles routing to devices in an address space. -use std::cmp::{Ord, Ordering, PartialEq, PartialOrd}; +use std::cmp::Ord; +use std::cmp::Ordering; +use std::cmp::PartialEq; +use std::cmp::PartialOrd; use std::collections::btree_map::BTreeMap; use std::fmt; use std::result; use std::sync::Arc; use remain::sorted; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; use sync::Mutex; use thiserror::Error; +#[cfg(feature = "stats")] +use crate::bus_stats::BusOperation; +#[cfg(feature = "stats")] +use crate::BusStatistics; +use crate::DeviceId; +use crate::PciAddress; +use crate::PciDevice; #[cfg(unix)] use crate::VfioPlatformDevice; -#[cfg(feature = "stats")] -use crate::{bus_stats::BusOperation, BusStatistics}; -use crate::{DeviceId, PciAddress, PciDevice}; /// Information about how a device was accessed. #[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] @@ -520,9 +528,8 @@ impl Bus { #[cfg(test)] mod tests { - use crate::pci::CrosvmDeviceId; - use super::*; + use crate::pci::CrosvmDeviceId; struct DummyDevice; impl BusDevice for DummyDevice { diff --git a/devices/src/bus_stats.rs b/devices/src/bus_stats.rs index 09172acb7..d9ea1134a 100644 --- a/devices/src/bus_stats.rs +++ b/devices/src/bus_stats.rs @@ -5,7 +5,8 @@ use std::cmp::Reverse; use std::fmt; use std::sync::Arc; -use std::time::{Duration, Instant}; +use std::time::Duration; +use std::time::Instant; use sync::Mutex; diff --git a/devices/src/cmos.rs b/devices/src/cmos.rs index e08114d4a..dfd3a769e 100644 --- a/devices/src/cmos.rs +++ b/devices/src/cmos.rs @@ -2,12 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::gmtime_secure; -use libc::{time, time_t, tm}; use std::cmp::min; use std::mem; -use crate::{pci::CrosvmDeviceId, BusAccessInfo, BusDevice, DeviceId}; +use base::gmtime_secure; +use libc::time; +use libc::time_t; +use libc::tm; + +use crate::pci::CrosvmDeviceId; +use crate::BusAccessInfo; +use crate::BusDevice; +use crate::DeviceId; const INDEX_MASK: u8 = 0x7f; const INDEX_OFFSET: u64 = 0x0; diff --git a/devices/src/debugcon.rs b/devices/src/debugcon.rs index d9eb74706..dae1a9838 100644 --- a/devices/src/debugcon.rs +++ b/devices/src/debugcon.rs @@ -2,16 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::io::{self, Write}; +use std::io::Write; +use std::io::{self}; +use base::error; #[cfg(windows)] use base::named_pipes; -use base::{error, Event, FileSync, RawDescriptor, Result}; +use base::Event; +use base::FileSync; +use base::RawDescriptor; +use base::Result; use hypervisor::ProtectionType; use crate::pci::CrosvmDeviceId; use crate::serial_device::SerialInput; -use crate::{BusAccessInfo, BusDevice, DeviceId, SerialDevice}; +use crate::BusAccessInfo; +use crate::BusDevice; +use crate::DeviceId; +use crate::SerialDevice; const BOCHS_DEBUGCON_READBACK: u8 = 0xe9; @@ -82,12 +90,13 @@ impl Debugcon { #[cfg(test)] mod tests { - use super::*; use std::io; use std::sync::Arc; use sync::Mutex; + use super::*; + const ADDR: BusAccessInfo = BusAccessInfo { offset: 0, address: 0, diff --git a/devices/src/direct_io.rs b/devices/src/direct_io.rs index 536e9b65f..4bddd30bc 100644 --- a/devices/src/direct_io.rs +++ b/devices/src/direct_io.rs @@ -2,18 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::pci::CrosvmDeviceId; -use crate::{BusAccessInfo, BusDevice, BusDeviceSync, BusRange, DeviceId}; -use base::{ - error, pagesize, round_up_to_page_size, MemoryMapping, MemoryMappingBuilder, Protection, -}; -use std::fs::{File, OpenOptions}; +use std::fs::File; +use std::fs::OpenOptions; use std::io; use std::os::unix::fs::OpenOptionsExt; use std::os::unix::prelude::FileExt; use std::path::Path; use std::sync::Mutex; +use base::error; +use base::pagesize; +use base::round_up_to_page_size; +use base::MemoryMapping; +use base::MemoryMappingBuilder; +use base::Protection; + +use crate::pci::CrosvmDeviceId; +use crate::BusAccessInfo; +use crate::BusDevice; +use crate::BusDeviceSync; +use crate::BusRange; +use crate::DeviceId; + pub struct DirectIo { dev: Mutex, read_only: bool, diff --git a/devices/src/direct_irq.rs b/devices/src/direct_irq.rs index 4e76d56ad..13ed3dccb 100644 --- a/devices/src/direct_irq.rs +++ b/devices/src/direct_irq.rs @@ -2,17 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::{ioctl_with_ref, AsRawDescriptor, Event, RawDescriptor}; -use data_model::vec_with_array_field; -use std::fs::{File, OpenOptions}; +use std::fs::File; +use std::fs::OpenOptions; use std::io; use std::mem::size_of; +use base::ioctl_with_ref; +use base::AsRawDescriptor; +use base::Event; +use base::RawDescriptor; +use data_model::vec_with_array_field; use remain::sorted; use thiserror::Error; use vfio_sys::*; -use crate::{IrqEdgeEvent, IrqLevelEvent}; +use crate::IrqEdgeEvent; +use crate::IrqLevelEvent; #[sorted] #[derive(Error, Debug)] diff --git a/devices/src/i8042.rs b/devices/src/i8042.rs index 9273f319f..f36bba3e9 100644 --- a/devices/src/i8042.rs +++ b/devices/src/i8042.rs @@ -2,9 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::{error, SendTube, VmEventType}; +use base::error; +use base::SendTube; +use base::VmEventType; -use crate::{pci::CrosvmDeviceId, BusAccessInfo, BusDevice, DeviceId}; +use crate::pci::CrosvmDeviceId; +use crate::BusAccessInfo; +use crate::BusDevice; +use crate::DeviceId; /// A i8042 PS/2 controller that emulates just enough to shutdown the machine. pub struct I8042Device { diff --git a/devices/src/irq_event.rs b/devices/src/irq_event.rs index 2eb650063..74600282f 100644 --- a/devices/src/irq_event.rs +++ b/devices/src/irq_event.rs @@ -2,7 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::{AsRawDescriptor, AsRawDescriptors, Event, RawDescriptor, Result}; +use base::AsRawDescriptor; +use base::AsRawDescriptors; +use base::Event; +use base::RawDescriptor; +use base::Result; /// A structure suitable for implementing edge triggered interrupts in device backends. pub struct IrqEdgeEvent(Event); diff --git a/devices/src/irqchip/apic.rs b/devices/src/irqchip/apic.rs index d25822a65..a1332cf93 100644 --- a/devices/src/irqchip/apic.rs +++ b/devices/src/irqchip/apic.rs @@ -14,8 +14,10 @@ // * external interrupts -- these are handled by querying `Pic` separately in // `UserspaceIrqChip::inject_interrupts` -use std::convert::{TryFrom, TryInto}; -use std::time::{Duration, Instant}; +use std::convert::TryFrom; +use std::convert::TryInto; +use std::time::Duration; +use std::time::Instant; #[cfg(test)] use base::FakeTimer as Timer; @@ -24,10 +26,15 @@ use base::Timer; // TODO(srichman): Rate-limit error messages? use base::{error, warn}; use bit_field::*; -use hypervisor::{ - DeliveryMode, DeliveryStatus, DestinationMode, LapicState, Level, MPState, MsiAddressMessage, - MsiDataMessage, TriggerMode, -}; +use hypervisor::DeliveryMode; +use hypervisor::DeliveryStatus; +use hypervisor::DestinationMode; +use hypervisor::LapicState; +use hypervisor::Level; +use hypervisor::MPState; +use hypervisor::MsiAddressMessage; +use hypervisor::MsiDataMessage; +use hypervisor::TriggerMode; pub type Vector = u8; @@ -895,10 +902,11 @@ mod tests { use std::mem; use std::sync::Arc; - use super::*; use base::FakeClock; use sync::Mutex; + use super::*; + #[test] fn struct_size() { assert_eq!(4, mem::size_of::()); diff --git a/devices/src/irqchip/ioapic.rs b/devices/src/irqchip/ioapic.rs index 3e828a380..437288d76 100644 --- a/devices/src/irqchip/ioapic.rs +++ b/devices/src/irqchip/ioapic.rs @@ -6,18 +6,31 @@ // See https://www.intel.com/content/dam/doc/datasheet/io-controller-hub-10-family-datasheet.pdf // for a specification. +use base::error; +use base::warn; +use base::Error; +use base::Event; +use base::Result; +use base::Tube; +use base::TubeError; +use hypervisor::IoapicRedirectionTableEntry; +use hypervisor::IoapicState; +use hypervisor::MsiAddressMessage; +use hypervisor::MsiDataMessage; +use hypervisor::TriggerMode; +use hypervisor::MAX_IOAPIC_PINS; +use hypervisor::NUM_IOAPIC_PINS; +use remain::sorted; +use thiserror::Error; +use vm_control::VmIrqRequest; +use vm_control::VmIrqResponse; + use super::IrqEvent; use crate::bus::BusAccessInfo; use crate::pci::CrosvmDeviceId; -use crate::{BusDevice, DeviceId, IrqEventSource}; -use base::{error, warn, Error, Event, Result, Tube, TubeError}; -use hypervisor::{ - IoapicRedirectionTableEntry, IoapicState, MsiAddressMessage, MsiDataMessage, TriggerMode, - MAX_IOAPIC_PINS, NUM_IOAPIC_PINS, -}; -use remain::sorted; -use thiserror::Error; -use vm_control::{VmIrqRequest, VmIrqResponse}; +use crate::BusDevice; +use crate::DeviceId; +use crate::IrqEventSource; // ICH10 I/O APIC version: 0x20 const IOAPIC_VERSION_ID: u32 = 0x00000020; @@ -506,8 +519,11 @@ enum IoapicError { #[cfg(test)] mod tests { + use hypervisor::DeliveryMode; + use hypervisor::DeliveryStatus; + use hypervisor::DestinationMode; + use super::*; - use hypervisor::{DeliveryMode, DeliveryStatus, DestinationMode}; const DEFAULT_VECTOR: u8 = 0x3a; const DEFAULT_DESTINATION_ID: u8 = 0x5f; diff --git a/devices/src/irqchip/kvm/aarch64.rs b/devices/src/irqchip/kvm/aarch64.rs index 25c51a935..13ae86f68 100644 --- a/devices/src/irqchip/kvm/aarch64.rs +++ b/devices/src/irqchip/kvm/aarch64.rs @@ -3,14 +3,21 @@ // found in the LICENSE file. use std::sync::Arc; + +use base::errno_result; +use base::ioctl_with_ref; +use base::Result; +use base::SafeDescriptor; +use hypervisor::kvm::KvmVcpu; +use hypervisor::kvm::KvmVm; +use hypervisor::DeviceKind; +use hypervisor::IrqRoute; +use hypervisor::Vm; +use kvm_sys::*; use sync::Mutex; -use base::{errno_result, ioctl_with_ref, Result, SafeDescriptor}; -use hypervisor::kvm::{KvmVcpu, KvmVm}; -use hypervisor::{DeviceKind, IrqRoute, Vm}; -use kvm_sys::*; - -use crate::{IrqChip, IrqChipAArch64}; +use crate::IrqChip; +use crate::IrqChipAArch64; /// Default ARM routing table. AARCH64_GIC_NR_SPIS pins go to VGIC. fn kvm_default_irq_routing_table() -> Vec { diff --git a/devices/src/irqchip/kvm/mod.rs b/devices/src/irqchip/kvm/mod.rs index 54ba09697..b51ff968e 100644 --- a/devices/src/irqchip/kvm/mod.rs +++ b/devices/src/irqchip/kvm/mod.rs @@ -2,17 +2,27 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{Bus, IrqEdgeEvent, IrqEventSource, IrqLevelEvent}; -use base::{error, Error, Event, Result}; +use base::error; +use base::Error; +use base::Event; +use base::Result; use hypervisor::kvm::KvmVcpu; +use hypervisor::HypervisorCap; +use hypervisor::IrqRoute; +use hypervisor::MPState; +use hypervisor::Vcpu; #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] use hypervisor::VmAArch64; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use hypervisor::VmX86_64; -use hypervisor::{HypervisorCap, IrqRoute, MPState, Vcpu}; use kvm_sys::kvm_mp_state; use resources::SystemAllocator; +use crate::Bus; +use crate::IrqEdgeEvent; +use crate::IrqEventSource; +use crate::IrqLevelEvent; + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] mod x86_64; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] @@ -23,7 +33,10 @@ mod aarch64; #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] pub use aarch64::*; -use crate::{IrqChip, IrqChipCap, IrqEventIndex, VcpuRunState}; +use crate::IrqChip; +use crate::IrqChipCap; +use crate::IrqEventIndex; +use crate::VcpuRunState; /// This IrqChip only works with Kvm so we only implement it for KvmVcpu. impl IrqChip for KvmKernelIrqChip { @@ -203,16 +216,19 @@ impl IrqChip for KvmKernelIrqChip { #[cfg(test)] mod tests { - use hypervisor::kvm::{Kvm, KvmVm}; - use hypervisor::{MPState, ProtectionType, Vm}; - use vm_memory::GuestMemory; - - use crate::irqchip::{IrqChip, KvmKernelIrqChip}; - + use hypervisor::kvm::Kvm; + use hypervisor::kvm::KvmVm; + use hypervisor::MPState; + use hypervisor::ProtectionType; + use hypervisor::Vm; #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] use hypervisor::VmAArch64; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use hypervisor::VmX86_64; + use vm_memory::GuestMemory; + + use crate::irqchip::IrqChip; + use crate::irqchip::KvmKernelIrqChip; #[test] fn create_kvm_kernel_irqchip() { diff --git a/devices/src/irqchip/kvm/x86_64.rs b/devices/src/irqchip/kvm/x86_64.rs index a7005f690..7d5ce9002 100644 --- a/devices/src/irqchip/kvm/x86_64.rs +++ b/devices/src/irqchip/kvm/x86_64.rs @@ -4,30 +4,51 @@ use std::sync::Arc; -use sync::Mutex; - +use base::error; #[cfg(not(test))] use base::Clock; +use base::Error; +use base::Event; #[cfg(test)] use base::FakeClock as Clock; -use hypervisor::kvm::{KvmVcpu, KvmVm}; -use hypervisor::{ - HypervisorCap, IoapicState, IrqRoute, IrqSource, IrqSourceChip, LapicState, MPState, PicSelect, - PicState, PitState, Vcpu, VcpuX86_64, Vm, VmX86_64, -}; +use base::Result; +use base::Tube; +use hypervisor::kvm::KvmVcpu; +use hypervisor::kvm::KvmVm; +use hypervisor::HypervisorCap; +use hypervisor::IoapicState; +use hypervisor::IrqRoute; +use hypervisor::IrqSource; +use hypervisor::IrqSourceChip; +use hypervisor::LapicState; +use hypervisor::MPState; +use hypervisor::PicSelect; +use hypervisor::PicState; +use hypervisor::PitState; +use hypervisor::Vcpu; +use hypervisor::VcpuX86_64; +use hypervisor::Vm; +use hypervisor::VmX86_64; use kvm_sys::*; use resources::SystemAllocator; +use sync::Mutex; -use base::{error, Error, Event, Result, Tube}; - -use crate::irqchip::{ - Ioapic, IrqEvent, IrqEventIndex, Pic, VcpuRunState, IOAPIC_BASE_ADDRESS, - IOAPIC_MEM_LENGTH_BYTES, -}; -use crate::{ - Bus, IrqChip, IrqChipCap, IrqChipX86_64, IrqEdgeEvent, IrqEventSource, IrqLevelEvent, Pit, - PitError, -}; +use crate::irqchip::Ioapic; +use crate::irqchip::IrqEvent; +use crate::irqchip::IrqEventIndex; +use crate::irqchip::Pic; +use crate::irqchip::VcpuRunState; +use crate::irqchip::IOAPIC_BASE_ADDRESS; +use crate::irqchip::IOAPIC_MEM_LENGTH_BYTES; +use crate::Bus; +use crate::IrqChip; +use crate::IrqChipCap; +use crate::IrqChipX86_64; +use crate::IrqEdgeEvent; +use crate::IrqEventSource; +use crate::IrqLevelEvent; +use crate::Pit; +use crate::PitError; /// PIT tube 0 timer is connected to IRQ 0 const PIT_CHANNEL0_IRQ: u32 = 0; @@ -789,17 +810,24 @@ impl IrqChipX86_64 for KvmSplitIrqChip { #[cfg(test)] mod tests { - use super::*; use base::EventReadResult; - use hypervisor::{ - kvm::Kvm, IoapicRedirectionTableEntry, PitRWMode, ProtectionType, TriggerMode, Vm, VmX86_64, - }; - use resources::{AddressRange, SystemAllocator, SystemAllocatorConfig}; + use hypervisor::kvm::Kvm; + use hypervisor::IoapicRedirectionTableEntry; + use hypervisor::PitRWMode; + use hypervisor::ProtectionType; + use hypervisor::TriggerMode; + use hypervisor::Vm; + use hypervisor::VmX86_64; + use resources::AddressRange; + use resources::SystemAllocator; + use resources::SystemAllocatorConfig; use vm_memory::GuestMemory; + use super::*; use crate::irqchip::tests::*; use crate::pci::CrosvmDeviceId; - use crate::{DeviceId, IrqChip}; + use crate::DeviceId; + use crate::IrqChip; /// Helper function for setting up a KvmKernelIrqChip fn get_kernel_chip() -> KvmKernelIrqChip { diff --git a/devices/src/irqchip/mod.rs b/devices/src/irqchip/mod.rs index 3ac9a39f1..ac86fd821 100644 --- a/devices/src/irqchip/mod.rs +++ b/devices/src/irqchip/mod.rs @@ -2,16 +2,23 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::marker::{Send, Sized}; +use std::marker::Send; +use std::marker::Sized; -use crate::{ - pci::{CrosvmDeviceId, PciId}, - Bus, BusDevice, IrqEdgeEvent, IrqLevelEvent, -}; -use base::{Event, Result}; -use hypervisor::{IrqRoute, MPState, Vcpu}; +use base::Event; +use base::Result; +use hypervisor::IrqRoute; +use hypervisor::MPState; +use hypervisor::Vcpu; use resources::SystemAllocator; +use crate::pci::CrosvmDeviceId; +use crate::pci::PciId; +use crate::Bus; +use crate::BusDevice; +use crate::IrqEdgeEvent; +use crate::IrqLevelEvent; + cfg_if::cfg_if! { if #[cfg(unix)] { mod kvm; diff --git a/devices/src/irqchip/pic.rs b/devices/src/irqchip/pic.rs index a795286bb..a0d54da05 100644 --- a/devices/src/irqchip/pic.rs +++ b/devices/src/irqchip/pic.rs @@ -12,10 +12,17 @@ // For the purposes of both using more descriptive terms and avoiding terms with lots of charged // emotional context, this file refers to them instead as "primary" and "secondary" PICs. -use crate::{bus::BusAccessInfo, pci::CrosvmDeviceId}; -use crate::{BusDevice, DeviceId}; -use base::{debug, warn, Event}; -use hypervisor::{PicInitState, PicSelect, PicState}; +use base::debug; +use base::warn; +use base::Event; +use hypervisor::PicInitState; +use hypervisor::PicSelect; +use hypervisor::PicState; + +use crate::bus::BusAccessInfo; +use crate::pci::CrosvmDeviceId; +use crate::BusDevice; +use crate::DeviceId; pub struct Pic { // Indicates a pending INTR signal to LINT0 of vCPU, checked by vCPU thread. diff --git a/devices/src/irqchip/userspace.rs b/devices/src/irqchip/userspace.rs index 10ec9b1f7..d3e7e5f46 100644 --- a/devices/src/irqchip/userspace.rs +++ b/devices/src/irqchip/userspace.rs @@ -2,8 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::convert::{TryFrom, TryInto}; -use std::fmt::{self, Display}; +use std::convert::TryFrom; +use std::convert::TryInto; +use std::fmt::Display; +use std::fmt::{self}; use std::iter; use std::sync::Arc; use std::thread; @@ -15,28 +17,65 @@ cfg_if::cfg_if! { use base::{Clock, Timer}; } } -use base::{ - error, info, warn, AsRawDescriptor, Descriptor, Error, Event, EventToken, Result, Tube, - WaitContext, -}; -use hypervisor::{ - DeliveryMode, IoapicState, IrqRoute, IrqSource, IrqSourceChip, LapicState, MPState, - MsiAddressMessage, MsiDataMessage, PicSelect, PicState, PitState, Vcpu, VcpuX86_64, -}; +use base::error; +use base::info; +use base::warn; +use base::AsRawDescriptor; +use base::Descriptor; +use base::Error; +use base::Event; +use base::EventToken; +use base::Result; +use base::Tube; +use base::WaitContext; +use hypervisor::DeliveryMode; +use hypervisor::IoapicState; +use hypervisor::IrqRoute; +use hypervisor::IrqSource; +use hypervisor::IrqSourceChip; +use hypervisor::LapicState; +use hypervisor::MPState; +use hypervisor::MsiAddressMessage; +use hypervisor::MsiDataMessage; +use hypervisor::PicSelect; +use hypervisor::PicState; +use hypervisor::PitState; +use hypervisor::Vcpu; +use hypervisor::VcpuX86_64; use resources::SystemAllocator; -use sync::{Condvar, Mutex}; +use sync::Condvar; +use sync::Mutex; use crate::bus::BusDeviceSync; -use crate::irqchip::{ - Apic, ApicBusMsg, DelayedIoApicIrqEvents, Interrupt, InterruptData, InterruptDestination, - Ioapic, IrqEvent, IrqEventIndex, Pic, Routes, VcpuRunState, APIC_BASE_ADDRESS, - APIC_MEM_LENGTH_BYTES, IOAPIC_BASE_ADDRESS, IOAPIC_MEM_LENGTH_BYTES, -}; +use crate::irqchip::Apic; +use crate::irqchip::ApicBusMsg; +use crate::irqchip::DelayedIoApicIrqEvents; +use crate::irqchip::Interrupt; +use crate::irqchip::InterruptData; +use crate::irqchip::InterruptDestination; +use crate::irqchip::Ioapic; +use crate::irqchip::IrqEvent; +use crate::irqchip::IrqEventIndex; +use crate::irqchip::Pic; +use crate::irqchip::Routes; +use crate::irqchip::VcpuRunState; +use crate::irqchip::APIC_BASE_ADDRESS; +use crate::irqchip::APIC_MEM_LENGTH_BYTES; +use crate::irqchip::IOAPIC_BASE_ADDRESS; +use crate::irqchip::IOAPIC_MEM_LENGTH_BYTES; use crate::pci::CrosvmDeviceId; -use crate::{ - Bus, BusAccessInfo, BusDevice, DeviceId, IrqChip, IrqChipCap, IrqChipX86_64, IrqEdgeEvent, - IrqEventSource, IrqLevelEvent, Pit, PitError, -}; +use crate::Bus; +use crate::BusAccessInfo; +use crate::BusDevice; +use crate::DeviceId; +use crate::IrqChip; +use crate::IrqChipCap; +use crate::IrqChipX86_64; +use crate::IrqEdgeEvent; +use crate::IrqEventSource; +use crate::IrqLevelEvent; +use crate::Pit; +use crate::PitError; /// PIT channel 0 timer is connected to IRQ 0 const PIT_CHANNEL0_IRQ: u32 = 0; @@ -989,22 +1028,36 @@ type TimerWorkerResult = std::result::Result; #[allow(unused)] #[cfg(test)] mod tests { - use super::super::tests::*; - use super::*; - use std::os::raw::c_int; - use std::time::{Duration, Instant}; + use std::time::Duration; + use std::time::Instant; - use super::super::DestinationShorthand; use base::EventReadResult; - use hypervisor::{ - CpuId, CpuIdEntry, DebugRegs, DestinationMode, Fpu, HypervHypercall, IoParams, - IoapicRedirectionTableEntry, Level, PitRWMode, Register, Regs, Sregs, TriggerMode, Vcpu, - VcpuExit, VcpuRunHandle, - }; - use resources::{AddressRange, SystemAllocatorConfig}; + use hypervisor::CpuId; + use hypervisor::CpuIdEntry; + use hypervisor::DebugRegs; + use hypervisor::DestinationMode; + use hypervisor::Fpu; + use hypervisor::HypervHypercall; + use hypervisor::IoParams; + use hypervisor::IoapicRedirectionTableEntry; + use hypervisor::Level; + use hypervisor::PitRWMode; + use hypervisor::Register; + use hypervisor::Regs; + use hypervisor::Sregs; + use hypervisor::TriggerMode; + use hypervisor::Vcpu; + use hypervisor::VcpuExit; + use hypervisor::VcpuRunHandle; + use resources::AddressRange; + use resources::SystemAllocatorConfig; use vm_memory::GuestAddress; + use super::super::tests::*; + use super::super::DestinationShorthand; + use super::*; + const APIC_ID: u64 = 0x20; const TPR: u64 = 0x80; const EOI: u64 = 0xB0; diff --git a/devices/src/irqchip/whpx.rs b/devices/src/irqchip/whpx.rs index 76f1b9b8f..6d3d69aa8 100644 --- a/devices/src/irqchip/whpx.rs +++ b/devices/src/irqchip/whpx.rs @@ -14,23 +14,49 @@ cfg_if::cfg_if! { use base::Clock; } } -use hypervisor::whpx::{WhpxVcpu, WhpxVm}; -use hypervisor::{ - IoapicState, IrqRoute, IrqSource, IrqSourceChip, LapicState, MPState, MsiAddressMessage, - MsiDataMessage, PicSelect, PicState, PitState, Vcpu, VcpuX86_64, Vm, -}; +use base::error; +use base::Error; +use base::Event; +use base::Result; +use base::Tube; +use hypervisor::whpx::WhpxVcpu; +use hypervisor::whpx::WhpxVm; +use hypervisor::IoapicState; +use hypervisor::IrqRoute; +use hypervisor::IrqSource; +use hypervisor::IrqSourceChip; +use hypervisor::LapicState; +use hypervisor::MPState; +use hypervisor::MsiAddressMessage; +use hypervisor::MsiDataMessage; +use hypervisor::PicSelect; +use hypervisor::PicState; +use hypervisor::PitState; +use hypervisor::Vcpu; +use hypervisor::VcpuX86_64; +use hypervisor::Vm; use resources::SystemAllocator; -use base::{error, Error, Event, Result, Tube}; - -use crate::irqchip::{ - DelayedIoApicIrqEvents, InterruptData, InterruptDestination, Ioapic, IrqEvent, IrqEventIndex, - Pic, Routes, VcpuRunState, IOAPIC_BASE_ADDRESS, IOAPIC_MEM_LENGTH_BYTES, -}; -use crate::{ - Bus, IrqChip, IrqChipCap, IrqChipX86_64, IrqEdgeEvent, IrqEventSource, IrqLevelEvent, Pit, - PitError, -}; +use crate::irqchip::DelayedIoApicIrqEvents; +use crate::irqchip::InterruptData; +use crate::irqchip::InterruptDestination; +use crate::irqchip::Ioapic; +use crate::irqchip::IrqEvent; +use crate::irqchip::IrqEventIndex; +use crate::irqchip::Pic; +use crate::irqchip::Routes; +use crate::irqchip::VcpuRunState; +use crate::irqchip::IOAPIC_BASE_ADDRESS; +use crate::irqchip::IOAPIC_MEM_LENGTH_BYTES; +use crate::Bus; +use crate::IrqChip; +use crate::IrqChipCap; +use crate::IrqChipX86_64; +use crate::IrqEdgeEvent; +use crate::IrqEventSource; +use crate::IrqLevelEvent; +use crate::Pit; +use crate::PitError; /// PIT channel 0 timer is connected to IRQ 0 const PIT_CHANNEL0_IRQ: u32 = 0; @@ -586,16 +612,23 @@ impl IrqChipX86_64 for WhpxSplitIrqChip { #[cfg(test)] mod tests { + use base::EventReadResult; + use hypervisor::whpx::Whpx; + use hypervisor::whpx::WhpxFeature; + use hypervisor::CpuId; + use hypervisor::IoapicRedirectionTableEntry; + use hypervisor::PitRWMode; + use hypervisor::TriggerMode; + use hypervisor::VmX86_64; + use resources::AddressRange; + use resources::SystemAllocatorConfig; + use vm_memory::GuestAddress; + use vm_memory::GuestMemory; + use super::super::tests::*; use super::*; - use crate::pci::CrosvmDeviceId; use crate::DeviceId; - use base::EventReadResult; - use hypervisor::whpx::{Whpx, WhpxFeature}; - use hypervisor::{CpuId, IoapicRedirectionTableEntry, PitRWMode, TriggerMode, VmX86_64}; - use resources::{AddressRange, SystemAllocatorConfig}; - use vm_memory::{GuestAddress, GuestMemory}; fn split_supported() -> bool { Whpx::check_whpx_feature(WhpxFeature::LocalApicEmulation) diff --git a/devices/src/irqchip/x86_64.rs b/devices/src/irqchip/x86_64.rs index be4ad6b0f..88720c532 100644 --- a/devices/src/irqchip/x86_64.rs +++ b/devices/src/irqchip/x86_64.rs @@ -2,11 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::{Error, Event, Result}; -use hypervisor::{ - IoapicState, IrqRoute, IrqSource, IrqSourceChip, LapicState, PicSelect, PicState, PitState, -}; -use std::{ops::Index, vec::Vec}; +use std::ops::Index; +use std::vec::Vec; + +use base::Error; +use base::Event; +use base::Result; +use hypervisor::IoapicState; +use hypervisor::IrqRoute; +use hypervisor::IrqSource; +use hypervisor::IrqSourceChip; +use hypervisor::LapicState; +use hypervisor::PicSelect; +use hypervisor::PicState; +use hypervisor::PitState; use crate::IrqChip; @@ -196,8 +205,11 @@ impl DelayedIoApicIrqEvents { #[cfg(test)] /// This module contains tests that apply to any implementations of IrqChipX86_64 pub(super) mod tests { + use hypervisor::IrqRoute; + use hypervisor::IrqSource; + use hypervisor::IrqSourceChip; + use super::*; - use hypervisor::{IrqRoute, IrqSource, IrqSourceChip}; pub fn test_get_pic(mut chip: impl IrqChipX86_64) { let state = chip diff --git a/devices/src/lib.rs b/devices/src/lib.rs index 791fee133..620e16667 100644 --- a/devices/src/lib.rs +++ b/devices/src/lib.rs @@ -44,41 +44,66 @@ cfg_if::cfg_if! { } pub use self::acpi::ACPIPMResource; -pub use self::bat::{BatteryError, GoldfishBattery}; -pub use self::bus::{ - Bus, BusAccessInfo, BusDevice, BusDeviceObj, BusDeviceSync, BusRange, BusResumeDevice, BusType, - Error as BusError, HostHotPlugKey, HotPlugBus, -}; +pub use self::bat::BatteryError; +pub use self::bat::GoldfishBattery; +pub use self::bus::Bus; +pub use self::bus::BusAccessInfo; +pub use self::bus::BusDevice; +pub use self::bus::BusDeviceObj; +pub use self::bus::BusDeviceSync; +pub use self::bus::BusRange; +pub use self::bus::BusResumeDevice; +pub use self::bus::BusType; +pub use self::bus::Error as BusError; +pub use self::bus::HostHotPlugKey; +pub use self::bus::HotPlugBus; #[cfg(feature = "stats")] pub use self::bus_stats::BusStatistics; pub use self::cmos::Cmos; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub use self::debugcon::Debugcon; #[cfg(feature = "direct")] -pub use self::direct_io::{DirectIo, DirectMmio}; +pub use self::direct_io::DirectIo; #[cfg(feature = "direct")] -pub use self::direct_irq::{DirectIrq, DirectIrqError}; +pub use self::direct_io::DirectMmio; +#[cfg(feature = "direct")] +pub use self::direct_irq::DirectIrq; +#[cfg(feature = "direct")] +pub use self::direct_irq::DirectIrqError; pub use self::i8042::I8042Device; -pub use self::irq_event::{IrqEdgeEvent, IrqLevelEvent}; +pub use self::irq_event::IrqEdgeEvent; +pub use self::irq_event::IrqLevelEvent; pub use self::irqchip::*; +pub use self::pci::BarRange; pub use self::pci::CrosvmDeviceId; -pub use self::pci::{ - BarRange, PciAddress, PciAddressError, PciBus, PciClassCode, PciConfigIo, PciConfigMmio, - PciDevice, PciDeviceError, PciInterruptPin, PciRoot, PciVirtualConfigMmio, StubPciDevice, - StubPciParameters, -}; +pub use self::pci::PciAddress; +pub use self::pci::PciAddressError; +pub use self::pci::PciBus; +pub use self::pci::PciClassCode; +pub use self::pci::PciConfigIo; +pub use self::pci::PciConfigMmio; +pub use self::pci::PciDevice; +pub use self::pci::PciDeviceError; +pub use self::pci::PciInterruptPin; +pub use self::pci::PciRoot; +pub use self::pci::PciVirtualConfigMmio; +pub use self::pci::StubPciDevice; +pub use self::pci::StubPciParameters; pub use self::pl030::Pl030; pub use self::serial::Serial; -pub use self::serial_device::{ - Error as SerialError, SerialDevice, SerialHardware, SerialParameters, SerialType, -}; +pub use self::serial_device::Error as SerialError; +pub use self::serial_device::SerialDevice; +pub use self::serial_device::SerialHardware; +pub use self::serial_device::SerialParameters; +pub use self::serial_device::SerialType; #[cfg(feature = "tpm")] pub use self::software_tpm::SoftwareTpm; #[cfg(all(feature = "tpm", feature = "chromeos", target_arch = "x86_64"))] pub use self::vtpm_proxy::VtpmProxy; mod pflash; -pub use self::pflash::{Pflash, PflashParameters}; +pub use self::pflash::Pflash; +pub use self::pflash::PflashParameters; cfg_if::cfg_if! { if #[cfg(unix)] { mod platform; @@ -119,7 +144,9 @@ cfg_if::cfg_if! { } /// Request CoIOMMU to unpin a specific range. -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +/// Request CoIOMMU to unpin a specific range. +use serde::Serialize; #[derive(Serialize, Deserialize, Debug)] pub struct UnpinRequest { /// The ranges presents (start gfn, count). diff --git a/devices/src/pci/ac97.rs b/devices/src/pci/ac97.rs index bde9916ef..bb8d261f8 100644 --- a/devices/src/pci/ac97.rs +++ b/devices/src/pci/ac97.rs @@ -6,25 +6,45 @@ use std::default::Default; use std::path::PathBuf; use std::str::FromStr; -use audio_streams::shm_streams::{NullShmStreamSource, ShmStreamSource}; -use base::{error, AsRawDescriptor, RawDescriptor}; +use audio_streams::shm_streams::NullShmStreamSource; +use audio_streams::shm_streams::ShmStreamSource; +use base::error; +use base::AsRawDescriptor; +use base::RawDescriptor; #[cfg(feature = "audio_cras")] -use libcras::{CrasClient, CrasClientType, CrasSocketType, CrasSysError}; +use libcras::CrasClient; +#[cfg(feature = "audio_cras")] +use libcras::CrasClientType; +#[cfg(feature = "audio_cras")] +use libcras::CrasSocketType; +#[cfg(feature = "audio_cras")] +use libcras::CrasSysError; use remain::sorted; -use resources::{Alloc, MmioType, SystemAllocator}; -use serde::{Deserialize, Serialize}; +use resources::Alloc; +use resources::MmioType; +use resources::SystemAllocator; +use serde::Deserialize; +use serde::Serialize; use thiserror::Error; use vm_memory::GuestMemory; use crate::pci::ac97_bus_master::Ac97BusMaster; use crate::pci::ac97_mixer::Ac97Mixer; use crate::pci::ac97_regs::*; -use crate::pci::pci_configuration::{ - PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciClassCode, PciConfiguration, - PciHeaderType, PciMultimediaSubclass, -}; -use crate::pci::pci_device::{self, BarRange, PciDevice, Result}; -use crate::pci::{PciAddress, PciDeviceError, PciInterruptPin}; +use crate::pci::pci_configuration::PciBarConfiguration; +use crate::pci::pci_configuration::PciBarPrefetchable; +use crate::pci::pci_configuration::PciBarRegionType; +use crate::pci::pci_configuration::PciClassCode; +use crate::pci::pci_configuration::PciConfiguration; +use crate::pci::pci_configuration::PciHeaderType; +use crate::pci::pci_configuration::PciMultimediaSubclass; +use crate::pci::pci_device::BarRange; +use crate::pci::pci_device::PciDevice; +use crate::pci::pci_device::Result; +use crate::pci::pci_device::{self}; +use crate::pci::PciAddress; +use crate::pci::PciDeviceError; +use crate::pci::PciInterruptPin; #[cfg(not(any(target_os = "linux", target_os = "android")))] use crate::virtio::snd::vios_backend::Error as VioSError; #[cfg(any(target_os = "linux", target_os = "android"))] @@ -441,11 +461,13 @@ impl PciDevice for Ac97Dev { #[cfg(test)] mod tests { - use super::*; use audio_streams::shm_streams::MockShmStreamSource; - use resources::{AddressRange, SystemAllocatorConfig}; + use resources::AddressRange; + use resources::SystemAllocatorConfig; use vm_memory::GuestAddress; + use super::*; + #[test] fn create() { let mem = GuestMemory::new(&[(GuestAddress(0u64), 4 * 1024 * 1024)]).unwrap(); diff --git a/devices/src/pci/ac97_bus_master.rs b/devices/src/pci/ac97_bus_master.rs index 17fbf76fc..7bb81a161 100644 --- a/devices/src/pci/ac97_bus_master.rs +++ b/devices/src/pci/ac97_bus_master.rs @@ -4,23 +4,36 @@ use std::collections::VecDeque; use std::convert::TryInto; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread; -use std::time::{Duration, Instant}; +use std::time::Duration; +use std::time::Instant; -use audio_streams::{ - shm_streams::{ShmStream, ShmStreamSource}, - BoxError, NoopStreamControl, SampleFormat, StreamControl, StreamDirection, StreamEffect, -}; -use base::{ - self, error, set_rt_prio_limit, set_rt_round_robin, warn, AsRawDescriptor, AsRawDescriptors, - FromRawDescriptor, RawDescriptor, -}; +use audio_streams::shm_streams::ShmStream; +use audio_streams::shm_streams::ShmStreamSource; +use audio_streams::BoxError; +use audio_streams::NoopStreamControl; +use audio_streams::SampleFormat; +use audio_streams::StreamControl; +use audio_streams::StreamDirection; +use audio_streams::StreamEffect; +use base::error; +use base::set_rt_prio_limit; +use base::set_rt_round_robin; +use base::warn; +use base::AsRawDescriptor; +use base::AsRawDescriptors; +use base::FromRawDescriptor; +use base::RawDescriptor; +use base::{self}; use remain::sorted; -use sync::{Condvar, Mutex}; +use sync::Condvar; +use sync::Mutex; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; use crate::pci::ac97_mixer::Ac97Mixer; use crate::pci::ac97_regs::*; @@ -959,10 +972,10 @@ fn current_buffer_size( #[cfg(test)] mod test { - use super::*; - use audio_streams::shm_streams::MockShmStreamSource; + use super::*; + #[test] fn bm_bdbar() { let mut bm = Ac97BusMaster::new( diff --git a/devices/src/pci/coiommu.rs b/devices/src/pci/coiommu.rs index 28f57301f..27eef8bf6 100644 --- a/devices/src/pci/coiommu.rs +++ b/devices/src/pci/coiommu.rs @@ -17,36 +17,70 @@ use std::collections::VecDeque; use std::convert::TryInto; use std::default::Default; +use std::fmt; +use std::mem; use std::panic; use std::str::FromStr; -use std::sync::atomic::{fence, AtomicU32, Ordering}; +use std::sync::atomic::fence; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; use std::sync::Arc; +use std::thread; use std::time::Duration; -use std::{fmt, mem, thread}; -use anyhow::{anyhow, bail, ensure, Context, Result}; -use base::{ - error, info, AsRawDescriptor, Event, EventToken, MemoryMapping, MemoryMappingBuilder, - Protection, RawDescriptor, SafeDescriptor, SharedMemory, Timer, Tube, TubeError, WaitContext, -}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::ensure; +use anyhow::Context; +use anyhow::Result; +use base::error; +use base::info; +use base::AsRawDescriptor; +use base::Event; +use base::EventToken; +use base::MemoryMapping; +use base::MemoryMappingBuilder; +use base::Protection; +use base::RawDescriptor; +use base::SafeDescriptor; +use base::SharedMemory; +use base::Timer; +use base::Tube; +use base::TubeError; +use base::WaitContext; use data_model::DataInit; use hypervisor::Datamatch; -use resources::{Alloc, MmioType, SystemAllocator}; -use serde::{Deserialize, Serialize}; +use resources::Alloc; +use resources::MmioType; +use resources::SystemAllocator; +use serde::Deserialize; +use serde::Serialize; use sync::Mutex; use thiserror::Error as ThisError; +use vm_control::VmMemoryDestination; +use vm_control::VmMemoryRequest; +use vm_control::VmMemoryResponse; +use vm_control::VmMemorySource; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; -use vm_control::{VmMemoryDestination, VmMemoryRequest, VmMemoryResponse, VmMemorySource}; -use vm_memory::{GuestAddress, GuestMemory}; - -use crate::pci::pci_configuration::{ - PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciClassCode, PciConfiguration, - PciHeaderType, PciOtherSubclass, COMMAND_REG, COMMAND_REG_MEMORY_SPACE_MASK, -}; -use crate::pci::pci_device::{BarRange, PciDevice, Result as PciResult}; -use crate::pci::{PciAddress, PciDeviceError}; +use crate::pci::pci_configuration::PciBarConfiguration; +use crate::pci::pci_configuration::PciBarPrefetchable; +use crate::pci::pci_configuration::PciBarRegionType; +use crate::pci::pci_configuration::PciClassCode; +use crate::pci::pci_configuration::PciConfiguration; +use crate::pci::pci_configuration::PciHeaderType; +use crate::pci::pci_configuration::PciOtherSubclass; +use crate::pci::pci_configuration::COMMAND_REG; +use crate::pci::pci_configuration::COMMAND_REG_MEMORY_SPACE_MASK; +use crate::pci::pci_device::BarRange; +use crate::pci::pci_device::PciDevice; +use crate::pci::pci_device::Result as PciResult; +use crate::pci::PciAddress; +use crate::pci::PciDeviceError; use crate::vfio::VfioContainer; -use crate::{UnpinRequest, UnpinResponse}; +use crate::UnpinRequest; +use crate::UnpinResponse; const PCI_VENDOR_ID_COIOMMU: u16 = 0x1234; const PCI_DEVICE_ID_COIOMMU: u16 = 0xabcd; diff --git a/devices/src/pci/mod.rs b/devices/src/pci/mod.rs index e4c6f4d15..9f91ddd8b 100644 --- a/devices/src/pci/mod.rs +++ b/devices/src/pci/mod.rs @@ -37,22 +37,49 @@ use libc::EINVAL; #[cfg(all(unix, feature = "audio"))] pub use self::ac97::{Ac97Backend, Ac97Dev, Ac97Parameters}; #[cfg(unix)] -pub use self::coiommu::{CoIommuDev, CoIommuParameters, CoIommuUnpinPolicy}; +pub use self::coiommu::CoIommuDev; +#[cfg(unix)] +pub use self::coiommu::CoIommuParameters; +#[cfg(unix)] +pub use self::coiommu::CoIommuUnpinPolicy; pub use self::msi::MsiConfig; -pub use self::msix::{MsixCap, MsixConfig, MsixStatus}; +pub use self::msix::MsixCap; +pub use self::msix::MsixConfig; +pub use self::msix::MsixStatus; pub use self::pci_address::Error as PciAddressError; pub use self::pci_address::PciAddress; -pub use self::pci_configuration::{ - PciBarConfiguration, PciBarIndex, PciBarPrefetchable, PciBarRegionType, PciCapability, - PciCapabilityID, PciClassCode, PciConfiguration, PciDisplaySubclass, PciHeaderType, - PciProgrammingInterface, PciSerialBusSubClass, PciSubclass, CAPABILITY_LIST_HEAD_OFFSET, -}; -pub use self::pci_device::{BarRange, Error as PciDeviceError, PciBus, PciDevice}; -pub use self::pci_root::{PciConfigIo, PciConfigMmio, PciRoot, PciVirtualConfigMmio}; +pub use self::pci_configuration::PciBarConfiguration; +pub use self::pci_configuration::PciBarIndex; +pub use self::pci_configuration::PciBarPrefetchable; +pub use self::pci_configuration::PciBarRegionType; +pub use self::pci_configuration::PciCapability; +pub use self::pci_configuration::PciCapabilityID; +pub use self::pci_configuration::PciClassCode; +pub use self::pci_configuration::PciConfiguration; +pub use self::pci_configuration::PciDisplaySubclass; +pub use self::pci_configuration::PciHeaderType; +pub use self::pci_configuration::PciProgrammingInterface; +pub use self::pci_configuration::PciSerialBusSubClass; +pub use self::pci_configuration::PciSubclass; +pub use self::pci_configuration::CAPABILITY_LIST_HEAD_OFFSET; +pub use self::pci_device::BarRange; +pub use self::pci_device::Error as PciDeviceError; +pub use self::pci_device::PciBus; +pub use self::pci_device::PciDevice; +pub use self::pci_root::PciConfigIo; +pub use self::pci_root::PciConfigMmio; +pub use self::pci_root::PciRoot; +pub use self::pci_root::PciVirtualConfigMmio; #[cfg(unix)] -pub use self::pcie::{PciBridge, PcieHostPort, PcieRootPort}; -pub use self::pvpanic::{PvPanicCode, PvPanicPciDevice}; -pub use self::stub::{StubPciDevice, StubPciParameters}; +pub use self::pcie::PciBridge; +#[cfg(unix)] +pub use self::pcie::PcieHostPort; +#[cfg(unix)] +pub use self::pcie::PcieRootPort; +pub use self::pvpanic::PvPanicCode; +pub use self::pvpanic::PvPanicPciDevice; +pub use self::stub::StubPciDevice; +pub use self::stub::StubPciParameters; #[cfg(unix)] pub use self::vfio_pci::VfioPciDevice; diff --git a/devices/src/pci/msi.rs b/devices/src/pci/msi.rs index ca980e915..307f839ca 100644 --- a/devices/src/pci/msi.rs +++ b/devices/src/pci/msi.rs @@ -4,12 +4,18 @@ #![cfg_attr(windows, allow(dead_code))] -use base::{error, AsRawDescriptor, Event, RawDescriptor, Tube}; +use base::error; +use base::AsRawDescriptor; +use base::Event; +use base::RawDescriptor; +use base::Tube; use bit_field::*; use data_model::DataInit; -use vm_control::{VmIrqRequest, VmIrqResponse}; +use vm_control::VmIrqRequest; +use vm_control::VmIrqResponse; -use crate::pci::{PciCapability, PciCapabilityID}; +use crate::pci::PciCapability; +use crate::pci::PciCapabilityID; // MSI registers pub const PCI_MSI_NEXT_POINTER: u32 = 0x1; // Next cap pointer pub const PCI_MSI_FLAGS: u32 = 0x2; // Message Control diff --git a/devices/src/pci/msix.rs b/devices/src/pci/msix.rs index 214fa3313..342be5f52 100644 --- a/devices/src/pci/msix.rs +++ b/devices/src/pci/msix.rs @@ -2,15 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::{error, AsRawDescriptor, Error as SysError, Event, RawDescriptor, Tube, TubeError}; +use std::convert::TryInto; + +use base::error; +use base::AsRawDescriptor; +use base::Error as SysError; +use base::Event; +use base::RawDescriptor; +use base::Tube; +use base::TubeError; use bit_field::*; use data_model::DataInit; use remain::sorted; -use std::convert::TryInto; use thiserror::Error; -use vm_control::{VmIrqRequest, VmIrqResponse}; +use vm_control::VmIrqRequest; +use vm_control::VmIrqResponse; -use crate::pci::{PciCapability, PciCapabilityID}; +use crate::pci::PciCapability; +use crate::pci::PciCapabilityID; const MAX_MSIX_VECTORS_PER_DEVICE: u16 = 2048; pub const MSIX_TABLE_ENTRIES_MODULO: u64 = 16; diff --git a/devices/src/pci/pci_address.rs b/devices/src/pci/pci_address.rs index 0e00713d9..c62d294be 100644 --- a/devices/src/pci/pci_address.rs +++ b/devices/src/pci/pci_address.rs @@ -2,11 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::fmt::{self, Display}; +use std::fmt::Display; +use std::fmt::{self}; use std::str::FromStr; use remain::sorted; -use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde::Deserialize; +use serde::Deserializer; +use serde::Serialize; +use serde::Serializer; use thiserror::Error as ThisError; /// Identifies a single component of a [`PciAddress`]. diff --git a/devices/src/pci/pci_configuration.rs b/devices/src/pci/pci_configuration.rs index 392cc4412..a33486c43 100644 --- a/devices/src/pci/pci_configuration.rs +++ b/devices/src/pci/pci_configuration.rs @@ -7,10 +7,12 @@ use std::convert::TryInto; use base::warn; use remain::sorted; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; use thiserror::Error; -use crate::pci::{PciAddress, PciInterruptPin}; +use crate::pci::PciAddress; +use crate::pci::PciInterruptPin; // The number of 32bit registers in the config space, 256 bytes. const NUM_CONFIGURATION_REGISTERS: usize = 64; diff --git a/devices/src/pci/pci_device.rs b/devices/src/pci/pci_device.rs index d98c41443..de59f14ca 100644 --- a/devices/src/pci/pci_device.rs +++ b/devices/src/pci/pci_device.rs @@ -2,31 +2,47 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; +use std::collections::HashSet; use std::sync::Arc; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use acpi_tables::sdt::SDT; use anyhow::bail; -use base::{error, Event, RawDescriptor}; +use base::error; +use base::Event; +use base::RawDescriptor; use hypervisor::Datamatch; use remain::sorted; -use resources::{Error as SystemAllocatorFaliure, SystemAllocator}; +use resources::Error as SystemAllocatorFaliure; +use resources::SystemAllocator; use sync::Mutex; use thiserror::Error; -use crate::bus::{BusDeviceObj, BusRange, BusType, ConfigWriteResult}; -use crate::pci::pci_configuration::{ - self, PciBarConfiguration, BAR0_REG, COMMAND_REG, COMMAND_REG_IO_SPACE_MASK, - COMMAND_REG_MEMORY_SPACE_MASK, NUM_BAR_REGS, PCI_ID_REG, ROM_BAR_REG, -}; -use crate::pci::{PciAddress, PciAddressError, PciInterruptPin}; +use super::PciId; +use crate::bus::BusDeviceObj; +use crate::bus::BusRange; +use crate::bus::BusType; +use crate::bus::ConfigWriteResult; +use crate::pci::pci_configuration::PciBarConfiguration; +use crate::pci::pci_configuration::BAR0_REG; +use crate::pci::pci_configuration::COMMAND_REG; +use crate::pci::pci_configuration::COMMAND_REG_IO_SPACE_MASK; +use crate::pci::pci_configuration::COMMAND_REG_MEMORY_SPACE_MASK; +use crate::pci::pci_configuration::NUM_BAR_REGS; +use crate::pci::pci_configuration::PCI_ID_REG; +use crate::pci::pci_configuration::ROM_BAR_REG; +use crate::pci::pci_configuration::{self}; +use crate::pci::PciAddress; +use crate::pci::PciAddressError; +use crate::pci::PciInterruptPin; use crate::virtio::ipc_memory_mapper::IpcMemoryMapper; #[cfg(all(unix, feature = "audio"))] use crate::virtio::snd::vios_backend::Error as VioSError; -use crate::{BusAccessInfo, BusDevice, DeviceId, IrqLevelEvent}; - -use super::PciId; +use crate::BusAccessInfo; +use crate::BusDevice; +use crate::DeviceId; +use crate::IrqLevelEvent; #[sorted] #[derive(Error, Debug)] @@ -644,11 +660,14 @@ impl BusDeviceObj for T { #[cfg(test)] mod tests { + use pci_configuration::PciBarPrefetchable; + use pci_configuration::PciBarRegionType; + use pci_configuration::PciClassCode; + use pci_configuration::PciConfiguration; + use pci_configuration::PciHeaderType; + use pci_configuration::PciMultimediaSubclass; + use super::*; - use pci_configuration::{ - PciBarPrefetchable, PciBarRegionType, PciClassCode, PciConfiguration, PciHeaderType, - PciMultimediaSubclass, - }; const BAR0_SIZE: u64 = 0x1000; const BAR2_SIZE: u64 = 0x20; diff --git a/devices/src/pci/pci_root.rs b/devices/src/pci/pci_root.rs index 9cca74fee..8bac84672 100644 --- a/devices/src/pci/pci_root.rs +++ b/devices/src/pci/pci_root.rs @@ -5,19 +5,34 @@ use std::collections::BTreeMap; use std::convert::TryInto; use std::ops::Bound::Included; -use std::sync::{Arc, Weak}; +use std::sync::Arc; +use std::sync::Weak; -use base::{error, RawDescriptor, SendTube, VmEventType}; +use base::error; +use base::RawDescriptor; +use base::SendTube; +use base::VmEventType; +use resources::SystemAllocator; use sync::Mutex; -use crate::pci::pci_configuration::{ - PciBarConfiguration, PciBridgeSubclass, PciClassCode, PciConfiguration, PciHeaderType, - HEADER_TYPE_MULTIFUNCTION_MASK, HEADER_TYPE_REG, -}; -use crate::pci::pci_device::{Error, PciBus, PciDevice}; -use crate::pci::{PciAddress, PciId, PCI_VENDOR_ID_INTEL}; -use crate::{Bus, BusAccessInfo, BusDevice, BusType, DeviceId}; -use resources::SystemAllocator; +use crate::pci::pci_configuration::PciBarConfiguration; +use crate::pci::pci_configuration::PciBridgeSubclass; +use crate::pci::pci_configuration::PciClassCode; +use crate::pci::pci_configuration::PciConfiguration; +use crate::pci::pci_configuration::PciHeaderType; +use crate::pci::pci_configuration::HEADER_TYPE_MULTIFUNCTION_MASK; +use crate::pci::pci_configuration::HEADER_TYPE_REG; +use crate::pci::pci_device::Error; +use crate::pci::pci_device::PciBus; +use crate::pci::pci_device::PciDevice; +use crate::pci::PciAddress; +use crate::pci::PciId; +use crate::pci::PCI_VENDOR_ID_INTEL; +use crate::Bus; +use crate::BusAccessInfo; +use crate::BusDevice; +use crate::BusType; +use crate::DeviceId; // A PciDevice that holds the root hub's configuration. struct PciRootConfiguration { diff --git a/devices/src/pci/pcie/pci_bridge.rs b/devices/src/pci/pcie/pci_bridge.rs index 4ebd59190..b30794fab 100644 --- a/devices/src/pci/pcie/pci_bridge.rs +++ b/devices/src/pci/pcie/pci_bridge.rs @@ -1,22 +1,35 @@ // Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::cmp::{max, min}; +use std::cmp::max; +use std::cmp::min; use std::sync::Arc; + +use base::warn; +use base::AsRawDescriptors; +use base::RawDescriptor; +use base::Tube; +use resources::Alloc; +use resources::MmioType; +use resources::SystemAllocator; use sync::Mutex; -use crate::pci::msi::{MsiCap, MsiConfig}; +use crate::pci::msi::MsiCap; +use crate::pci::msi::MsiConfig; use crate::pci::pci_configuration::PciBridgeSubclass; -use crate::pci::{ - BarRange, PciAddress, PciBarConfiguration, PciBus, PciClassCode, PciConfiguration, PciDevice, - PciDeviceError, PciHeaderType, PCI_VENDOR_ID_INTEL, -}; -use crate::PciInterruptPin; -use base::{warn, AsRawDescriptors, RawDescriptor, Tube}; -use resources::{Alloc, MmioType, SystemAllocator}; - use crate::pci::pcie::pcie_device::PcieDevice; +use crate::pci::BarRange; +use crate::pci::PciAddress; +use crate::pci::PciBarConfiguration; +use crate::pci::PciBus; +use crate::pci::PciClassCode; +use crate::pci::PciConfiguration; +use crate::pci::PciDevice; +use crate::pci::PciDeviceError; +use crate::pci::PciHeaderType; +use crate::pci::PCI_VENDOR_ID_INTEL; use crate::IrqLevelEvent; +use crate::PciInterruptPin; pub const BR_BUS_NUMBER_REG: usize = 0x6; pub const BR_BUS_SUBORDINATE_OFFSET: usize = 0x2; diff --git a/devices/src/pci/pcie/pcie_device.rs b/devices/src/pci/pcie/pcie_device.rs index c5d493f46..289fe3eed 100644 --- a/devices/src/pci/pcie/pcie_device.rs +++ b/devices/src/pci/pcie/pcie_device.rs @@ -2,14 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::sync::Arc; + +use data_model::DataInit; +use resources::SystemAllocator; use sync::Mutex; use crate::pci::pci_configuration::PciCapabilityID; use crate::pci::pcie::pci_bridge::PciBridgeBusRange; use crate::pci::pcie::*; -use crate::pci::{MsiConfig, PciAddress, PciCapability, PciDeviceError}; -use data_model::DataInit; -use resources::SystemAllocator; +use crate::pci::MsiConfig; +use crate::pci::PciAddress; +use crate::pci::PciCapability; +use crate::pci::PciDeviceError; pub trait PcieDevice: Send { fn get_device_id(&self) -> u16; diff --git a/devices/src/pci/pcie/pcie_host.rs b/devices/src/pci/pcie/pcie_host.rs index 94f2b7fb7..150fd4d47 100644 --- a/devices/src/pci/pcie/pcie_host.rs +++ b/devices/src/pci/pcie/pcie_host.rs @@ -2,35 +2,53 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::fs::read; #[cfg(feature = "direct")] use std::fs::read_to_string; -use std::fs::{read, write, File, OpenOptions}; +use std::fs::write; +use std::fs::File; +use std::fs::OpenOptions; use std::os::unix::fs::FileExt; -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::path::PathBuf; use std::sync::Arc; use std::thread; -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; +use base::error; #[cfg(feature = "direct")] use base::warn; -use base::{error, Tube}; +use base::Tube; use data_model::DataInit; use sync::Mutex; -use vm_control::{VmRequest, VmResponse}; +use vm_control::VmRequest; +use vm_control::VmResponse; -use crate::pci::{PciCapabilityID, PciClassCode}; - -use crate::pci::pci_configuration::{ - PciBridgeSubclass, CAPABILITY_LIST_HEAD_OFFSET, HEADER_TYPE_REG, PCI_CAP_NEXT_POINTER, -}; +use crate::pci::pci_configuration::PciBridgeSubclass; +use crate::pci::pci_configuration::CAPABILITY_LIST_HEAD_OFFSET; #[cfg(feature = "direct")] -use crate::pci::pci_configuration::{CLASS_REG, CLASS_REG_REVISION_ID_OFFSET}; - -use crate::pci::pcie::pci_bridge::{ - PciBridgeBusRange, BR_BUS_NUMBER_REG, BR_MEM_BASE_MASK, BR_MEM_BASE_SHIFT, BR_MEM_LIMIT_MASK, - BR_MEM_MINIMUM, BR_MEM_REG, BR_PREF_MEM_64BIT, BR_PREF_MEM_BASE_HIGH_REG, - BR_PREF_MEM_LIMIT_HIGH_REG, BR_PREF_MEM_LOW_REG, BR_WINDOW_ALIGNMENT, -}; +use crate::pci::pci_configuration::CLASS_REG; +#[cfg(feature = "direct")] +use crate::pci::pci_configuration::CLASS_REG_REVISION_ID_OFFSET; +use crate::pci::pci_configuration::HEADER_TYPE_REG; +use crate::pci::pci_configuration::PCI_CAP_NEXT_POINTER; +use crate::pci::pcie::pci_bridge::PciBridgeBusRange; +use crate::pci::pcie::pci_bridge::BR_BUS_NUMBER_REG; +use crate::pci::pcie::pci_bridge::BR_MEM_BASE_MASK; +use crate::pci::pcie::pci_bridge::BR_MEM_BASE_SHIFT; +use crate::pci::pcie::pci_bridge::BR_MEM_LIMIT_MASK; +use crate::pci::pcie::pci_bridge::BR_MEM_MINIMUM; +use crate::pci::pcie::pci_bridge::BR_MEM_REG; +use crate::pci::pcie::pci_bridge::BR_PREF_MEM_64BIT; +use crate::pci::pcie::pci_bridge::BR_PREF_MEM_BASE_HIGH_REG; +use crate::pci::pcie::pci_bridge::BR_PREF_MEM_LIMIT_HIGH_REG; +use crate::pci::pcie::pci_bridge::BR_PREF_MEM_LOW_REG; +use crate::pci::pcie::pci_bridge::BR_WINDOW_ALIGNMENT; +use crate::pci::PciCapabilityID; +use crate::pci::PciClassCode; // Host Pci device's sysfs config file struct PciHostConfig { diff --git a/devices/src/pci/pcie/pcie_port.rs b/devices/src/pci/pcie/pcie_port.rs index 8a6e6a40c..08cfef511 100644 --- a/devices/src/pci/pcie/pcie_port.rs +++ b/devices/src/pci/pcie/pcie_port.rs @@ -5,18 +5,20 @@ use std::str::FromStr; use std::sync::Arc; -use crate::pci::pci_configuration::PciCapabilityID; -use crate::pci::{MsiConfig, PciAddress, PciDeviceError}; +use base::warn; +use data_model::DataInit; +use resources::Alloc; +use resources::SystemAllocator; +use sync::Mutex; +use crate::pci::pci_configuration::PciCapabilityID; use crate::pci::pcie::pci_bridge::PciBridgeBusRange; use crate::pci::pcie::pcie_device::PmcConfig; use crate::pci::pcie::pcie_host::PcieHostPort; use crate::pci::pcie::*; - -use base::warn; -use data_model::DataInit; -use resources::{Alloc, SystemAllocator}; -use sync::Mutex; +use crate::pci::MsiConfig; +use crate::pci::PciAddress; +use crate::pci::PciDeviceError; // reserve 8MB memory window const PCIE_BR_MEM_SIZE: u64 = 0x80_0000; diff --git a/devices/src/pci/pcie/pcie_rp.rs b/devices/src/pci/pcie/pcie_rp.rs index 0f328afcf..3fd68db10 100644 --- a/devices/src/pci/pcie/pcie_rp.rs +++ b/devices/src/pci/pcie/pcie_rp.rs @@ -3,22 +3,27 @@ // found in the LICENSE file. use std::collections::BTreeMap; use std::sync::Arc; -use sync::Mutex; - -use crate::bus::{HostHotPlugKey, HotPlugBus}; -use crate::pci::pci_configuration::PciCapabilityID; -use crate::pci::{MsiConfig, PciAddress, PciCapability, PciDeviceError}; - -use crate::pci::pcie::pci_bridge::PciBridgeBusRange; -use crate::pci::pcie::pcie_device::{PciPmcCap, PcieCap, PcieDevice}; -use crate::pci::pcie::pcie_host::PcieHostPort; -use crate::pci::pcie::pcie_port::PciePort; -use crate::pci::pcie::*; use anyhow::Result; use resources::SystemAllocator; +use sync::Mutex; use vm_control::GpeNotify; +use crate::bus::HostHotPlugKey; +use crate::bus::HotPlugBus; +use crate::pci::pci_configuration::PciCapabilityID; +use crate::pci::pcie::pci_bridge::PciBridgeBusRange; +use crate::pci::pcie::pcie_device::PciPmcCap; +use crate::pci::pcie::pcie_device::PcieCap; +use crate::pci::pcie::pcie_device::PcieDevice; +use crate::pci::pcie::pcie_host::PcieHostPort; +use crate::pci::pcie::pcie_port::PciePort; +use crate::pci::pcie::*; +use crate::pci::MsiConfig; +use crate::pci::PciAddress; +use crate::pci::PciCapability; +use crate::pci::PciDeviceError; + const PCIE_RP_DID: u16 = 0x3420; pub struct PcieRootPort { pcie_port: PciePort, diff --git a/devices/src/pci/pcie/pcie_switch.rs b/devices/src/pci/pcie/pcie_switch.rs index 6606ce3ec..19ffa312a 100644 --- a/devices/src/pci/pcie/pcie_switch.rs +++ b/devices/src/pci/pcie/pcie_switch.rs @@ -3,17 +3,21 @@ // found in the LICENSE file. use std::sync::Arc; + +use resources::SystemAllocator; use sync::Mutex; use crate::pci::pci_configuration::PciCapabilityID; -use crate::pci::{MsiConfig, PciAddress, PciCapability, PciDeviceError}; - use crate::pci::pcie::pci_bridge::PciBridgeBusRange; -use crate::pci::pcie::pcie_device::{PciPmcCap, PcieCap, PcieDevice}; +use crate::pci::pcie::pcie_device::PciPmcCap; +use crate::pci::pcie::pcie_device::PcieCap; +use crate::pci::pcie::pcie_device::PcieDevice; use crate::pci::pcie::pcie_port::PciePort; use crate::pci::pcie::*; - -use resources::SystemAllocator; +use crate::pci::MsiConfig; +use crate::pci::PciAddress; +use crate::pci::PciCapability; +use crate::pci::PciDeviceError; const PCIE_UP_DID: u16 = 0x3500; const PCIE_DP_DID: u16 = 0x3510; diff --git a/devices/src/pci/pvpanic.rs b/devices/src/pci/pvpanic.rs index b938cfd96..5bf491fb1 100644 --- a/devices/src/pci/pvpanic.rs +++ b/devices/src/pci/pvpanic.rs @@ -14,16 +14,29 @@ use std::fmt; +use base::error; use base::RawDescriptor; -use base::{self, error, SendTube, VmEventType}; -use resources::{Alloc, MmioType, SystemAllocator}; +use base::SendTube; +use base::VmEventType; +use base::{self}; +use resources::Alloc; +use resources::MmioType; +use resources::SystemAllocator; -use crate::pci::pci_configuration::{ - PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciClassCode, PciConfiguration, - PciHeaderType, PciOtherSubclass, -}; -use crate::pci::pci_device::{self, BarRange, PciDevice, Result}; -use crate::pci::{PciAddress, PciDeviceError, PCI_VENDOR_ID_REDHAT}; +use crate::pci::pci_configuration::PciBarConfiguration; +use crate::pci::pci_configuration::PciBarPrefetchable; +use crate::pci::pci_configuration::PciBarRegionType; +use crate::pci::pci_configuration::PciClassCode; +use crate::pci::pci_configuration::PciConfiguration; +use crate::pci::pci_configuration::PciHeaderType; +use crate::pci::pci_configuration::PciOtherSubclass; +use crate::pci::pci_device::BarRange; +use crate::pci::pci_device::PciDevice; +use crate::pci::pci_device::Result; +use crate::pci::pci_device::{self}; +use crate::pci::PciAddress; +use crate::pci::PciDeviceError; +use crate::pci::PCI_VENDOR_ID_REDHAT; const PCI_DEVICE_ID_REDHAT_PVPANIC: u16 = 0x0011; const PCI_PVPANIC_REVISION_ID: u8 = 1; @@ -194,9 +207,12 @@ impl PciDevice for PvPanicPciDevice { #[cfg(test)] mod test { - use super::*; use base::Tube; - use resources::{AddressRange, SystemAllocator, SystemAllocatorConfig}; + use resources::AddressRange; + use resources::SystemAllocator; + use resources::SystemAllocatorConfig; + + use super::*; #[test] fn pvpanic_read_write() { diff --git a/devices/src/pci/stub.rs b/devices/src/pci/stub.rs index cc42ae042..0643150c9 100644 --- a/devices/src/pci/stub.rs +++ b/devices/src/pci/stub.rs @@ -13,15 +13,21 @@ //! something to the guest on function 0. use base::RawDescriptor; -use resources::{Alloc, SystemAllocator}; +use resources::Alloc; +use resources::SystemAllocator; +use serde::Deserialize; +use serde::Serialize; -use crate::pci::pci_configuration::{ - PciBarConfiguration, PciClassCode, PciConfiguration, PciHeaderType, PciProgrammingInterface, - PciSubclass, -}; -use crate::pci::pci_device::{PciDevice, Result}; -use crate::pci::{PciAddress, PciDeviceError}; -use serde::{Deserialize, Serialize}; +use crate::pci::pci_configuration::PciBarConfiguration; +use crate::pci::pci_configuration::PciClassCode; +use crate::pci::pci_configuration::PciConfiguration; +use crate::pci::pci_configuration::PciHeaderType; +use crate::pci::pci_configuration::PciProgrammingInterface; +use crate::pci::pci_configuration::PciSubclass; +use crate::pci::pci_device::PciDevice; +use crate::pci::pci_device::Result; +use crate::pci::PciAddress; +use crate::pci::PciDeviceError; #[derive(Serialize, Deserialize)] pub struct StubPciParameters { @@ -128,8 +134,11 @@ impl PciDevice for StubPciDevice { #[cfg(test)] mod test { + use resources::AddressRange; + use resources::SystemAllocator; + use resources::SystemAllocatorConfig; + use super::*; - use resources::{AddressRange, SystemAllocator, SystemAllocatorConfig}; const CONFIG: StubPciParameters = StubPciParameters { address: PciAddress { diff --git a/devices/src/pci/vfio_pci.rs b/devices/src/pci/vfio_pci.rs index d01793f63..8da295a09 100644 --- a/devices/src/pci/vfio_pci.rs +++ b/devices/src/pci/vfio_pci.rs @@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#[cfg(feature = "direct")] -use anyhow::Context; -use std::cmp::{max, min, Reverse}; -use std::collections::{BTreeMap, BTreeSet}; +use std::cmp::max; +use std::cmp::min; +use std::cmp::Reverse; +use std::collections::BTreeMap; +use std::collections::BTreeSet; use std::fs; #[cfg(feature = "direct")] use std::path::Path; @@ -14,38 +15,66 @@ use std::str::FromStr; use std::sync::Arc; use std::thread; use std::u32; -use sync::Mutex; - -use base::{ - error, pagesize, warn, AsRawDescriptor, AsRawDescriptors, Event, EventToken, Protection, - RawDescriptor, Tube, WaitContext, -}; -use hypervisor::MemSlot; - -use resources::{Alloc, MmioType, SystemAllocator}; - -use vfio_sys::*; -use vm_control::{ - VmMemoryDestination, VmMemoryRequest, VmMemoryResponse, VmMemorySource, VmRequest, VmResponse, -}; - -use crate::pci::msi::{ - MsiConfig, MsiStatus, PCI_MSI_FLAGS, PCI_MSI_FLAGS_64BIT, PCI_MSI_FLAGS_MASKBIT, - PCI_MSI_NEXT_POINTER, -}; -use crate::pci::msix::{ - MsixConfig, MsixStatus, BITS_PER_PBA_ENTRY, MSIX_PBA_ENTRIES_MODULO, MSIX_TABLE_ENTRIES_MODULO, -}; #[cfg(feature = "direct")] -use crate::pci::pci_configuration::{CLASS_REG, CLASS_REG_REVISION_ID_OFFSET, HEADER_TYPE_REG}; -use crate::pci::pci_device::{BarRange, Error as PciDeviceError, PciDevice}; -use crate::pci::{ - PciAddress, PciBarConfiguration, PciBarIndex, PciBarPrefetchable, PciBarRegionType, - PciClassCode, PciId, PciInterruptPin, PCI_VENDOR_ID_INTEL, -}; +use anyhow::Context; +use base::error; +use base::pagesize; +use base::warn; +use base::AsRawDescriptor; +use base::AsRawDescriptors; +use base::Event; +use base::EventToken; +use base::Protection; +use base::RawDescriptor; +use base::Tube; +use base::WaitContext; +use hypervisor::MemSlot; +use resources::Alloc; +use resources::MmioType; +use resources::SystemAllocator; +use sync::Mutex; +use vfio_sys::*; +use vm_control::VmMemoryDestination; +use vm_control::VmMemoryRequest; +use vm_control::VmMemoryResponse; +use vm_control::VmMemorySource; +use vm_control::VmRequest; +use vm_control::VmResponse; -use crate::vfio::{VfioDevice, VfioError, VfioIrqType, VfioPciConfig}; +use crate::pci::msi::MsiConfig; +use crate::pci::msi::MsiStatus; +use crate::pci::msi::PCI_MSI_FLAGS; +use crate::pci::msi::PCI_MSI_FLAGS_64BIT; +use crate::pci::msi::PCI_MSI_FLAGS_MASKBIT; +use crate::pci::msi::PCI_MSI_NEXT_POINTER; +use crate::pci::msix::MsixConfig; +use crate::pci::msix::MsixStatus; +use crate::pci::msix::BITS_PER_PBA_ENTRY; +use crate::pci::msix::MSIX_PBA_ENTRIES_MODULO; +use crate::pci::msix::MSIX_TABLE_ENTRIES_MODULO; +#[cfg(feature = "direct")] +use crate::pci::pci_configuration::CLASS_REG; +#[cfg(feature = "direct")] +use crate::pci::pci_configuration::CLASS_REG_REVISION_ID_OFFSET; +#[cfg(feature = "direct")] +use crate::pci::pci_configuration::HEADER_TYPE_REG; +use crate::pci::pci_device::BarRange; +use crate::pci::pci_device::Error as PciDeviceError; +use crate::pci::pci_device::PciDevice; +use crate::pci::PciAddress; +use crate::pci::PciBarConfiguration; +use crate::pci::PciBarIndex; +use crate::pci::PciBarPrefetchable; +use crate::pci::PciBarRegionType; +use crate::pci::PciClassCode; +use crate::pci::PciId; +use crate::pci::PciInterruptPin; +use crate::pci::PCI_VENDOR_ID_INTEL; +use crate::vfio::VfioDevice; +use crate::vfio::VfioError; +use crate::vfio::VfioIrqType; +use crate::vfio::VfioPciConfig; use crate::IrqLevelEvent; const PCI_VENDOR_ID: u32 = 0x0; diff --git a/devices/src/pflash.rs b/devices/src/pflash.rs index b0bffe340..697b3001b 100644 --- a/devices/src/pflash.rs +++ b/devices/src/pflash.rs @@ -27,10 +27,13 @@ use anyhow::bail; use base::error; use data_model::VolatileSlice; use disk::DiskFile; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; use crate::pci::CrosvmDeviceId; -use crate::{BusAccessInfo, BusDevice, DeviceId}; +use crate::BusAccessInfo; +use crate::BusDevice; +use crate::DeviceId; const COMMAND_WRITE_BYTE: u8 = 0x10; const COMMAND_BLOCK_ERASE: u8 = 0x20; @@ -228,11 +231,11 @@ impl BusDevice for Pflash { #[cfg(test)] mod tests { - use super::*; - use base::FileReadWriteAtVolatile; use tempfile::tempfile; + use super::*; + const IMAGE_SIZE: usize = 4 * (1 << 20); // 4M const BLOCK_SIZE: u32 = 4 * (1 << 10); // 4K diff --git a/devices/src/pit.rs b/devices/src/pit.rs index e36ed6c28..19a4ee70e 100644 --- a/devices/src/pit.rs +++ b/devices/src/pit.rs @@ -6,12 +6,21 @@ use std::io::Error as IoError; use std::sync::Arc; use std::thread; -use std::time::{Duration, Instant}; +use std::time::Duration; +use std::time::Instant; -use base::{error, warn, Error as SysError, Event, EventToken, WaitContext}; +use base::error; +use base::warn; +use base::Error as SysError; +use base::Event; +use base::EventToken; +use base::WaitContext; use bit_field::BitField1; use bit_field::*; -use hypervisor::{PitChannelState, PitRWMode, PitRWState, PitState}; +use hypervisor::PitChannelState; +use hypervisor::PitRWMode; +use hypervisor::PitRWState; +use hypervisor::PitState; use remain::sorted; use sync::Mutex; use thiserror::Error; diff --git a/devices/src/pl030.rs b/devices/src/pl030.rs index 74cbeec82..75bdbed75 100644 --- a/devices/src/pl030.rs +++ b/devices/src/pl030.rs @@ -2,12 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::warn; use std::convert::TryFrom; -use std::time::{SystemTime, UNIX_EPOCH}; +use std::time::SystemTime; +use std::time::UNIX_EPOCH; + +use base::warn; use crate::pci::CrosvmDeviceId; -use crate::{BusAccessInfo, BusDevice, DeviceId, IrqEdgeEvent}; +use crate::BusAccessInfo; +use crate::BusDevice; +use crate::DeviceId; +use crate::IrqEdgeEvent; // Register offsets // Data register diff --git a/devices/src/platform/vfio_platform.rs b/devices/src/platform/vfio_platform.rs index 5fef3a184..4c83affcc 100644 --- a/devices/src/platform/vfio_platform.rs +++ b/devices/src/platform/vfio_platform.rs @@ -1,20 +1,41 @@ // Copyright 2022 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::pci::CrosvmDeviceId; -use crate::vfio::{VfioDevice, VfioError, VfioIrq}; -use crate::{BusAccessInfo, BusDevice, BusDeviceObj, DeviceId, IrqEdgeEvent, IrqLevelEvent}; -use anyhow::{bail, Context, Result}; -use base::{ - error, pagesize, AsRawDescriptor, AsRawDescriptors, Event, MappedRegion, MemoryMapping, - MemoryMappingBuilder, Protection, RawDescriptor, Tube, -}; -use resources::SystemAllocator; use std::fs::File; use std::sync::Arc; use std::u32; + +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; +use base::error; +use base::pagesize; +use base::AsRawDescriptor; +use base::AsRawDescriptors; +use base::Event; +use base::MappedRegion; +use base::MemoryMapping; +use base::MemoryMappingBuilder; +use base::Protection; +use base::RawDescriptor; +use base::Tube; +use resources::SystemAllocator; use vfio_sys::*; -use vm_control::{VmMemoryDestination, VmMemoryRequest, VmMemoryResponse, VmMemorySource}; +use vm_control::VmMemoryDestination; +use vm_control::VmMemoryRequest; +use vm_control::VmMemoryResponse; +use vm_control::VmMemorySource; + +use crate::pci::CrosvmDeviceId; +use crate::vfio::VfioDevice; +use crate::vfio::VfioError; +use crate::vfio::VfioIrq; +use crate::BusAccessInfo; +use crate::BusDevice; +use crate::BusDeviceObj; +use crate::DeviceId; +use crate::IrqEdgeEvent; +use crate::IrqLevelEvent; struct MmioInfo { index: u32, diff --git a/devices/src/proxy.rs b/devices/src/proxy.rs index d8378513f..7a4797888 100644 --- a/devices/src/proxy.rs +++ b/devices/src/proxy.rs @@ -7,16 +7,28 @@ use std::ffi::CString; use std::time::Duration; -use base::{error, AsRawDescriptor, RawDescriptor, Tube, TubeError}; -use libc::{self, pid_t}; -use minijail::{self, Minijail}; +use base::error; +use base::AsRawDescriptor; +use base::RawDescriptor; +use base::Tube; +use base::TubeError; +use libc::pid_t; +use libc::{self}; +use minijail::Minijail; +use minijail::{self}; use remain::sorted; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; use thiserror::Error; use crate::bus::ConfigWriteResult; -use crate::pci::{CrosvmDeviceId, PciAddress}; -use crate::{BusAccessInfo, BusDevice, BusRange, BusType, DeviceId}; +use crate::pci::CrosvmDeviceId; +use crate::pci::PciAddress; +use crate::BusAccessInfo; +use crate::BusDevice; +use crate::BusRange; +use crate::BusType; +use crate::DeviceId; /// Errors for proxy devices. #[sorted] @@ -355,9 +367,8 @@ impl Drop for ProxyDevice { /// the process. #[cfg(test)] mod tests { - use crate::pci::PciId; - use super::*; + use crate::pci::PciId; /// A simple test echo device that outputs the same u8 that was written to it. struct EchoDevice { diff --git a/devices/src/register_space/register.rs b/devices/src/register_space/register.rs index 407a8ee1e..5ab331f03 100644 --- a/devices/src/register_space/register.rs +++ b/devices/src/register_space/register.rs @@ -3,13 +3,18 @@ // found in the LICENSE file. use std::boxed::Box; -use std::cmp::{max, min, Ord, Ordering, PartialOrd}; +use std::cmp::max; +use std::cmp::min; +use std::cmp::Ord; +use std::cmp::Ordering; +use std::cmp::PartialOrd; use std::mem::size_of; -use std::sync::{Arc, MutexGuard}; -use sync::Mutex; +use std::sync::Arc; +use std::sync::MutexGuard; use base::error; use data_model::DataInit; +use sync::Mutex; /// Type of offset in the register space. pub type RegisterOffset = u64; diff --git a/devices/src/register_space/register_space.rs b/devices/src/register_space/register_space.rs index 3f30ac09a..b1e1db7e3 100644 --- a/devices/src/register_space/register_space.rs +++ b/devices/src/register_space/register_space.rs @@ -2,9 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::register::{Register, RegisterInterface, RegisterOffset, RegisterRange, RegisterValue}; use std::collections::btree_map::BTreeMap; +use super::register::Register; +use super::register::RegisterInterface; +use super::register::RegisterOffset; +use super::register::RegisterRange; +use super::register::RegisterValue; + /// Register space repesents a set of registers. It can handle read/write operations. pub struct RegisterSpace { regs: BTreeMap>, @@ -93,10 +98,12 @@ impl RegisterSpace { #[cfg(test)] mod tests { - use super::*; use std::sync::Arc; + use sync::Mutex; + use super::*; + #[test] fn regs_no_reg() { let regs = RegisterSpace::new(); diff --git a/devices/src/serial.rs b/devices/src/serial.rs index 0fd146d22..94b954445 100644 --- a/devices/src/serial.rs +++ b/devices/src/serial.rs @@ -6,17 +6,23 @@ pub(crate) mod sys; use std::collections::VecDeque; use std::io; -use std::sync::atomic::{AtomicU8, Ordering}; -use std::sync::mpsc::{channel, Receiver, TryRecvError}; +use std::sync::atomic::AtomicU8; +use std::sync::atomic::Ordering; +use std::sync::mpsc::channel; +use std::sync::mpsc::Receiver; +use std::sync::mpsc::TryRecvError; use std::sync::Arc; use std::thread::{self}; -use base::{error, Event, Result}; +use base::error; +use base::Event; +use base::Result; use crate::bus::BusAccessInfo; use crate::pci::CrosvmDeviceId; use crate::serial_device::SerialInput; -use crate::{BusDevice, DeviceId}; +use crate::BusDevice; +use crate::DeviceId; const LOOP_SIZE: usize = 0x40; @@ -397,13 +403,13 @@ impl BusDevice for Serial { #[cfg(test)] mod tests { - use super::*; use std::io; use std::sync::Arc; use hypervisor::ProtectionType; use sync::Mutex; + use super::*; pub use crate::sys::serial_device::SerialDevice; #[derive(Clone)] diff --git a/devices/src/serial/sys/unix.rs b/devices/src/serial/sys/unix.rs index 2e3824440..9b871ac77 100644 --- a/devices/src/serial/sys/unix.rs +++ b/devices/src/serial/sys/unix.rs @@ -4,7 +4,10 @@ use std::io; -use base::{Event, FileSync, RawDescriptor, Result}; +use base::Event; +use base::FileSync; +use base::RawDescriptor; +use base::Result; use hypervisor::ProtectionType; use crate::serial_device::SerialInput; diff --git a/devices/src/serial/sys/windows.rs b/devices/src/serial/sys/windows.rs index 1752ecdc6..ca11367b9 100644 --- a/devices/src/serial/sys/windows.rs +++ b/devices/src/serial/sys/windows.rs @@ -4,13 +4,18 @@ use std::io; use std::io::Write; -use std::thread::{self, JoinHandle}; +use std::thread::JoinHandle; +use std::thread::{self}; use std::time::Duration; -use base::{ - error, named_pipes::PipeConnection, Event, EventToken, FileSync, RawDescriptor, Result, - WaitContext, -}; +use base::error; +use base::named_pipes::PipeConnection; +use base::Event; +use base::EventToken; +use base::FileSync; +use base::RawDescriptor; +use base::Result; +use base::WaitContext; use hypervisor::ProtectionType; use crate::bus::BusDevice; @@ -234,10 +239,9 @@ impl SyncWorker { #[cfg(test)] mod tests { - use super::*; - use regex::Regex; + use super::*; use crate::serial::tests::*; use crate::serial::*; @@ -284,7 +288,8 @@ mod tests { #[test] fn named_pipe() { use base::named_pipes; - use base::named_pipes::{BlockingMode, FramingMode}; + use base::named_pipes::BlockingMode; + use base::named_pipes::FramingMode; use rand::Rng; let path_str = format!(r"\\.\pipe\kiwi_test_{}", rand::thread_rng().gen::()); diff --git a/devices/src/serial_device.rs b/devices/src/serial_device.rs index 45fff80a3..440b2fd5f 100644 --- a/devices/src/serial_device.rs +++ b/devices/src/serial_device.rs @@ -2,19 +2,29 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::fmt::{self, Display}; -use std::fs::{File, OpenOptions}; -use std::io::{self, stdin, stdout}; +use std::fmt::Display; +use std::fmt::{self}; +use std::fs::File; +use std::fs::OpenOptions; +use std::io::stdin; +use std::io::stdout; +use std::io::{self}; use std::path::PathBuf; +use base::error; +use base::open_file; #[cfg(windows)] use base::platform::Console as WinConsole; -use base::{ - error, open_file, syslog, AsRawDescriptor, Event, FileSync, RawDescriptor, ReadNotifier, -}; +use base::syslog; +use base::AsRawDescriptor; +use base::Event; +use base::FileSync; +use base::RawDescriptor; +use base::ReadNotifier; use hypervisor::ProtectionType; use remain::sorted; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; use thiserror::Error as ThisError; pub use crate::sys::serial_device::SerialDevice; @@ -212,9 +222,10 @@ impl SerialParameters { #[cfg(test)] mod tests { - use super::*; use serde_keyvalue::*; + use super::*; + fn from_serial_arg(options: &str) -> Result { from_key_values(options) } diff --git a/devices/src/sys/unix.rs b/devices/src/sys/unix.rs index 290069392..ff15f4fe6 100644 --- a/devices/src/sys/unix.rs +++ b/devices/src/sys/unix.rs @@ -6,4 +6,5 @@ mod acpi; pub(crate) mod bat; pub(crate) mod serial_device; -pub(crate) use acpi::{acpi_event_run, get_acpi_event_sock}; +pub(crate) use acpi::acpi_event_run; +pub(crate) use acpi::get_acpi_event_sock; diff --git a/devices/src/sys/unix/acpi.rs b/devices/src/sys/unix/acpi.rs index 3f0a244fd..976a76ab6 100644 --- a/devices/src/sys/unix/acpi.rs +++ b/devices/src/sys/unix/acpi.rs @@ -4,13 +4,18 @@ use std::sync::Arc; -use base::{error, info, warn, AcpiNotifyEvent, NetlinkGenericSocket}; +use base::error; +use base::info; +use base::warn; +use base::AcpiNotifyEvent; +use base::NetlinkGenericSocket; use sync::Mutex; -use crate::{ - acpi::{ACPIPMError, GpeResource, Pm1Resource, BITMASK_PM1STS_PWRBTN_STS}, - IrqLevelEvent, -}; +use crate::acpi::ACPIPMError; +use crate::acpi::GpeResource; +use crate::acpi::Pm1Resource; +use crate::acpi::BITMASK_PM1STS_PWRBTN_STS; +use crate::IrqLevelEvent; pub(crate) fn get_acpi_event_sock() -> Result, ACPIPMError> { // Get group id corresponding to acpi_mc_group of acpi_event family diff --git a/devices/src/sys/unix/bat.rs b/devices/src/sys/unix/bat.rs index b3889ba28..91e5403ca 100644 --- a/devices/src/sys/unix/bat.rs +++ b/devices/src/sys/unix/bat.rs @@ -4,14 +4,17 @@ use std::sync::Arc; -use base::{error, Descriptor, WaitContext}; -use power_monitor::{BatteryStatus, CreatePowerMonitorFn, PowerMonitor}; +use base::error; +use base::Descriptor; +use base::WaitContext; +use power_monitor::BatteryStatus; +use power_monitor::CreatePowerMonitorFn; +use power_monitor::PowerMonitor; use sync::Mutex; -use crate::{ - bat::{GoldfishBatteryState, Token}, - IrqLevelEvent, -}; +use crate::bat::GoldfishBatteryState; +use crate::bat::Token; +use crate::IrqLevelEvent; const BATTERY_STATUS_VAL_CHARGING: u32 = 1; const BATTERY_STATUS_VAL_DISCHARGING: u32 = 2; diff --git a/devices/src/sys/unix/serial_device.rs b/devices/src/sys/unix/serial_device.rs index aa87baa4d..180b9a493 100644 --- a/devices/src/sys/unix/serial_device.rs +++ b/devices/src/sys/unix/serial_device.rs @@ -2,19 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::{error, AsRawDescriptor, Event, FileSync, RawDescriptor, ReadNotifier}; -use base::{info, read_raw_stdin}; -use hypervisor::ProtectionType; use std::borrow::Cow; use std::fs::OpenOptions; use std::io; -use std::io::{ErrorKind, Write}; +use std::io::ErrorKind; +use std::io::Write; use std::os::unix::net::UnixDatagram; -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::path::PathBuf; use std::thread; use std::time::Duration; -use crate::serial_device::{Error, SerialInput, SerialParameters}; +use base::error; +use base::info; +use base::read_raw_stdin; +use base::AsRawDescriptor; +use base::Event; +use base::FileSync; +use base::RawDescriptor; +use base::ReadNotifier; +use hypervisor::ProtectionType; + +use crate::serial_device::Error; +use crate::serial_device::SerialInput; +use crate::serial_device::SerialParameters; pub const SYSTEM_SERIAL_TYPE_NAME: &str = "UnixSocket"; diff --git a/devices/src/sys/windows.rs b/devices/src/sys/windows.rs index 96e97a528..a6ce80834 100644 --- a/devices/src/sys/windows.rs +++ b/devices/src/sys/windows.rs @@ -5,4 +5,5 @@ mod acpi; pub(crate) mod serial_device; -pub(crate) use acpi::{acpi_event_run, get_acpi_event_sock}; +pub(crate) use acpi::acpi_event_run; +pub(crate) use acpi::get_acpi_event_sock; diff --git a/devices/src/sys/windows/acpi.rs b/devices/src/sys/windows/acpi.rs index 05d543a63..ec2c38009 100644 --- a/devices/src/sys/windows/acpi.rs +++ b/devices/src/sys/windows/acpi.rs @@ -7,10 +7,10 @@ use std::sync::Arc; use base::Descriptor; use sync::Mutex; -use crate::{ - acpi::{ACPIPMError, GpeResource, Pm1Resource}, - IrqLevelEvent, -}; +use crate::acpi::ACPIPMError; +use crate::acpi::GpeResource; +use crate::acpi::Pm1Resource; +use crate::IrqLevelEvent; pub(crate) fn get_acpi_event_sock() -> Result, ACPIPMError> { Ok(None) diff --git a/devices/src/sys/windows/serial_device.rs b/devices/src/sys/windows/serial_device.rs index fd2697ff7..a0f7a1162 100644 --- a/devices/src/sys/windows/serial_device.rs +++ b/devices/src/sys/windows/serial_device.rs @@ -2,15 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::serial_device::{Error, SerialInput, SerialParameters}; -use base::named_pipes; -use base::named_pipes::{BlockingMode, FramingMode}; -use base::FileSync; -use base::{AsRawDescriptor, Event, RawDescriptor}; -use hypervisor::ProtectionType; use std::io::{self}; +use base::named_pipes; +use base::named_pipes::BlockingMode; +use base::named_pipes::FramingMode; +use base::AsRawDescriptor; pub use base::Console as ConsoleInput; +use base::Event; +use base::FileSync; +use base::RawDescriptor; +use hypervisor::ProtectionType; + +use crate::serial_device::Error; +use crate::serial_device::SerialInput; +use crate::serial_device::SerialParameters; pub const SYSTEM_SERIAL_TYPE_NAME: &str = "NamedPipe"; diff --git a/devices/src/tsc.rs b/devices/src/tsc.rs index 06279ec15..247ae79ed 100644 --- a/devices/src/tsc.rs +++ b/devices/src/tsc.rs @@ -7,11 +7,14 @@ // TODO(b/213149158): Remove after uses are added. #![allow(dead_code)] -use anyhow::{anyhow, Result}; -use base::{debug, error}; -use once_cell::sync::Lazy; use std::arch::x86_64::_rdtsc; +use anyhow::anyhow; +use anyhow::Result; +use base::debug; +use base::error; +use once_cell::sync::Lazy; + mod calibrate; mod cpuid; mod grouping; @@ -144,10 +147,13 @@ fn tsc_sync_mitigations_inner( #[cfg(test)] mod tests { - use super::*; - use crate::tsc::grouping::{CoreGroup, CoreGrouping, CoreOffset}; use std::time::Duration; + use super::*; + use crate::tsc::grouping::CoreGroup; + use crate::tsc::grouping::CoreGrouping; + use crate::tsc::grouping::CoreOffset; + #[test] fn test_sync_mitigation_set_offsets() { let offsets = vec![(0, 0), (1, 1000), (2, -1000), (3, 2000)]; diff --git a/devices/src/tsc/calibrate.rs b/devices/src/tsc/calibrate.rs index 73371c924..b9bab2654 100644 --- a/devices/src/tsc/calibrate.rs +++ b/devices/src/tsc/calibrate.rs @@ -2,14 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use anyhow::{anyhow, bail, Context, Result}; -use remain::sorted; use std::collections::HashSet; use std::iter::FromIterator; -use std::time::{Duration, Instant}; -use thiserror::Error; +use std::time::Duration; +use std::time::Instant; -use base::{set_cpu_affinity, warn}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; +use base::set_cpu_affinity; +use base::warn; +use remain::sorted; +use thiserror::Error; use super::grouping::*; use super::rdtsc_safe; @@ -342,9 +347,10 @@ fn calibrate_tsc_state_inner(rdtsc: fn() -> u64, cores: Vec) -> Result + Ord>(x: T, y: T) -> T { if x < y { y - x diff --git a/devices/src/usb/host_backend/error.rs b/devices/src/usb/host_backend/error.rs index aad8f5449..12d5b5ecf 100644 --- a/devices/src/usb/host_backend/error.rs +++ b/devices/src/usb/host_backend/error.rs @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::usb::xhci::scatter_gather_buffer::Error as BufferError; -use crate::usb::xhci::xhci_transfer::Error as XhciTransferError; -use crate::utils::Error as UtilsError; - use base::TubeError; use remain::sorted; use thiserror::Error; use usb_util::Error as UsbUtilError; +use crate::usb::xhci::scatter_gather_buffer::Error as BufferError; +use crate::usb::xhci::xhci_transfer::Error as XhciTransferError; +use crate::utils::Error as UtilsError; + #[sorted] #[derive(Error, Debug)] pub enum Error { diff --git a/devices/src/usb/host_backend/host_backend_device_provider.rs b/devices/src/usb/host_backend/host_backend_device_provider.rs index 9401efc7f..0ff537fba 100644 --- a/devices/src/usb/host_backend/host_backend_device_provider.rs +++ b/devices/src/usb/host_backend/host_backend_device_provider.rs @@ -2,26 +2,33 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::collections::HashMap; use std::fs::File; +use std::mem; use std::sync::Arc; +use std::time::Duration; + +use anyhow::Context; +use base::error; +use base::AsRawDescriptor; +use base::EventType; +use base::RawDescriptor; +use base::Tube; +use sync::Mutex; +use usb_util::Device; +use vm_control::UsbControlAttachedDevice; +use vm_control::UsbControlCommand; +use vm_control::UsbControlResult; +use vm_control::USB_CONTROL_MAX_PORTS; use super::error::*; use super::host_device::HostDevice; use crate::usb::xhci::usb_hub::UsbHub; use crate::usb::xhci::xhci_backend_device_provider::XhciBackendDeviceProvider; use crate::utils::AsyncJobQueue; -use crate::utils::{EventHandler, EventLoop, FailHandle}; - -use anyhow::Context; -use base::{error, AsRawDescriptor, EventType, RawDescriptor, Tube}; -use std::collections::HashMap; -use std::mem; -use std::time::Duration; -use sync::Mutex; -use usb_util::Device; -use vm_control::{ - UsbControlAttachedDevice, UsbControlCommand, UsbControlResult, USB_CONTROL_MAX_PORTS, -}; +use crate::utils::EventHandler; +use crate::utils::EventLoop; +use crate::utils::FailHandle; const SOCKET_TIMEOUT_MS: u64 = 2000; diff --git a/devices/src/usb/host_backend/host_device.rs b/devices/src/usb/host_backend/host_device.rs index 82a85777d..4bb348c12 100644 --- a/devices/src/usb/host_backend/host_device.rs +++ b/devices/src/usb/host_backend/host_device.rs @@ -2,27 +2,40 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::collections::HashMap; +use std::mem; use std::mem::drop; use std::sync::Arc; +use base::error; +use base::warn; +use data_model::DataInit; +use sync::Mutex; +use usb_util::ConfigDescriptorTree; +use usb_util::ControlRequestDataPhaseTransferDirection; +use usb_util::ControlRequestRecipient; +use usb_util::DescriptorHeader; +use usb_util::DescriptorType; +use usb_util::Device; +use usb_util::InterfaceDescriptor; +use usb_util::StandardControlRequest; +use usb_util::Transfer; +use usb_util::TransferStatus; +use usb_util::UsbRequestSetup; + use super::error::*; use super::usb_endpoint::UsbEndpoint; -use super::utils::{submit_transfer, update_transfer_state}; +use super::utils::submit_transfer; +use super::utils::update_transfer_state; use crate::usb::xhci::scatter_gather_buffer::ScatterGatherBuffer; -use crate::usb::xhci::xhci_backend_device::{BackendType, UsbDeviceAddress, XhciBackendDevice}; -use crate::usb::xhci::xhci_transfer::{XhciTransfer, XhciTransferState, XhciTransferType}; +use crate::usb::xhci::xhci_backend_device::BackendType; +use crate::usb::xhci::xhci_backend_device::UsbDeviceAddress; +use crate::usb::xhci::xhci_backend_device::XhciBackendDevice; +use crate::usb::xhci::xhci_transfer::XhciTransfer; +use crate::usb::xhci::xhci_transfer::XhciTransferState; +use crate::usb::xhci::xhci_transfer::XhciTransferType; use crate::utils::AsyncJobQueue; use crate::utils::FailHandle; -use base::{error, warn}; -use data_model::DataInit; -use std::collections::HashMap; -use std::mem; -use sync::Mutex; -use usb_util::{ - ConfigDescriptorTree, ControlRequestDataPhaseTransferDirection, ControlRequestRecipient, - DescriptorHeader, DescriptorType, Device, InterfaceDescriptor, StandardControlRequest, - Transfer, TransferStatus, UsbRequestSetup, -}; #[derive(PartialEq)] pub enum ControlEndpointState { diff --git a/devices/src/usb/host_backend/usb_endpoint.rs b/devices/src/usb/host_backend/usb_endpoint.rs index 9d40c399c..d534b5575 100644 --- a/devices/src/usb/host_backend/usb_endpoint.rs +++ b/devices/src/usb/host_backend/usb_endpoint.rs @@ -5,19 +5,25 @@ use std::cmp; use std::sync::Arc; -use super::error::*; -use super::utils::{submit_transfer, update_transfer_state}; -use crate::usb::xhci::scatter_gather_buffer::ScatterGatherBuffer; -use crate::usb::xhci::xhci_transfer::{ - TransferDirection, XhciTransfer, XhciTransferState, XhciTransferType, -}; -use crate::utils::AsyncJobQueue; -use crate::utils::FailHandle; use base::error; use sync::Mutex; -use usb_util::{ - Device, EndpointDirection, EndpointType, Transfer, TransferStatus, ENDPOINT_DIRECTION_OFFSET, -}; +use usb_util::Device; +use usb_util::EndpointDirection; +use usb_util::EndpointType; +use usb_util::Transfer; +use usb_util::TransferStatus; +use usb_util::ENDPOINT_DIRECTION_OFFSET; + +use super::error::*; +use super::utils::submit_transfer; +use super::utils::update_transfer_state; +use crate::usb::xhci::scatter_gather_buffer::ScatterGatherBuffer; +use crate::usb::xhci::xhci_transfer::TransferDirection; +use crate::usb::xhci::xhci_transfer::XhciTransfer; +use crate::usb::xhci::xhci_transfer::XhciTransferState; +use crate::usb::xhci::xhci_transfer::XhciTransferType; +use crate::utils::AsyncJobQueue; +use crate::utils::FailHandle; /// Isochronous, Bulk or Interrupt endpoint. pub struct UsbEndpoint { diff --git a/devices/src/usb/host_backend/utils.rs b/devices/src/usb/host_backend/utils.rs index 1be10a337..2f5ba0b86 100644 --- a/devices/src/usb/host_backend/utils.rs +++ b/devices/src/usb/host_backend/utils.rs @@ -5,12 +5,17 @@ use std::mem; use std::sync::Arc; +use base::error; +use base::warn; +use usb_util::Device; +use usb_util::Transfer; +use usb_util::TransferStatus; + use super::error::*; -use crate::usb::xhci::xhci_transfer::{XhciTransfer, XhciTransferState}; +use crate::usb::xhci::xhci_transfer::XhciTransfer; +use crate::usb::xhci::xhci_transfer::XhciTransferState; use crate::utils::AsyncJobQueue; use crate::utils::FailHandle; -use base::{error, warn}; -use usb_util::{Device, Transfer, TransferStatus}; /// Helper function to update xhci_transfer state. pub fn update_transfer_state( diff --git a/devices/src/usb/xhci/command_ring_controller.rs b/devices/src/usb/xhci/command_ring_controller.rs index 2987c0d34..3a4436189 100644 --- a/devices/src/usb/xhci/command_ring_controller.rs +++ b/devices/src/usb/xhci/command_ring_controller.rs @@ -2,27 +2,43 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::device_slot::{DeviceSlot, DeviceSlots, Error as DeviceSlotError}; -use super::interrupter::{Error as InterrupterError, Interrupter}; -use super::ring_buffer_controller::{ - Error as RingBufferControllerError, RingBufferController, TransferDescriptorHandler, -}; -use super::xhci_abi::{ - AddressDeviceCommandTrb, AddressedTrb, ConfigureEndpointCommandTrb, DisableSlotCommandTrb, - Error as TrbError, EvaluateContextCommandTrb, ResetDeviceCommandTrb, - SetTRDequeuePointerCommandTrb, StopEndpointCommandTrb, TransferDescriptor, TrbCast, - TrbCompletionCode, TrbType, -}; -use super::xhci_regs::{valid_slot_id, MAX_SLOTS}; -use crate::utils::EventLoop; +use std::sync::Arc; use anyhow::Context; -use base::{error, warn, Error as SysError, Event}; +use base::error; +use base::warn; +use base::Error as SysError; +use base::Event; use remain::sorted; -use std::sync::Arc; use sync::Mutex; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; + +use super::device_slot::DeviceSlot; +use super::device_slot::DeviceSlots; +use super::device_slot::Error as DeviceSlotError; +use super::interrupter::Error as InterrupterError; +use super::interrupter::Interrupter; +use super::ring_buffer_controller::Error as RingBufferControllerError; +use super::ring_buffer_controller::RingBufferController; +use super::ring_buffer_controller::TransferDescriptorHandler; +use super::xhci_abi::AddressDeviceCommandTrb; +use super::xhci_abi::AddressedTrb; +use super::xhci_abi::ConfigureEndpointCommandTrb; +use super::xhci_abi::DisableSlotCommandTrb; +use super::xhci_abi::Error as TrbError; +use super::xhci_abi::EvaluateContextCommandTrb; +use super::xhci_abi::ResetDeviceCommandTrb; +use super::xhci_abi::SetTRDequeuePointerCommandTrb; +use super::xhci_abi::StopEndpointCommandTrb; +use super::xhci_abi::TransferDescriptor; +use super::xhci_abi::TrbCast; +use super::xhci_abi::TrbCompletionCode; +use super::xhci_abi::TrbType; +use super::xhci_regs::valid_slot_id; +use super::xhci_regs::MAX_SLOTS; +use crate::utils::EventLoop; #[sorted] #[derive(Error, Debug)] diff --git a/devices/src/usb/xhci/device_slot.rs b/devices/src/usb/xhci/device_slot.rs index 06df8237d..134eeb3a0 100644 --- a/devices/src/usb/xhci/device_slot.rs +++ b/devices/src/usb/xhci/device_slot.rs @@ -2,28 +2,46 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::interrupter::Interrupter; -use super::transfer_ring_controller::{TransferRingController, TransferRingControllerError}; -use super::usb_hub::{self, UsbHub}; -use super::xhci_abi::{ - AddressDeviceCommandTrb, ConfigureEndpointCommandTrb, DequeuePtr, DeviceContext, - DeviceSlotState, EndpointContext, EndpointState, EvaluateContextCommandTrb, - InputControlContext, SlotContext, TrbCompletionCode, DEVICE_CONTEXT_ENTRY_SIZE, -}; -use super::xhci_regs::{valid_slot_id, MAX_PORTS, MAX_SLOTS}; -use crate::register_space::Register; -use crate::usb::host_backend::error::Error as HostBackendProviderError; -use crate::usb::xhci::ring_buffer_stop_cb::{fallible_closure, RingBufferStopCallback}; -use crate::utils::{EventLoop, FailHandle}; +use std::mem::size_of; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::sync::Arc; + use base::error; use bit_field::Error as BitFieldError; use remain::sorted; -use std::mem::size_of; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; use sync::Mutex; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory, GuestMemoryError}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +use vm_memory::GuestMemoryError; + +use super::interrupter::Interrupter; +use super::transfer_ring_controller::TransferRingController; +use super::transfer_ring_controller::TransferRingControllerError; +use super::usb_hub::UsbHub; +use super::usb_hub::{self}; +use super::xhci_abi::AddressDeviceCommandTrb; +use super::xhci_abi::ConfigureEndpointCommandTrb; +use super::xhci_abi::DequeuePtr; +use super::xhci_abi::DeviceContext; +use super::xhci_abi::DeviceSlotState; +use super::xhci_abi::EndpointContext; +use super::xhci_abi::EndpointState; +use super::xhci_abi::EvaluateContextCommandTrb; +use super::xhci_abi::InputControlContext; +use super::xhci_abi::SlotContext; +use super::xhci_abi::TrbCompletionCode; +use super::xhci_abi::DEVICE_CONTEXT_ENTRY_SIZE; +use super::xhci_regs::valid_slot_id; +use super::xhci_regs::MAX_PORTS; +use super::xhci_regs::MAX_SLOTS; +use crate::register_space::Register; +use crate::usb::host_backend::error::Error as HostBackendProviderError; +use crate::usb::xhci::ring_buffer_stop_cb::fallible_closure; +use crate::usb::xhci::ring_buffer_stop_cb::RingBufferStopCallback; +use crate::utils::EventLoop; +use crate::utils::FailHandle; #[sorted] #[derive(Error, Debug)] diff --git a/devices/src/usb/xhci/event_ring.rs b/devices/src/usb/xhci/event_ring.rs index 8b006c9f4..693aad1b4 100644 --- a/devices/src/usb/xhci/event_ring.rs +++ b/devices/src/usb/xhci/event_ring.rs @@ -2,12 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::mem::size_of; +use std::sync::atomic::fence; +use std::sync::atomic::Ordering; + use data_model::DataInit; use remain::sorted; -use std::mem::size_of; -use std::sync::atomic::{fence, Ordering}; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory, GuestMemoryError}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +use vm_memory::GuestMemoryError; use super::xhci_abi::*; @@ -206,9 +210,10 @@ impl EventRing { #[cfg(test)] mod test { - use super::*; use std::mem::size_of; + use super::*; + #[test] fn test_uninited() { let gm = GuestMemory::new(&[(GuestAddress(0), 0x1000)]).unwrap(); diff --git a/devices/src/usb/xhci/interrupter.rs b/devices/src/usb/xhci/interrupter.rs index 3fc48ee61..40c9a7206 100644 --- a/devices/src/usb/xhci/interrupter.rs +++ b/devices/src/usb/xhci/interrupter.rs @@ -2,17 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::event_ring::{Error as EventRingError, EventRing}; -use super::xhci_abi::{ - CommandCompletionEventTrb, Error as TrbError, PortStatusChangeEventTrb, TransferEventTrb, Trb, - TrbCast, TrbCompletionCode, TrbType, -}; -use super::xhci_regs::*; -use crate::register_space::Register; -use base::{Error as SysError, Event}; +use base::Error as SysError; +use base::Event; use remain::sorted; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; + +use super::event_ring::Error as EventRingError; +use super::event_ring::EventRing; +use super::xhci_abi::CommandCompletionEventTrb; +use super::xhci_abi::Error as TrbError; +use super::xhci_abi::PortStatusChangeEventTrb; +use super::xhci_abi::TransferEventTrb; +use super::xhci_abi::Trb; +use super::xhci_abi::TrbCast; +use super::xhci_abi::TrbCompletionCode; +use super::xhci_abi::TrbType; +use super::xhci_regs::*; +use crate::register_space::Register; #[sorted] #[derive(Error, Debug)] diff --git a/devices/src/usb/xhci/intr_resample_handler.rs b/devices/src/usb/xhci/intr_resample_handler.rs index 0b99f2b6b..696e06f04 100644 --- a/devices/src/usb/xhci/intr_resample_handler.rs +++ b/devices/src/usb/xhci/intr_resample_handler.rs @@ -2,14 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::interrupter::Interrupter; -use crate::utils::{EventHandler, EventLoop}; +use std::sync::Arc; use anyhow::Context; -use base::{error, Event, EventType}; -use std::sync::Arc; +use base::error; +use base::Event; +use base::EventType; use sync::Mutex; +use super::interrupter::Interrupter; +use crate::utils::EventHandler; +use crate::utils::EventLoop; + /// Interrupt Resample handler handles resample event. It will reassert interrupt if needed. pub struct IntrResampleHandler { interrupter: Arc>, diff --git a/devices/src/usb/xhci/ring_buffer.rs b/devices/src/usb/xhci/ring_buffer.rs index d3ac8596f..ee9c0e85f 100644 --- a/devices/src/usb/xhci/ring_buffer.rs +++ b/devices/src/usb/xhci/ring_buffer.rs @@ -2,14 +2,23 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::xhci_abi::{ - AddressedTrb, Error as TrbError, LinkTrb, TransferDescriptor, Trb, TrbCast, TrbType, -}; -use remain::sorted; -use std::fmt::{self, Display}; +use std::fmt::Display; +use std::fmt::{self}; use std::mem::size_of; + +use remain::sorted; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory, GuestMemoryError}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +use vm_memory::GuestMemoryError; + +use super::xhci_abi::AddressedTrb; +use super::xhci_abi::Error as TrbError; +use super::xhci_abi::LinkTrb; +use super::xhci_abi::TransferDescriptor; +use super::xhci_abi::Trb; +use super::xhci_abi::TrbCast; +use super::xhci_abi::TrbType; #[sorted] #[derive(Error, Debug)] diff --git a/devices/src/usb/xhci/ring_buffer_controller.rs b/devices/src/usb/xhci/ring_buffer_controller.rs index 2e07d2a26..112528e6e 100644 --- a/devices/src/usb/xhci/ring_buffer_controller.rs +++ b/devices/src/usb/xhci/ring_buffer_controller.rs @@ -2,20 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::ring_buffer_stop_cb::RingBufferStopCallback; -use super::xhci_abi::*; -use crate::utils::{self, EventHandler, EventLoop}; -use std::fmt::{self, Display}; -use std::sync::{Arc, MutexGuard}; -use sync::Mutex; +use std::fmt::Display; +use std::fmt::{self}; +use std::sync::Arc; +use std::sync::MutexGuard; use anyhow::Context; -use base::{error, Error as SysError, Event, EventType}; +use base::error; +use base::Error as SysError; +use base::Event; +use base::EventType; use remain::sorted; +use sync::Mutex; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; use super::ring_buffer::RingBuffer; +use super::ring_buffer_stop_cb::RingBufferStopCallback; +use super::xhci_abi::*; +use crate::utils::EventHandler; +use crate::utils::EventLoop; +use crate::utils::{self}; #[sorted] #[derive(Error, Debug)] @@ -219,9 +227,11 @@ where #[cfg(test)] mod tests { - use super::*; use std::mem::size_of; - use std::sync::mpsc::{channel, Sender}; + use std::sync::mpsc::channel; + use std::sync::mpsc::Sender; + + use super::*; struct TestHandler { sender: Sender, diff --git a/devices/src/usb/xhci/ring_buffer_stop_cb.rs b/devices/src/usb/xhci/ring_buffer_stop_cb.rs index 503276fea..08db56a78 100644 --- a/devices/src/usb/xhci/ring_buffer_stop_cb.rs +++ b/devices/src/usb/xhci/ring_buffer_stop_cb.rs @@ -2,9 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::utils::FailHandle; +use std::sync::Arc; +use std::sync::Mutex; + use base::error; -use std::sync::{Arc, Mutex}; + +use crate::utils::FailHandle; /// RingBufferStopCallback wraps a callback. The callback will be invoked when last instance of /// RingBufferStopCallback and its clones is dropped. @@ -53,8 +56,10 @@ pub fn fallible_closure Result<(), E> + 'sta #[cfg(test)] mod tests { + use std::sync::Arc; + use std::sync::Mutex; + use super::*; - use std::sync::{Arc, Mutex}; fn task(_: RingBufferStopCallback) {} diff --git a/devices/src/usb/xhci/scatter_gather_buffer.rs b/devices/src/usb/xhci/scatter_gather_buffer.rs index e3130dca5..66d81aa06 100644 --- a/devices/src/usb/xhci/scatter_gather_buffer.rs +++ b/devices/src/usb/xhci/scatter_gather_buffer.rs @@ -2,13 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::xhci_abi::{ - AddressedTrb, Error as TrbError, NormalTrb, TransferDescriptor, TrbCast, TrbType, -}; use bit_field::Error as BitFieldError; use remain::sorted; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory, GuestMemoryError}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +use vm_memory::GuestMemoryError; + +use super::xhci_abi::AddressedTrb; +use super::xhci_abi::Error as TrbError; +use super::xhci_abi::NormalTrb; +use super::xhci_abi::TransferDescriptor; +use super::xhci_abi::TrbCast; +use super::xhci_abi::TrbType; #[sorted] #[derive(Error, Debug)] @@ -140,7 +146,8 @@ impl ScatterGatherBuffer { #[cfg(test)] mod test { use super::*; - use crate::usb::xhci::xhci_abi::{AddressedTrb, Trb}; + use crate::usb::xhci::xhci_abi::AddressedTrb; + use crate::usb::xhci::xhci_abi::Trb; #[test] fn scatter_gather_buffer_test() { diff --git a/devices/src/usb/xhci/transfer_ring_controller.rs b/devices/src/usb/xhci/transfer_ring_controller.rs index d46928cf4..2206eb0fc 100644 --- a/devices/src/usb/xhci/transfer_ring_controller.rs +++ b/devices/src/usb/xhci/transfer_ring_controller.rs @@ -2,14 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::usb::xhci::ring_buffer_controller::{ - Error as RingBufferControllerError, RingBufferController, TransferDescriptorHandler, -}; -use crate::utils::EventLoop; +use std::sync::Arc; use anyhow::Context; use base::Event; -use std::sync::Arc; use sync::Mutex; use vm_memory::GuestMemory; @@ -17,6 +13,10 @@ use super::interrupter::Interrupter; use super::usb_hub::UsbPort; use super::xhci_abi::TransferDescriptor; use super::xhci_transfer::XhciTransferManager; +use crate::usb::xhci::ring_buffer_controller::Error as RingBufferControllerError; +use crate::usb::xhci::ring_buffer_controller::RingBufferController; +use crate::usb::xhci::ring_buffer_controller::TransferDescriptorHandler; +use crate::utils::EventLoop; /// Transfer ring controller manages transfer ring. pub type TransferRingController = RingBufferController; diff --git a/devices/src/usb/xhci/usb_hub.rs b/devices/src/usb/xhci/usb_hub.rs index d529e106b..ef7ed0797 100644 --- a/devices/src/usb/xhci/usb_hub.rs +++ b/devices/src/usb/xhci/usb_hub.rs @@ -2,19 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::interrupter::{Error as InterrupterError, Interrupter}; -use super::xhci_backend_device::{BackendType, XhciBackendDevice}; -use super::xhci_regs::{ - XhciRegs, MAX_PORTS, PORTSC_CONNECT_STATUS_CHANGE, PORTSC_CURRENT_CONNECT_STATUS, - PORTSC_PORT_ENABLED, PORTSC_PORT_ENABLED_DISABLED_CHANGE, USB2_PORTS_END, USB2_PORTS_START, - USB3_PORTS_END, USB3_PORTS_START, USB_STS_PORT_CHANGE_DETECT, -}; -use crate::register_space::Register; +use std::sync::Arc; +use std::sync::MutexGuard; + use remain::sorted; -use std::sync::{Arc, MutexGuard}; use sync::Mutex; use thiserror::Error; +use super::interrupter::Error as InterrupterError; +use super::interrupter::Interrupter; +use super::xhci_backend_device::BackendType; +use super::xhci_backend_device::XhciBackendDevice; +use super::xhci_regs::XhciRegs; +use super::xhci_regs::MAX_PORTS; +use super::xhci_regs::PORTSC_CONNECT_STATUS_CHANGE; +use super::xhci_regs::PORTSC_CURRENT_CONNECT_STATUS; +use super::xhci_regs::PORTSC_PORT_ENABLED; +use super::xhci_regs::PORTSC_PORT_ENABLED_DISABLED_CHANGE; +use super::xhci_regs::USB2_PORTS_END; +use super::xhci_regs::USB2_PORTS_START; +use super::xhci_regs::USB3_PORTS_END; +use super::xhci_regs::USB3_PORTS_START; +use super::xhci_regs::USB_STS_PORT_CHANGE_DETECT; +use crate::register_space::Register; + #[sorted] #[derive(Error, Debug)] pub enum Error { diff --git a/devices/src/usb/xhci/xhci.rs b/devices/src/usb/xhci/xhci.rs index 56e9a0431..f42a4266c 100644 --- a/devices/src/usb/xhci/xhci.rs +++ b/devices/src/usb/xhci/xhci.rs @@ -2,27 +2,33 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::command_ring_controller::{CommandRingController, CommandRingControllerError}; -use super::device_slot::{DeviceSlots, Error as DeviceSlotError}; -use super::interrupter::{Error as InterrupterError, Interrupter}; +use std::sync::Arc; +use std::thread; + +use base::error; +use remain::sorted; +use sync::Mutex; +use thiserror::Error; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; + +use super::command_ring_controller::CommandRingController; +use super::command_ring_controller::CommandRingControllerError; +use super::device_slot::DeviceSlots; +use super::device_slot::Error as DeviceSlotError; +use super::interrupter::Error as InterrupterError; +use super::interrupter::Interrupter; use super::intr_resample_handler::IntrResampleHandler; use super::ring_buffer_stop_cb::RingBufferStopCallback; use super::usb_hub::UsbHub; use super::xhci_backend_device_provider::XhciBackendDeviceProvider; use super::xhci_regs::*; -use crate::usb::host_backend::{ - error::Error as HostBackendProviderError, - host_backend_device_provider::HostBackendDeviceProvider, -}; -use crate::utils::{Error as UtilsError, EventLoop, FailHandle}; +use crate::usb::host_backend::error::Error as HostBackendProviderError; +use crate::usb::host_backend::host_backend_device_provider::HostBackendDeviceProvider; +use crate::utils::Error as UtilsError; +use crate::utils::EventLoop; +use crate::utils::FailHandle; use crate::IrqLevelEvent; -use base::error; -use remain::sorted; -use std::sync::Arc; -use std::thread; -use sync::Mutex; -use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory}; #[sorted] #[derive(Error, Debug)] diff --git a/devices/src/usb/xhci/xhci_abi.rs b/devices/src/usb/xhci/xhci_abi.rs index bde8a5bf9..3125c5614 100644 --- a/devices/src/usb/xhci/xhci_abi.rs +++ b/devices/src/usb/xhci/xhci_abi.rs @@ -2,11 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::fmt::Display; +use std::fmt::{self}; + use bit_field::Error as BitFieldError; use bit_field::*; use data_model::DataInit; use remain::sorted; -use std::fmt::{self, Display}; use thiserror::Error; use vm_memory::GuestAddress; diff --git a/devices/src/usb/xhci/xhci_backend_device_provider.rs b/devices/src/usb/xhci/xhci_backend_device_provider.rs index ca416cc02..5a58ed97b 100644 --- a/devices/src/usb/xhci/xhci_backend_device_provider.rs +++ b/devices/src/usb/xhci/xhci_backend_device_provider.rs @@ -2,11 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::sync::Arc; + +use base::RawDescriptor; + use super::super::host_backend::error::Result; use super::usb_hub::UsbHub; -use crate::utils::{EventLoop, FailHandle}; -use base::RawDescriptor; -use std::sync::Arc; +use crate::utils::EventLoop; +use crate::utils::FailHandle; /// Xhci backend provider will run on an EventLoop and connect new devices to usb ports. pub trait XhciBackendDeviceProvider: Send { diff --git a/devices/src/usb/xhci/xhci_controller.rs b/devices/src/usb/xhci/xhci_controller.rs index 132dd39e9..f761a3b02 100644 --- a/devices/src/usb/xhci/xhci_controller.rs +++ b/devices/src/usb/xhci/xhci_controller.rs @@ -2,25 +2,41 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::pci::{ - BarRange, PciAddress, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciClassCode, - PciConfiguration, PciDevice, PciDeviceError, PciHeaderType, PciInterruptPin, - PciProgrammingInterface, PciSerialBusSubClass, -}; +use std::mem; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::sync::Arc; -use crate::register_space::{Register, RegisterSpace}; +use base::error; +use base::AsRawDescriptor; +use base::RawDescriptor; +use resources::Alloc; +use resources::MmioType; +use resources::SystemAllocator; +use vm_memory::GuestMemory; + +use crate::pci::BarRange; +use crate::pci::PciAddress; +use crate::pci::PciBarConfiguration; +use crate::pci::PciBarPrefetchable; +use crate::pci::PciBarRegionType; +use crate::pci::PciClassCode; +use crate::pci::PciConfiguration; +use crate::pci::PciDevice; +use crate::pci::PciDeviceError; +use crate::pci::PciHeaderType; +use crate::pci::PciInterruptPin; +use crate::pci::PciProgrammingInterface; +use crate::pci::PciSerialBusSubClass; +use crate::register_space::Register; +use crate::register_space::RegisterSpace; use crate::usb::host_backend::host_backend_device_provider::HostBackendDeviceProvider; use crate::usb::xhci::xhci::Xhci; use crate::usb::xhci::xhci_backend_device_provider::XhciBackendDeviceProvider; -use crate::usb::xhci::xhci_regs::{init_xhci_mmio_space_and_regs, XhciRegs}; +use crate::usb::xhci::xhci_regs::init_xhci_mmio_space_and_regs; +use crate::usb::xhci::xhci_regs::XhciRegs; use crate::utils::FailHandle; use crate::IrqLevelEvent; -use base::{error, AsRawDescriptor, RawDescriptor}; -use resources::{Alloc, MmioType, SystemAllocator}; -use std::mem; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; -use vm_memory::GuestMemory; const XHCI_BAR0_SIZE: u64 = 0x10000; diff --git a/devices/src/usb/xhci/xhci_regs.rs b/devices/src/usb/xhci/xhci_regs.rs index 810c44ea1..11be81c6b 100644 --- a/devices/src/usb/xhci/xhci_regs.rs +++ b/devices/src/usb/xhci/xhci_regs.rs @@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::register_space::{Register, RegisterSpace}; +use crate::register_space::Register; +use crate::register_space::RegisterSpace; /// Max interrupter number. pub const MAX_INTERRUPTER: u8 = 1; diff --git a/devices/src/usb/xhci/xhci_transfer.rs b/devices/src/usb/xhci/xhci_transfer.rs index 83dce9a9c..31e99f8fd 100644 --- a/devices/src/usb/xhci/xhci_transfer.rs +++ b/devices/src/usb/xhci/xhci_transfer.rs @@ -2,26 +2,40 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::interrupter::{Error as InterrupterError, Interrupter}; -use super::scatter_gather_buffer::{Error as BufferError, ScatterGatherBuffer}; -use super::usb_hub::{Error as HubError, UsbPort}; -use super::xhci_abi::{ - AddressedTrb, Error as TrbError, EventDataTrb, SetupStageTrb, TransferDescriptor, TrbCast, - TrbCompletionCode, TrbType, -}; -use super::xhci_regs::MAX_INTERRUPTER; -use base::{error, Error as SysError, Event}; +use std::cmp::min; +use std::fmt::Display; +use std::fmt::{self}; +use std::mem; +use std::sync::Arc; +use std::sync::Weak; + +use base::error; +use base::Error as SysError; +use base::Event; use bit_field::Error as BitFieldError; use remain::sorted; -use std::cmp::min; -use std::fmt::{self, Display}; -use std::mem; -use std::sync::{Arc, Weak}; use sync::Mutex; use thiserror::Error; -use usb_util::{TransferStatus, UsbRequestSetup}; +use usb_util::TransferStatus; +use usb_util::UsbRequestSetup; use vm_memory::GuestMemory; +use super::interrupter::Error as InterrupterError; +use super::interrupter::Interrupter; +use super::scatter_gather_buffer::Error as BufferError; +use super::scatter_gather_buffer::ScatterGatherBuffer; +use super::usb_hub::Error as HubError; +use super::usb_hub::UsbPort; +use super::xhci_abi::AddressedTrb; +use super::xhci_abi::Error as TrbError; +use super::xhci_abi::EventDataTrb; +use super::xhci_abi::SetupStageTrb; +use super::xhci_abi::TransferDescriptor; +use super::xhci_abi::TrbCast; +use super::xhci_abi::TrbCompletionCode; +use super::xhci_abi::TrbType; +use super::xhci_regs::MAX_INTERRUPTER; + #[sorted] #[derive(Error, Debug)] pub enum Error { diff --git a/devices/src/utils/async_job_queue.rs b/devices/src/utils/async_job_queue.rs index 8ec8fb6c4..7e2014aa7 100644 --- a/devices/src/utils/async_job_queue.rs +++ b/devices/src/utils/async_job_queue.rs @@ -2,15 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::{Error, Result}; -use super::{EventHandler, EventLoop}; - -use anyhow::Context; -use base::{Event, EventType}; use std::mem; use std::sync::Arc; + +use anyhow::Context; +use base::Event; +use base::EventType; use sync::Mutex; +use super::Error; +use super::EventHandler; +use super::EventLoop; +use super::Result; + /// Async Job Queue can schedule async jobs. pub struct AsyncJobQueue { jobs: Mutex>>, diff --git a/devices/src/utils/event_loop.rs b/devices/src/utils/event_loop.rs index 2d596096d..847dc6f0b 100644 --- a/devices/src/utils/event_loop.rs +++ b/devices/src/utils/event_loop.rs @@ -2,14 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::error::{Error, Result}; -use base::{error, warn, AsRawDescriptor, Descriptor, Event, EventType, WaitContext}; use std::collections::BTreeMap; use std::mem::drop; -use std::sync::{Arc, Weak}; +use std::sync::Arc; +use std::sync::Weak; use std::thread; + +use base::error; +use base::warn; +use base::AsRawDescriptor; +use base::Descriptor; +use base::Event; +use base::EventType; +use base::WaitContext; use sync::Mutex; +use super::error::Error; +use super::error::Result; + /// A fail handle will do the clean up when we cannot recover from some error. pub trait FailHandle: Send + Sync { /// Fail the code. @@ -193,9 +203,13 @@ impl EventLoop { #[cfg(test)] mod tests { - use super::*; + use std::sync::Arc; + use std::sync::Condvar; + use std::sync::Mutex; + use base::Event; - use std::sync::{Arc, Condvar, Mutex}; + + use super::*; struct EventLoopTestHandler { val: Mutex, diff --git a/devices/src/vfio.rs b/devices/src/vfio.rs index 842a155a9..f831e21f9 100644 --- a/devices/src/vfio.rs +++ b/devices/src/vfio.rs @@ -5,32 +5,48 @@ use std::cell::RefCell; use std::collections::HashMap; use std::ffi::CString; -use std::fs::{File, OpenOptions}; +use std::fs::File; +use std::fs::OpenOptions; use std::io; use std::mem; use std::os::raw::c_ulong; use std::os::unix::prelude::FileExt; -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::path::PathBuf; use std::slice; use std::sync::Arc; use std::u32; -use crate::IommuDevType; use base::error; -use base::{ - ioctl, ioctl_with_mut_ptr, ioctl_with_mut_ref, ioctl_with_ptr, ioctl_with_ref, ioctl_with_val, - warn, AsRawDescriptor, Error, Event, FromRawDescriptor, RawDescriptor, SafeDescriptor, -}; -use data_model::{vec_with_array_field, DataInit}; -use hypervisor::{DeviceKind, Vm}; +use base::ioctl; +use base::ioctl_with_mut_ptr; +use base::ioctl_with_mut_ref; +use base::ioctl_with_ptr; +use base::ioctl_with_ref; +use base::ioctl_with_val; +use base::warn; +use base::AsRawDescriptor; +use base::Error; +use base::Event; +use base::FromRawDescriptor; +use base::RawDescriptor; +use base::SafeDescriptor; +use data_model::vec_with_array_field; +use data_model::DataInit; +use hypervisor::DeviceKind; +use hypervisor::Vm; use once_cell::sync::OnceCell; use remain::sorted; use resources::address_allocator::AddressAllocator; -use resources::{AddressRange, Alloc, Error as ResourcesError}; +use resources::AddressRange; +use resources::Alloc; +use resources::Error as ResourcesError; use sync::Mutex; use thiserror::Error; use vfio_sys::*; +use crate::IommuDevType; + #[sorted] #[derive(Error, Debug)] pub enum VfioError { diff --git a/devices/src/virtio/async_device.rs b/devices/src/virtio/async_device.rs index 2c630aa9f..c4a456dd5 100644 --- a/devices/src/virtio/async_device.rs +++ b/devices/src/virtio/async_device.rs @@ -6,14 +6,16 @@ #![cfg_attr(windows, allow(dead_code))] -use anyhow::{bail, Context}; +use anyhow::bail; +use anyhow::Context; use async_task::Task; use base::warn; -use cros_async::{AsyncResult, Executor}; -use futures::{ - future::{AbortHandle, Abortable, Pending}, - Future, -}; +use cros_async::AsyncResult; +use cros_async::Executor; +use futures::future::AbortHandle; +use futures::future::Abortable; +use futures::future::Pending; +use futures::Future; /// A queue for which processing can be started on an async executor. /// diff --git a/devices/src/virtio/async_utils.rs b/devices/src/virtio/async_utils.rs index 2250a4ee6..a02d7a0d1 100644 --- a/devices/src/virtio/async_utils.rs +++ b/devices/src/virtio/async_utils.rs @@ -7,11 +7,14 @@ use std::cell::RefCell; use std::rc::Rc; -use anyhow::{Context, Result}; +use anyhow::Context; +use anyhow::Result; use base::Event; -use cros_async::{EventAsync, Executor}; +use cros_async::EventAsync; +use cros_async::Executor; -use super::{Interrupt, SignalableInterrupt}; +use super::Interrupt; +use super::SignalableInterrupt; /// Async task that waits for a signal from `event`. Once this event is readable, exit. Exiting /// this future will cause the main loop to break and the worker thread to exit. diff --git a/devices/src/virtio/balloon.rs b/devices/src/virtio/balloon.rs index 511cdba56..2272e6950 100644 --- a/devices/src/virtio/balloon.rs +++ b/devices/src/virtio/balloon.rs @@ -10,21 +10,46 @@ use std::rc::Rc; use std::sync::Arc; use std::thread; -use futures::{channel::mpsc, pin_mut, StreamExt}; +use balloon_control::BalloonStats; +use balloon_control::BalloonTubeCommand; +use balloon_control::BalloonTubeResult; +use base::error; +use base::warn; +use base::AsRawDescriptor; +use base::Event; +use base::RawDescriptor; +use base::Tube; +use base::{self}; +use cros_async::block_on; +use cros_async::select7; +use cros_async::sync::Mutex as AsyncMutex; +use cros_async::AsyncTube; +use cros_async::EventAsync; +use cros_async::Executor; +use data_model::DataInit; +use data_model::Le16; +use data_model::Le32; +use data_model::Le64; +use futures::channel::mpsc; +use futures::pin_mut; +use futures::StreamExt; use remain::sorted; use thiserror::Error as ThisError; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; -use balloon_control::{BalloonStats, BalloonTubeCommand, BalloonTubeResult}; -use base::{self, error, warn, AsRawDescriptor, Event, RawDescriptor, Tube}; -use cros_async::{block_on, select7, sync::Mutex as AsyncMutex, AsyncTube, EventAsync, Executor}; -use data_model::{DataInit, Le16, Le32, Le64}; -use vm_memory::{GuestAddress, GuestMemory}; - -use super::{ - async_utils, copy_config, descriptor_utils, DescriptorChain, DeviceType, Interrupt, Queue, - Reader, SignalableInterrupt, VirtioDevice, -}; -use crate::{UnpinRequest, UnpinResponse}; +use super::async_utils; +use super::copy_config; +use super::descriptor_utils; +use super::DescriptorChain; +use super::DeviceType; +use super::Interrupt; +use super::Queue; +use super::Reader; +use super::SignalableInterrupt; +use super::VirtioDevice; +use crate::UnpinRequest; +use crate::UnpinResponse; #[sorted] #[derive(ThisError, Debug)] @@ -795,8 +820,8 @@ impl VirtioDevice for Balloon { #[cfg(test)] mod tests { use super::*; - - use crate::virtio::descriptor_utils::{create_descriptor_chain, DescriptorType}; + use crate::virtio::descriptor_utils::create_descriptor_chain; + use crate::virtio::descriptor_utils::DescriptorType; #[test] fn desc_parsing_inflate() { diff --git a/devices/src/virtio/balloon/sys.rs b/devices/src/virtio/balloon/sys.rs index 92b04947b..ba3b0d2c5 100644 --- a/devices/src/virtio/balloon/sys.rs +++ b/devices/src/virtio/balloon/sys.rs @@ -12,7 +12,8 @@ cfg_if::cfg_if! { } } -pub(in crate::virtio::balloon) use platform::{ - free_memory, reclaim_memory, send_adjusted_response, send_adjusted_response_async, - send_adjusted_response_if_needed, -}; +pub(in crate::virtio::balloon) use platform::free_memory; +pub(in crate::virtio::balloon) use platform::reclaim_memory; +pub(in crate::virtio::balloon) use platform::send_adjusted_response; +pub(in crate::virtio::balloon) use platform::send_adjusted_response_async; +pub(in crate::virtio::balloon) use platform::send_adjusted_response_if_needed; diff --git a/devices/src/virtio/balloon/sys/unix.rs b/devices/src/virtio/balloon/sys/unix.rs index d58314a0b..bbc52d7a0 100644 --- a/devices/src/virtio/balloon/sys/unix.rs +++ b/devices/src/virtio/balloon/sys/unix.rs @@ -5,12 +5,18 @@ use std::sync::Arc; use balloon_control::BalloonTubeResult; -use base::{error, warn, Tube}; -use cros_async::{block_on, sync::Mutex as AsyncMutex, AsyncTube}; -use vm_memory::{GuestAddress, GuestMemory}; +use base::error; +use base::warn; +use base::Tube; +use cros_async::block_on; +use cros_async::sync::Mutex as AsyncMutex; +use cros_async::AsyncTube; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; use crate::virtio::balloon::virtio_balloon_config; -use crate::virtio::balloon::{BalloonState, VIRTIO_BALLOON_PFN_SHIFT}; +use crate::virtio::balloon::BalloonState; +use crate::virtio::balloon::VIRTIO_BALLOON_PFN_SHIFT; // TODO nkgold (b/222588331): This relies on deref-ing an AsyncTube to a Tube. We should // not allow AsyncTube to be deref'd to Tube and refactor this method. diff --git a/devices/src/virtio/balloon/sys/windows.rs b/devices/src/virtio/balloon/sys/windows.rs index 82791eac9..7bc7b328d 100644 --- a/devices/src/virtio/balloon/sys/windows.rs +++ b/devices/src/virtio/balloon/sys/windows.rs @@ -5,13 +5,18 @@ use std::sync::Arc; use balloon_control::BalloonTubeResult; -use base::{warn, Tube}; -use cros_async::{block_on, sync::Mutex as AsyncMutex, AsyncTube}; -use vm_control::{VmMemoryRequest, VmMemoryResponse}; +use base::warn; +use base::Tube; +use cros_async::block_on; +use cros_async::sync::Mutex as AsyncMutex; +use cros_async::AsyncTube; +use vm_control::VmMemoryRequest; +use vm_control::VmMemoryResponse; use vm_memory::GuestAddress; use crate::virtio::balloon::virtio_balloon_config; -use crate::virtio::balloon::{BalloonState, VIRTIO_BALLOON_PFN_SHIFT}; +use crate::virtio::balloon::BalloonState; +use crate::virtio::balloon::VIRTIO_BALLOON_PFN_SHIFT; // TODO nkgold (b/222588331): Need AsyncTube to be able to be de-ref'd to Tube before this can be // implemented. diff --git a/devices/src/virtio/block/asynchronous.rs b/devices/src/virtio/block/asynchronous.rs index 6c8e9ae92..f54719a23 100644 --- a/devices/src/virtio/block/asynchronous.rs +++ b/devices/src/virtio/block/asynchronous.rs @@ -3,37 +3,62 @@ // found in the LICENSE file. use std::cell::RefCell; -use std::io::{self, Write}; +use std::io::Write; +use std::io::{self}; use std::mem::size_of; use std::rc::Rc; use std::result; -use std::sync::{atomic::AtomicU64, atomic::Ordering, Arc}; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; +use std::sync::Arc; use std::thread; use std::time::Duration; use std::u32; +use base::error; +use base::info; +use base::warn; +use base::AsRawDescriptor; +use base::Error as SysError; +use base::Event; +use base::RawDescriptor; +use base::Result as SysResult; +use base::Timer; +use base::Tube; +use base::TubeError; +use cros_async::select5; +use cros_async::sync::Mutex as AsyncMutex; +use cros_async::AsyncError; +use cros_async::AsyncTube; +use cros_async::EventAsync; +use cros_async::Executor; +use cros_async::SelectResult; +use cros_async::TimerAsync; +use data_model::DataInit; +use disk::AsyncDisk; +use disk::ToAsyncDisk; use futures::pin_mut; -use futures::stream::{FuturesUnordered, StreamExt}; +use futures::stream::FuturesUnordered; +use futures::stream::StreamExt; use remain::sorted; use thiserror::Error as ThisError; - -use base::Error as SysError; -use base::Result as SysResult; -use base::{error, info, warn, AsRawDescriptor, Event, RawDescriptor, Timer, Tube, TubeError}; -use cros_async::{ - select5, sync::Mutex as AsyncMutex, AsyncError, AsyncTube, EventAsync, Executor, SelectResult, - TimerAsync, -}; -use data_model::DataInit; -use disk::{AsyncDisk, ToAsyncDisk}; -use vm_control::{DiskControlCommand, DiskControlResult}; +use vm_control::DiskControlCommand; +use vm_control::DiskControlResult; use vm_memory::GuestMemory; use super::common::*; -use crate::virtio::{ - async_utils, block::sys::*, copy_config, DescriptorChain, DescriptorError, DeviceType, - Interrupt, Queue, Reader, SignalableInterrupt, VirtioDevice, Writer, -}; +use crate::virtio::async_utils; +use crate::virtio::block::sys::*; +use crate::virtio::copy_config; +use crate::virtio::DescriptorChain; +use crate::virtio::DescriptorError; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::Reader; +use crate::virtio::SignalableInterrupt; +use crate::virtio::VirtioDevice; +use crate::virtio::Writer; const QUEUE_SIZE: u16 = 256; const NUM_QUEUES: u16 = 16; @@ -832,21 +857,22 @@ impl VirtioDevice for BlockAsync { #[cfg(test)] mod tests { - use std::fs::{File, OpenOptions}; + use std::fs::File; + use std::fs::OpenOptions; use std::mem::size_of_val; use std::sync::atomic::AtomicU64; - use data_model::{Le32, Le64}; + use data_model::Le32; + use data_model::Le64; use disk::SingleFileDisk; use hypervisor::ProtectionType; use tempfile::TempDir; use vm_memory::GuestAddress; - use crate::virtio::base_features; - use crate::virtio::block::common::*; - use crate::virtio::descriptor_utils::{create_descriptor_chain, DescriptorType}; - use super::*; + use crate::virtio::base_features; + use crate::virtio::descriptor_utils::create_descriptor_chain; + use crate::virtio::descriptor_utils::DescriptorType; #[test] fn read_size() { diff --git a/devices/src/virtio/block/block.rs b/devices/src/virtio/block/block.rs index 7c80bd151..8bb6d4fb9 100644 --- a/devices/src/virtio/block/block.rs +++ b/devices/src/virtio/block/block.rs @@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::io::{self, Write}; +use std::io::Write; +use std::io::{self}; use std::mem::size_of; #[cfg(windows)] use std::num::NonZeroU32; @@ -13,26 +14,43 @@ use std::thread; use std::time::Duration; use std::u32; +use base::error; +use base::info; +use base::warn; #[cfg(unix)] use base::AsRawDescriptor; use base::Error as SysError; +use base::Event; +use base::EventToken; +use base::RawDescriptor; use base::Result as SysResult; -use base::{error, info, warn, Event, EventToken, RawDescriptor, Timer, Tube, WaitContext}; +use base::Timer; +use base::Tube; +use base::WaitContext; use data_model::DataInit; use disk::DiskFile; - use remain::sorted; -use serde::{Deserialize, Deserializer, Serialize}; +use serde::Deserialize; +use serde::Deserializer; +use serde::Serialize; use sync::Mutex; use thiserror::Error; -use vm_control::{DiskControlCommand, DiskControlResult}; +use vm_control::DiskControlCommand; +use vm_control::DiskControlResult; use vm_memory::GuestMemory; use super::common::*; -use crate::virtio::{ - block::sys::*, copy_config, DescriptorChain, DescriptorError, DeviceType, Interrupt, Queue, - Reader, SignalableInterrupt, VirtioDevice, Writer, -}; +use crate::virtio::block::sys::*; +use crate::virtio::copy_config; +use crate::virtio::DescriptorChain; +use crate::virtio::DescriptorError; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::Reader; +use crate::virtio::SignalableInterrupt; +use crate::virtio::VirtioDevice; +use crate::virtio::Writer; const QUEUE_SIZE: u16 = 256; const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE]; @@ -772,17 +790,17 @@ impl VirtioDevice for Block { mod tests { use std::mem::size_of_val; - use data_model::{Le32, Le64}; + use data_model::Le32; + use data_model::Le64; use hypervisor::ProtectionType; use serde_keyvalue::*; use tempfile::tempfile; use vm_memory::GuestAddress; - use crate::virtio::base_features; - use crate::virtio::block::common::*; - use crate::virtio::descriptor_utils::{create_descriptor_chain, DescriptorType}; - use super::*; + use crate::virtio::base_features; + use crate::virtio::descriptor_utils::create_descriptor_chain; + use crate::virtio::descriptor_utils::DescriptorType; #[test] fn read_size() { diff --git a/devices/src/virtio/block/common.rs b/devices/src/virtio/block/common.rs index 9d38cf3e4..6fad2d3f9 100644 --- a/devices/src/virtio/block/common.rs +++ b/devices/src/virtio/block/common.rs @@ -2,7 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use data_model::{DataInit, Le16, Le32, Le64}; +use data_model::DataInit; +use data_model::Le16; +use data_model::Le32; +use data_model::Le64; pub const SECTOR_SHIFT: u8 = 9; pub const SECTOR_SIZE: u64 = 0x01 << SECTOR_SHIFT; diff --git a/devices/src/virtio/block/mod.rs b/devices/src/virtio/block/mod.rs index d564fc4a2..e0a49de71 100644 --- a/devices/src/virtio/block/mod.rs +++ b/devices/src/virtio/block/mod.rs @@ -7,6 +7,7 @@ pub mod block; pub(crate) mod common; pub(crate) mod sys; -pub use asynchronous::{BlockAsync, DiskState}; +pub use asynchronous::BlockAsync; +pub use asynchronous::DiskState; pub use block::Block; pub use common::*; diff --git a/devices/src/virtio/block/sys/unix.rs b/devices/src/virtio/block/sys/unix.rs index a51e87582..2d4a5120b 100644 --- a/devices/src/virtio/block/sys/unix.rs +++ b/devices/src/virtio/block/sys/unix.rs @@ -2,8 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::cmp::max; +use std::cmp::min; + use base::iov_max; -use std::cmp::{max, min}; pub fn get_seg_max(queue_size: u16) -> u32 { let seg_max = min(max(iov_max(), 1), u32::max_value() as usize) as u32; diff --git a/devices/src/virtio/console.rs b/devices/src/virtio/console.rs index 4fb839c21..45cb0bd67 100644 --- a/devices/src/virtio/console.rs +++ b/devices/src/virtio/console.rs @@ -10,24 +10,39 @@ pub mod asynchronous; mod sys; use std::collections::VecDeque; -use std::io::{self, Read, Write}; +use std::io::Read; +use std::io::Write; +use std::io::{self}; use std::ops::DerefMut; use std::result; use std::sync::Arc; use std::thread; -use base::{error, AsRawDescriptor, Descriptor, Event, EventToken, RawDescriptor, WaitContext}; -use data_model::{DataInit, Le16, Le32}; +use base::error; +use base::AsRawDescriptor; +use base::Descriptor; +use base::Event; +use base::EventToken; +use base::RawDescriptor; +use base::WaitContext; +use data_model::DataInit; +use data_model::Le16; +use data_model::Le32; use hypervisor::ProtectionType; use remain::sorted; use sync::Mutex; use thiserror::Error as ThisError; use vm_memory::GuestMemory; -use crate::virtio::{ - base_features, copy_config, DeviceType, Interrupt, Queue, Reader, SignalableInterrupt, - VirtioDevice, Writer, -}; +use crate::virtio::base_features; +use crate::virtio::copy_config; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::Reader; +use crate::virtio::SignalableInterrupt; +use crate::virtio::VirtioDevice; +use crate::virtio::Writer; pub(crate) const QUEUE_SIZE: u16 = 256; diff --git a/devices/src/virtio/console/asynchronous.rs b/devices/src/virtio/console/asynchronous.rs index ae0df0d1e..058fe3b12 100644 --- a/devices/src/virtio/console/asynchronous.rs +++ b/devices/src/virtio/console/asynchronous.rs @@ -4,11 +4,24 @@ //! Asynchronous console device which implementation can be shared by VMM and vhost-user. -use std::{collections::VecDeque, io, sync::Arc, thread}; +use std::collections::VecDeque; +use std::io; +use std::sync::Arc; +use std::thread; use anyhow::Context; -use base::{error, warn, AsRawDescriptor, Event, FileSync, RawDescriptor}; -use cros_async::{select2, AsyncResult, EventAsync, Executor, IntoAsync, IoSourceExt}; +use base::error; +use base::warn; +use base::AsRawDescriptor; +use base::Event; +use base::FileSync; +use base::RawDescriptor; +use cros_async::select2; +use cros_async::AsyncResult; +use cros_async::EventAsync; +use cros_async::Executor; +use cros_async::IntoAsync; +use cros_async::IoSourceExt; use data_model::DataInit; use futures::FutureExt; use hypervisor::ProtectionType; @@ -16,17 +29,23 @@ use sync::Mutex; use vm_memory::GuestMemory; use vmm_vhost::message::VhostUserVirtioFeatures; -use crate::{ - serial_device::SerialInput, - virtio::{ - self, async_device::AsyncQueueState, async_utils, base_features, copy_config, - virtio_console_config, ConsoleError, DeviceType, Interrupt, Queue, SignalableInterrupt, - VirtioDevice, - }, - SerialDevice, -}; - -use super::{handle_input, process_transmit_queue, QUEUE_SIZES}; +use super::handle_input; +use super::process_transmit_queue; +use super::QUEUE_SIZES; +use crate::serial_device::SerialInput; +use crate::virtio::async_device::AsyncQueueState; +use crate::virtio::async_utils; +use crate::virtio::base_features; +use crate::virtio::copy_config; +use crate::virtio::virtio_console_config; +use crate::virtio::ConsoleError; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::SignalableInterrupt; +use crate::virtio::VirtioDevice; +use crate::virtio::{self}; +use crate::SerialDevice; /// Wrapper that makes any `SerialInput` usable as an async source by providing an implementation of /// `IntoAsync`. diff --git a/devices/src/virtio/console/sys.rs b/devices/src/virtio/console/sys.rs index 024a09993..803aa12fa 100644 --- a/devices/src/virtio/console/sys.rs +++ b/devices/src/virtio/console/sys.rs @@ -12,4 +12,5 @@ cfg_if::cfg_if! { } } -pub(in crate::virtio::console) use platform::{is_a_fatal_input_error, read_delay_if_needed}; +pub(in crate::virtio::console) use platform::is_a_fatal_input_error; +pub(in crate::virtio::console) use platform::read_delay_if_needed; diff --git a/devices/src/virtio/console/sys/unix.rs b/devices/src/virtio/console/sys/unix.rs index ca5016141..1db7faab0 100644 --- a/devices/src/virtio/console/sys/unix.rs +++ b/devices/src/virtio/console/sys/unix.rs @@ -4,10 +4,13 @@ use std::io; -use base::{Event, FileSync, RawDescriptor}; +use base::Event; +use base::FileSync; +use base::RawDescriptor; use crate::serial_device::SerialInput; -use crate::virtio::console::{Console, ConsoleInput}; +use crate::virtio::console::Console; +use crate::virtio::console::ConsoleInput; use crate::virtio::ProtectionType; use crate::SerialDevice; diff --git a/devices/src/virtio/console/sys/windows.rs b/devices/src/virtio/console/sys/windows.rs index 811c14109..71341ca60 100644 --- a/devices/src/virtio/console/sys/windows.rs +++ b/devices/src/virtio/console/sys/windows.rs @@ -6,10 +6,14 @@ use std::io; use std::thread; use std::time::Duration; -use base::{named_pipes, Event, FileSync, RawDescriptor}; +use base::named_pipes; +use base::Event; +use base::FileSync; +use base::RawDescriptor; use crate::serial_device::SerialInput; -use crate::virtio::console::{Console, ConsoleInput}; +use crate::virtio::console::Console; +use crate::virtio::console::ConsoleInput; use crate::virtio::ProtectionType; use crate::SerialDevice; diff --git a/devices/src/virtio/descriptor_utils.rs b/devices/src/virtio/descriptor_utils.rs index aa02cc8b1..394addf64 100644 --- a/devices/src/virtio/descriptor_utils.rs +++ b/devices/src/virtio/descriptor_utils.rs @@ -7,7 +7,8 @@ mod sys; use std::borrow::Cow; use std::cmp; use std::convert::TryInto; -use std::io::{self, Write}; +use std::io::Write; +use std::io::{self}; use std::iter::FromIterator; use std::marker::PhantomData; use std::ptr::copy_nonoverlapping; @@ -15,14 +16,21 @@ use std::result; use std::sync::Arc; use anyhow::Context; -use base::{FileReadWriteAtVolatile, FileReadWriteVolatile}; +use base::FileReadWriteAtVolatile; +use base::FileReadWriteVolatile; use cros_async::MemRegion; -use data_model::{DataInit, Le16, Le32, Le64, VolatileMemoryError, VolatileSlice}; +use data_model::DataInit; +use data_model::Le16; +use data_model::Le32; +use data_model::Le64; +use data_model::VolatileMemoryError; +use data_model::VolatileSlice; use disk::AsyncDisk; use remain::sorted; use smallvec::SmallVec; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; use super::DescriptorChain; @@ -809,12 +817,13 @@ pub fn create_descriptor_chain( #[cfg(test)] mod tests { - use super::*; use std::fs::File; use std::io::Read; use tempfile::tempfile; + use super::*; + #[test] fn reader_test_simple_chain() { use DescriptorType::*; diff --git a/devices/src/virtio/fs/mod.rs b/devices/src/virtio/fs/mod.rs index 3081ca7ea..ac345f367 100644 --- a/devices/src/virtio/fs/mod.rs +++ b/devices/src/virtio/fs/mod.rs @@ -7,22 +7,36 @@ use std::mem; use std::sync::Arc; use std::thread; -use base::{error, warn, AsRawDescriptor, Error as SysError, Event, RawDescriptor, Tube}; -use data_model::{DataInit, Le32}; +use base::error; +use base::warn; +use base::AsRawDescriptor; +use base::Error as SysError; +use base::Event; +use base::RawDescriptor; +use base::Tube; +use data_model::DataInit; +use data_model::Le32; use remain::sorted; use resources::Alloc; use sync::Mutex; use thiserror::Error; -use vm_control::{FsMappingRequest, VmResponse}; +use vm_control::FsMappingRequest; +use vm_control::VmResponse; use vm_memory::GuestMemory; -use crate::pci::{ - PciAddress, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciCapability, -}; -use crate::virtio::{ - copy_config, DescriptorError, DeviceType, Interrupt, PciCapabilityType, Queue, VirtioDevice, - VirtioPciShmCap, -}; +use crate::pci::PciAddress; +use crate::pci::PciBarConfiguration; +use crate::pci::PciBarPrefetchable; +use crate::pci::PciBarRegionType; +use crate::pci::PciCapability; +use crate::virtio::copy_config; +use crate::virtio::DescriptorError; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::PciCapabilityType; +use crate::virtio::Queue; +use crate::virtio::VirtioDevice; +use crate::virtio::VirtioPciShmCap; mod caps; mod multikey; @@ -32,9 +46,8 @@ mod worker; use fuse::Server; use passthrough::PassthroughFs; -use worker::Worker; - pub use worker::process_fs_queue; +use worker::Worker; // The fs device does not have a fixed number of queues. pub const QUEUE_SIZE: u16 = 1024; diff --git a/devices/src/virtio/fs/passthrough.rs b/devices/src/virtio/fs/passthrough.rs index 32efe40f3..770ab5956 100644 --- a/devices/src/virtio/fs/passthrough.rs +++ b/devices/src/virtio/fs/passthrough.rs @@ -2,51 +2,77 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - borrow::Cow, - cmp, - collections::{btree_map, BTreeMap}, - ffi::{CStr, CString}, - fs::File, - io, - mem::{self, size_of, MaybeUninit}, - os::raw::{c_int, c_long}, - ptr::{addr_of, addr_of_mut}, - str::FromStr, - sync::{ - atomic::{AtomicBool, AtomicU64, Ordering}, - Arc, - }, - time::Duration, -}; +use std::borrow::Cow; +use std::cmp; +use std::collections::btree_map; +use std::collections::BTreeMap; +use std::ffi::CStr; +use std::ffi::CString; +use std::fs::File; +use std::io; +use std::mem::size_of; +use std::mem::MaybeUninit; +use std::mem::{self}; +use std::os::raw::c_int; +use std::os::raw::c_long; +use std::ptr::addr_of; +use std::ptr::addr_of_mut; +use std::str::FromStr; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::time::Duration; -use base::{ - error, ioctl_ior_nr, ioctl_iow_nr, ioctl_iowr_nr, ioctl_with_mut_ptr, ioctl_with_ptr, syscall, - AsRawDescriptor, FileFlags, FromRawDescriptor, RawDescriptor, -}; +use base::error; +use base::ioctl_ior_nr; +use base::ioctl_iow_nr; +use base::ioctl_iowr_nr; +use base::ioctl_with_mut_ptr; +use base::ioctl_with_ptr; +use base::syscall; +use base::AsRawDescriptor; +use base::FileFlags; +use base::FromRawDescriptor; +use base::RawDescriptor; use data_model::DataInit; -use fuse::filesystem::{ - Context, DirectoryIterator, Entry, FileSystem, FsOptions, GetxattrReply, IoctlFlags, - IoctlReply, ListxattrReply, OpenOptions, RemoveMappingOne, SetattrValid, ZeroCopyReader, - ZeroCopyWriter, ROOT_ID, -}; +use fuse::filesystem::Context; +use fuse::filesystem::DirectoryIterator; +use fuse::filesystem::Entry; +use fuse::filesystem::FileSystem; +use fuse::filesystem::FsOptions; +use fuse::filesystem::GetxattrReply; +use fuse::filesystem::IoctlFlags; +use fuse::filesystem::IoctlReply; +use fuse::filesystem::ListxattrReply; +use fuse::filesystem::OpenOptions; +use fuse::filesystem::RemoveMappingOne; +use fuse::filesystem::SetattrValid; +use fuse::filesystem::ZeroCopyReader; +use fuse::filesystem::ZeroCopyWriter; +use fuse::filesystem::ROOT_ID; use fuse::sys::WRITE_KILL_PRIV; use fuse::Mapper; -use serde::{Deserialize, Serialize}; -use sync::Mutex; - #[cfg(feature = "chromeos")] -use { - protobuf::Message, - system_api::client::OrgChromiumArcQuota, - system_api::UserDataAuth::{ - SetMediaRWDataFileProjectIdReply, SetMediaRWDataFileProjectIdRequest, - SetMediaRWDataFileProjectInheritanceFlagReply, - SetMediaRWDataFileProjectInheritanceFlagRequest, - }, -}; +use protobuf::Message; +use serde::Deserialize; +use serde::Serialize; +use sync::Mutex; +#[cfg(feature = "chromeos")] +use system_api::client::OrgChromiumArcQuota; +#[cfg(feature = "chromeos")] +use system_api::UserDataAuth::SetMediaRWDataFileProjectIdReply; +#[cfg(feature = "chromeos")] +use system_api::UserDataAuth::SetMediaRWDataFileProjectIdRequest; +#[cfg(feature = "chromeos")] +use system_api::UserDataAuth::SetMediaRWDataFileProjectInheritanceFlagReply; +#[cfg(feature = "chromeos")] +use system_api::UserDataAuth::SetMediaRWDataFileProjectInheritanceFlagRequest; -use crate::virtio::fs::caps::{Capability, Caps, Set as CapSet, Value as CapValue}; +use crate::virtio::fs::caps::Capability; +use crate::virtio::fs::caps::Caps; +use crate::virtio::fs::caps::Set as CapSet; +use crate::virtio::fs::caps::Value as CapValue; use crate::virtio::fs::multikey::MultikeyBTreeMap; use crate::virtio::fs::read_dir::ReadDir; diff --git a/devices/src/virtio/fs/read_dir.rs b/devices/src/virtio/fs/read_dir.rs index 710943caf..8d29655ae 100644 --- a/devices/src/virtio/fs/read_dir.rs +++ b/devices/src/virtio/fs/read_dir.rs @@ -5,11 +5,13 @@ use std::ffi::CStr; use std::io; use std::mem::size_of; -use std::ops::{Deref, DerefMut}; +use std::ops::Deref; +use std::ops::DerefMut; use base::AsRawDescriptor; use data_model::DataInit; -use fuse::filesystem::{DirEntry, DirectoryIterator}; +use fuse::filesystem::DirEntry; +use fuse::filesystem::DirectoryIterator; #[repr(C, packed)] #[derive(Clone, Copy)] diff --git a/devices/src/virtio/fs/worker.rs b/devices/src/virtio/fs/worker.rs index f74f7655f..acd0ee43e 100644 --- a/devices/src/virtio/fs/worker.rs +++ b/devices/src/virtio/fs/worker.rs @@ -2,20 +2,36 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::convert::{TryFrom, TryInto}; +use std::convert::TryFrom; +use std::convert::TryInto; use std::fs::File; use std::io; use std::os::unix::io::AsRawFd; use std::sync::Arc; -use base::{error, syscall, Event, EventToken, Protection, SafeDescriptor, Tube, WaitContext}; -use fuse::filesystem::{FileSystem, ZeroCopyReader, ZeroCopyWriter}; +use base::error; +use base::syscall; +use base::Event; +use base::EventToken; +use base::Protection; +use base::SafeDescriptor; +use base::Tube; +use base::WaitContext; +use fuse::filesystem::FileSystem; +use fuse::filesystem::ZeroCopyReader; +use fuse::filesystem::ZeroCopyWriter; use sync::Mutex; -use vm_control::{FsMappingRequest, VmResponse}; +use vm_control::FsMappingRequest; +use vm_control::VmResponse; use vm_memory::GuestMemory; -use crate::virtio::fs::{Error, Result}; -use crate::virtio::{Interrupt, Queue, Reader, SignalableInterrupt, Writer}; +use crate::virtio::fs::Error; +use crate::virtio::fs::Result; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::Reader; +use crate::virtio::SignalableInterrupt; +use crate::virtio::Writer; impl fuse::Reader for Reader {} diff --git a/devices/src/virtio/gpu/mod.rs b/devices/src/virtio/gpu/mod.rs index ff63273d4..c3dcc0b86 100644 --- a/devices/src/virtio/gpu/mod.rs +++ b/devices/src/virtio/gpu/mod.rs @@ -7,11 +7,13 @@ mod protocol; mod virtio_gpu; use std::cell::RefCell; -use std::collections::{BTreeMap, VecDeque}; +use std::collections::BTreeMap; +use std::collections::VecDeque; use std::convert::TryFrom; use std::i64; use std::io::Read; -use std::mem::{self, size_of}; +use std::mem::size_of; +use std::mem::{self}; use std::path::PathBuf; use std::rc::Rc; use std::sync::Arc; @@ -19,47 +21,62 @@ use std::thread; use std::time::Duration; use anyhow::Context; - -use base::{ - debug, error, warn, AsRawDescriptor, Event, EventToken, ExternalMapping, RawDescriptor, - SafeDescriptor, SendTube, Tube, VmEventType, WaitContext, -}; - +use base::debug; +use base::error; +use base::warn; +use base::AsRawDescriptor; +use base::Event; +use base::EventToken; +use base::ExternalMapping; +use base::RawDescriptor; +use base::SafeDescriptor; +use base::SendTube; +use base::Tube; +use base::VmEventType; +use base::WaitContext; use data_model::*; - pub use gpu_display::EventDevice; use gpu_display::*; -use rutabaga_gfx::*; - +pub use parameters::DisplayParameters as GpuDisplayParameters; +pub use parameters::GpuParameters; +pub use parameters::DEFAULT_DISPLAY_HEIGHT; +pub use parameters::DEFAULT_DISPLAY_WIDTH; use resources::Alloc; - -use serde::{Deserialize, Serialize}; +use rutabaga_gfx::*; +use serde::Deserialize; +use serde::Serialize; use sync::Mutex; -use vm_memory::{GuestAddress, GuestMemory}; - -use super::{ - copy_config, resource_bridge::*, DescriptorChain, DeviceType, Interrupt, Queue, Reader, - SignalableInterrupt, VirtioDevice, Writer, -}; - -use super::{PciCapabilityType, VirtioPciShmCap}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +pub use self::protocol::virtio_gpu_config; +pub use self::protocol::VIRTIO_GPU_F_CONTEXT_INIT; +pub use self::protocol::VIRTIO_GPU_F_CREATE_GUEST_HANDLE; +pub use self::protocol::VIRTIO_GPU_F_EDID; +pub use self::protocol::VIRTIO_GPU_F_RESOURCE_BLOB; +pub use self::protocol::VIRTIO_GPU_F_RESOURCE_SYNC; +pub use self::protocol::VIRTIO_GPU_F_RESOURCE_UUID; +pub use self::protocol::VIRTIO_GPU_F_VIRGL; +pub use self::protocol::VIRTIO_GPU_SHM_ID_HOST_VISIBLE; use self::protocol::*; -pub use self::protocol::{ - virtio_gpu_config, VIRTIO_GPU_F_CONTEXT_INIT, VIRTIO_GPU_F_CREATE_GUEST_HANDLE, - VIRTIO_GPU_F_EDID, VIRTIO_GPU_F_RESOURCE_BLOB, VIRTIO_GPU_F_RESOURCE_SYNC, - VIRTIO_GPU_F_RESOURCE_UUID, VIRTIO_GPU_F_VIRGL, VIRTIO_GPU_SHM_ID_HOST_VISIBLE, -}; use self::virtio_gpu::VirtioGpu; - -use crate::pci::{ - PciAddress, PciBarConfiguration, PciBarPrefetchable, PciBarRegionType, PciCapability, -}; - -pub use parameters::{ - DisplayParameters as GpuDisplayParameters, GpuParameters, DEFAULT_DISPLAY_HEIGHT, - DEFAULT_DISPLAY_WIDTH, -}; +use super::copy_config; +use super::resource_bridge::*; +use super::DescriptorChain; +use super::DeviceType; +use super::Interrupt; +use super::PciCapabilityType; +use super::Queue; +use super::Reader; +use super::SignalableInterrupt; +use super::VirtioDevice; +use super::VirtioPciShmCap; +use super::Writer; +use crate::pci::PciAddress; +use crate::pci::PciBarConfiguration; +use crate::pci::PciBarPrefetchable; +use crate::pci::PciBarRegionType; +use crate::pci::PciCapability; #[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum GpuMode { diff --git a/devices/src/virtio/gpu/parameters.rs b/devices/src/virtio/gpu/parameters.rs index e031e2e9c..1c912e127 100644 --- a/devices/src/virtio/gpu/parameters.rs +++ b/devices/src/virtio/gpu/parameters.rs @@ -4,10 +4,11 @@ //! Definitions and utilities for GPU related parameters. -use super::GpuMode; use rutabaga_gfx::RutabagaWsi; +use serde::Deserialize; +use serde::Serialize; -use serde::{Deserialize, Serialize}; +use super::GpuMode; pub const DEFAULT_DISPLAY_WIDTH: u32 = 1280; pub const DEFAULT_DISPLAY_HEIGHT: u32 = 1024; diff --git a/devices/src/virtio/gpu/protocol.rs b/devices/src/virtio/gpu/protocol.rs index 3d9d22b25..d68d04f37 100644 --- a/devices/src/virtio/gpu/protocol.rs +++ b/devices/src/virtio/gpu/protocol.rs @@ -7,24 +7,31 @@ use std::cmp::min; use std::convert::From; -use std::fmt::{self, Display}; -use std::io::{self, Write}; +use std::fmt::Display; +use std::fmt::{self}; +use std::io::Write; +use std::io::{self}; use std::marker::PhantomData; -use std::mem::{size_of, size_of_val}; +use std::mem::size_of; +use std::mem::size_of_val; use std::str::from_utf8; -use super::super::DescriptorError; -use super::{Reader, Writer}; use base::Error as BaseError; -use base::{ExternalMappingError, TubeError}; -use data_model::{DataInit, Le32, Le64}; +use base::ExternalMappingError; +use base::TubeError; +use data_model::DataInit; +use data_model::Le32; +use data_model::Le64; use gpu_display::GpuDisplayError; use remain::sorted; use rutabaga_gfx::RutabagaError; use thiserror::Error; - use vm_memory::udmabuf::UdmabufError; +use super::super::DescriptorError; +use super::Reader; +use super::Writer; + pub const VIRTIO_GPU_F_VIRGL: u32 = 0; pub const VIRTIO_GPU_F_EDID: u32 = 1; pub const VIRTIO_GPU_F_RESOURCE_UUID: u32 = 2; diff --git a/devices/src/virtio/gpu/virtio_gpu.rs b/devices/src/virtio/gpu/virtio_gpu.rs index f13c437c7..a93472909 100644 --- a/devices/src/virtio/gpu/virtio_gpu.rs +++ b/devices/src/virtio/gpu/virtio_gpu.rs @@ -9,34 +9,47 @@ use std::rc::Rc; use std::result::Result; use std::sync::Arc; -use crate::virtio::gpu::GpuDisplayParameters; -use crate::virtio::resource_bridge::{BufferInfo, PlaneInfo, ResourceInfo, ResourceResponse}; -use base::{error, ExternalMapping, Protection, SafeDescriptor, Tube}; - +use base::error; +use base::ExternalMapping; +use base::Protection; +use base::SafeDescriptor; +use base::Tube; use data_model::VolatileSlice; - use gpu_display::*; -use rutabaga_gfx::{ - ResourceCreate3D, ResourceCreateBlob, Rutabaga, RutabagaBuilder, RutabagaFence, - RutabagaFenceHandler, RutabagaHandle, RutabagaIovec, Transfer3D, - RUTABAGA_MEM_HANDLE_TYPE_DMABUF, -}; - use libc::c_void; - use resources::Alloc; - -use super::protocol::{ - GpuResponse::{self, *}, - GpuResponsePlaneInfo, VirtioGpuResult, VIRTIO_GPU_BLOB_FLAG_CREATE_GUEST_HANDLE, - VIRTIO_GPU_BLOB_MEM_HOST3D, -}; -use super::VirtioScanoutBlobData; +use rutabaga_gfx::ResourceCreate3D; +use rutabaga_gfx::ResourceCreateBlob; +use rutabaga_gfx::Rutabaga; +use rutabaga_gfx::RutabagaBuilder; +use rutabaga_gfx::RutabagaFence; +use rutabaga_gfx::RutabagaFenceHandler; +use rutabaga_gfx::RutabagaHandle; +use rutabaga_gfx::RutabagaIovec; +use rutabaga_gfx::Transfer3D; +use rutabaga_gfx::RUTABAGA_MEM_HANDLE_TYPE_DMABUF; use sync::Mutex; +use vm_control::MemSlot; +use vm_control::VmMemoryDestination; +use vm_control::VmMemoryRequest; +use vm_control::VmMemoryResponse; +use vm_control::VmMemorySource; +use vm_memory::udmabuf::UdmabufDriver; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; -use vm_memory::{udmabuf::UdmabufDriver, GuestAddress, GuestMemory}; - -use vm_control::{MemSlot, VmMemoryDestination, VmMemoryRequest, VmMemoryResponse, VmMemorySource}; +use super::protocol::GpuResponse::*; +use super::protocol::GpuResponse::{self}; +use super::protocol::GpuResponsePlaneInfo; +use super::protocol::VirtioGpuResult; +use super::protocol::VIRTIO_GPU_BLOB_FLAG_CREATE_GUEST_HANDLE; +use super::protocol::VIRTIO_GPU_BLOB_MEM_HOST3D; +use super::VirtioScanoutBlobData; +use crate::virtio::gpu::GpuDisplayParameters; +use crate::virtio::resource_bridge::BufferInfo; +use crate::virtio::resource_bridge::PlaneInfo; +use crate::virtio::resource_bridge::ResourceInfo; +use crate::virtio::resource_bridge::ResourceResponse; struct VirtioGpuResource { resource_id: u32, diff --git a/devices/src/virtio/input/evdev.rs b/devices/src/virtio/input/evdev.rs index 19af6291d..c3fd0c2ab 100644 --- a/devices/src/virtio/input/evdev.rs +++ b/devices/src/virtio/input/evdev.rs @@ -2,9 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::{ - ioctl_ior_nr, ioctl_iow_nr, ioctl_with_mut_ref, ioctl_with_ptr, ioctl_with_ref, AsRawDescriptor, -}; +use std::collections::BTreeMap; +use std::os::raw::c_uint; +use std::ptr::null; + +use base::ioctl_ior_nr; +use base::ioctl_iow_nr; +use base::ioctl_with_mut_ref; +use base::ioctl_with_ptr; +use base::ioctl_with_ref; +use base::AsRawDescriptor; use data_model::Le32; use super::constants::*; @@ -14,10 +21,6 @@ use super::virtio_input_device_ids; use super::InputError; use super::Result; -use std::collections::BTreeMap; -use std::os::raw::c_uint; -use std::ptr::null; - const EVDEV: c_uint = 69; #[repr(C)] diff --git a/devices/src/virtio/input/event_source.rs b/devices/src/virtio/input/event_source.rs index bdce4c005..26cb221ec 100644 --- a/devices/src/virtio/input/event_source.rs +++ b/devices/src/virtio/input/event_source.rs @@ -2,17 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::constants::*; -use super::evdev::{grab_evdev, ungrab_evdev}; -use super::InputError; -use super::Result; -use base::{warn, AsRawDescriptor, RawDescriptor}; -use data_model::DataInit; -use linux_input_sys::{input_event, virtio_input_event, InputEventDecoder}; use std::collections::VecDeque; use std::io::Read; use std::io::Write; +use base::warn; +use base::AsRawDescriptor; +use base::RawDescriptor; +use data_model::DataInit; +use linux_input_sys::input_event; +use linux_input_sys::virtio_input_event; +use linux_input_sys::InputEventDecoder; + +use super::constants::*; +use super::evdev::grab_evdev; +use super::evdev::ungrab_evdev; +use super::InputError; +use super::Result; + /// Encapsulates a socket or device node into an abstract event source, providing a common /// interface. /// It supports read and write operations to provide and accept events just like an event device @@ -240,12 +247,17 @@ where #[cfg(test)] mod tests { use std::cmp::min; - use std::io::{Read, Write}; + use std::io::Read; + use std::io::Write; - use data_model::{DataInit, Le16, SLe32}; + use data_model::DataInit; + use data_model::Le16; + use data_model::SLe32; use linux_input_sys::InputEventDecoder; - use crate::virtio::input::event_source::{input_event, virtio_input_event, EventSourceImpl}; + use crate::virtio::input::event_source::input_event; + use crate::virtio::input::event_source::virtio_input_event; + use crate::virtio::input::event_source::EventSourceImpl; struct SourceMock { events: Vec, diff --git a/devices/src/virtio/input/mod.rs b/devices/src/virtio/input/mod.rs index 717ca607b..1e53ed9af 100644 --- a/devices/src/virtio/input/mod.rs +++ b/devices/src/virtio/input/mod.rs @@ -8,25 +8,42 @@ mod defaults; mod evdev; mod event_source; -use self::constants::*; - -use base::{error, warn, AsRawDescriptor, Event, EventToken, RawDescriptor, WaitContext}; -use data_model::{DataInit, Le16, Le32}; -use remain::sorted; -use thiserror::Error; -use vm_memory::GuestMemory; - -use self::event_source::{EvdevEventSource, EventSource, SocketEventSource}; -use super::{ - copy_config, DescriptorChain, DescriptorError, DeviceType, Interrupt, Queue, Reader, - SignalableInterrupt, VirtioDevice, Writer, -}; -use linux_input_sys::{virtio_input_event, InputEventDecoder}; use std::collections::BTreeMap; use std::io::Read; use std::io::Write; use std::thread; +use base::error; +use base::warn; +use base::AsRawDescriptor; +use base::Event; +use base::EventToken; +use base::RawDescriptor; +use base::WaitContext; +use data_model::DataInit; +use data_model::Le16; +use data_model::Le32; +use linux_input_sys::virtio_input_event; +use linux_input_sys::InputEventDecoder; +use remain::sorted; +use thiserror::Error; +use vm_memory::GuestMemory; + +use self::constants::*; +use self::event_source::EvdevEventSource; +use self::event_source::EventSource; +use self::event_source::SocketEventSource; +use super::copy_config; +use super::DescriptorChain; +use super::DescriptorError; +use super::DeviceType; +use super::Interrupt; +use super::Queue; +use super::Reader; +use super::SignalableInterrupt; +use super::VirtioDevice; +use super::Writer; + const EVENT_QUEUE_SIZE: u16 = 64; const STATUS_QUEUE_SIZE: u16 = 64; const QUEUE_SIZES: &[u16] = &[EVENT_QUEUE_SIZE, STATUS_QUEUE_SIZE]; diff --git a/devices/src/virtio/interrupt.rs b/devices/src/virtio/interrupt.rs index 3ed6ccc7e..9051b0568 100644 --- a/devices/src/virtio/interrupt.rs +++ b/devices/src/virtio/interrupt.rs @@ -2,16 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use super::{INTERRUPT_STATUS_CONFIG_CHANGED, INTERRUPT_STATUS_USED_RING, VIRTIO_MSI_NO_VECTOR}; -use crate::irq_event::IrqLevelEvent; -use crate::pci::MsixConfig; -use base::Event; use std::cell::RefCell; use std::rc::Rc; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; use std::sync::Arc; + +use base::Event; use sync::Mutex; +use super::INTERRUPT_STATUS_CONFIG_CHANGED; +use super::INTERRUPT_STATUS_USED_RING; +use super::VIRTIO_MSI_NO_VECTOR; +use crate::irq_event::IrqLevelEvent; +use crate::pci::MsixConfig; + pub trait SignalableInterrupt { /// Writes to the irqfd to VMM to deliver virtual interrupt to the guest. fn signal(&self, vector: u16, interrupt_status_mask: u32); diff --git a/devices/src/virtio/iommu.rs b/devices/src/virtio/iommu.rs index 381ed0484..10d5dd4df 100644 --- a/devices/src/virtio/iommu.rs +++ b/devices/src/virtio/iommu.rs @@ -9,40 +9,63 @@ pub mod protocol; pub(crate) mod sys; use std::cell::RefCell; -use std::collections::{btree_map::Entry, BTreeMap}; -use std::io::{self, Write}; +use std::collections::btree_map::Entry; +use std::collections::BTreeMap; +use std::io::Write; +use std::io::{self}; use std::mem::size_of; use std::ops::RangeInclusive; use std::rc::Rc; +use std::result; use std::sync::Arc; -use std::{result, thread}; +use std::thread; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use acpi_tables::sdt::SDT; use anyhow::Context; +use base::error; +use base::pagesize; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use base::warn; -use base::{ - error, pagesize, AsRawDescriptor, Error as SysError, Event, Protection, RawDescriptor, - Result as SysResult, Tube, TubeError, -}; -use cros_async::{AsyncError, AsyncTube, EventAsync, Executor}; -use data_model::{DataInit, Le64}; -use futures::{select, FutureExt}; +use base::AsRawDescriptor; +use base::Error as SysError; +use base::Event; +use base::Protection; +use base::RawDescriptor; +use base::Result as SysResult; +use base::Tube; +use base::TubeError; +use cros_async::AsyncError; +use cros_async::AsyncTube; +use cros_async::EventAsync; +use cros_async::Executor; +use data_model::DataInit; +use data_model::Le64; +use futures::select; +use futures::FutureExt; use remain::sorted; use sync::Mutex; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory, GuestMemoryError}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +use vm_memory::GuestMemoryError; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use crate::pci::PciAddress; +use crate::virtio::async_utils; +use crate::virtio::copy_config; use crate::virtio::iommu::ipc_memory_mapper::*; use crate::virtio::iommu::memory_mapper::*; use crate::virtio::iommu::protocol::*; -use crate::virtio::{ - async_utils, copy_config, DescriptorChain, DescriptorError, DeviceType, Interrupt, Queue, - Reader, SignalableInterrupt, VirtioDevice, Writer, -}; +use crate::virtio::DescriptorChain; +use crate::virtio::DescriptorError; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::Reader; +use crate::virtio::SignalableInterrupt; +use crate::virtio::VirtioDevice; +use crate::virtio::Writer; const QUEUE_SIZE: u16 = 256; const NUM_QUEUES: usize = 2; diff --git a/devices/src/virtio/iommu/ipc_memory_mapper.rs b/devices/src/virtio/iommu/ipc_memory_mapper.rs index c62c38c6c..ef5efda1c 100644 --- a/devices/src/virtio/iommu/ipc_memory_mapper.rs +++ b/devices/src/virtio/iommu/ipc_memory_mapper.rs @@ -4,9 +4,14 @@ //! Provide utility to communicate with an iommu in another process -use anyhow::{Context, Result}; -use base::{AsRawDescriptor, AsRawDescriptors, RawDescriptor, Tube}; -use serde::{Deserialize, Serialize}; +use anyhow::Context; +use anyhow::Result; +use base::AsRawDescriptor; +use base::AsRawDescriptors; +use base::RawDescriptor; +use base::Tube; +use serde::Deserialize; +use serde::Serialize; use crate::virtio::memory_mapper::MemRegion; @@ -89,11 +94,13 @@ pub fn create_ipc_mapper(endpoint_id: u32, request_tx: Tube) -> CreateIpcMapperR #[cfg(test)] mod tests { - use super::*; - use base::Protection; use std::thread; + + use base::Protection; use vm_memory::GuestAddress; + use super::*; + #[test] fn test() { let (request_tx, request_rx) = Tube::pair().expect("failed to create tube pair"); diff --git a/devices/src/virtio/iommu/memory_mapper.rs b/devices/src/virtio/iommu/memory_mapper.rs index 5bab31b99..496144cb8 100644 --- a/devices/src/virtio/iommu/memory_mapper.rs +++ b/devices/src/virtio/iommu/memory_mapper.rs @@ -8,11 +8,18 @@ use std::any::Any; use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; -use anyhow::{anyhow, bail, Context, Result}; -use base::{AsRawDescriptors, Protection, RawDescriptor}; -use serde::{Deserialize, Serialize}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; +use base::AsRawDescriptors; +use base::Protection; +use base::RawDescriptor; +use serde::Deserialize; +use serde::Serialize; use vm_memory::GuestAddress; #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -238,9 +245,10 @@ impl AsRawDescriptors for BasicMemoryMapper { #[cfg(test)] mod tests { - use super::*; use std::fmt::Debug; + use super::*; + #[test] fn test_mapping_info() { // Overflow diff --git a/devices/src/virtio/iommu/memory_util.rs b/devices/src/virtio/iommu/memory_util.rs index 743e7faee..c97eae191 100644 --- a/devices/src/virtio/iommu/memory_util.rs +++ b/devices/src/virtio/iommu/memory_util.rs @@ -6,12 +6,14 @@ use std::convert::TryInto; use std::sync::Arc; -use sync::Mutex; -use anyhow::{bail, Context}; +use anyhow::bail; +use anyhow::Context; use base::Protection; use data_model::DataInit; -use vm_memory::{GuestAddress, GuestMemory}; +use sync::Mutex; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; use crate::virtio::iommu::IpcMemoryMapper; diff --git a/devices/src/virtio/iommu/protocol.rs b/devices/src/virtio/iommu/protocol.rs index 0a9f1bafc..1c8583344 100644 --- a/devices/src/virtio/iommu/protocol.rs +++ b/devices/src/virtio/iommu/protocol.rs @@ -27,7 +27,10 @@ #![cfg_attr(windows, allow(dead_code))] #![allow(non_camel_case_types)] -use data_model::{DataInit, Le16, Le32, Le64}; +use data_model::DataInit; +use data_model::Le16; +use data_model::Le32; +use data_model::Le64; pub const VIRTIO_IOMMU_F_INPUT_RANGE: u32 = 0; pub const VIRTIO_IOMMU_F_DOMAIN_RANGE: u32 = 1; diff --git a/devices/src/virtio/iommu/sys.rs b/devices/src/virtio/iommu/sys.rs index cda34aef2..43082f3de 100644 --- a/devices/src/virtio/iommu/sys.rs +++ b/devices/src/virtio/iommu/sys.rs @@ -12,4 +12,5 @@ cfg_if::cfg_if! { } } -pub(in crate::virtio::iommu) use platform::{handle_command_tube, handle_translate_request}; +pub(in crate::virtio::iommu) use platform::handle_command_tube; +pub(in crate::virtio::iommu) use platform::handle_translate_request; diff --git a/devices/src/virtio/iommu/sys/unix.rs b/devices/src/virtio/iommu/sys/unix.rs index 2f21d9a39..bf49c7108 100644 --- a/devices/src/virtio/iommu/sys/unix.rs +++ b/devices/src/virtio/iommu/sys/unix.rs @@ -9,16 +9,20 @@ use std::collections::BTreeMap; use std::rc::Rc; use std::sync::Arc; -use base::{error, TubeError}; +use base::error; +use base::TubeError; use cros_async::AsyncTube; use sync::Mutex; -use vm_control::{ - VirtioIOMMURequest, VirtioIOMMUResponse, VirtioIOMMUVfioCommand, VirtioIOMMUVfioResult, -}; +use vm_control::VirtioIOMMURequest; +use vm_control::VirtioIOMMUResponse; +use vm_control::VirtioIOMMUVfioCommand; +use vm_control::VirtioIOMMUVfioResult; use self::vfio_wrapper::VfioWrapper; - -use crate::virtio::iommu::{MemRegion, Result, State, TranslateRequest}; +use crate::virtio::iommu::MemRegion; +use crate::virtio::iommu::Result; +use crate::virtio::iommu::State; +use crate::virtio::iommu::TranslateRequest; use crate::virtio::IommuError; use crate::VfioContainer; diff --git a/devices/src/virtio/iommu/sys/unix/vfio_wrapper.rs b/devices/src/virtio/iommu/sys/unix/vfio_wrapper.rs index 84616fa5c..b52db2179 100644 --- a/devices/src/virtio/iommu/sys/unix/vfio_wrapper.rs +++ b/devices/src/virtio/iommu/sys/unix/vfio_wrapper.rs @@ -7,12 +7,18 @@ use std::sync::Arc; use anyhow::Context; -use base::{AsRawDescriptor, AsRawDescriptors, Protection, RawDescriptor}; +use base::AsRawDescriptor; +use base::AsRawDescriptors; +use base::Protection; +use base::RawDescriptor; use sync::Mutex; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; use crate::vfio::VfioError; -use crate::virtio::iommu::memory_mapper::{AddMapResult, MappingInfo, MemoryMapper}; +use crate::virtio::iommu::memory_mapper::AddMapResult; +use crate::virtio::iommu::memory_mapper::MappingInfo; +use crate::virtio::iommu::memory_mapper::MemoryMapper; use crate::VfioContainer; pub struct VfioWrapper { diff --git a/devices/src/virtio/iommu/sys/windows.rs b/devices/src/virtio/iommu/sys/windows.rs index 1cb4c4ccb..398b11d8a 100644 --- a/devices/src/virtio/iommu/sys/windows.rs +++ b/devices/src/virtio/iommu/sys/windows.rs @@ -8,7 +8,8 @@ use std::rc::Rc; use cros_async::AsyncTube; -use crate::virtio::iommu::{Result, State}; +use crate::virtio::iommu::Result; +use crate::virtio::iommu::State; pub(in crate::virtio::iommu) async fn handle_command_tube( _state: &Rc>, diff --git a/devices/src/virtio/mod.rs b/devices/src/virtio/mod.rs index 8195d23b1..2914a8664 100644 --- a/devices/src/virtio/mod.rs +++ b/devices/src/virtio/mod.rs @@ -84,7 +84,8 @@ use std::cmp; use std::convert::TryFrom; use hypervisor::ProtectionType; -use virtio_sys::virtio_config::{VIRTIO_F_ACCESS_PLATFORM, VIRTIO_F_VERSION_1}; +use virtio_sys::virtio_config::VIRTIO_F_ACCESS_PLATFORM; +use virtio_sys::virtio_config::VIRTIO_F_VERSION_1; use virtio_sys::virtio_ids; use virtio_sys::virtio_ring::VIRTIO_RING_F_EVENT_IDX; diff --git a/devices/src/virtio/net.rs b/devices/src/virtio/net.rs index d3495f019..22418f405 100644 --- a/devices/src/virtio/net.rs +++ b/devices/src/virtio/net.rs @@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::io::{self, Write}; +use std::io::Write; +use std::io::{self}; use std::mem; use std::net::Ipv4Addr; use std::os::raw::c_uint; @@ -10,25 +11,42 @@ use std::result; use std::sync::Arc; use std::thread; +use base::error; +use base::warn; +use base::AsRawDescriptor; use base::Error as SysError; -use base::{ - error, warn, AsRawDescriptor, Event, EventToken, EventType, RawDescriptor, WaitContext, -}; -use data_model::{DataInit, Le16, Le64}; -use net_util::{Error as TapError, MacAddress, TapT}; +use base::Event; +use base::EventToken; +use base::EventType; +use base::RawDescriptor; +use base::WaitContext; +use data_model::DataInit; +use data_model::Le16; +use data_model::Le64; +use net_util::Error as TapError; +use net_util::MacAddress; +use net_util::TapT; use remain::sorted; use thiserror::Error as ThisError; use virtio_sys::virtio_net; -use virtio_sys::virtio_net::{ - virtio_net_hdr_v1, VIRTIO_NET_CTRL_GUEST_OFFLOADS, VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, - VIRTIO_NET_CTRL_MQ, VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, VIRTIO_NET_ERR, VIRTIO_NET_OK, -}; +use virtio_sys::virtio_net::virtio_net_hdr_v1; +use virtio_sys::virtio_net::VIRTIO_NET_CTRL_GUEST_OFFLOADS; +use virtio_sys::virtio_net::VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET; +use virtio_sys::virtio_net::VIRTIO_NET_CTRL_MQ; +use virtio_sys::virtio_net::VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET; +use virtio_sys::virtio_net::VIRTIO_NET_ERR; +use virtio_sys::virtio_net::VIRTIO_NET_OK; use vm_memory::GuestMemory; -use super::{ - copy_config, DescriptorError, DeviceType, Interrupt, Queue, Reader, SignalableInterrupt, - VirtioDevice, Writer, -}; +use super::copy_config; +use super::DescriptorError; +use super::DeviceType; +use super::Interrupt; +use super::Queue; +use super::Reader; +use super::SignalableInterrupt; +use super::VirtioDevice; +use super::Writer; const QUEUE_SIZE: u16 = 256; diff --git a/devices/src/virtio/p9.rs b/devices/src/virtio/p9.rs index 88b73f0c7..8b747d5d2 100644 --- a/devices/src/virtio/p9.rs +++ b/devices/src/virtio/p9.rs @@ -2,20 +2,32 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::io::{self, Write}; +use std::io::Write; +use std::io::{self}; use std::mem; use std::result; use std::thread; -use base::{error, warn, Error as SysError, Event, EventToken, RawDescriptor, WaitContext}; +use base::error; +use base::warn; +use base::Error as SysError; +use base::Event; +use base::EventToken; +use base::RawDescriptor; +use base::WaitContext; use remain::sorted; use thiserror::Error; use vm_memory::GuestMemory; -use super::{ - copy_config, DescriptorError, DeviceType, Interrupt, Queue, Reader, SignalableInterrupt, - VirtioDevice, Writer, -}; +use super::copy_config; +use super::DescriptorError; +use super::DeviceType; +use super::Interrupt; +use super::Queue; +use super::Reader; +use super::SignalableInterrupt; +use super::VirtioDevice; +use super::Writer; const QUEUE_SIZE: u16 = 128; const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE]; diff --git a/devices/src/virtio/pmem.rs b/devices/src/virtio/pmem.rs index ca0483a65..29d32a8eb 100644 --- a/devices/src/virtio/pmem.rs +++ b/devices/src/virtio/pmem.rs @@ -8,20 +8,38 @@ use std::io; use std::rc::Rc; use std::thread; -use base::{error, AsRawDescriptor, Event, RawDescriptor, Tube}; -use base::{Error as SysError, Result as SysResult}; -use cros_async::{select3, EventAsync, Executor}; -use data_model::{DataInit, Le32, Le64}; +use base::error; +use base::AsRawDescriptor; +use base::Error as SysError; +use base::Event; +use base::RawDescriptor; +use base::Result as SysResult; +use base::Tube; +use cros_async::select3; +use cros_async::EventAsync; +use cros_async::Executor; +use data_model::DataInit; +use data_model::Le32; +use data_model::Le64; use futures::pin_mut; use remain::sorted; use thiserror::Error; -use vm_control::{MemSlot, VmMsyncRequest, VmMsyncResponse}; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_control::MemSlot; +use vm_control::VmMsyncRequest; +use vm_control::VmMsyncResponse; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; -use super::{ - async_utils, copy_config, DescriptorChain, DescriptorError, DeviceType, Interrupt, Queue, - Reader, VirtioDevice, Writer, -}; +use super::async_utils; +use super::copy_config; +use super::DescriptorChain; +use super::DescriptorError; +use super::DeviceType; +use super::Interrupt; +use super::Queue; +use super::Reader; +use super::VirtioDevice; +use super::Writer; const QUEUE_SIZE: u16 = 256; const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE]; diff --git a/devices/src/virtio/queue.rs b/devices/src/virtio/queue.rs index 0f4a4a1ee..c981db242 100644 --- a/devices/src/virtio/queue.rs +++ b/devices/src/virtio/queue.rs @@ -5,23 +5,33 @@ use std::cmp::min; use std::convert::TryInto; use std::num::Wrapping; -use std::sync::atomic::{fence, Ordering}; +use std::sync::atomic::fence; +use std::sync::atomic::Ordering; use std::sync::Arc; + +use anyhow::bail; +use anyhow::Context; +use base::error; +use base::warn; +use base::Protection; +use cros_async::AsyncError; +use cros_async::EventAsync; +use data_model::DataInit; +use data_model::Le16; +use data_model::Le32; +use data_model::Le64; use sync::Mutex; - -use anyhow::{bail, Context}; -use base::{error, warn, Protection}; -use cros_async::{AsyncError, EventAsync}; -use data_model::{DataInit, Le16, Le32, Le64}; use virtio_sys::virtio_ring::VIRTIO_RING_F_EVENT_IDX; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; -use super::{SignalableInterrupt, VIRTIO_MSI_NO_VECTOR}; +use super::SignalableInterrupt; +use super::VIRTIO_MSI_NO_VECTOR; use crate::virtio::ipc_memory_mapper::IpcMemoryMapper; use crate::virtio::memory_mapper::MemRegion; -use crate::virtio::memory_util::{ - is_valid_wrapper, read_obj_from_addr_wrapper, write_obj_at_addr_wrapper, -}; +use crate::virtio::memory_util::is_valid_wrapper; +use crate::virtio::memory_util::read_obj_from_addr_wrapper; +use crate::virtio::memory_util::write_obj_at_addr_wrapper; const VIRTQ_DESC_F_NEXT: u16 = 0x1; const VIRTQ_DESC_F_WRITE: u16 = 0x2; @@ -784,14 +794,16 @@ impl Queue { #[cfg(test)] mod tests { - use super::super::Interrupt; - use super::*; - use crate::IrqLevelEvent; - use memoffset::offset_of; use std::convert::TryInto; use std::sync::atomic::AtomicUsize; use std::sync::Arc; + use memoffset::offset_of; + + use super::super::Interrupt; + use super::*; + use crate::IrqLevelEvent; + const GUEST_MEMORY_SIZE: u64 = 0x10000; const DESC_OFFSET: u64 = 0; const AVAIL_OFFSET: u64 = 0x200; diff --git a/devices/src/virtio/resource_bridge.rs b/devices/src/virtio/resource_bridge.rs index dfc1601a1..fe601f1b6 100644 --- a/devices/src/virtio/resource_bridge.rs +++ b/devices/src/virtio/resource_bridge.rs @@ -8,12 +8,14 @@ use std::fmt; use std::fs::File; +use base::with_as_descriptor; +use base::Tube; +use base::TubeError; use remain::sorted; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; use thiserror::Error; -use base::{with_as_descriptor, Tube, TubeError}; - #[derive(Debug, Serialize, Deserialize)] pub enum ResourceRequest { GetBuffer { id: u32 }, diff --git a/devices/src/virtio/rng.rs b/devices/src/virtio/rng.rs index 615d317a7..a12aa1221 100644 --- a/devices/src/virtio/rng.rs +++ b/devices/src/virtio/rng.rs @@ -2,18 +2,27 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::io::{self, Write}; +use std::io::Write; +use std::io::{self}; use std::thread; -use base::{error, warn, Event, EventToken, RawDescriptor, WaitContext}; +use base::error; +use base::warn; +use base::Event; +use base::EventToken; +use base::RawDescriptor; +use base::WaitContext; use rand::rngs::OsRng; use rand::RngCore; use remain::sorted; use thiserror::Error; use vm_memory::GuestMemory; -use super::{DeviceType, Interrupt, Queue, SignalableInterrupt, VirtioDevice}; - +use super::DeviceType; +use super::Interrupt; +use super::Queue; +use super::SignalableInterrupt; +use super::VirtioDevice; use crate::virtio::Writer; const QUEUE_SIZE: u16 = 256; diff --git a/devices/src/virtio/snd/common_backend/async_funcs.rs b/devices/src/virtio/snd/common_backend/async_funcs.rs index 6b6d43fc9..d61b0b9c4 100644 --- a/devices/src/virtio/snd/common_backend/async_funcs.rs +++ b/devices/src/virtio/snd/common_backend/async_funcs.rs @@ -2,26 +2,40 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use futures::{ - channel::{mpsc, oneshot}, - SinkExt, StreamExt, -}; -use std::io::{self, Read, Write}; +use std::io::Read; +use std::io::Write; +use std::io::{self}; use std::rc::Rc; -use audio_streams::{capture::AsyncCaptureBuffer, AsyncPlaybackBuffer}; -use base::{debug, error}; -use cros_async::{sync::Mutex as AsyncMutex, EventAsync, Executor}; -use data_model::{DataInit, Le32}; +use audio_streams::capture::AsyncCaptureBuffer; +use audio_streams::AsyncPlaybackBuffer; +use base::debug; +use base::error; +use cros_async::sync::Mutex as AsyncMutex; +use cros_async::EventAsync; +use cros_async::Executor; +use data_model::DataInit; +use data_model::Le32; +use futures::channel::mpsc; +use futures::channel::oneshot; +use futures::SinkExt; +use futures::StreamExt; use vm_memory::GuestMemory; +use super::DirectionalStream; +use super::Error; +use super::SndData; +use super::StreamInfo; +use super::WorkerStatus; use crate::virtio::snd::common::*; use crate::virtio::snd::common_backend::PcmResponse; use crate::virtio::snd::constants::*; use crate::virtio::snd::layout::*; -use crate::virtio::{DescriptorChain, Queue, Reader, SignalableInterrupt, Writer}; - -use super::{DirectionalStream, Error, SndData, StreamInfo, WorkerStatus}; +use crate::virtio::DescriptorChain; +use crate::virtio::Queue; +use crate::virtio::Reader; +use crate::virtio::SignalableInterrupt; +use crate::virtio::Writer; // Returns true if the operation is successful. Returns error if there is // a runtime/internal error diff --git a/devices/src/virtio/snd/common_backend/mod.rs b/devices/src/virtio/snd/common_backend/mod.rs index 2c03be6f3..e2699c3fb 100644 --- a/devices/src/virtio/snd/common_backend/mod.rs +++ b/devices/src/virtio/snd/common_backend/mod.rs @@ -11,33 +11,49 @@ use std::rc::Rc; use std::thread; use anyhow::Context; -use audio_streams::{BoxError, SampleFormat, StreamSource, StreamSourceGenerator}; -use base::{error, warn, Error as SysError, Event, RawDescriptor}; +use audio_streams::BoxError; +use audio_streams::SampleFormat; +use audio_streams::StreamSource; +use audio_streams::StreamSourceGenerator; +use base::error; +use base::warn; +use base::Error as SysError; +use base::Event; +use base::RawDescriptor; use cros_async::sync::Mutex as AsyncMutex; -use cros_async::{AsyncError, EventAsync, Executor}; +use cros_async::AsyncError; +use cros_async::EventAsync; +use cros_async::Executor; use data_model::DataInit; -use futures::channel::{ - mpsc, - oneshot::{self, Canceled}, -}; -use futures::{pin_mut, select, Future, FutureExt, TryFutureExt}; +use futures::channel::mpsc; +use futures::channel::oneshot::Canceled; +use futures::channel::oneshot::{self}; +use futures::pin_mut; +use futures::select; +use futures::Future; +use futures::FutureExt; +use futures::TryFutureExt; use thiserror::Error as ThisError; use vm_memory::GuestMemory; +use crate::virtio::async_utils; +use crate::virtio::copy_config; use crate::virtio::snd::common::*; use crate::virtio::snd::common_backend::async_funcs::*; use crate::virtio::snd::constants::*; use crate::virtio::snd::layout::*; use crate::virtio::snd::null_backend::create_null_stream_source_generators; -use crate::virtio::snd::parameters::{Parameters, StreamSourceBackend}; -use crate::virtio::snd::sys::{ - create_stream_source_generators as sys_create_stream_source_generators, - set_audio_thread_priority, -}; -use crate::virtio::{ - async_utils, copy_config, DescriptorChain, DescriptorError, DeviceType, Interrupt, Queue, - VirtioDevice, Writer, -}; +use crate::virtio::snd::parameters::Parameters; +use crate::virtio::snd::parameters::StreamSourceBackend; +use crate::virtio::snd::sys::create_stream_source_generators as sys_create_stream_source_generators; +use crate::virtio::snd::sys::set_audio_thread_priority; +use crate::virtio::DescriptorChain; +use crate::virtio::DescriptorError; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::VirtioDevice; +use crate::virtio::Writer; pub mod async_funcs; diff --git a/devices/src/virtio/snd/layout.rs b/devices/src/virtio/snd/layout.rs index a217bff3d..925220d8a 100644 --- a/devices/src/virtio/snd/layout.rs +++ b/devices/src/virtio/snd/layout.rs @@ -2,8 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use data_model::DataInit; +use data_model::Le32; +use data_model::Le64; + use crate::virtio::snd::constants::VIRTIO_SND_CHMAP_MAX_SIZE; -use data_model::{DataInit, Le32, Le64}; #[derive(Copy, Clone, Default)] #[repr(C, packed)] diff --git a/devices/src/virtio/snd/null_backend.rs b/devices/src/virtio/snd/null_backend.rs index dfba7897d..8629d0a7c 100644 --- a/devices/src/virtio/snd/null_backend.rs +++ b/devices/src/virtio/snd/null_backend.rs @@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use audio_streams::{NoopStreamSourceGenerator, StreamSourceGenerator}; +use audio_streams::NoopStreamSourceGenerator; +use audio_streams::StreamSourceGenerator; use crate::virtio::snd::common_backend::SndData; diff --git a/devices/src/virtio/snd/parameters.rs b/devices/src/virtio/snd/parameters.rs index 9516824fb..3cacc686b 100644 --- a/devices/src/virtio/snd/parameters.rs +++ b/devices/src/virtio/snd/parameters.rs @@ -3,13 +3,17 @@ // found in the LICENSE file. use std::num::ParseIntError; -use std::str::{FromStr, ParseBoolError}; +use std::str::FromStr; +use std::str::ParseBoolError; #[cfg(all(unix, feature = "audio_cras"))] -use libcras::{CrasClientType, CrasSocketType}; +use libcras::CrasClientType; +#[cfg(all(unix, feature = "audio_cras"))] +use libcras::CrasSocketType; use thiserror::Error as ThisError; -use crate::virtio::snd::sys::{parse_args, StreamSourceBackend as SysStreamSourceBackend}; +use crate::virtio::snd::sys::parse_args; +use crate::virtio::snd::sys::StreamSourceBackend as SysStreamSourceBackend; #[derive(ThisError, Debug)] pub enum Error { diff --git a/devices/src/virtio/snd/sys/mod.rs b/devices/src/virtio/snd/sys/mod.rs index 7a3754565..96101d664 100644 --- a/devices/src/virtio/snd/sys/mod.rs +++ b/devices/src/virtio/snd/sys/mod.rs @@ -14,5 +14,7 @@ cfg_if::cfg_if! { } } +pub(crate) use platform::create_stream_source_generators; +pub(crate) use platform::parse_args; +pub(crate) use platform::set_audio_thread_priority; pub use platform::StreamSourceBackend; -pub(crate) use platform::{create_stream_source_generators, parse_args, set_audio_thread_priority}; diff --git a/devices/src/virtio/snd/sys/unix.rs b/devices/src/virtio/snd/sys/unix.rs index cd109c6d1..3719b1903 100644 --- a/devices/src/virtio/snd/sys/unix.rs +++ b/devices/src/virtio/snd/sys/unix.rs @@ -4,17 +4,16 @@ use std::str::FromStr; +use audio_streams::StreamSourceGenerator; +use base::set_rt_prio_limit; +use base::set_rt_round_robin; +use base::warn; #[cfg(feature = "audio_cras")] use libcras::CrasStreamSourceGenerator; -use { - audio_streams::StreamSourceGenerator, - base::{set_rt_prio_limit, set_rt_round_robin, warn}, -}; -use crate::virtio::snd::{ - common_backend::SndData, - parameters::{Error, Parameters}, -}; +use crate::virtio::snd::common_backend::SndData; +use crate::virtio::snd::parameters::Error; +use crate::virtio::snd::parameters::Parameters; const AUDIO_THREAD_RTPRIO: u16 = 10; // Matches other cros audio clients. diff --git a/devices/src/virtio/snd/sys/windows.rs b/devices/src/virtio/snd/sys/windows.rs index dd7288618..efa757337 100644 --- a/devices/src/virtio/snd/sys/windows.rs +++ b/devices/src/virtio/snd/sys/windows.rs @@ -6,10 +6,9 @@ use std::str::FromStr; use audio_streams::StreamSourceGenerator; -use crate::virtio::snd::{ - common_backend::SndData, - parameters::{Error, Parameters}, -}; +use crate::virtio::snd::common_backend::SndData; +use crate::virtio::snd::parameters::Error; +use crate::virtio::snd::parameters::Parameters; #[derive(Debug, Clone, Copy, PartialEq)] pub enum StreamSourceBackend {} diff --git a/devices/src/virtio/snd/vios_backend/mod.rs b/devices/src/virtio/snd/vios_backend/mod.rs index 47e3beea5..0900a8cde 100644 --- a/devices/src/virtio/snd/vios_backend/mod.rs +++ b/devices/src/virtio/snd/vios_backend/mod.rs @@ -7,32 +7,39 @@ mod shm_vios; #[cfg(any(target_os = "linux", target_os = "android"))] pub use self::shm_streams::*; - pub use self::shm_vios::*; pub mod streams; mod worker; +use std::io::Error as IoError; +use std::path::Path; +use std::sync::mpsc::RecvError; +use std::sync::mpsc::SendError; +use std::sync::Arc; use std::thread; -use crate::virtio::{copy_config, DescriptorError, DeviceType, Interrupt, Queue, VirtioDevice}; -use base::{error, Error as BaseError, Event, RawDescriptor}; -use data_model::{DataInit, Le32}; +use base::error; +use base::Error as BaseError; +use base::Event; +use base::RawDescriptor; +use data_model::DataInit; +use data_model::Le32; use remain::sorted; -use sync::Mutex; -use vm_memory::GuestMemory; - -use std::path::Path; -use std::sync::mpsc::{RecvError, SendError}; -use std::sync::Arc; - -use super::layout::*; use streams::StreamMsg; +use sync::Mutex; +use thiserror::Error as ThisError; +use vm_memory::GuestMemory; use worker::*; -use std::io::Error as IoError; -use thiserror::Error as ThisError; +use super::layout::*; +use crate::virtio::copy_config; +use crate::virtio::DescriptorError; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::VirtioDevice; const QUEUE_SIZES: &[u16] = &[64, 64, 64, 64]; diff --git a/devices/src/virtio/snd/vios_backend/shm_streams.rs b/devices/src/virtio/snd/vios_backend/shm_streams.rs index 8c551b2a3..a2581ee37 100644 --- a/devices/src/virtio/snd/vios_backend/shm_streams.rs +++ b/devices/src/virtio/snd/vios_backend/shm_streams.rs @@ -7,30 +7,38 @@ //! Given that the VioS server doesn't emit an event when the next buffer is expected, this //! implementation uses thread::sleep to drive the frame timings. -use super::shm_vios::{VioSClient, VioSStreamParams}; - -use crate::virtio::snd::common::*; -use crate::virtio::snd::constants::*; - -use audio_streams::shm_streams::{ - BufferSet, ServerRequest, SharedMemory as AudioSharedMemory, ShmStream, ShmStreamSource, -}; -use audio_streams::{BoxError, SampleFormat, StreamDirection, StreamEffect}; - -use base::{ - error, Error as SysError, MemoryMapping, MemoryMappingBuilder, RawDescriptor, SharedMemory, - SharedMemoryUnix, -}; -use data_model::VolatileMemory; -use sync::Mutex; - use std::fs::File; use std::os::unix::io::FromRawFd; use std::path::Path; use std::sync::Arc; -use std::time::{Duration, Instant}; +use std::time::Duration; +use std::time::Instant; -use super::shm_vios::{Error, Result}; +use audio_streams::shm_streams::BufferSet; +use audio_streams::shm_streams::ServerRequest; +use audio_streams::shm_streams::SharedMemory as AudioSharedMemory; +use audio_streams::shm_streams::ShmStream; +use audio_streams::shm_streams::ShmStreamSource; +use audio_streams::BoxError; +use audio_streams::SampleFormat; +use audio_streams::StreamDirection; +use audio_streams::StreamEffect; +use base::error; +use base::Error as SysError; +use base::MemoryMapping; +use base::MemoryMappingBuilder; +use base::RawDescriptor; +use base::SharedMemory; +use base::SharedMemoryUnix; +use data_model::VolatileMemory; +use sync::Mutex; + +use super::shm_vios::Error; +use super::shm_vios::Result; +use super::shm_vios::VioSClient; +use super::shm_vios::VioSStreamParams; +use crate::virtio::snd::common::*; +use crate::virtio::snd::constants::*; // This is the error type used in audio_streams::shm_streams. Unfortunately, it's not declared // public there so it needs to be re-declared here. It also prevents the usage of anyhow::Error. diff --git a/devices/src/virtio/snd/vios_backend/shm_vios.rs b/devices/src/virtio/snd/vios_backend/shm_vios.rs index c7909c51a..aad25ae79 100644 --- a/devices/src/virtio/snd/vios_backend/shm_vios.rs +++ b/devices/src/virtio/snd/vios_backend/shm_vios.rs @@ -2,30 +2,49 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::virtio::snd::constants::*; -use crate::virtio::snd::layout::*; - -use base::{ - error, AsRawDescriptor, Error as BaseError, Event, EventToken, FromRawDescriptor, - IntoRawDescriptor, MemoryMapping, MemoryMappingBuilder, MmapError, RawDescriptor, - SafeDescriptor, ScmSocket, UnixSeqpacket, WaitContext, -}; -use data_model::{DataInit, VolatileMemory, VolatileMemoryError, VolatileSlice}; - -use std::collections::{HashMap, VecDeque}; +use std::collections::HashMap; +use std::collections::VecDeque; use std::fs::File; -use std::io::{Error as IOError, ErrorKind as IOErrorKind, IoSliceMut, Seek, SeekFrom}; +use std::io::Error as IOError; +use std::io::ErrorKind as IOErrorKind; +use std::io::IoSliceMut; +use std::io::Seek; +use std::io::SeekFrom; use std::os::unix::io::RawFd; use std::path::Path; -use std::sync::mpsc::{channel, Receiver, RecvError, Sender}; +use std::sync::mpsc::channel; +use std::sync::mpsc::Receiver; +use std::sync::mpsc::RecvError; +use std::sync::mpsc::Sender; use std::sync::Arc; use std::thread::JoinHandle; -use sync::Mutex; - +use base::error; +use base::AsRawDescriptor; +use base::Error as BaseError; +use base::Event; +use base::EventToken; +use base::FromRawDescriptor; +use base::IntoRawDescriptor; +use base::MemoryMapping; +use base::MemoryMappingBuilder; +use base::MmapError; +use base::RawDescriptor; +use base::SafeDescriptor; +use base::ScmSocket; +use base::UnixSeqpacket; +use base::WaitContext; +use data_model::DataInit; +use data_model::VolatileMemory; +use data_model::VolatileMemoryError; +use data_model::VolatileSlice; use remain::sorted; +use sync::Mutex; use thiserror::Error as ThisError; +use crate::virtio::snd::constants::*; +use crate::virtio::snd::layout::*; + pub type Result = std::result::Result; #[sorted] diff --git a/devices/src/virtio/snd/vios_backend/streams.rs b/devices/src/virtio/snd/vios_backend/streams.rs index cf5166a63..c8d6dbcf2 100644 --- a/devices/src/virtio/snd/vios_backend/streams.rs +++ b/devices/src/virtio/snd/vios_backend/streams.rs @@ -4,23 +4,34 @@ use std::collections::VecDeque; use std::ops::Deref; -use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::mpsc::channel; +use std::sync::mpsc::Receiver; +use std::sync::mpsc::Sender; use std::sync::Arc; use std::thread; -use std::time::{Duration, Instant}; +use std::time::Duration; +use std::time::Instant; -use crate::virtio::{DescriptorChain, Interrupt, Queue, Reader, Writer}; -use base::{error, set_rt_prio_limit, set_rt_round_robin, warn}; +use base::error; +use base::set_rt_prio_limit; +use base::set_rt_round_robin; +use base::warn; use data_model::Le32; use sync::Mutex; use vm_memory::GuestMemory; use super::Error as VioSError; +use super::Result; +use super::SoundError; use super::*; -use super::{Result, SoundError}; use crate::virtio::snd::common::from_virtio_frame_rate; use crate::virtio::snd::constants::*; use crate::virtio::snd::layout::*; +use crate::virtio::DescriptorChain; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::Reader; +use crate::virtio::Writer; /// Messages that the worker can send to the stream (thread). pub enum StreamMsg { diff --git a/devices/src/virtio/snd/vios_backend/worker.rs b/devices/src/virtio/snd/vios_backend/worker.rs index 9a9306191..7c90e54a7 100644 --- a/devices/src/virtio/snd/vios_backend/worker.rs +++ b/devices/src/virtio/snd/vios_backend/worker.rs @@ -4,20 +4,32 @@ use std::io::Read; use std::ops::Deref; -use std::sync::{mpsc::Sender, Arc}; +use std::sync::mpsc::Sender; +use std::sync::Arc; use std::thread; -use crate::virtio::{DescriptorChain, Interrupt, Queue, Reader, SignalableInterrupt, Writer}; -use base::{error, warn, Event, EventToken, WaitContext}; -use data_model::{DataInit, Le32}; +use base::error; +use base::warn; +use base::Event; +use base::EventToken; +use base::WaitContext; +use data_model::DataInit; +use data_model::Le32; use sync::Mutex; use vm_memory::GuestMemory; use super::super::constants::*; use super::super::layout::*; use super::streams::*; +use super::Result; +use super::SoundError; use super::*; -use super::{Result, SoundError}; +use crate::virtio::DescriptorChain; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::Reader; +use crate::virtio::SignalableInterrupt; +use crate::virtio::Writer; pub struct Worker { // Lock order: Must never hold more than one queue lock at the same time. diff --git a/devices/src/virtio/tpm.rs b/devices/src/virtio/tpm.rs index 60993706b..08158bd38 100644 --- a/devices/src/virtio/tpm.rs +++ b/devices/src/virtio/tpm.rs @@ -2,19 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::io::{self, Read, Write}; +use std::io::Read; +use std::io::Write; +use std::io::{self}; use std::ops::BitOrAssign; use std::thread; -use base::{error, Event, EventToken, RawDescriptor, WaitContext}; +use base::error; +use base::Event; +use base::EventToken; +use base::RawDescriptor; +use base::WaitContext; use remain::sorted; use thiserror::Error; use vm_memory::GuestMemory; -use super::{ - DescriptorChain, DescriptorError, DeviceType, Interrupt, Queue, Reader, SignalableInterrupt, - VirtioDevice, Writer, -}; +use super::DescriptorChain; +use super::DescriptorError; +use super::DeviceType; +use super::Interrupt; +use super::Queue; +use super::Reader; +use super::SignalableInterrupt; +use super::VirtioDevice; +use super::Writer; // A single queue of size 2. The guest kernel driver will enqueue a single // descriptor chain containing one command buffer and one response buffer at a diff --git a/devices/src/virtio/vhost/control_socket.rs b/devices/src/virtio/vhost/control_socket.rs index 18553885d..bd5256ddd 100644 --- a/devices/src/virtio/vhost/control_socket.rs +++ b/devices/src/virtio/vhost/control_socket.rs @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use serde::{Deserialize, Serialize}; - use base::Error as SysError; +use serde::Deserialize; +use serde::Serialize; #[derive(Serialize, Deserialize, Debug)] pub enum VhostDevRequest { diff --git a/devices/src/virtio/vhost/mod.rs b/devices/src/virtio/vhost/mod.rs index 58bbaaa6d..1ef2b250b 100644 --- a/devices/src/virtio/vhost/mod.rs +++ b/devices/src/virtio/vhost/mod.rs @@ -4,13 +4,16 @@ //! Implements vhost-based virtio devices. -use base::{Error as SysError, TubeError}; +use base::Error as SysError; +use base::TubeError; use data_model::DataInit; use net_util::Error as TapError; use remain::sorted; use thiserror::Error; use vhost::Error as VhostError; -use vmm_vhost::message::{MasterReq, Req, VhostUserMsgHeader}; +use vmm_vhost::message::MasterReq; +use vmm_vhost::message::Req; +use vmm_vhost::message::VhostUserMsgHeader; mod control_socket; pub mod user; diff --git a/devices/src/virtio/vhost/net.rs b/devices/src/virtio/vhost/net.rs index 428db0861..fd363be49 100644 --- a/devices/src/virtio/vhost/net.rs +++ b/devices/src/virtio/vhost/net.rs @@ -7,18 +7,27 @@ use std::net::Ipv4Addr; use std::path::Path; use std::thread; -use net_util::{MacAddress, TapT}; - -use base::{error, warn, AsRawDescriptor, Event, RawDescriptor, Tube}; +use base::error; +use base::warn; +use base::AsRawDescriptor; +use base::Event; +use base::RawDescriptor; +use base::Tube; +use net_util::MacAddress; +use net_util::TapT; use vhost::NetT as VhostNetT; use virtio_sys::virtio_net; use vm_memory::GuestMemory; use super::control_socket::*; use super::worker::Worker; -use super::{Error, Result}; +use super::Error; +use super::Result; use crate::pci::MsixStatus; -use crate::virtio::{DeviceType, Interrupt, Queue, VirtioDevice}; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::VirtioDevice; const QUEUE_SIZE: u16 = 256; const NUM_QUEUES: usize = 2; @@ -349,18 +358,22 @@ where #[cfg(test)] pub mod tests { - use super::*; - use crate::virtio::base_features; - use crate::virtio::VIRTIO_MSI_NO_VECTOR; - use crate::IrqLevelEvent; - use hypervisor::ProtectionType; - use net_util::sys::unix::fakes::FakeTap; use std::path::PathBuf; use std::result; use std::sync::atomic::AtomicUsize; use std::sync::Arc; + + use hypervisor::ProtectionType; + use net_util::sys::unix::fakes::FakeTap; use vhost::net::fakes::FakeNet; - use vm_memory::{GuestAddress, GuestMemory, GuestMemoryError}; + use vm_memory::GuestAddress; + use vm_memory::GuestMemory; + use vm_memory::GuestMemoryError; + + use super::*; + use crate::virtio::base_features; + use crate::virtio::VIRTIO_MSI_NO_VECTOR; + use crate::IrqLevelEvent; fn create_guest_memory() -> result::Result { let start_addr1 = GuestAddress(0x0); diff --git a/devices/src/virtio/vhost/user/device/block.rs b/devices/src/virtio/vhost/user/device/block.rs index 7773df308..2adc8d2ef 100644 --- a/devices/src/virtio/vhost/user/device/block.rs +++ b/devices/src/virtio/vhost/user/device/block.rs @@ -6,24 +6,41 @@ mod sys; use std::cell::RefCell; use std::rc::Rc; -use std::sync::{atomic::AtomicU64, atomic::Ordering, Arc}; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; +use std::sync::Arc; -use anyhow::{anyhow, bail, Context}; -use base::{warn, Event, Timer}; -use cros_async::{sync::Mutex as AsyncMutex, EventAsync, Executor, TimerAsync}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; +use base::warn; +use base::Event; +use base::Timer; +use cros_async::sync::Mutex as AsyncMutex; +use cros_async::EventAsync; +use cros_async::Executor; +use cros_async::TimerAsync; use data_model::DataInit; use disk::AsyncDisk; -use futures::future::{AbortHandle, Abortable}; +use futures::future::AbortHandle; +use futures::future::Abortable; use sync::Mutex; +pub use sys::start_device as run_block_device; +pub use sys::Options; use vm_memory::GuestMemory; use vmm_vhost::message::*; -use crate::virtio::block::asynchronous::{flush_disk, handle_queue}; -use crate::virtio::block::{build_avail_features, build_config_space, DiskState, SECTOR_SIZE}; -use crate::virtio::vhost::user::device::handler::{sys::Doorbell, VhostUserBackend}; -use crate::virtio::{self, block::sys::*, copy_config}; - -pub use sys::{start_device as run_block_device, Options}; +use crate::virtio::block::asynchronous::flush_disk; +use crate::virtio::block::asynchronous::handle_queue; +use crate::virtio::block::build_avail_features; +use crate::virtio::block::build_config_space; +use crate::virtio::block::sys::*; +use crate::virtio::block::DiskState; +use crate::virtio::block::SECTOR_SIZE; +use crate::virtio::copy_config; +use crate::virtio::vhost::user::device::handler::sys::Doorbell; +use crate::virtio::vhost::user::device::handler::VhostUserBackend; +use crate::virtio::{self}; const QUEUE_SIZE: u16 = 256; const NUM_QUEUES: u16 = 16; diff --git a/devices/src/virtio/vhost/user/device/block/sys.rs b/devices/src/virtio/vhost/user/device/block/sys.rs index c5500dfb2..249b603a1 100644 --- a/devices/src/virtio/vhost/user/device/block/sys.rs +++ b/devices/src/virtio/vhost/user/device/block/sys.rs @@ -12,4 +12,5 @@ cfg_if::cfg_if! { } } -pub use platform::{start_device, Options}; +pub use platform::start_device; +pub use platform::Options; diff --git a/devices/src/virtio/vhost/user/device/block/sys/unix.rs b/devices/src/virtio/vhost/user/device/block/sys/unix.rs index cc8062205..f3c246610 100644 --- a/devices/src/virtio/vhost/user/device/block/sys/unix.rs +++ b/devices/src/virtio/vhost/user/device/block/sys/unix.rs @@ -4,18 +4,18 @@ use std::fs::OpenOptions; -use anyhow::{bail, Context}; +use anyhow::bail; +use anyhow::Context; use argh::FromArgs; use cros_async::Executor; use disk::create_async_disk_file; use hypervisor::ProtectionType; use crate::virtio::base_features; -use crate::virtio::vhost::user::device::{ - block::BlockBackend, - handler::VhostUserBackend, - listener::{sys::VhostUserListener, VhostUserListenerTrait}, -}; +use crate::virtio::vhost::user::device::block::BlockBackend; +use crate::virtio::vhost::user::device::handler::VhostUserBackend; +use crate::virtio::vhost::user::device::listener::sys::VhostUserListener; +use crate::virtio::vhost::user::device::listener::VhostUserListenerTrait; impl BlockBackend { /// Creates a new block backend. diff --git a/devices/src/virtio/vhost/user/device/block/sys/windows.rs b/devices/src/virtio/vhost/user/device/block/sys/windows.rs index 646874b81..ffe9c1cbd 100644 --- a/devices/src/virtio/vhost/user/device/block/sys/windows.rs +++ b/devices/src/virtio/vhost/user/device/block/sys/windows.rs @@ -6,16 +6,24 @@ use std::fs::File; use std::fs::OpenOptions; use std::os::windows::fs::OpenOptionsExt; -use anyhow::{bail, Context}; +use anyhow::bail; +use anyhow::Context; use argh::FromArgs; -use base::{enable_high_res_timers, info, Event, RawDescriptor}; -use broker_ipc::{common_child_setup, CommonChildStartupArgs}; +use base::enable_high_res_timers; +use base::info; +use base::Event; +use base::RawDescriptor; +use broker_ipc::common_child_setup; +use broker_ipc::CommonChildStartupArgs; use cros_async::Executor; -use disk::{async_ok, AsyncDisk, SingleFileDisk}; +use disk::async_ok; +use disk::AsyncDisk; +use disk::SingleFileDisk; use hypervisor::ProtectionType; use tracing; use tube_transporter::TubeToken; -use winapi::um::winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE}; +use winapi::um::winnt::FILE_SHARE_READ; +use winapi::um::winnt::FILE_SHARE_WRITE; use crate::virtio::base_features; use crate::virtio::block::block::DiskOption; diff --git a/devices/src/virtio/vhost/user/device/console.rs b/devices/src/virtio/vhost/user/device/console.rs index 17ea04093..716dd1b04 100644 --- a/devices/src/virtio/vhost/user/device/console.rs +++ b/devices/src/virtio/vhost/user/device/console.rs @@ -2,32 +2,36 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{path::PathBuf, sync::Arc}; +use std::path::PathBuf; +use std::sync::Arc; -use anyhow::{anyhow, bail, Context}; -use base::{error, Event, Terminal}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; +use argh::FromArgs; +use base::error; +use base::Event; +use base::Terminal; use cros_async::Executor; use data_model::DataInit; - -use argh::FromArgs; use hypervisor::ProtectionType; use sync::Mutex; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; -use crate::{ - virtio::{ - self, - console::{asynchronous::ConsoleDevice, virtio_console_config}, - copy_config, - vhost::user::device::{ - handler::{sys::Doorbell, VhostUserBackend}, - listener::{sys::VhostUserListener, VhostUserListenerTrait}, - VhostUserDevice, - }, - }, - SerialHardware, SerialParameters, SerialType, -}; +use crate::virtio::console::asynchronous::ConsoleDevice; +use crate::virtio::console::virtio_console_config; +use crate::virtio::copy_config; +use crate::virtio::vhost::user::device::handler::sys::Doorbell; +use crate::virtio::vhost::user::device::handler::VhostUserBackend; +use crate::virtio::vhost::user::device::listener::sys::VhostUserListener; +use crate::virtio::vhost::user::device::listener::VhostUserListenerTrait; +use crate::virtio::vhost::user::device::VhostUserDevice; +use crate::virtio::{self}; +use crate::SerialHardware; +use crate::SerialParameters; +use crate::SerialType; const MAX_QUEUE_NUM: usize = 2 /* transmit and receive queues */; const MAX_VRING_LEN: u16 = 256; diff --git a/devices/src/virtio/vhost/user/device/fs.rs b/devices/src/virtio/vhost/user/device/fs.rs index 793f19195..098e33c8f 100644 --- a/devices/src/virtio/vhost/user/device/fs.rs +++ b/devices/src/virtio/vhost/user/device/fs.rs @@ -4,28 +4,41 @@ mod sys; -pub use sys::start_device as run_fs_device; - use std::path::PathBuf; use std::sync::Arc; -use anyhow::{anyhow, bail, Context}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; use argh::FromArgs; -use base::{error, warn, AsRawDescriptors, Event, RawDescriptor, Tube}; -use cros_async::{EventAsync, Executor}; -use data_model::{DataInit, Le32}; +use base::error; +use base::warn; +use base::AsRawDescriptors; +use base::Event; +use base::RawDescriptor; +use base::Tube; +use cros_async::EventAsync; +use cros_async::Executor; +use data_model::DataInit; +use data_model::Le32; use fuse::Server; -use futures::future::{AbortHandle, Abortable}; +use futures::future::AbortHandle; +use futures::future::Abortable; use hypervisor::ProtectionType; use sync::Mutex; +pub use sys::start_device as run_fs_device; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; use crate::virtio; use crate::virtio::copy_config; use crate::virtio::fs::passthrough::PassthroughFs; -use crate::virtio::fs::{process_fs_queue, virtio_fs_config, FS_MAX_TAG_LEN}; -use crate::virtio::vhost::user::device::handler::{sys::Doorbell, VhostUserBackend}; +use crate::virtio::fs::process_fs_queue; +use crate::virtio::fs::virtio_fs_config; +use crate::virtio::fs::FS_MAX_TAG_LEN; +use crate::virtio::vhost::user::device::handler::sys::Doorbell; +use crate::virtio::vhost::user::device::handler::VhostUserBackend; const MAX_QUEUE_NUM: usize = 2; /* worker queue and high priority queue */ const MAX_VRING_LEN: u16 = 1024; diff --git a/devices/src/virtio/vhost/user/device/fs/sys/unix.rs b/devices/src/virtio/vhost/user/device/fs/sys/unix.rs index 2d01e775f..fe8941d1d 100644 --- a/devices/src/virtio/vhost/user/device/fs/sys/unix.rs +++ b/devices/src/virtio/vhost/user/device/fs/sys/unix.rs @@ -3,18 +3,22 @@ // found in the LICENSE file. use std::io; -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::path::PathBuf; -use anyhow::{bail, Context}; -use base::{get_max_open_files, RawDescriptor}; +use anyhow::bail; +use anyhow::Context; +use base::get_max_open_files; +use base::RawDescriptor; use cros_async::Executor; -use minijail::{self, Minijail}; +use minijail::Minijail; +use minijail::{self}; -use crate::virtio::vhost::user::device::fs::{FsBackend, Options}; -use crate::virtio::vhost::user::device::{ - handler::VhostUserBackend, - listener::{sys::VhostUserListener, VhostUserListenerTrait}, -}; +use crate::virtio::vhost::user::device::fs::FsBackend; +use crate::virtio::vhost::user::device::fs::Options; +use crate::virtio::vhost::user::device::handler::VhostUserBackend; +use crate::virtio::vhost::user::device::listener::sys::VhostUserListener; +use crate::virtio::vhost::user::device::listener::VhostUserListenerTrait; fn default_uidmap() -> String { let euid = unsafe { libc::geteuid() }; diff --git a/devices/src/virtio/vhost/user/device/gpu.rs b/devices/src/virtio/vhost/user/device/gpu.rs index 059524a86..3cc3c9250 100644 --- a/devices/src/virtio/vhost/user/device/gpu.rs +++ b/devices/src/virtio/vhost/user/device/gpu.rs @@ -2,34 +2,58 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{cell::RefCell, collections::BTreeMap, fs::File, path::PathBuf, rc::Rc, sync::Arc}; +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::fs::File; +use std::path::PathBuf; +use std::rc::Rc; +use std::sync::Arc; -use anyhow::{anyhow, bail, Context}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; use argh::FromArgs; use async_task::Task; -use base::{ - clone_descriptor, error, warn, Event, FromRawDescriptor, IntoRawDescriptor, SafeDescriptor, - Timer, Tube, UnixSeqpacketListener, UnlinkUnixSeqpacketListener, -}; -use cros_async::{AsyncTube, AsyncWrapper, EventAsync, Executor, IoSourceExt, TimerAsync}; -use futures::{ - future::{select, Either}, - pin_mut, -}; +use base::clone_descriptor; +use base::error; +use base::warn; +use base::Event; +use base::FromRawDescriptor; +use base::IntoRawDescriptor; +use base::SafeDescriptor; +use base::Timer; +use base::Tube; +use base::UnixSeqpacketListener; +use base::UnlinkUnixSeqpacketListener; +use cros_async::AsyncTube; +use cros_async::AsyncWrapper; +use cros_async::EventAsync; +use cros_async::Executor; +use cros_async::IoSourceExt; +use cros_async::TimerAsync; +use futures::future::select; +use futures::future::Either; +use futures::pin_mut; use hypervisor::ProtectionType; use sync::Mutex; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; -use crate::virtio::{ - self, gpu, - vhost::user::device::{ - handler::{sys::Doorbell, VhostUserBackend}, - listener::{sys::VhostUserListener, VhostUserListenerTrait}, - wl::parse_wayland_sock, - }, - DescriptorChain, Gpu, GpuDisplayParameters, GpuParameters, Queue, QueueReader, VirtioDevice, -}; +use crate::virtio::gpu; +use crate::virtio::vhost::user::device::handler::sys::Doorbell; +use crate::virtio::vhost::user::device::handler::VhostUserBackend; +use crate::virtio::vhost::user::device::listener::sys::VhostUserListener; +use crate::virtio::vhost::user::device::listener::VhostUserListenerTrait; +use crate::virtio::vhost::user::device::wl::parse_wayland_sock; +use crate::virtio::DescriptorChain; +use crate::virtio::Gpu; +use crate::virtio::GpuDisplayParameters; +use crate::virtio::GpuParameters; +use crate::virtio::Queue; +use crate::virtio::QueueReader; +use crate::virtio::VirtioDevice; +use crate::virtio::{self}; const MAX_QUEUE_NUM: usize = gpu::QUEUE_SIZES.len(); const MAX_VRING_LEN: u16 = gpu::QUEUE_SIZES[0]; diff --git a/devices/src/virtio/vhost/user/device/handler.rs b/devices/src/virtio/vhost/user/device/handler.rs index 2087292fc..56957b1b9 100644 --- a/devices/src/virtio/vhost/user/device/handler.rs +++ b/devices/src/virtio/vhost/user/device/handler.rs @@ -47,39 +47,65 @@ pub(super) mod sys; -use sys::Doorbell; - use std::collections::BTreeMap; -use std::convert::{From, TryFrom}; +use std::convert::From; +use std::convert::TryFrom; use std::fs::File; use std::num::Wrapping; +#[cfg(unix)] +use std::os::unix::io::AsRawFd; use std::sync::Arc; -use anyhow::{bail, Context, Result}; -use base::{ - error, info, AsRawDescriptor, Event, FromRawDescriptor, IntoRawDescriptor, Protection, - SafeDescriptor, SharedMemory, -}; -use cros_async::{AsyncWrapper, Executor}; -use sync::Mutex; -use vm_control::VmMemorySource; -use vm_memory::{GuestAddress, GuestMemory, MemoryRegion}; -use vmm_vhost::{ - connection::Endpoint, - message::{ - MasterReq, SlaveReq, VhostSharedMemoryRegion, VhostUserConfigFlags, VhostUserInflight, - VhostUserMemoryRegion, VhostUserProtocolFeatures, VhostUserShmemMapMsg, - VhostUserShmemMapMsgFlags, VhostUserShmemUnmapMsg, VhostUserSingleMemoryRegion, - VhostUserVirtioFeatures, VhostUserVringAddrFlags, VhostUserVringState, - }, - Error as VhostError, Protocol, Result as VhostResult, Slave, SlaveReqHandler, - VhostUserMasterReqHandler, VhostUserSlaveReqHandler, VhostUserSlaveReqHandlerMut, -}; - -use crate::virtio::{Queue, SharedMemoryMapper, SharedMemoryRegion, SignalableInterrupt}; - +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; #[cfg(unix)] -use {base::clear_fd_flags, std::os::unix::io::AsRawFd}; +use base::clear_fd_flags; +use base::error; +use base::info; +use base::AsRawDescriptor; +use base::Event; +use base::FromRawDescriptor; +use base::IntoRawDescriptor; +use base::Protection; +use base::SafeDescriptor; +use base::SharedMemory; +use cros_async::AsyncWrapper; +use cros_async::Executor; +use sync::Mutex; +use sys::Doorbell; +use vm_control::VmMemorySource; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +use vm_memory::MemoryRegion; +use vmm_vhost::connection::Endpoint; +use vmm_vhost::message::MasterReq; +use vmm_vhost::message::SlaveReq; +use vmm_vhost::message::VhostSharedMemoryRegion; +use vmm_vhost::message::VhostUserConfigFlags; +use vmm_vhost::message::VhostUserInflight; +use vmm_vhost::message::VhostUserMemoryRegion; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserShmemMapMsg; +use vmm_vhost::message::VhostUserShmemMapMsgFlags; +use vmm_vhost::message::VhostUserShmemUnmapMsg; +use vmm_vhost::message::VhostUserSingleMemoryRegion; +use vmm_vhost::message::VhostUserVirtioFeatures; +use vmm_vhost::message::VhostUserVringAddrFlags; +use vmm_vhost::message::VhostUserVringState; +use vmm_vhost::Error as VhostError; +use vmm_vhost::Protocol; +use vmm_vhost::Result as VhostResult; +use vmm_vhost::Slave; +use vmm_vhost::SlaveReqHandler; +use vmm_vhost::VhostUserMasterReqHandler; +use vmm_vhost::VhostUserSlaveReqHandler; +use vmm_vhost::VhostUserSlaveReqHandlerMut; + +use crate::virtio::Queue; +use crate::virtio::SharedMemoryMapper; +use crate::virtio::SharedMemoryRegion; +use crate::virtio::SignalableInterrupt; /// An event to deliver an interrupt to the guest. /// @@ -791,18 +817,20 @@ impl SharedMemoryMapper for VhostShmemMapper { #[cfg(test)] mod tests { - use super::*; - #[cfg(unix)] use std::sync::mpsc::channel; #[cfg(unix)] use std::sync::Barrier; - use anyhow::{anyhow, bail}; + use anyhow::anyhow; + use anyhow::bail; use data_model::DataInit; #[cfg(unix)] - use tempfile::{Builder, TempDir}; + use tempfile::Builder; + #[cfg(unix)] + use tempfile::TempDir; + use super::*; use crate::virtio::vhost::user::vmm::VhostUserHandler; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -910,7 +938,8 @@ mod tests { #[cfg(unix)] #[test] fn test_vhost_user_activate() { - use vmm_vhost::{connection::socket::Listener as SocketListener, SlaveListener}; + use vmm_vhost::connection::socket::Listener as SocketListener; + use vmm_vhost::SlaveListener; const QUEUES_NUM: usize = 2; diff --git a/devices/src/virtio/vhost/user/device/handler/sys/unix.rs b/devices/src/virtio/vhost/user/device/handler/sys/unix.rs index af7a488ae..0c0485dde 100644 --- a/devices/src/virtio/vhost/user/device/handler/sys/unix.rs +++ b/devices/src/virtio/vhost/user/device/handler/sys/unix.rs @@ -5,33 +5,39 @@ use std::fs::File; use std::sync::Arc; -use anyhow::{bail, Context, Result}; -use base::{error, info, AsRawDescriptor, Event, SafeDescriptor}; -use cros_async::{AsyncWrapper, Executor}; +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; +use base::error; +use base::info; +use base::AsRawDescriptor; +use base::Event; +use base::SafeDescriptor; +use cros_async::AsyncWrapper; +use cros_async::Executor; use vm_memory::GuestMemory; -use vmm_vhost::{ - connection::{Endpoint, Listener}, - message::{MasterReq, VhostUserMemoryRegion}, - Error as VhostError, Protocol, Result as VhostResult, SlaveListener, SlaveReqHandler, - VhostUserSlaveReqHandler, -}; +use vmm_vhost::connection::Endpoint; +use vmm_vhost::connection::Listener; +use vmm_vhost::message::MasterReq; +use vmm_vhost::message::VhostUserMemoryRegion; +use vmm_vhost::Error as VhostError; +use vmm_vhost::Protocol; +use vmm_vhost::Result as VhostResult; +use vmm_vhost::SlaveListener; +use vmm_vhost::SlaveReqHandler; +use vmm_vhost::VhostUserSlaveReqHandler; -use crate::{ - vfio::VfioDevice, - virtio::{ - vhost::user::device::{ - handler::{ - CallEvent, DeviceRequestHandler, GuestAddress, MappingInfo, MemoryRegion, - VhostUserPlatformOps, - }, - vvu::{ - doorbell::DoorbellRegion, - pci::{VvuPciCaps, VvuPciDevice}, - }, - }, - SignalableInterrupt, - }, -}; +use crate::vfio::VfioDevice; +use crate::virtio::vhost::user::device::handler::CallEvent; +use crate::virtio::vhost::user::device::handler::DeviceRequestHandler; +use crate::virtio::vhost::user::device::handler::GuestAddress; +use crate::virtio::vhost::user::device::handler::MappingInfo; +use crate::virtio::vhost::user::device::handler::MemoryRegion; +use crate::virtio::vhost::user::device::handler::VhostUserPlatformOps; +use crate::virtio::vhost::user::device::vvu::doorbell::DoorbellRegion; +use crate::virtio::vhost::user::device::vvu::pci::VvuPciCaps; +use crate::virtio::vhost::user::device::vvu::pci::VvuPciDevice; +use crate::virtio::SignalableInterrupt; /// A Doorbell that supports both regular call events and signaling through a VVU device. pub enum Doorbell { @@ -243,24 +249,25 @@ impl DeviceRequestHandler { #[cfg(test)] mod tests { - use super::*; - use std::sync::mpsc::channel; use std::sync::Barrier; + use tempfile::Builder; + use tempfile::TempDir; + + use super::*; use crate::virtio::vhost::user::device::handler::tests::*; use crate::virtio::vhost::user::device::handler::*; use crate::virtio::vhost::user::vmm::VhostUserHandler; - use tempfile::{Builder, TempDir}; - fn temp_dir() -> TempDir { Builder::new().prefix("/tmp/vhost_test").tempdir().unwrap() } #[test] fn test_vhost_user_activate() { - use vmm_vhost::{connection::socket::Listener as SocketListener, SlaveListener}; + use vmm_vhost::connection::socket::Listener as SocketListener; + use vmm_vhost::SlaveListener; const QUEUES_NUM: usize = 2; diff --git a/devices/src/virtio/vhost/user/device/handler/sys/windows.rs b/devices/src/virtio/vhost/user/device/handler/sys/windows.rs index e4ab389f2..d62d8d76f 100644 --- a/devices/src/virtio/vhost/user/device/handler/sys/windows.rs +++ b/devices/src/virtio/vhost/user/device/handler/sys/windows.rs @@ -4,18 +4,30 @@ use std::mem::ManuallyDrop; -use anyhow::{Context, Result}; -use base::named_pipes::{BlockingMode, FramingMode, PipeConnection}; -use base::{info, CloseNotifier, Event, FromRawDescriptor, RawDescriptor, ReadNotifier, Tube}; -use cros_async::{EventAsync, Executor}; +use anyhow::Context; +use anyhow::Result; +use base::info; +use base::named_pipes::BlockingMode; +use base::named_pipes::FramingMode; +use base::named_pipes::PipeConnection; +use base::CloseNotifier; +use base::Event; +use base::FromRawDescriptor; +use base::RawDescriptor; +use base::ReadNotifier; +use base::Tube; +use cros_async::EventAsync; +use cros_async::Executor; +use futures::pin_mut; +use futures::select; use futures::FutureExt; -use futures::{pin_mut, select}; -use tube_transporter::{TubeTransferDataList, TubeTransporterReader}; +use tube_transporter::TubeTransferDataList; +use tube_transporter::TubeTransporterReader; use vmm_vhost::SlaveReqHandler; -use crate::virtio::vhost::user::device::handler::{ - CallEvent, DeviceRequestHandler, VhostUserRegularOps, -}; +use crate::virtio::vhost::user::device::handler::CallEvent; +use crate::virtio::vhost::user::device::handler::DeviceRequestHandler; +use crate::virtio::vhost::user::device::handler::VhostUserRegularOps; pub type Doorbell = CallEvent; @@ -108,13 +120,12 @@ impl DeviceRequestHandler { #[cfg(test)] mod tests { - use super::*; + use std::sync::Barrier; + use super::*; use crate::virtio::vhost::user::device::handler::tests::*; use crate::virtio::vhost::user::device::handler::*; use crate::virtio::vhost::user::vmm::VhostUserHandler; - - use std::sync::Barrier; #[test] fn test_vhost_user_activate() { const QUEUES_NUM: usize = 2; diff --git a/devices/src/virtio/vhost/user/device/listener.rs b/devices/src/virtio/vhost/user/device/listener.rs index e16e5db97..c60fa9917 100644 --- a/devices/src/virtio/vhost/user/device/listener.rs +++ b/devices/src/virtio/vhost/user/device/listener.rs @@ -3,13 +3,13 @@ // found in the LICENSE file. pub mod sys; -pub use sys::VhostUserListener; - -use std::{any::Any, pin::Pin}; +use std::any::Any; +use std::pin::Pin; use base::RawDescriptor; use cros_async::Executor; use futures::Future; +pub use sys::VhostUserListener; use crate::virtio::vhost::user::device::handler::VhostUserBackend; diff --git a/devices/src/virtio/vhost/user/device/listener/sys/unix.rs b/devices/src/virtio/vhost/user/device/listener/sys/unix.rs index ba2f0d946..fc22c5716 100644 --- a/devices/src/virtio/vhost/user/device/listener/sys/unix.rs +++ b/devices/src/virtio/vhost/user/device/listener/sys/unix.rs @@ -2,25 +2,26 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{pin::Pin, str::FromStr}; +use std::pin::Pin; +use std::str::FromStr; use anyhow::bail; -use base::{AsRawDescriptor, RawDescriptor}; +use base::AsRawDescriptor; +use base::RawDescriptor; use cros_async::Executor; -use futures::{Future, FutureExt}; -use vmm_vhost::connection::{ - socket::Listener as SocketListener, - vfio::{Device, Listener as VfioListener}, -}; +use futures::Future; +use futures::FutureExt; +use vmm_vhost::connection::socket::Listener as SocketListener; +use vmm_vhost::connection::vfio::Device; +use vmm_vhost::connection::vfio::Listener as VfioListener; -use crate::{ - virtio::vhost::user::device::{ - handler::{sys::unix::VvuOps, DeviceRequestHandler, VhostUserBackend}, - listener::VhostUserListenerTrait, - vvu::{pci::VvuPciDevice, VvuDevice}, - }, - PciAddress, -}; +use crate::virtio::vhost::user::device::handler::sys::unix::VvuOps; +use crate::virtio::vhost::user::device::handler::DeviceRequestHandler; +use crate::virtio::vhost::user::device::handler::VhostUserBackend; +use crate::virtio::vhost::user::device::listener::VhostUserListenerTrait; +use crate::virtio::vhost::user::device::vvu::pci::VvuPciDevice; +use crate::virtio::vhost::user::device::vvu::VvuDevice; +use crate::PciAddress; //// On Unix we can listen to either a socket or a vhost-user device. pub enum VhostUserListener { diff --git a/devices/src/virtio/vhost/user/device/listener/sys/windows.rs b/devices/src/virtio/vhost/user/device/listener/sys/windows.rs index 626750fd9..c8bdce938 100644 --- a/devices/src/virtio/vhost/user/device/listener/sys/windows.rs +++ b/devices/src/virtio/vhost/user/device/listener/sys/windows.rs @@ -8,9 +8,8 @@ use base::RawDescriptor; use cros_async::Executor; use futures::Future; -use crate::virtio::vhost::user::device::{ - handler::VhostUserBackend, listener::VhostUserListenerTrait, -}; +use crate::virtio::vhost::user::device::handler::VhostUserBackend; +use crate::virtio::vhost::user::device::listener::VhostUserListenerTrait; /// TODO implement this. On Windows the `vhost_user_tube` can be provided through the `path` /// constructor string, and the future returned by `run_backend` can be listened to alonside the diff --git a/devices/src/virtio/vhost/user/device/mod.rs b/devices/src/virtio/vhost/user/device/mod.rs index d5ebd66d9..5eb6f7f01 100644 --- a/devices/src/virtio/vhost/user/device/mod.rs +++ b/devices/src/virtio/vhost/user/device/mod.rs @@ -6,8 +6,8 @@ mod block; mod handler; mod listener; -pub use block::{run_block_device, Options as BlockOptions}; - +pub use block::run_block_device; +pub use block::Options as BlockOptions; use cros_async::Executor; use crate::virtio::vhost::user::device::handler::VhostUserBackend; diff --git a/devices/src/virtio/vhost/user/device/net.rs b/devices/src/virtio/vhost/user/device/net.rs index 24267bcb6..7ef713366 100644 --- a/devices/src/virtio/vhost/user/device/net.rs +++ b/devices/src/virtio/vhost/user/device/net.rs @@ -6,22 +6,31 @@ pub mod sys; use std::sync::Arc; -use anyhow::{anyhow, bail, Context}; -use base::{error, Event}; -use cros_async::{EventAsync, Executor, IntoAsync}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; +use base::error; +use base::Event; +use cros_async::EventAsync; +use cros_async::Executor; +use cros_async::IntoAsync; use data_model::DataInit; use futures::future::AbortHandle; use net_util::TapT; use once_cell::sync::OnceCell; use sync::Mutex; +pub use sys::start_device as run_net_device; +pub use sys::Options; use vm_memory::GuestMemory; use vmm_vhost::message::VhostUserProtocolFeatures; use crate::virtio; -use crate::virtio::net::{build_config, process_ctrl, process_tx, virtio_features_to_tap_offload}; -use crate::virtio::vhost::user::device::handler::{sys::Doorbell, VhostUserBackend}; - -pub use sys::{start_device as run_net_device, Options}; +use crate::virtio::net::build_config; +use crate::virtio::net::process_ctrl; +use crate::virtio::net::process_tx; +use crate::virtio::net::virtio_features_to_tap_offload; +use crate::virtio::vhost::user::device::handler::sys::Doorbell; +use crate::virtio::vhost::user::device::handler::VhostUserBackend; thread_local! { pub(crate) static NET_EXECUTOR: OnceCell = OnceCell::new(); diff --git a/devices/src/virtio/vhost/user/device/net/sys.rs b/devices/src/virtio/vhost/user/device/net/sys.rs index a912a8d72..418169a65 100644 --- a/devices/src/virtio/vhost/user/device/net/sys.rs +++ b/devices/src/virtio/vhost/user/device/net/sys.rs @@ -12,5 +12,6 @@ cfg_if::cfg_if! { } } +pub use platform::start_device; pub(in crate::virtio::vhost::user::device::net) use platform::start_queue; -pub use platform::{start_device, Options}; +pub use platform::Options; diff --git a/devices/src/virtio/vhost/user/device/net/sys/unix.rs b/devices/src/virtio/vhost/user/device/net/sys/unix.rs index bc6c93059..128c85e30 100644 --- a/devices/src/virtio/vhost/user/device/net/sys/unix.rs +++ b/devices/src/virtio/vhost/user/device/net/sys/unix.rs @@ -7,30 +7,44 @@ use std::str::FromStr; use std::sync::Arc; use std::thread; -use anyhow::{anyhow, bail, Context}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; use argh::FromArgs; +use base::error; use base::validate_raw_descriptor; -use base::{error, warn, Event, RawDescriptor}; -use cros_async::{EventAsync, Executor, IntoAsync, IoSourceExt}; -use futures::future::{AbortHandle, Abortable}; +use base::warn; +use base::Event; +use base::RawDescriptor; +use cros_async::EventAsync; +use cros_async::Executor; +use cros_async::IntoAsync; +use cros_async::IoSourceExt; +use futures::future::AbortHandle; +use futures::future::Abortable; use hypervisor::ProtectionType; +use net_util::sys::unix::Tap; +use net_util::MacAddress; use net_util::TapT; -use net_util::{sys::unix::Tap, MacAddress}; use sync::Mutex; use virtio_sys::virtio_net; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; +use crate::virtio; +use crate::virtio::net::process_rx; use crate::virtio::net::validate_and_configure_tap; -use crate::virtio::net::{process_rx, NetError}; -use crate::virtio::vhost::user::device::net::{ - run_ctrl_queue, run_tx_queue, NetBackend, NET_EXECUTOR, -}; -use crate::virtio::vhost::user::device::{ - handler::{sys::Doorbell, VhostUserBackend}, - listener::{sys::VhostUserListener, VhostUserListenerTrait}, -}; -use crate::{virtio, PciAddress}; +use crate::virtio::net::NetError; +use crate::virtio::vhost::user::device::handler::sys::Doorbell; +use crate::virtio::vhost::user::device::handler::VhostUserBackend; +use crate::virtio::vhost::user::device::listener::sys::VhostUserListener; +use crate::virtio::vhost::user::device::listener::VhostUserListenerTrait; +use crate::virtio::vhost::user::device::net::run_ctrl_queue; +use crate::virtio::vhost::user::device::net::run_tx_queue; +use crate::virtio::vhost::user::device::net::NetBackend; +use crate::virtio::vhost::user::device::net::NET_EXECUTOR; +use crate::PciAddress; struct TapConfig { host_ip: Ipv4Addr, diff --git a/devices/src/virtio/vhost/user/device/net/sys/windows.rs b/devices/src/virtio/vhost/user/device/net/sys/windows.rs index ac7e14f95..99d94a180 100644 --- a/devices/src/virtio/vhost/user/device/net/sys/windows.rs +++ b/devices/src/virtio/vhost/user/device/net/sys/windows.rs @@ -2,35 +2,54 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::virtio; -#[cfg(feature = "slirp")] -use crate::virtio::net::MAX_BUFFER_SIZE; -use crate::virtio::net::{process_rx, NetError}; -use crate::virtio::vhost::user::device::handler::sys::windows::read_from_tube_transporter; -use crate::virtio::vhost::user::device::handler::{sys::Doorbell, DeviceRequestHandler}; -use crate::virtio::vhost::user::device::net::{ - run_ctrl_queue, run_tx_queue, NetBackend, NET_EXECUTOR, -}; -use crate::virtio::{base_features, SignalableInterrupt}; -use anyhow::{bail, Context}; +use std::sync::Arc; + +use anyhow::bail; +use anyhow::Context; use argh::FromArgs; -use base::named_pipes::{OverlappedWrapper, PipeConnection}; -use base::{error, warn, Event, RawDescriptor}; -use broker_ipc::{common_child_setup, CommonChildStartupArgs}; -use cros_async::{EventAsync, Executor, IntoAsync, IoSourceExt}; -use futures::future::{AbortHandle, Abortable}; +use base::error; +use base::named_pipes::OverlappedWrapper; +use base::named_pipes::PipeConnection; +use base::warn; +use base::Event; +use base::RawDescriptor; +use broker_ipc::common_child_setup; +use broker_ipc::CommonChildStartupArgs; +use cros_async::EventAsync; +use cros_async::Executor; +use cros_async::IntoAsync; +use cros_async::IoSourceExt; +use futures::future::AbortHandle; +use futures::future::Abortable; use hypervisor::ProtectionType; #[cfg(feature = "slirp")] use net_util::Slirp; use net_util::TapT; #[cfg(feature = "slirp")] -use serde::{Deserialize, Serialize}; -use std::sync::Arc; +use serde::Deserialize; +#[cfg(feature = "slirp")] +use serde::Serialize; use sync::Mutex; use tube_transporter::TubeToken; use virtio_sys::virtio_net; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; + +use crate::virtio; +use crate::virtio::base_features; +use crate::virtio::net::process_rx; +use crate::virtio::net::NetError; +#[cfg(feature = "slirp")] +use crate::virtio::net::MAX_BUFFER_SIZE; +use crate::virtio::vhost::user::device::handler::sys::windows::read_from_tube_transporter; +use crate::virtio::vhost::user::device::handler::sys::Doorbell; +use crate::virtio::vhost::user::device::handler::DeviceRequestHandler; +use crate::virtio::vhost::user::device::net::run_ctrl_queue; +use crate::virtio::vhost::user::device::net::run_tx_queue; +use crate::virtio::vhost::user::device::net::NetBackend; +use crate::virtio::vhost::user::device::net::NET_EXECUTOR; +use crate::virtio::SignalableInterrupt; impl NetBackend where diff --git a/devices/src/virtio/vhost/user/device/snd.rs b/devices/src/virtio/vhost/user/device/snd.rs index e95002e14..1781da45a 100644 --- a/devices/src/virtio/vhost/user/device/snd.rs +++ b/devices/src/virtio/vhost/user/device/snd.rs @@ -5,32 +5,46 @@ use std::rc::Rc; use std::sync::Arc; -use anyhow::{anyhow, bail, Context}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; use argh::FromArgs; -use base::{error, warn, Event}; -use cros_async::{sync::Mutex as AsyncMutex, EventAsync, Executor}; +use base::error; +use base::warn; +use base::Event; +use cros_async::sync::Mutex as AsyncMutex; +use cros_async::EventAsync; +use cros_async::Executor; use data_model::DataInit; use futures::channel::mpsc; -use futures::future::{AbortHandle, Abortable}; +use futures::future::AbortHandle; +use futures::future::Abortable; use hypervisor::ProtectionType; use once_cell::sync::OnceCell; use sync::Mutex; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; -use crate::virtio::snd::common_backend::{ - async_funcs::{handle_ctrl_queue, handle_pcm_queue, send_pcm_response_worker}, - hardcoded_snd_data, hardcoded_virtio_snd_config, PcmResponse, SndData, StreamInfo, - MAX_QUEUE_NUM, MAX_VRING_LEN, -}; +use crate::virtio::copy_config; +use crate::virtio::snd::common_backend::async_funcs::handle_ctrl_queue; +use crate::virtio::snd::common_backend::async_funcs::handle_pcm_queue; +use crate::virtio::snd::common_backend::async_funcs::send_pcm_response_worker; +use crate::virtio::snd::common_backend::hardcoded_snd_data; +use crate::virtio::snd::common_backend::hardcoded_virtio_snd_config; +use crate::virtio::snd::common_backend::PcmResponse; +use crate::virtio::snd::common_backend::SndData; +use crate::virtio::snd::common_backend::StreamInfo; +use crate::virtio::snd::common_backend::MAX_QUEUE_NUM; +use crate::virtio::snd::common_backend::MAX_VRING_LEN; use crate::virtio::snd::layout::virtio_snd_config; use crate::virtio::snd::parameters::Parameters; use crate::virtio::snd::sys::create_cras_stream_source_generators; -use crate::virtio::vhost::user::device::{ - handler::{sys::Doorbell, VhostUserBackend}, - listener::{sys::VhostUserListener, VhostUserListenerTrait}, -}; -use crate::virtio::{self, copy_config}; +use crate::virtio::vhost::user::device::handler::sys::Doorbell; +use crate::virtio::vhost::user::device::handler::VhostUserBackend; +use crate::virtio::vhost::user::device::listener::sys::VhostUserListener; +use crate::virtio::vhost::user::device::listener::VhostUserListenerTrait; +use crate::virtio::{self}; static SND_EXECUTOR: OnceCell = OnceCell::new(); diff --git a/devices/src/virtio/vhost/user/device/vsock.rs b/devices/src/virtio/vhost/user/device/vsock.rs index e0bfb46e4..0d7345a78 100644 --- a/devices/src/virtio/vhost/user/device/vsock.rs +++ b/devices/src/virtio/vhost/user/device/vsock.rs @@ -2,53 +2,67 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::convert::TryInto; +use std::convert::{self}; +use std::fs::File; +use std::fs::OpenOptions; +use std::mem::size_of; +use std::num::Wrapping; use std::os::unix::fs::OpenOptionsExt; -use std::{ - convert::{self, TryInto}, - fs::{File, OpenOptions}, - mem::size_of, - num::Wrapping, - os::unix::net::UnixListener, - path::Path, - str, - sync::{Arc, Mutex as StdMutex}, -}; +use std::os::unix::net::UnixListener; +use std::path::Path; +use std::str; +use std::sync::Arc; +use std::sync::Mutex as StdMutex; -use anyhow::{bail, Context}; +use anyhow::bail; +use anyhow::Context; use argh::FromArgs; -use base::{Event, FromRawDescriptor, IntoRawDescriptor, UnlinkUnixListener}; -use cros_async::{EventAsync, Executor}; -use data_model::{DataInit, Le64}; +use base::Event; +use base::FromRawDescriptor; +use base::IntoRawDescriptor; +use base::UnlinkUnixListener; +use cros_async::EventAsync; +use cros_async::Executor; +use data_model::DataInit; +use data_model::Le64; use hypervisor::ProtectionType; use sync::Mutex; -use vhost::{self, Vhost, Vsock}; +use vhost::Vhost; +use vhost::Vsock; +use vhost::{self}; use vm_memory::GuestMemory; -use vmm_vhost::{ - connection::vfio::Listener as VfioListener, - message::{ - VhostSharedMemoryRegion, VhostUserConfigFlags, VhostUserInflight, VhostUserMemoryRegion, - VhostUserProtocolFeatures, VhostUserSingleMemoryRegion, VhostUserVirtioFeatures, - VhostUserVringAddrFlags, VhostUserVringState, - }, - Error, Result, SlaveReqHandler, VhostUserSlaveReqHandlerMut, -}; -use vmm_vhost::{Protocol, SlaveListener}; - -use crate::virtio::vhost::user::device::handler::{run_handler, VhostUserRegularOps}; -use crate::virtio::{ - base_features, - vhost::{ - user::device::{ - handler::{vmm_va_to_gpa, MappingInfo, VhostUserPlatformOps}, - vvu::{doorbell::DoorbellRegion, pci::VvuPciDevice, VvuDevice}, - }, - vsock, - }, - Queue, SignalableInterrupt, -}; +use vmm_vhost::connection::vfio::Listener as VfioListener; +use vmm_vhost::message::VhostSharedMemoryRegion; +use vmm_vhost::message::VhostUserConfigFlags; +use vmm_vhost::message::VhostUserInflight; +use vmm_vhost::message::VhostUserMemoryRegion; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserSingleMemoryRegion; +use vmm_vhost::message::VhostUserVirtioFeatures; +use vmm_vhost::message::VhostUserVringAddrFlags; +use vmm_vhost::message::VhostUserVringState; +use vmm_vhost::Error; +use vmm_vhost::Protocol; +use vmm_vhost::Result; +use vmm_vhost::SlaveListener; +use vmm_vhost::SlaveReqHandler; +use vmm_vhost::VhostUserSlaveReqHandlerMut; +use crate::virtio::base_features; +use crate::virtio::vhost::user::device::handler::run_handler; // TODO(acourbot) try to remove the system dependencies and make the device usable on all platforms. use crate::virtio::vhost::user::device::handler::sys::unix::{Doorbell, VvuOps}; +use crate::virtio::vhost::user::device::handler::vmm_va_to_gpa; +use crate::virtio::vhost::user::device::handler::MappingInfo; +use crate::virtio::vhost::user::device::handler::VhostUserPlatformOps; +use crate::virtio::vhost::user::device::handler::VhostUserRegularOps; +use crate::virtio::vhost::user::device::vvu::doorbell::DoorbellRegion; +use crate::virtio::vhost::user::device::vvu::pci::VvuPciDevice; +use crate::virtio::vhost::user::device::vvu::VvuDevice; +use crate::virtio::vhost::vsock; +use crate::virtio::Queue; +use crate::virtio::SignalableInterrupt; const MAX_VRING_LEN: u16 = vsock::QUEUE_SIZE; const NUM_QUEUES: usize = vsock::QUEUE_SIZES.len(); diff --git a/devices/src/virtio/vhost/user/device/vvu/bus.rs b/devices/src/virtio/vhost/user/device/vvu/bus.rs index a1580e8c9..10416a8b1 100644 --- a/devices/src/virtio/vhost/user/device/vvu/bus.rs +++ b/devices/src/virtio/vhost/user/device/vvu/bus.rs @@ -7,10 +7,12 @@ use std::path::Path; use std::sync::Arc; -use anyhow::{Context, Result}; +use anyhow::Context; +use anyhow::Result; use sync::Mutex; -use crate::vfio::{VfioContainer, VfioDevice}; +use crate::vfio::VfioContainer; +use crate::vfio::VfioDevice; /// Opens device with given sysfs path as `VfioDevice`. pub fn open_vfio_device>(vfio_path: &P) -> Result { diff --git a/devices/src/virtio/vhost/user/device/vvu/device.rs b/devices/src/virtio/vhost/user/device/vvu/device.rs index 0db0096ef..d871cdf1a 100644 --- a/devices/src/virtio/vhost/user/device/vvu/device.rs +++ b/devices/src/virtio/vhost/user/device/vvu/device.rs @@ -5,25 +5,38 @@ //! Implement a struct that works as a `vmm_vhost`'s backend. use std::cmp::Ordering; -use std::io::{IoSlice, IoSliceMut}; +use std::io::IoSlice; +use std::io::IoSliceMut; use std::mem; -use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::mpsc::channel; +use std::sync::mpsc::Receiver; +use std::sync::mpsc::Sender; use std::sync::Arc; use std::thread; -use anyhow::{anyhow, bail, Context, Result}; -use base::{error, info, Event, RawDescriptor}; -use cros_async::{EventAsync, Executor}; -use futures::{pin_mut, select, FutureExt}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; +use base::error; +use base::info; +use base::Event; +use base::RawDescriptor; +use cros_async::EventAsync; +use cros_async::Executor; +use futures::pin_mut; +use futures::select; +use futures::FutureExt; use sync::Mutex; -use vmm_vhost::connection::vfio::{Device as VfioDeviceTrait, RecvIntoBufsError}; +use vmm_vhost::connection::vfio::Device as VfioDeviceTrait; +use vmm_vhost::connection::vfio::RecvIntoBufsError; use vmm_vhost::message::MasterReq; -use crate::virtio::vhost::user::device::vvu::{ - pci::{QueueNotifier, VvuPciDevice}, - queue::UserQueue, -}; -use crate::virtio::vhost::{vhost_header_from_bytes, HEADER_LEN}; +use crate::virtio::vhost::user::device::vvu::pci::QueueNotifier; +use crate::virtio::vhost::user::device::vvu::pci::VvuPciDevice; +use crate::virtio::vhost::user::device::vvu::queue::UserQueue; +use crate::virtio::vhost::vhost_header_from_bytes; +use crate::virtio::vhost::HEADER_LEN; // Helper class for forwarding messages from the virtqueue thread to the main worker thread. struct VfioSender { diff --git a/devices/src/virtio/vhost/user/device/vvu/doorbell.rs b/devices/src/virtio/vhost/user/device/vvu/doorbell.rs index 56fda1a5a..d2aec7a7e 100644 --- a/devices/src/virtio/vhost/user/device/vvu/doorbell.rs +++ b/devices/src/virtio/vhost/user/device/vvu/doorbell.rs @@ -4,8 +4,12 @@ use std::sync::Arc; -use base::{error, Event, MemoryMapping, MemoryMappingBuilder}; -use vmm_vhost::{Error as VhostError, Result as VhostResult}; +use base::error; +use base::Event; +use base::MemoryMapping; +use base::MemoryMappingBuilder; +use vmm_vhost::Error as VhostError; +use vmm_vhost::Result as VhostResult; use crate::vfio::VfioDevice; use crate::virtio::vhost::user::device::vvu::pci::VvuPciCaps; diff --git a/devices/src/virtio/vhost/user/device/vvu/pci.rs b/devices/src/virtio/vhost/user/device/vvu/pci.rs index 0696ad4bc..aa78ddf92 100644 --- a/devices/src/virtio/vhost/user/device/vvu/pci.rs +++ b/devices/src/virtio/vhost/user/device/vvu/pci.rs @@ -6,23 +6,37 @@ use std::str::FromStr; use std::sync::Arc; -use std::time::{Duration, Instant}; +use std::time::Duration; +use std::time::Instant; -use anyhow::{anyhow, bail, Context, Result}; -use base::{info, Event, MemoryMapping, MemoryMappingBuilder}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; +use base::info; +use base::Event; +use base::MemoryMapping; +use base::MemoryMappingBuilder; use data_model::DataInit; use memoffset::offset_of; use resources::Alloc; use vfio_sys::*; -use virtio_sys::virtio_config::{self, VIRTIO_F_VERSION_1}; +use virtio_sys::virtio_config::VIRTIO_F_VERSION_1; +use virtio_sys::virtio_config::{self}; -use crate::pci::{MsixCap, PciAddress, PciCapabilityID, CAPABILITY_LIST_HEAD_OFFSET}; -use crate::vfio::{VfioDevice, VfioPciConfig, VfioRegionAddr}; -use crate::virtio::vhost::user::device::vvu::{ - bus::open_vfio_device, - queue::{DescTableAddrs, IovaAllocator, UserQueue}, -}; -use crate::virtio::{PciCapabilityType, VirtioPciCap}; +use crate::pci::MsixCap; +use crate::pci::PciAddress; +use crate::pci::PciCapabilityID; +use crate::pci::CAPABILITY_LIST_HEAD_OFFSET; +use crate::vfio::VfioDevice; +use crate::vfio::VfioPciConfig; +use crate::vfio::VfioRegionAddr; +use crate::virtio::vhost::user::device::vvu::bus::open_vfio_device; +use crate::virtio::vhost::user::device::vvu::queue::DescTableAddrs; +use crate::virtio::vhost::user::device::vvu::queue::IovaAllocator; +use crate::virtio::vhost::user::device::vvu::queue::UserQueue; +use crate::virtio::PciCapabilityType; +use crate::virtio::VirtioPciCap; const VIRTIO_CONFIG_STATUS_RESET: u8 = 0; diff --git a/devices/src/virtio/vhost/user/device/vvu/queue.rs b/devices/src/virtio/vhost/user/device/vvu/queue.rs index e0aedca96..523512f30 100644 --- a/devices/src/virtio/vhost/user/device/vvu/queue.rs +++ b/devices/src/virtio/vhost/user/device/vvu/queue.rs @@ -7,12 +7,21 @@ use std::mem; use std::num::Wrapping; -use std::sync::atomic::{fence, Ordering}; +use std::sync::atomic::fence; +use std::sync::atomic::Ordering; -use anyhow::{anyhow, bail, Context, Result}; -use data_model::{DataInit, Le16, Le32, Le64, VolatileSlice}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; +use data_model::DataInit; +use data_model::Le16; +use data_model::Le32; +use data_model::Le64; +use data_model::VolatileSlice; use virtio_sys::virtio_ring::VRING_DESC_F_WRITE; -use vm_memory::{GuestAddress as IOVA, GuestMemory as QueueMemory}; +use vm_memory::GuestAddress as IOVA; +use vm_memory::GuestMemory as QueueMemory; use crate::virtio::Desc; @@ -423,13 +432,14 @@ impl UserQueue { #[cfg(test)] mod test { - use super::*; - use std::cell::RefCell; use std::io::Read; use std::io::Write; - use crate::virtio::{Queue as DeviceQueue, Reader, Writer}; + use super::*; + use crate::virtio::Queue as DeviceQueue; + use crate::virtio::Reader; + use crate::virtio::Writer; // An allocator that just allocates 0 as an IOVA. struct SimpleIovaAllocator(RefCell); diff --git a/devices/src/virtio/vhost/user/device/wl.rs b/devices/src/virtio/vhost/user/device/wl.rs index 7fa4df520..ff5c4a099 100644 --- a/devices/src/virtio/vhost/user/device/wl.rs +++ b/devices/src/virtio/vhost/user/device/wl.rs @@ -8,27 +8,44 @@ use std::path::PathBuf; use std::rc::Rc; use std::sync::Arc; use std::thread; -use std::time::{Duration, Instant}; +use std::time::Duration; +use std::time::Instant; -use anyhow::{anyhow, bail, Context}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; use argh::FromArgs; -use base::{ - clone_descriptor, error, warn, Event, FromRawDescriptor, SafeDescriptor, Tube, UnixSeqpacket, -}; -use cros_async::{AsyncWrapper, EventAsync, Executor, IoSourceExt}; -use futures::future::{AbortHandle, Abortable}; +use base::clone_descriptor; +use base::error; +use base::warn; +use base::Event; +use base::FromRawDescriptor; +use base::SafeDescriptor; +use base::Tube; +use base::UnixSeqpacket; +use cros_async::AsyncWrapper; +use cros_async::EventAsync; +use cros_async::Executor; +use cros_async::IoSourceExt; +use futures::future::AbortHandle; +use futures::future::Abortable; use hypervisor::ProtectionType; #[cfg(feature = "minigbm")] use rutabaga_gfx::RutabagaGralloc; use sync::Mutex; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; -use crate::virtio::vhost::user::device::{ - handler::{sys::Doorbell, VhostUserBackend}, - listener::{sys::VhostUserListener, VhostUserListenerTrait}, -}; -use crate::virtio::{base_features, wl, Queue, SharedMemoryMapper, SharedMemoryRegion}; +use crate::virtio::base_features; +use crate::virtio::vhost::user::device::handler::sys::Doorbell; +use crate::virtio::vhost::user::device::handler::VhostUserBackend; +use crate::virtio::vhost::user::device::listener::sys::VhostUserListener; +use crate::virtio::vhost::user::device::listener::VhostUserListenerTrait; +use crate::virtio::wl; +use crate::virtio::Queue; +use crate::virtio::SharedMemoryMapper; +use crate::virtio::SharedMemoryRegion; const MAX_QUEUE_NUM: usize = wl::QUEUE_SIZES.len(); const MAX_VRING_LEN: u16 = wl::QUEUE_SIZE; diff --git a/devices/src/virtio/vhost/user/proxy.rs b/devices/src/virtio/vhost/user/proxy.rs index e561da032..b64e007f8 100644 --- a/devices/src/virtio/vhost/user/proxy.rs +++ b/devices/src/virtio/vhost/user/proxy.rs @@ -17,40 +17,68 @@ use std::os::unix::net::UnixListener; use std::sync::Arc; use std::thread; -use anyhow::{anyhow, bail, Context}; -use base::{ - error, info, AsRawDescriptor, Event, EventToken, EventType, FromRawDescriptor, - IntoRawDescriptor, Protection, RawDescriptor, SafeDescriptor, Tube, WaitContext, -}; -use data_model::{DataInit, Le32}; -use libc::{recv, MSG_DONTWAIT, MSG_PEEK}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; +use base::error; +use base::info; +use base::AsRawDescriptor; +use base::Event; +use base::EventToken; +use base::EventType; +use base::FromRawDescriptor; +use base::IntoRawDescriptor; +use base::Protection; +use base::RawDescriptor; +use base::SafeDescriptor; +use base::Tube; +use base::WaitContext; +use data_model::DataInit; +use data_model::Le32; +use libc::recv; +use libc::MSG_DONTWAIT; +use libc::MSG_PEEK; use resources::Alloc; use sync::Mutex; use uuid::Uuid; -use vm_control::{MemSlot, VmMemoryDestination, VmMemoryRequest, VmMemoryResponse, VmMemorySource}; +use vm_control::MemSlot; +use vm_control::VmMemoryDestination; +use vm_control::VmMemoryRequest; +use vm_control::VmMemoryResponse; +use vm_control::VmMemorySource; use vm_memory::GuestMemory; -use vmm_vhost::{ - connection::socket::Endpoint as SocketEndpoint, - connection::EndpointExt, - message::{ - MasterReq, Req, VhostUserMemory, VhostUserMemoryRegion, VhostUserMsgHeader, - VhostUserMsgValidator, VhostUserU64, - }, - Protocol, SlaveReqHelper, -}; +use vmm_vhost::connection::socket::Endpoint as SocketEndpoint; +use vmm_vhost::connection::EndpointExt; +use vmm_vhost::message::MasterReq; +use vmm_vhost::message::Req; +use vmm_vhost::message::VhostUserMemory; +use vmm_vhost::message::VhostUserMemoryRegion; +use vmm_vhost::message::VhostUserMsgHeader; +use vmm_vhost::message::VhostUserMsgValidator; +use vmm_vhost::message::VhostUserU64; +use vmm_vhost::Protocol; +use vmm_vhost::SlaveReqHelper; -use crate::virtio::{ - copy_config, DescriptorChain, DeviceType, Interrupt, PciCapabilityType, Queue, Reader, - SignalableInterrupt, VirtioDevice, VirtioPciCap, Writer, -}; +use crate::pci::PciBarConfiguration; +use crate::pci::PciBarIndex; +use crate::pci::PciBarPrefetchable; +use crate::pci::PciBarRegionType; +use crate::pci::PciCapability; +use crate::pci::PciCapabilityID; +use crate::virtio::copy_config; +use crate::virtio::DescriptorChain; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::PciCapabilityType; +use crate::virtio::Queue; +use crate::virtio::Reader; +use crate::virtio::SignalableInterrupt; +use crate::virtio::VirtioDevice; +use crate::virtio::VirtioPciCap; +use crate::virtio::Writer; +use crate::virtio::VIRTIO_F_ACCESS_PLATFORM; +use crate::virtio::VIRTIO_MSI_NO_VECTOR; use crate::PciAddress; -use crate::{ - pci::{ - PciBarConfiguration, PciBarIndex, PciBarPrefetchable, PciBarRegionType, PciCapability, - PciCapabilityID, - }, - virtio::{VIRTIO_F_ACCESS_PLATFORM, VIRTIO_MSI_NO_VECTOR}, -}; // Note: There are two sets of queues that will be mentioned here. 1st set is // for this Virtio PCI device itself. 2nd set is the actual device backends diff --git a/devices/src/virtio/vhost/user/vmm/block.rs b/devices/src/virtio/vhost/user/vmm/block.rs index dc29b1197..386101b43 100644 --- a/devices/src/virtio/vhost/user/vmm/block.rs +++ b/devices/src/virtio/vhost/user/vmm/block.rs @@ -8,13 +8,20 @@ use std::cell::RefCell; use std::thread; use std::u32; -use base::{error, Event, RawDescriptor}; +use base::error; +use base::Event; +use base::RawDescriptor; use virtio_sys::virtio_ring::VIRTIO_RING_F_EVENT_IDX; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; +use crate::virtio::block::common::virtio_blk_config; use crate::virtio::vhost::user::vmm::handler::VhostUserHandler; -use crate::virtio::{block::common::virtio_blk_config, DeviceType, Interrupt, Queue, VirtioDevice}; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::VirtioDevice; const VIRTIO_BLK_F_SEG_MAX: u32 = 2; const VIRTIO_BLK_F_RO: u32 = 5; diff --git a/devices/src/virtio/vhost/user/vmm/block/sys/unix.rs b/devices/src/virtio/vhost/user/vmm/block/sys/unix.rs index 680974633..55d99afc6 100644 --- a/devices/src/virtio/vhost/user/vmm/block/sys/unix.rs +++ b/devices/src/virtio/vhost/user/vmm/block/sys/unix.rs @@ -6,9 +6,11 @@ use std::cell::RefCell; use std::os::unix::net::UnixStream; use std::path::Path; -use crate::virtio::vhost::user::vmm::block::{Block, QUEUE_SIZE}; +use crate::virtio::vhost::user::vmm::block::Block; +use crate::virtio::vhost::user::vmm::block::QUEUE_SIZE; +use crate::virtio::vhost::user::vmm::handler::VhostUserHandler; use crate::virtio::vhost::user::vmm::Error; -use crate::virtio::vhost::user::vmm::{handler::VhostUserHandler, Result}; +use crate::virtio::vhost::user::vmm::Result; impl Block { pub fn new>(base_features: u64, socket_path: P) -> Result { diff --git a/devices/src/virtio/vhost/user/vmm/block/sys/windows.rs b/devices/src/virtio/vhost/user/vmm/block/sys/windows.rs index 07832a2fb..601e02f5c 100644 --- a/devices/src/virtio/vhost/user/vmm/block/sys/windows.rs +++ b/devices/src/virtio/vhost/user/vmm/block/sys/windows.rs @@ -6,8 +6,10 @@ use std::cell::RefCell; use base::Tube; -use crate::virtio::vhost::user::vmm::block::{Block, QUEUE_SIZE}; -use crate::virtio::vhost::user::vmm::{handler::VhostUserHandler, Result}; +use crate::virtio::vhost::user::vmm::block::Block; +use crate::virtio::vhost::user::vmm::block::QUEUE_SIZE; +use crate::virtio::vhost::user::vmm::handler::VhostUserHandler; +use crate::virtio::vhost::user::vmm::Result; impl Block { pub fn new(base_features: u64, tube: Tube) -> Result { diff --git a/devices/src/virtio/vhost/user/vmm/console.rs b/devices/src/virtio/vhost/user/vmm/console.rs index a767ce191..baacd5ba4 100644 --- a/devices/src/virtio/vhost/user/vmm/console.rs +++ b/devices/src/virtio/vhost/user/vmm/console.rs @@ -7,13 +7,22 @@ use std::os::unix::net::UnixStream; use std::path::Path; use std::thread; -use base::{error, Event, RawDescriptor}; +use base::error; +use base::Event; +use base::RawDescriptor; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; -use crate::virtio::console::{virtio_console_config, QUEUE_SIZE}; -use crate::virtio::vhost::user::vmm::{handler::VhostUserHandler, Error, Result}; -use crate::virtio::{DeviceType, Interrupt, Queue, VirtioDevice}; +use crate::virtio::console::virtio_console_config; +use crate::virtio::console::QUEUE_SIZE; +use crate::virtio::vhost::user::vmm::handler::VhostUserHandler; +use crate::virtio::vhost::user::vmm::Error; +use crate::virtio::vhost::user::vmm::Result; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::VirtioDevice; pub struct Console { kill_evt: Option, diff --git a/devices/src/virtio/vhost/user/vmm/fs.rs b/devices/src/virtio/vhost/user/vmm/fs.rs index c578af26d..47e797d8c 100644 --- a/devices/src/virtio/vhost/user/vmm/fs.rs +++ b/devices/src/virtio/vhost/user/vmm/fs.rs @@ -7,16 +7,27 @@ use std::os::unix::net::UnixStream; use std::path::Path; use std::thread; -use base::{error, Event, RawDescriptor}; -use data_model::{DataInit, Le32}; +use base::error; +use base::Event; +use base::RawDescriptor; +use data_model::DataInit; +use data_model::Le32; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; use vmm_vhost::Error as VhostUserError; -use crate::virtio::fs::{virtio_fs_config, FS_MAX_TAG_LEN, QUEUE_SIZE}; -use crate::virtio::vhost::user::vmm::{handler::VhostUserHandler, Error, Result}; -use crate::virtio::{copy_config, DeviceType}; -use crate::virtio::{Interrupt, Queue, VirtioDevice}; +use crate::virtio::copy_config; +use crate::virtio::fs::virtio_fs_config; +use crate::virtio::fs::FS_MAX_TAG_LEN; +use crate::virtio::fs::QUEUE_SIZE; +use crate::virtio::vhost::user::vmm::handler::VhostUserHandler; +use crate::virtio::vhost::user::vmm::Error; +use crate::virtio::vhost::user::vmm::Result; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::VirtioDevice; pub struct Fs { cfg: virtio_fs_config, diff --git a/devices/src/virtio/vhost/user/vmm/gpu.rs b/devices/src/virtio/vhost/user/vmm/gpu.rs index d0b4aea2c..a6cdccc64 100644 --- a/devices/src/virtio/vhost/user/vmm/gpu.rs +++ b/devices/src/virtio/vhost/user/vmm/gpu.rs @@ -2,24 +2,40 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{cell::RefCell, path::Path, thread}; +use std::cell::RefCell; +use std::path::Path; +use std::thread; -use base::{error, Event, RawDescriptor, Tube}; +use base::error; +use base::Event; +use base::RawDescriptor; +use base::Tube; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; -use crate::{ - pci::{PciBarConfiguration, PciCapability}, - virtio::{ - gpu::QUEUE_SIZES, - vhost::user::vmm::{Result, VhostUserHandler}, - virtio_gpu_config, DeviceType, Interrupt, PciCapabilityType, Queue, VirtioDevice, - VirtioPciShmCap, GPU_BAR_NUM, GPU_BAR_OFFSET, VIRTIO_GPU_F_CONTEXT_INIT, - VIRTIO_GPU_F_CREATE_GUEST_HANDLE, VIRTIO_GPU_F_RESOURCE_BLOB, VIRTIO_GPU_F_RESOURCE_SYNC, - VIRTIO_GPU_F_RESOURCE_UUID, VIRTIO_GPU_F_VIRGL, VIRTIO_GPU_SHM_ID_HOST_VISIBLE, - }, - PciAddress, -}; +use crate::pci::PciBarConfiguration; +use crate::pci::PciCapability; +use crate::virtio::gpu::QUEUE_SIZES; +use crate::virtio::vhost::user::vmm::Result; +use crate::virtio::vhost::user::vmm::VhostUserHandler; +use crate::virtio::virtio_gpu_config; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::PciCapabilityType; +use crate::virtio::Queue; +use crate::virtio::VirtioDevice; +use crate::virtio::VirtioPciShmCap; +use crate::virtio::GPU_BAR_NUM; +use crate::virtio::GPU_BAR_OFFSET; +use crate::virtio::VIRTIO_GPU_F_CONTEXT_INIT; +use crate::virtio::VIRTIO_GPU_F_CREATE_GUEST_HANDLE; +use crate::virtio::VIRTIO_GPU_F_RESOURCE_BLOB; +use crate::virtio::VIRTIO_GPU_F_RESOURCE_SYNC; +use crate::virtio::VIRTIO_GPU_F_RESOURCE_UUID; +use crate::virtio::VIRTIO_GPU_F_VIRGL; +use crate::virtio::VIRTIO_GPU_SHM_ID_HOST_VISIBLE; +use crate::PciAddress; /// Current state of our Gpu. enum GpuState { diff --git a/devices/src/virtio/vhost/user/vmm/handler.rs b/devices/src/virtio/vhost/user/vmm/handler.rs index 5dbd53c66..7cb590643 100644 --- a/devices/src/virtio/vhost/user/vmm/handler.rs +++ b/devices/src/virtio/vhost/user/vmm/handler.rs @@ -8,21 +8,34 @@ mod worker; use std::io::Write; use std::thread; -use base::{error, AsRawDescriptor, Event, Protection, SafeDescriptor, Tube}; +use base::error; +use base::AsRawDescriptor; +use base::Event; +use base::Protection; +use base::SafeDescriptor; +use base::Tube; use vm_control::VmMemorySource; use vm_memory::GuestMemory; -use vmm_vhost::message::{ - VhostUserConfigFlags, VhostUserProtocolFeatures, VhostUserShmemMapMsg, VhostUserShmemUnmapMsg, - VhostUserVirtioFeatures, -}; -use vmm_vhost::{ - HandlerResult, VhostBackend, VhostUserMaster, VhostUserMasterReqHandlerMut, - VhostUserMemoryRegionInfo, VringConfigData, -}; +use vmm_vhost::message::VhostUserConfigFlags; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserShmemMapMsg; +use vmm_vhost::message::VhostUserShmemUnmapMsg; +use vmm_vhost::message::VhostUserVirtioFeatures; +use vmm_vhost::HandlerResult; +use vmm_vhost::VhostBackend; +use vmm_vhost::VhostUserMaster; +use vmm_vhost::VhostUserMasterReqHandlerMut; +use vmm_vhost::VhostUserMemoryRegionInfo; +use vmm_vhost::VringConfigData; -use crate::virtio::vhost::user::vmm::handler::sys::{BackendReqHandler, SocketMaster}; -use crate::virtio::vhost::user::vmm::{Error, Result}; -use crate::virtio::{Interrupt, Queue, SharedMemoryMapper, SharedMemoryRegion}; +use crate::virtio::vhost::user::vmm::handler::sys::BackendReqHandler; +use crate::virtio::vhost::user::vmm::handler::sys::SocketMaster; +use crate::virtio::vhost::user::vmm::Error; +use crate::virtio::vhost::user::vmm::Result; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::SharedMemoryMapper; +use crate::virtio::SharedMemoryRegion; fn set_features(vu: &mut SocketMaster, avail_features: u64, ack_features: u64) -> Result { let features = avail_features & ack_features; diff --git a/devices/src/virtio/vhost/user/vmm/handler/sys.rs b/devices/src/virtio/vhost/user/vmm/handler/sys.rs index 4a478a48a..e74fb8def 100644 --- a/devices/src/virtio/vhost/user/vmm/handler/sys.rs +++ b/devices/src/virtio/vhost/user/vmm/handler/sys.rs @@ -14,4 +14,5 @@ cfg_if::cfg_if! { } } -pub(super) use platform::{run_backend_request_handler, BackendReqHandler}; +pub(super) use platform::run_backend_request_handler; +pub(super) use platform::BackendReqHandler; diff --git a/devices/src/virtio/vhost/user/vmm/handler/sys/unix.rs b/devices/src/virtio/vhost/user/vmm/handler/sys/unix.rs index 3cd50df49..637ea807f 100644 --- a/devices/src/virtio/vhost/user/vmm/handler/sys/unix.rs +++ b/devices/src/virtio/vhost/user/vmm/handler/sys/unix.rs @@ -4,17 +4,30 @@ use std::os::unix::net::UnixStream; use std::path::Path; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; +use std::sync::Mutex; -use anyhow::{bail, Context, Result}; -use base::{info, AsRawDescriptor, Descriptor, SafeDescriptor}; -use cros_async::{AsyncWrapper, Executor}; +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; +use base::info; +use base::AsRawDescriptor; +use base::Descriptor; +use base::SafeDescriptor; +use cros_async::AsyncWrapper; +use cros_async::Executor; use vmm_vhost::connection::socket::Endpoint as SocketEndpoint; -use vmm_vhost::message::{MasterReq, VhostUserProtocolFeatures}; -use vmm_vhost::{Error as VhostError, Master, MasterReqHandler, VhostUserMaster}; +use vmm_vhost::message::MasterReq; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::Error as VhostError; +use vmm_vhost::Master; +use vmm_vhost::MasterReqHandler; +use vmm_vhost::VhostUserMaster; -use crate::virtio::vhost::user::vmm::handler::{BackendReqHandlerImpl, VhostUserHandler}; -use crate::virtio::vhost::user::vmm::{Error, Result as VhostResult}; +use crate::virtio::vhost::user::vmm::handler::BackendReqHandlerImpl; +use crate::virtio::vhost::user::vmm::handler::VhostUserHandler; +use crate::virtio::vhost::user::vmm::Error; +use crate::virtio::vhost::user::vmm::Result as VhostResult; pub(in crate::virtio::vhost::user::vmm::handler) type SocketMaster = Master>; diff --git a/devices/src/virtio/vhost/user/vmm/handler/sys/windows.rs b/devices/src/virtio/vhost/user/vmm/handler/sys/windows.rs index d8c15df4e..73865c016 100644 --- a/devices/src/virtio/vhost/user/vmm/handler/sys/windows.rs +++ b/devices/src/virtio/vhost/user/vmm/handler/sys/windows.rs @@ -7,11 +7,16 @@ use std::sync::Mutex; use base::Tube; use cros_async::Executor; use vmm_vhost::connection::TubeEndpoint; -use vmm_vhost::message::{MasterReq, VhostUserProtocolFeatures}; -use vmm_vhost::{Error as VhostError, Master, VhostUserMasterReqHandler}; +use vmm_vhost::message::MasterReq; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::Error as VhostError; +use vmm_vhost::Master; +use vmm_vhost::VhostUserMasterReqHandler; -use crate::virtio::vhost::user::vmm::handler::{BackendReqHandlerImpl, VhostUserHandler}; -use crate::virtio::vhost::user::vmm::{Error, Result}; +use crate::virtio::vhost::user::vmm::handler::BackendReqHandlerImpl; +use crate::virtio::vhost::user::vmm::handler::VhostUserHandler; +use crate::virtio::vhost::user::vmm::Error; +use crate::virtio::vhost::user::vmm::Result; // TODO(rizhang): upstream CL so SocketMaster is renamed to EndpointMaster to make it more cross // platform. diff --git a/devices/src/virtio/vhost/user/vmm/handler/worker.rs b/devices/src/virtio/vhost/user/vmm/handler/worker.rs index 1feb788c6..15d1cd4f9 100644 --- a/devices/src/virtio/vhost/user/vmm/handler/worker.rs +++ b/devices/src/virtio/vhost/user/vmm/handler/worker.rs @@ -6,14 +6,17 @@ use std::cell::RefCell; use std::rc::Rc; use base::Event; -use cros_async::{select3, Executor, SelectResult}; +use cros_async::select3; +use cros_async::Executor; +use cros_async::SelectResult; use futures::pin_mut; use vm_memory::GuestMemory; -use crate::virtio::vhost::user::vmm::handler::sys::{ - run_backend_request_handler, BackendReqHandler, -}; -use crate::virtio::{async_utils, Interrupt, Queue}; +use crate::virtio::async_utils; +use crate::virtio::vhost::user::vmm::handler::sys::run_backend_request_handler; +use crate::virtio::vhost::user::vmm::handler::sys::BackendReqHandler; +use crate::virtio::Interrupt; +use crate::virtio::Queue; pub struct Worker { pub queues: Vec, diff --git a/devices/src/virtio/vhost/user/vmm/mac80211_hwsim.rs b/devices/src/virtio/vhost/user/vmm/mac80211_hwsim.rs index 970e3b93b..e45bea6c1 100644 --- a/devices/src/virtio/vhost/user/vmm/mac80211_hwsim.rs +++ b/devices/src/virtio/vhost/user/vmm/mac80211_hwsim.rs @@ -5,16 +5,22 @@ use std::cell::RefCell; use std::os::unix::net::UnixStream; use std::path::Path; +use std::result::Result; use std::thread; -use base::{error, Event, RawDescriptor}; +use base::error; +use base::Event; +use base::RawDescriptor; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; -use crate::virtio::vhost::user::vmm::{handler::VhostUserHandler, Error}; -use crate::virtio::{DeviceType, Interrupt, Queue, VirtioDevice}; - -use std::result::Result; +use crate::virtio::vhost::user::vmm::handler::VhostUserHandler; +use crate::virtio::vhost::user::vmm::Error; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::VirtioDevice; const QUEUE_SIZE: u16 = 256; const QUEUE_COUNT: usize = 2; diff --git a/devices/src/virtio/vhost/user/vmm/mod.rs b/devices/src/virtio/vhost/user/vmm/mod.rs index ef886506f..cfb048a8f 100644 --- a/devices/src/virtio/vhost/user/vmm/mod.rs +++ b/devices/src/virtio/vhost/user/vmm/mod.rs @@ -5,14 +5,14 @@ mod block; mod handler; -pub use self::block::*; -pub use self::handler::VhostUserHandler; - use remain::sorted; use thiserror::Error as ThisError; use vm_memory::GuestMemoryError; use vmm_vhost::Error as VhostError; +pub use self::block::*; +pub use self::handler::VhostUserHandler; + cfg_if::cfg_if! { if #[cfg(unix)] { mod console; diff --git a/devices/src/virtio/vhost/user/vmm/net.rs b/devices/src/virtio/vhost/user/vmm/net.rs index 1da95a693..d6e519c67 100644 --- a/devices/src/virtio/vhost/user/vmm/net.rs +++ b/devices/src/virtio/vhost/user/vmm/net.rs @@ -7,13 +7,21 @@ mod sys; use std::cell::RefCell; use std::thread; -use base::{error, Event, RawDescriptor}; +use base::error; +use base::Event; +use base::RawDescriptor; use virtio_sys::virtio_net; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; -use crate::virtio::vhost::user::vmm::{handler::VhostUserHandler, Error}; -use crate::virtio::{DeviceType, Interrupt, Queue, VirtioDevice, VirtioNetConfig}; +use crate::virtio::vhost::user::vmm::handler::VhostUserHandler; +use crate::virtio::vhost::user::vmm::Error; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::VirtioDevice; +use crate::virtio::VirtioNetConfig; type Result = std::result::Result; diff --git a/devices/src/virtio/vhost/user/vmm/net/sys/unix.rs b/devices/src/virtio/vhost/user/vmm/net/sys/unix.rs index 08f36f2b8..5ded6a4e2 100644 --- a/devices/src/virtio/vhost/user/vmm/net/sys/unix.rs +++ b/devices/src/virtio/vhost/user/vmm/net/sys/unix.rs @@ -6,8 +6,11 @@ use std::cell::RefCell; use std::os::unix::net::UnixStream; use std::path::Path; -use crate::virtio::vhost::user::vmm::net::{Net, Result, QUEUE_SIZE}; -use crate::virtio::vhost::user::vmm::{handler::VhostUserHandler, Error}; +use crate::virtio::vhost::user::vmm::handler::VhostUserHandler; +use crate::virtio::vhost::user::vmm::net::Net; +use crate::virtio::vhost::user::vmm::net::Result; +use crate::virtio::vhost::user::vmm::net::QUEUE_SIZE; +use crate::virtio::vhost::user::vmm::Error; impl Net { pub fn new>(base_features: u64, socket_path: P) -> Result { diff --git a/devices/src/virtio/vhost/user/vmm/net/sys/windows.rs b/devices/src/virtio/vhost/user/vmm/net/sys/windows.rs index 9587ed873..c5a239040 100644 --- a/devices/src/virtio/vhost/user/vmm/net/sys/windows.rs +++ b/devices/src/virtio/vhost/user/vmm/net/sys/windows.rs @@ -2,11 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::Tube; use std::cell::RefCell; +use base::Tube; + use crate::virtio::vhost::user::vmm::handler::VhostUserHandler; -use crate::virtio::vhost::user::vmm::net::{Net, Result, QUEUE_SIZE}; +use crate::virtio::vhost::user::vmm::net::Net; +use crate::virtio::vhost::user::vmm::net::Result; +use crate::virtio::vhost::user::vmm::net::QUEUE_SIZE; impl Net { pub fn new(base_features: u64, tube: Tube) -> Result { diff --git a/devices/src/virtio/vhost/user/vmm/snd.rs b/devices/src/virtio/vhost/user/vmm/snd.rs index 230c6ef71..cc78d2dab 100644 --- a/devices/src/virtio/vhost/user/vmm/snd.rs +++ b/devices/src/virtio/vhost/user/vmm/snd.rs @@ -7,13 +7,21 @@ use std::os::unix::net::UnixStream; use std::path::Path; use std::thread; -use base::{error, Event, RawDescriptor}; +use base::error; +use base::Event; +use base::RawDescriptor; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; use crate::virtio::snd::layout::virtio_snd_config; -use crate::virtio::vhost::user::vmm::{handler::VhostUserHandler, Error, Result}; -use crate::virtio::{DeviceType, Interrupt, Queue, VirtioDevice}; +use crate::virtio::vhost::user::vmm::handler::VhostUserHandler; +use crate::virtio::vhost::user::vmm::Error; +use crate::virtio::vhost::user::vmm::Result; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::VirtioDevice; // A vhost-user snd device. pub struct Snd { diff --git a/devices/src/virtio/vhost/user/vmm/vsock.rs b/devices/src/virtio/vhost/user/vmm/vsock.rs index 6d2e4adc7..092a1177b 100644 --- a/devices/src/virtio/vhost/user/vmm/vsock.rs +++ b/devices/src/virtio/vhost/user/vmm/vsock.rs @@ -2,20 +2,27 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{cell::RefCell, os::unix::net::UnixStream, path::Path, thread}; +use std::cell::RefCell; +use std::os::unix::net::UnixStream; +use std::path::Path; +use std::thread; -use base::{error, Event, RawDescriptor}; +use base::error; +use base::Event; +use base::RawDescriptor; use data_model::Le64; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; -use crate::virtio::{ - vhost::{ - user::vmm::{handler::VhostUserHandler, Error, Result}, - vsock, - }, - DeviceType, Interrupt, Queue, VirtioDevice, -}; +use crate::virtio::vhost::user::vmm::handler::VhostUserHandler; +use crate::virtio::vhost::user::vmm::Error; +use crate::virtio::vhost::user::vmm::Result; +use crate::virtio::vhost::vsock; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::VirtioDevice; pub struct Vsock { kill_evt: Option, diff --git a/devices/src/virtio/vhost/user/vmm/wl.rs b/devices/src/virtio/vhost/user/vmm/wl.rs index ace852be8..9eb495f97 100644 --- a/devices/src/virtio/vhost/user/vmm/wl.rs +++ b/devices/src/virtio/vhost/user/vmm/wl.rs @@ -6,18 +6,26 @@ use std::cell::RefCell; use std::path::Path; use std::thread; -use base::{error, Event, RawDescriptor}; +use base::error; +use base::Event; +use base::RawDescriptor; use vm_memory::GuestMemory; -use vmm_vhost::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures}; +use vmm_vhost::message::VhostUserProtocolFeatures; +use vmm_vhost::message::VhostUserVirtioFeatures; -use crate::virtio::vhost::user::vmm::{Result, VhostUserHandler}; -use crate::virtio::wl::{ - QUEUE_SIZE, QUEUE_SIZES, VIRTIO_WL_F_SEND_FENCES, VIRTIO_WL_F_TRANS_FLAGS, - VIRTIO_WL_F_USE_SHMEM, -}; -use crate::virtio::{ - DeviceType, Interrupt, Queue, SharedMemoryMapper, SharedMemoryRegion, VirtioDevice, -}; +use crate::virtio::vhost::user::vmm::Result; +use crate::virtio::vhost::user::vmm::VhostUserHandler; +use crate::virtio::wl::QUEUE_SIZE; +use crate::virtio::wl::QUEUE_SIZES; +use crate::virtio::wl::VIRTIO_WL_F_SEND_FENCES; +use crate::virtio::wl::VIRTIO_WL_F_TRANS_FLAGS; +use crate::virtio::wl::VIRTIO_WL_F_USE_SHMEM; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::SharedMemoryMapper; +use crate::virtio::SharedMemoryRegion; +use crate::virtio::VirtioDevice; pub struct Wl { kill_evt: Option, diff --git a/devices/src/virtio/vhost/vsock.rs b/devices/src/virtio/vhost/vsock.rs index 60419efda..14131f040 100644 --- a/devices/src/virtio/vhost/vsock.rs +++ b/devices/src/virtio/vhost/vsock.rs @@ -8,16 +8,27 @@ use std::path::PathBuf; use std::thread; use anyhow::Context; -use base::{error, open_file, warn, AsRawDescriptor, Event, RawDescriptor}; -use data_model::{DataInit, Le64}; +use base::error; +use base::open_file; +use base::warn; +use base::AsRawDescriptor; +use base::Event; +use base::RawDescriptor; +use data_model::DataInit; +use data_model::Le64; use serde::Deserialize; use vhost::Vhost; use vhost::Vsock as VhostVsockHandle; use vm_memory::GuestMemory; use super::worker::Worker; -use super::{Error, Result}; -use crate::virtio::{copy_config, DeviceType, Interrupt, Queue, VirtioDevice}; +use super::Error; +use super::Result; +use crate::virtio::copy_config; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::VirtioDevice; pub const QUEUE_SIZE: u16 = 256; const NUM_QUEUES: usize = 3; diff --git a/devices/src/virtio/vhost/worker.rs b/devices/src/virtio/vhost/worker.rs index 7cf07989b..528ed6fda 100644 --- a/devices/src/virtio/vhost/worker.rs +++ b/devices/src/virtio/vhost/worker.rs @@ -4,14 +4,23 @@ use std::os::raw::c_ulonglong; -use base::{error, Error as SysError, Event, EventToken, Tube, WaitContext}; +use base::error; +use base::Error as SysError; +use base::Event; +use base::EventToken; +use base::Tube; +use base::WaitContext; +use libc::EIO; use vhost::Vhost; use vm_memory::GuestMemory; -use super::control_socket::{VhostDevRequest, VhostDevResponse}; -use super::{Error, Result}; -use crate::virtio::{Interrupt, Queue, SignalableInterrupt}; -use libc::EIO; +use super::control_socket::VhostDevRequest; +use super::control_socket::VhostDevResponse; +use super::Error; +use super::Result; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::SignalableInterrupt; /// Worker that takes care of running the vhost device. pub struct Worker { diff --git a/devices/src/virtio/video/async_cmd_desc_map.rs b/devices/src/virtio/video/async_cmd_desc_map.rs index 657ce62b0..32a030bc5 100644 --- a/devices/src/virtio/video/async_cmd_desc_map.rs +++ b/devices/src/virtio/video/async_cmd_desc_map.rs @@ -6,7 +6,8 @@ use std::collections::BTreeMap; use crate::virtio::queue::DescriptorChain; use crate::virtio::video::command::QueueType; -use crate::virtio::video::device::{AsyncCmdResponse, AsyncCmdTag}; +use crate::virtio::video::device::AsyncCmdResponse; +use crate::virtio::video::device::AsyncCmdTag; use crate::virtio::video::error::VideoError; use crate::virtio::video::protocol; use crate::virtio::video::response::CmdResponse; diff --git a/devices/src/virtio/video/command.rs b/devices/src/virtio/video/command.rs index 12ec37146..1ddf25336 100644 --- a/devices/src/virtio/video/command.rs +++ b/devices/src/virtio/video/command.rs @@ -4,20 +4,22 @@ //! Data structures for commands of virtio video devices. -use remain::sorted; -use std::convert::{TryFrom, TryInto}; +use std::convert::TryFrom; +use std::convert::TryInto; use std::io; -use thiserror::Error as ThisError; use base::error; use data_model::Le32; use enumn::N; +use remain::sorted; +use thiserror::Error as ThisError; use crate::virtio::video::control::*; use crate::virtio::video::format::*; use crate::virtio::video::params::Params; use crate::virtio::video::protocol::*; -use crate::virtio::video::resource::{ResourceType, UnresolvedResourceEntry}; +use crate::virtio::video::resource::ResourceType; +use crate::virtio::video::resource::UnresolvedResourceEntry; use crate::virtio::Reader; /// An error indicating a failure while reading a request from the guest. diff --git a/devices/src/virtio/video/control.rs b/devices/src/virtio/video/control.rs index 4fcaf8d46..808078f36 100644 --- a/devices/src/virtio/video/control.rs +++ b/devices/src/virtio/video/control.rs @@ -9,7 +9,10 @@ use std::io; use data_model::Le32; -use crate::virtio::video::format::{BitrateMode, Format, Level, Profile}; +use crate::virtio::video::format::BitrateMode; +use crate::virtio::video::format::Format; +use crate::virtio::video::format::Level; +use crate::virtio::video::format::Profile; use crate::virtio::video::protocol::*; use crate::virtio::video::response::Response; use crate::virtio::Writer; diff --git a/devices/src/virtio/video/decoder/backend/ffmpeg.rs b/devices/src/virtio/video/decoder/backend/ffmpeg.rs index a1d102a83..ca7284110 100644 --- a/devices/src/virtio/video/decoder/backend/ffmpeg.rs +++ b/devices/src/virtio/video/decoder/backend/ffmpeg.rs @@ -15,22 +15,33 @@ //! abstractions over the ffmpeg libraries are provided in sub-modules, one per ffmpeg library we //! want to support. -use std::collections::{BTreeMap, VecDeque}; +use std::collections::BTreeMap; +use std::collections::VecDeque; -use anyhow::{anyhow, Context}; -use base::{error, info, warn, MappedRegion, MemoryMappingArena, MmapError}; +use ::ffmpeg::avcodec::*; +use ::ffmpeg::swscale::*; +use ::ffmpeg::*; +use anyhow::anyhow; +use anyhow::Context; +use base::error; +use base::info; +use base::warn; +use base::MappedRegion; +use base::MemoryMappingArena; +use base::MmapError; use thiserror::Error as ThisError; -use crate::virtio::video::{ - decoder::backend::{ - utils::{EventQueue, OutputQueue}, - *, - }, - format::{FormatDesc, FormatRange, FrameFormat, Level, Profile}, - resource::{BufferHandle, GuestResource, GuestResourceHandle}, -}; - -use ::ffmpeg::{avcodec::*, swscale::*, *}; +use crate::virtio::video::decoder::backend::utils::EventQueue; +use crate::virtio::video::decoder::backend::utils::OutputQueue; +use crate::virtio::video::decoder::backend::*; +use crate::virtio::video::format::FormatDesc; +use crate::virtio::video::format::FormatRange; +use crate::virtio::video::format::FrameFormat; +use crate::virtio::video::format::Level; +use crate::virtio::video::format::Profile; +use crate::virtio::video::resource::BufferHandle; +use crate::virtio::video::resource::GuestResource; +use crate::virtio::video::resource::GuestResourceHandle; /// Structure maintaining a mapping for an encoded input buffer that can be used as a libavcodec /// buffer source. @@ -754,15 +765,17 @@ impl DecoderBackend for FfmpegDecoder { #[cfg(test)] mod tests { - use crate::virtio::video::{ - format::FramePlane, - resource::{GuestMemArea, GuestMemHandle, VirtioObjectHandle}, - }; + use base::FromRawDescriptor; + use base::MappedRegion; + use base::MemoryMappingBuilder; + use base::SafeDescriptor; + use base::SharedMemory; use super::*; - use base::{ - FromRawDescriptor, MappedRegion, MemoryMappingBuilder, SafeDescriptor, SharedMemory, - }; + use crate::virtio::video::format::FramePlane; + use crate::virtio::video::resource::GuestMemArea; + use crate::virtio::video::resource::GuestMemHandle; + use crate::virtio::video::resource::VirtioObjectHandle; // Test video stream and its properties. const H264_STREAM: &[u8] = include_bytes!("test-25fps.h264"); diff --git a/devices/src/virtio/video/decoder/backend/mod.rs b/devices/src/virtio/video/decoder/backend/mod.rs index 0bad4ec16..c31848db5 100644 --- a/devices/src/virtio/video/decoder/backend/mod.rs +++ b/devices/src/virtio/video/decoder/backend/mod.rs @@ -5,14 +5,16 @@ //! This module implements the interface that actual decoder devices need to //! implement in order to provide video decoding capability to the guest. -use crate::virtio::video::{ - decoder::Capability, - error::{VideoError, VideoResult}, - format::{Format, Rect}, - resource::{GuestResource, GuestResourceHandle}, -}; use base::AsRawDescriptor; +use crate::virtio::video::decoder::Capability; +use crate::virtio::video::error::VideoError; +use crate::virtio::video::error::VideoResult; +use crate::virtio::video::format::Format; +use crate::virtio::video::format::Rect; +use crate::virtio::video::resource::GuestResource; +use crate::virtio::video::resource::GuestResourceHandle; + #[cfg(feature = "ffmpeg")] pub mod ffmpeg; pub mod utils; diff --git a/devices/src/virtio/video/decoder/backend/utils.rs b/devices/src/virtio/video/decoder/backend/utils.rs index 44fea4a36..e7b375b38 100644 --- a/devices/src/virtio/video/decoder/backend/utils.rs +++ b/devices/src/virtio/video/decoder/backend/utils.rs @@ -5,18 +5,18 @@ // TODO(acourbot): Remove once we start using this file #![allow(dead_code)] -use std::{ - collections::{btree_map::Entry, BTreeMap, VecDeque}, - time::Duration, -}; +use std::collections::btree_map::Entry; +use std::collections::BTreeMap; +use std::collections::VecDeque; +use std::time::Duration; -use base::{AsRawDescriptor, Event}; +use base::AsRawDescriptor; +use base::Event; use thiserror::Error as ThisError; -use crate::virtio::video::resource::GuestResource; - #[cfg(feature = "ffmpeg")] use crate::virtio::video::resource::BufferHandle; +use crate::virtio::video::resource::GuestResource; /// Manages a pollable queue of events to be sent to the decoder or encoder. pub struct EventQueue { @@ -213,9 +213,12 @@ impl OutputQueue { mod tests { use std::time::Duration; + use base::EventToken; + use base::WaitContext; + use super::*; - use crate::virtio::video::{decoder::DecoderEvent, format::Rect}; - use base::{EventToken, WaitContext}; + use crate::virtio::video::decoder::DecoderEvent; + use crate::virtio::video::format::Rect; /// Test basic queue/dequeue functionality of `EventQueue`. #[test] diff --git a/devices/src/virtio/video/decoder/backend/vaapi.rs b/devices/src/virtio/video/decoder/backend/vaapi.rs index 0323aa34d..215589786 100644 --- a/devices/src/virtio/video/decoder/backend/vaapi.rs +++ b/devices/src/virtio/video/decoder/backend/vaapi.rs @@ -8,21 +8,42 @@ use std::any::Any; use std::borrow::Borrow; use std::cell::RefCell; use std::collections::btree_map::Entry; -use std::collections::{BTreeMap, VecDeque}; +use std::collections::BTreeMap; +use std::collections::VecDeque; use std::marker::PhantomData; use std::rc::Rc; -use anyhow::{anyhow, Result}; -use base::{MappedRegion, MemoryMappingArena}; -use libva::{Config, Context, Display, Image, Picture, PictureSync, Surface, UsageHint}; +use anyhow::anyhow; +use anyhow::Result; +use base::MappedRegion; +use base::MemoryMappingArena; +use libva::Config; +use libva::Context; +use libva::Display; +use libva::Image; +use libva::Picture; +use libva::PictureSync; +use libva::Surface; +use libva::UsageHint; -use crate::virtio::video::decoder::utils::{EventQueue, OutputQueue}; -use crate::virtio::video::decoder::{Capability, DecoderBackend, DecoderEvent, DecoderSession}; -use crate::virtio::video::error::{VideoError, VideoResult}; -use crate::virtio::video::format::{ - Format, FormatDesc, FormatRange, FrameFormat, Level, Profile, Rect, -}; -use crate::virtio::video::resource::{BufferHandle, GuestResource, GuestResourceHandle}; +use crate::virtio::video::decoder::utils::EventQueue; +use crate::virtio::video::decoder::utils::OutputQueue; +use crate::virtio::video::decoder::Capability; +use crate::virtio::video::decoder::DecoderBackend; +use crate::virtio::video::decoder::DecoderEvent; +use crate::virtio::video::decoder::DecoderSession; +use crate::virtio::video::error::VideoError; +use crate::virtio::video::error::VideoResult; +use crate::virtio::video::format::Format; +use crate::virtio::video::format::FormatDesc; +use crate::virtio::video::format::FormatRange; +use crate::virtio::video::format::FrameFormat; +use crate::virtio::video::format::Level; +use crate::virtio::video::format::Profile; +use crate::virtio::video::format::Rect; +use crate::virtio::video::resource::BufferHandle; +use crate::virtio::video::resource::GuestResource; +use crate::virtio::video::resource::GuestResourceHandle; mod vp8; @@ -1070,10 +1091,14 @@ downcast_rs::impl_downcast!(VaapiCodec); // Used in unit tests. #[cfg(test)] mod tests { - use base::{FromRawDescriptor, MemoryMappingBuilder, SafeDescriptor, SharedMemory}; + use base::FromRawDescriptor; + use base::MemoryMappingBuilder; + use base::SafeDescriptor; + use base::SharedMemory; use super::*; - use crate::virtio::video::resource::{GuestMemArea, GuestMemHandle}; + use crate::virtio::video::resource::GuestMemArea; + use crate::virtio::video::resource::GuestMemHandle; pub(crate) fn build_resource(slice: &[u8]) -> GuestResourceHandle { let input_shm = SharedMemory::new("", u64::try_from(slice.len()).unwrap()).unwrap(); diff --git a/devices/src/virtio/video/decoder/backend/vaapi/vp8.rs b/devices/src/virtio/video/decoder/backend/vaapi/vp8.rs index 6b7ec662c..8a9f7408e 100644 --- a/devices/src/virtio/video/decoder/backend/vaapi/vp8.rs +++ b/devices/src/virtio/video/decoder/backend/vaapi/vp8.rs @@ -2,21 +2,32 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{cell::RefCell, convert::TryFrom, rc::Rc}; +use std::cell::RefCell; +use std::convert::TryFrom; +use std::rc::Rc; -use anyhow::{anyhow, Context, Result}; -use libva::{BufferType, IQMatrix, IQMatrixBufferVP8, Picture, ProbabilityDataBufferVP8}; +use anyhow::anyhow; +use anyhow::Context; +use anyhow::Result; +use libva::BufferType; +use libva::IQMatrix; +use libva::IQMatrixBufferVP8; +use libva::Picture; +use libva::ProbabilityDataBufferVP8; use vp8::parser as vp8; -use crate::virtio::video::{ - decoder::backend::vaapi::{ - BufferMapping, DecodedFrameHandle, DrcParams, Resolution, StreamMetadataState, - SurfacePoolHandle, VaapiCodec, VaapiDecoderSession, - }, - error::VideoError, - format::{Format, Rect}, - resource::GuestResourceHandle, -}; +use crate::virtio::video::decoder::backend::vaapi::BufferMapping; +use crate::virtio::video::decoder::backend::vaapi::DecodedFrameHandle; +use crate::virtio::video::decoder::backend::vaapi::DrcParams; +use crate::virtio::video::decoder::backend::vaapi::Resolution; +use crate::virtio::video::decoder::backend::vaapi::StreamMetadataState; +use crate::virtio::video::decoder::backend::vaapi::SurfacePoolHandle; +use crate::virtio::video::decoder::backend::vaapi::VaapiCodec; +use crate::virtio::video::decoder::backend::vaapi::VaapiDecoderSession; +use crate::virtio::video::error::VideoError; +use crate::virtio::video::format::Format; +use crate::virtio::video::format::Rect; +use crate::virtio::video::resource::GuestResourceHandle; /// The number of surfaces to allocate for this codec. Same as GStreamer's vavp8dec. const NUM_SURFACES: usize = 7; @@ -642,24 +653,34 @@ impl VaapiCodec for Vp8Codec { #[cfg(test)] mod tests { - use std::io::{Cursor, Read, Seek}; + use std::io::Cursor; + use std::io::Read; + use std::io::Seek; - use base::{FromRawDescriptor, SafeDescriptor, SharedMemory}; + use base::FromRawDescriptor; + use base::SafeDescriptor; + use base::SharedMemory; use bytes::Buf; - use libva::{BufferType, IQMatrix, PictureParameter, SliceParameter}; + use libva::BufferType; + use libva::IQMatrix; + use libva::PictureParameter; + use libva::SliceParameter; - use crate::virtio::video::{ - decoder::backend::{ - vaapi::{ - tests::build_resource, - vp8::{Vp8Codec, NUM_SURFACES}, - VaapiDecoder, VaapiDecoderSession, - }, - DecoderBackend, DecoderEvent, DecoderSession, - }, - format::{Format, FramePlane, Rect}, - resource::{GuestMemArea, GuestMemHandle, GuestResource, GuestResourceHandle}, - }; + use crate::virtio::video::decoder::backend::vaapi::tests::build_resource; + use crate::virtio::video::decoder::backend::vaapi::vp8::Vp8Codec; + use crate::virtio::video::decoder::backend::vaapi::vp8::NUM_SURFACES; + use crate::virtio::video::decoder::backend::vaapi::VaapiDecoder; + use crate::virtio::video::decoder::backend::vaapi::VaapiDecoderSession; + use crate::virtio::video::decoder::backend::DecoderBackend; + use crate::virtio::video::decoder::backend::DecoderEvent; + use crate::virtio::video::decoder::backend::DecoderSession; + use crate::virtio::video::format::Format; + use crate::virtio::video::format::FramePlane; + use crate::virtio::video::format::Rect; + use crate::virtio::video::resource::GuestMemArea; + use crate::virtio::video::resource::GuestMemHandle; + use crate::virtio::video::resource::GuestResource; + use crate::virtio::video::resource::GuestResourceHandle; fn get_codec(session: &mut VaapiDecoderSession) -> &mut Vp8Codec { session.codec.as_mut().downcast_mut::().unwrap() diff --git a/devices/src/virtio/video/decoder/backend/vda.rs b/devices/src/virtio/video/decoder/backend/vda.rs index 3bcfae061..dd9a40525 100644 --- a/devices/src/virtio/video/decoder/backend/vda.rs +++ b/devices/src/virtio/video/decoder/backend/vda.rs @@ -2,19 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use anyhow::anyhow; -use base::{error, warn, AsRawDescriptor, IntoRawDescriptor}; use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::convert::TryFrom; +use anyhow::anyhow; +use base::error; +use base::warn; +use base::AsRawDescriptor; +use base::IntoRawDescriptor; use libvda::decode::Event as LibvdaEvent; -use crate::virtio::video::{ - decoder::{backend::*, Capability}, - error::{VideoError, VideoResult}, - format::*, -}; +use crate::virtio::video::decoder::backend::*; +use crate::virtio::video::decoder::Capability; +use crate::virtio::video::error::VideoError; +use crate::virtio::video::error::VideoResult; +use crate::virtio::video::format::*; impl TryFrom for libvda::Profile { type Error = VideoError; diff --git a/devices/src/virtio/video/decoder/mod.rs b/devices/src/virtio/video/decoder/mod.rs index f4df77282..9aa67f346 100644 --- a/devices/src/virtio/video/decoder/mod.rs +++ b/devices/src/virtio/video/decoder/mod.rs @@ -5,15 +5,22 @@ //! Implementation of a virtio video decoder backed by a device. use std::collections::btree_map::Entry; -use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::collections::BTreeMap; +use std::collections::BTreeSet; +use std::collections::VecDeque; use backend::*; -use base::{error, Tube, WaitContext}; +use base::error; +use base::Tube; +use base::WaitContext; use vm_memory::GuestMemory; use crate::virtio::video::async_cmd_desc_map::AsyncCmdDescMap; -use crate::virtio::video::command::{QueueType, VideoCmd}; -use crate::virtio::video::control::{CtrlType, CtrlVal, QueryCtrlType}; +use crate::virtio::video::command::QueueType; +use crate::virtio::video::command::VideoCmd; +use crate::virtio::video::control::CtrlType; +use crate::virtio::video::control::CtrlVal; +use crate::virtio::video::control::QueryCtrlType; use crate::virtio::video::device::*; use crate::virtio::video::error::*; use crate::virtio::video::event::*; diff --git a/devices/src/virtio/video/device.rs b/devices/src/virtio/video/device.rs index 924532fae..059f1cf6e 100644 --- a/devices/src/virtio/video/device.rs +++ b/devices/src/virtio/video/device.rs @@ -4,10 +4,12 @@ //! Definition of the trait `Device` that each backend video device must implement. -use base::{EventToken, WaitContext}; +use base::EventToken; +use base::WaitContext; use crate::virtio::video::async_cmd_desc_map::AsyncCmdDescMap; -use crate::virtio::video::command::{QueueType, VideoCmd}; +use crate::virtio::video::command::QueueType; +use crate::virtio::video::command::VideoCmd; use crate::virtio::video::error::*; use crate::virtio::video::event::VideoEvt; use crate::virtio::video::response; diff --git a/devices/src/virtio/video/encoder/backend/mod.rs b/devices/src/virtio/video/encoder/backend/mod.rs index d4147fb0a..0a3bf48df 100644 --- a/devices/src/virtio/video/encoder/backend/mod.rs +++ b/devices/src/virtio/video/encoder/backend/mod.rs @@ -7,15 +7,15 @@ pub mod vda; use base::AsRawDescriptor; +use super::encoder::EncoderCapabilities; +use super::encoder::EncoderEvent; +use super::encoder::InputBufferId; +use super::encoder::OutputBufferId; +use super::encoder::SessionConfig; use crate::virtio::video::error::VideoResult; -use crate::virtio::video::{ - format::Bitrate, - resource::{GuestResource, GuestResourceHandle}, -}; - -use super::encoder::{ - EncoderCapabilities, EncoderEvent, InputBufferId, OutputBufferId, SessionConfig, -}; +use crate::virtio::video::format::Bitrate; +use crate::virtio::video::resource::GuestResource; +use crate::virtio::video::resource::GuestResourceHandle; pub trait EncoderSession { /// Encodes the frame provided by `resource`. diff --git a/devices/src/virtio/video/encoder/backend/vda.rs b/devices/src/virtio/video/encoder/backend/vda.rs index 580cef023..c174e158b 100644 --- a/devices/src/virtio/video/encoder/backend/vda.rs +++ b/devices/src/virtio/video/encoder/backend/vda.rs @@ -5,19 +5,29 @@ use std::collections::btree_map::Entry; use std::collections::BTreeMap; -use anyhow::{anyhow, Context}; -use base::{error, warn, AsRawDescriptor, IntoRawDescriptor}; -use libvda::encode::{EncodeCapabilities, VeaImplType, VeaInstance}; +use anyhow::anyhow; +use anyhow::Context; +use base::error; +use base::warn; +use base::AsRawDescriptor; +use base::IntoRawDescriptor; +use libvda::encode::EncodeCapabilities; +use libvda::encode::VeaImplType; +use libvda::encode::VeaInstance; use super::*; -use crate::virtio::video::format::{ - Bitrate, Format, FormatDesc, FormatRange, FrameFormat, Level, Profile, -}; -use crate::virtio::video::{ - encoder::encoder::*, - error::{VideoError, VideoResult}, - resource::{GuestResource, GuestResourceHandle}, -}; +use crate::virtio::video::encoder::encoder::*; +use crate::virtio::video::error::VideoError; +use crate::virtio::video::error::VideoResult; +use crate::virtio::video::format::Bitrate; +use crate::virtio::video::format::Format; +use crate::virtio::video::format::FormatDesc; +use crate::virtio::video::format::FormatRange; +use crate::virtio::video::format::FrameFormat; +use crate::virtio::video::format::Level; +use crate::virtio::video::format::Profile; +use crate::virtio::video::resource::GuestResource; +use crate::virtio::video::resource::GuestResourceHandle; impl From for libvda::encode::Bitrate { fn from(bitrate: Bitrate) -> Self { diff --git a/devices/src/virtio/video/encoder/encoder.rs b/devices/src/virtio/video/encoder/encoder.rs index da464604a..9af37d2fd 100644 --- a/devices/src/virtio/video/encoder/encoder.rs +++ b/devices/src/virtio/video/encoder/encoder.rs @@ -6,11 +6,16 @@ use std::collections::BTreeMap; use base::error; +use crate::virtio::video::error::VideoError; +use crate::virtio::video::error::VideoResult; +use crate::virtio::video::format::find_closest_resolution; +use crate::virtio::video::format::Bitrate; +use crate::virtio::video::format::Format; +use crate::virtio::video::format::FormatDesc; +use crate::virtio::video::format::Level; +use crate::virtio::video::format::PlaneFormat; +use crate::virtio::video::format::Profile; use crate::virtio::video::params::Params; -use crate::virtio::video::{ - error::{VideoError, VideoResult}, - format::{find_closest_resolution, Bitrate, Format, FormatDesc, Level, PlaneFormat, Profile}, -}; pub type InputBufferId = u32; pub type OutputBufferId = u32; diff --git a/devices/src/virtio/video/encoder/mod.rs b/devices/src/virtio/video/encoder/mod.rs index b37d7a419..1160d689d 100644 --- a/devices/src/virtio/video/encoder/mod.rs +++ b/devices/src/virtio/video/encoder/mod.rs @@ -8,29 +8,45 @@ pub mod backend; mod encoder; -use base::{error, info, warn, Tube, WaitContext}; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; +use std::collections::BTreeSet; + +use backend::*; +use base::error; +use base::info; +use base::warn; +use base::Tube; +use base::WaitContext; use vm_memory::GuestMemory; use crate::virtio::video::async_cmd_desc_map::AsyncCmdDescMap; -use crate::virtio::video::command::{QueueType, VideoCmd}; +use crate::virtio::video::command::QueueType; +use crate::virtio::video::command::VideoCmd; use crate::virtio::video::control::*; +use crate::virtio::video::device::AsyncCmdResponse; +use crate::virtio::video::device::AsyncCmdTag; +use crate::virtio::video::device::Device; +use crate::virtio::video::device::Token; use crate::virtio::video::device::VideoCmdResponseType; -use crate::virtio::video::device::{ - AsyncCmdResponse, AsyncCmdTag, Device, Token, VideoEvtResponseType, -}; -use crate::virtio::video::encoder::encoder::{ - EncoderEvent, InputBufferId, OutputBufferId, SessionConfig, -}; +use crate::virtio::video::device::VideoEvtResponseType; +use crate::virtio::video::encoder::encoder::EncoderEvent; +use crate::virtio::video::encoder::encoder::InputBufferId; +use crate::virtio::video::encoder::encoder::OutputBufferId; +use crate::virtio::video::encoder::encoder::SessionConfig; use crate::virtio::video::error::*; -use crate::virtio::video::event::{EvtType, VideoEvt}; -use crate::virtio::video::format::{Bitrate, BitrateMode, Format, Level, PlaneFormat, Profile}; +use crate::virtio::video::event::EvtType; +use crate::virtio::video::event::VideoEvt; +use crate::virtio::video::format::Bitrate; +use crate::virtio::video::format::BitrateMode; +use crate::virtio::video::format::Format; +use crate::virtio::video::format::Level; +use crate::virtio::video::format::PlaneFormat; +use crate::virtio::video::format::Profile; use crate::virtio::video::params::Params; use crate::virtio::video::protocol; use crate::virtio::video::resource::*; use crate::virtio::video::response::CmdResponse; use crate::virtio::video::EosBufferManager; -use backend::*; #[derive(Debug)] struct QueuedInputResourceParams { diff --git a/devices/src/virtio/video/format.rs b/devices/src/virtio/video/format.rs index eda82d8ec..73a3cbea4 100644 --- a/devices/src/virtio/video/format.rs +++ b/devices/src/virtio/video/format.rs @@ -4,8 +4,11 @@ //! Data structures that represent video format information in virtio video devices. -use std::convert::{From, Into, TryFrom}; -use std::fmt::{self, Display}; +use std::convert::From; +use std::convert::Into; +use std::convert::TryFrom; +use std::fmt::Display; +use std::fmt::{self}; use std::io; use base::error; diff --git a/devices/src/virtio/video/mod.rs b/devices/src/virtio/video/mod.rs index 1d46eca92..41f061952 100644 --- a/devices/src/virtio/video/mod.rs +++ b/devices/src/virtio/video/mod.rs @@ -9,17 +9,28 @@ use std::thread; +use base::error; #[cfg(feature = "video-encoder")] use base::info; -use base::{error, AsRawDescriptor, Error as SysError, Event, RawDescriptor, Tube}; -use data_model::{DataInit, Le32}; +use base::AsRawDescriptor; +use base::Error as SysError; +use base::Event; +use base::RawDescriptor; +use base::Tube; +use data_model::DataInit; +use data_model::Le32; use remain::sorted; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; use thiserror::Error; use vm_memory::GuestMemory; +use crate::virtio::copy_config; use crate::virtio::virtio_device::VirtioDevice; -use crate::virtio::{self, copy_config, DescriptorError, DeviceType, Interrupt}; +use crate::virtio::DescriptorError; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::{self}; #[macro_use] mod macros; diff --git a/devices/src/virtio/video/params.rs b/devices/src/virtio/video/params.rs index 77ce5da0a..e79baef6f 100644 --- a/devices/src/virtio/video/params.rs +++ b/devices/src/virtio/video/params.rs @@ -4,12 +4,15 @@ //! Parameters for streams in virtio video devices. -use std::convert::{From, Into, TryFrom}; +use std::convert::From; +use std::convert::Into; +use std::convert::TryFrom; use base::error; use data_model::Le32; -use crate::virtio::video::command::{QueueType, ReadCmdError}; +use crate::virtio::video::command::QueueType; +use crate::virtio::video::command::ReadCmdError; use crate::virtio::video::format::*; use crate::virtio::video::protocol::*; use crate::virtio::video::resource::ResourceType; diff --git a/devices/src/virtio/video/protocol.rs b/devices/src/virtio/video/protocol.rs index 472b7a684..92f79f4fa 100644 --- a/devices/src/virtio/video/protocol.rs +++ b/devices/src/virtio/video/protocol.rs @@ -24,7 +24,9 @@ #![allow(dead_code, non_snake_case, non_camel_case_types)] -use data_model::{DataInit, Le32, Le64}; +use data_model::DataInit; +use data_model::Le32; +use data_model::Le64; pub const VIRTIO_VIDEO_F_RESOURCE_GUEST_PAGES: u32 = 0; pub const VIRTIO_VIDEO_F_RESOURCE_NON_CONTIG: u32 = 1; diff --git a/devices/src/virtio/video/resource.rs b/devices/src/virtio/video/resource.rs index d492a4ce4..d10eaa7e3 100644 --- a/devices/src/virtio/video/resource.rs +++ b/devices/src/virtio/video/resource.rs @@ -7,17 +7,27 @@ use std::convert::TryInto; use std::fmt; -use base::{ - self, FromRawDescriptor, IntoRawDescriptor, MemoryMappingArena, MemoryMappingBuilder, - MemoryMappingBuilderUnix, MmapError, SafeDescriptor, -}; -use vm_memory::{GuestAddress, GuestMemory, GuestMemoryError}; - +use base::FromRawDescriptor; +use base::IntoRawDescriptor; +use base::MemoryMappingArena; +use base::MemoryMappingBuilder; +use base::MemoryMappingBuilderUnix; +use base::MmapError; +use base::SafeDescriptor; +use base::{self}; use thiserror::Error as ThisError; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +use vm_memory::GuestMemoryError; -use crate::virtio::resource_bridge::{self, ResourceBridgeError, ResourceInfo, ResourceRequest}; -use crate::virtio::video::format::{FramePlane, PlaneFormat}; -use crate::virtio::video::protocol::{virtio_video_mem_entry, virtio_video_object_entry}; +use crate::virtio::resource_bridge::ResourceBridgeError; +use crate::virtio::resource_bridge::ResourceInfo; +use crate::virtio::resource_bridge::ResourceRequest; +use crate::virtio::resource_bridge::{self}; +use crate::virtio::video::format::FramePlane; +use crate::virtio::video::format::PlaneFormat; +use crate::virtio::video::protocol::virtio_video_mem_entry; +use crate::virtio::video::protocol::virtio_video_object_entry; /// Defines how resources for a given queue are represented. #[derive(Clone, Copy, Debug)] @@ -319,8 +329,11 @@ impl GuestResource { #[cfg(test)] mod tests { + use base::MappedRegion; + use base::SafeDescriptor; + use base::SharedMemory; + use super::*; - use base::{MappedRegion, SafeDescriptor, SharedMemory}; /// Creates a sparse guest memory handle using as many pages as there are entries in /// `page_order`. The page with index `0` will be the first page, `1` will be the second page, diff --git a/devices/src/virtio/video/response.rs b/devices/src/virtio/video/response.rs index 05cd05e3d..df0635092 100644 --- a/devices/src/virtio/video/response.rs +++ b/devices/src/virtio/video/response.rs @@ -6,7 +6,8 @@ use std::io; -use data_model::{Le32, Le64}; +use data_model::Le32; +use data_model::Le64; use crate::virtio::video::command::QueueType; use crate::virtio::video::control::*; diff --git a/devices/src/virtio/video/vda.rs b/devices/src/virtio/video/vda.rs index f05cd2b55..15b58b883 100644 --- a/devices/src/virtio/video/vda.rs +++ b/devices/src/virtio/video/vda.rs @@ -3,7 +3,9 @@ // found in the LICENSE file. //! Utility features shared by both the decoder and encoder VDA backends. -use crate::virtio::video::{error::VideoError, format::Profile, protocol}; +use crate::virtio::video::error::VideoError; +use crate::virtio::video::format::Profile; +use crate::virtio::video::protocol; /// Transparent convertion from libvda error to VideoError backend failure. impl From for VideoError { diff --git a/devices/src/virtio/video/worker.rs b/devices/src/virtio/video/worker.rs index 77e088e9e..eb58beb64 100644 --- a/devices/src/virtio/video/worker.rs +++ b/devices/src/virtio/video/worker.rs @@ -6,19 +6,34 @@ use std::collections::VecDeque; -use base::{error, info, Event, WaitContext}; +use base::error; +use base::info; +use base::Event; +use base::WaitContext; use vm_memory::GuestMemory; -use crate::virtio::queue::{DescriptorChain, Queue}; +use crate::virtio::queue::DescriptorChain; +use crate::virtio::queue::Queue; use crate::virtio::video::async_cmd_desc_map::AsyncCmdDescMap; -use crate::virtio::video::command::{QueueType, VideoCmd}; -use crate::virtio::video::device::{ - AsyncCmdResponse, AsyncCmdTag, Device, Token, VideoCmdResponseType, VideoEvtResponseType, -}; -use crate::virtio::video::event::{self, EvtType, VideoEvt}; -use crate::virtio::video::response::{self, Response}; -use crate::virtio::video::{Error, Result}; -use crate::virtio::{Interrupt, Reader, SignalableInterrupt, Writer}; +use crate::virtio::video::command::QueueType; +use crate::virtio::video::command::VideoCmd; +use crate::virtio::video::device::AsyncCmdResponse; +use crate::virtio::video::device::AsyncCmdTag; +use crate::virtio::video::device::Device; +use crate::virtio::video::device::Token; +use crate::virtio::video::device::VideoCmdResponseType; +use crate::virtio::video::device::VideoEvtResponseType; +use crate::virtio::video::event::EvtType; +use crate::virtio::video::event::VideoEvt; +use crate::virtio::video::event::{self}; +use crate::virtio::video::response::Response; +use crate::virtio::video::response::{self}; +use crate::virtio::video::Error; +use crate::virtio::video::Result; +use crate::virtio::Interrupt; +use crate::virtio::Reader; +use crate::virtio::SignalableInterrupt; +use crate::virtio::Writer; pub struct Worker { interrupt: Interrupt, diff --git a/devices/src/virtio/virtio_device.rs b/devices/src/virtio/virtio_device.rs index 61a7c087a..bec166239 100644 --- a/devices/src/virtio/virtio_device.rs +++ b/devices/src/virtio/virtio_device.rs @@ -5,12 +5,19 @@ #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use acpi_tables::sdt::SDT; use anyhow::Result; -use base::{Event, Protection, RawDescriptor}; +use base::Event; +use base::Protection; +use base::RawDescriptor; use vm_control::VmMemorySource; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; use super::*; -use crate::pci::{MsixStatus, PciAddress, PciBarConfiguration, PciBarIndex, PciCapability}; +use crate::pci::MsixStatus; +use crate::pci::PciAddress; +use crate::pci::PciBarConfiguration; +use crate::pci::PciBarIndex; +use crate::pci::PciCapability; #[derive(Clone)] pub struct SharedMemoryRegion { diff --git a/devices/src/virtio/virtio_pci_common_config.rs b/devices/src/virtio/virtio_pci_common_config.rs index 7bb050c20..ab1b4d7be 100644 --- a/devices/src/virtio/virtio_pci_common_config.rs +++ b/devices/src/virtio/virtio_pci_common_config.rs @@ -244,11 +244,12 @@ impl VirtioPciCommonConfig { #[cfg(test)] mod tests { - use super::*; - - use base::{Event, RawDescriptor}; + use base::Event; + use base::RawDescriptor; use vm_memory::GuestMemory; + use super::*; + struct DummyDevice(DeviceType); const QUEUE_SIZE: u16 = 256; const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE]; diff --git a/devices/src/virtio/virtio_pci_device.rs b/devices/src/virtio/virtio_pci_device.rs index 7f629a2cd..b89045844 100644 --- a/devices/src/virtio/virtio_pci_device.rs +++ b/devices/src/virtio/virtio_pci_device.rs @@ -3,38 +3,67 @@ // found in the LICENSE file. use std::collections::BTreeMap; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; use std::sync::Arc; -use sync::Mutex; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use acpi_tables::sdt::SDT; -use anyhow::{anyhow, bail, Context}; -use base::{ - error, AsRawDescriptor, AsRawDescriptors, Event, Protection, RawDescriptor, Result, Tube, -}; -use data_model::{DataInit, Le32}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; +use base::error; +use base::AsRawDescriptor; +use base::AsRawDescriptors; +use base::Event; +use base::Protection; +use base::RawDescriptor; +use base::Result; +use base::Tube; +use data_model::DataInit; +use data_model::Le32; use hypervisor::Datamatch; use libc::ERANGE; -use resources::{Alloc, MmioType, SystemAllocator}; -use virtio_sys::virtio_config::{ - VIRTIO_CONFIG_S_ACKNOWLEDGE, VIRTIO_CONFIG_S_DRIVER, VIRTIO_CONFIG_S_DRIVER_OK, - VIRTIO_CONFIG_S_FAILED, VIRTIO_CONFIG_S_FEATURES_OK, -}; -use vm_control::{MemSlot, VmMemoryDestination, VmMemoryRequest, VmMemoryResponse, VmMemorySource}; -use vm_memory::{GuestAddress, GuestMemory}; - -use super::*; -use crate::pci::{ - BarRange, MsixCap, MsixConfig, PciAddress, PciBarConfiguration, PciBarIndex, - PciBarPrefetchable, PciBarRegionType, PciCapability, PciCapabilityID, PciClassCode, - PciConfiguration, PciDevice, PciDeviceError, PciDisplaySubclass, PciHeaderType, PciId, - PciInterruptPin, PciSubclass, -}; -use crate::virtio::ipc_memory_mapper::IpcMemoryMapper; -use crate::IrqLevelEvent; +use resources::Alloc; +use resources::MmioType; +use resources::SystemAllocator; +use sync::Mutex; +use virtio_sys::virtio_config::VIRTIO_CONFIG_S_ACKNOWLEDGE; +use virtio_sys::virtio_config::VIRTIO_CONFIG_S_DRIVER; +use virtio_sys::virtio_config::VIRTIO_CONFIG_S_DRIVER_OK; +use virtio_sys::virtio_config::VIRTIO_CONFIG_S_FAILED; +use virtio_sys::virtio_config::VIRTIO_CONFIG_S_FEATURES_OK; +use vm_control::MemSlot; +use vm_control::VmMemoryDestination; +use vm_control::VmMemoryRequest; +use vm_control::VmMemoryResponse; +use vm_control::VmMemorySource; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; use self::virtio_pci_common_config::VirtioPciCommonConfig; +use super::*; +use crate::pci::BarRange; +use crate::pci::MsixCap; +use crate::pci::MsixConfig; +use crate::pci::PciAddress; +use crate::pci::PciBarConfiguration; +use crate::pci::PciBarIndex; +use crate::pci::PciBarPrefetchable; +use crate::pci::PciBarRegionType; +use crate::pci::PciCapability; +use crate::pci::PciCapabilityID; +use crate::pci::PciClassCode; +use crate::pci::PciConfiguration; +use crate::pci::PciDevice; +use crate::pci::PciDeviceError; +use crate::pci::PciDisplaySubclass; +use crate::pci::PciHeaderType; +use crate::pci::PciId; +use crate::pci::PciInterruptPin; +use crate::pci::PciSubclass; +use crate::virtio::ipc_memory_mapper::IpcMemoryMapper; +use crate::IrqLevelEvent; #[repr(u8)] #[derive(Debug, Copy, Clone, enumn::N)] diff --git a/devices/src/virtio/vsock/mod.rs b/devices/src/virtio/vsock/mod.rs index 1543d2143..09040e296 100644 --- a/devices/src/virtio/vsock/mod.rs +++ b/devices/src/virtio/vsock/mod.rs @@ -14,4 +14,5 @@ pub mod protocol; pub mod vsock; pub(crate) use protocol::*; -pub use vsock::{Vsock, VsockError}; +pub use vsock::Vsock; +pub use vsock::VsockError; diff --git a/devices/src/virtio/vsock/protocol.rs b/devices/src/virtio/vsock/protocol.rs index 7bbb03274..5a20ccd3b 100644 --- a/devices/src/virtio/vsock/protocol.rs +++ b/devices/src/virtio/vsock/protocol.rs @@ -2,7 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use data_model::{DataInit, Le16, Le32, Le64}; +use data_model::DataInit; +use data_model::Le16; +use data_model::Le32; +use data_model::Le64; pub const TYPE_STREAM_SOCKET: u16 = 1; diff --git a/devices/src/virtio/vsock/vsock.rs b/devices/src/virtio/vsock/vsock.rs index 98db1287e..844c2fac8 100644 --- a/devices/src/virtio/vsock/vsock.rs +++ b/devices/src/virtio/vsock/vsock.rs @@ -4,33 +4,63 @@ use std::cell::RefCell; use std::collections::HashMap; -use std::io::{self, Read, Write}; +use std::fmt; +use std::fmt::Display; +use std::io::Read; +use std::io::Write; +use std::io::{self}; use std::os::windows::io::RawHandle; use std::rc::Rc; -use std::sync::{Arc, RwLock}; +use std::result; +use std::sync::Arc; +use std::sync::RwLock; use std::thread; -use std::{fmt, result}; -use remain::sorted; -use thiserror::Error as ThisError; - -use base::named_pipes::{self, BlockingMode, FramingMode, OverlappedWrapper, PipeConnection}; +use base::error; +use base::info; +use base::named_pipes::BlockingMode; +use base::named_pipes::FramingMode; +use base::named_pipes::OverlappedWrapper; +use base::named_pipes::PipeConnection; +use base::named_pipes::{self}; +use base::warn; +use base::AsRawDescriptor; use base::Error as SysError; -use base::{error, info, warn, AsRawDescriptor, Event}; -use cros_async::{select2, select6, AsyncError, EventAsync, Executor, SelectResult}; -use data_model::{DataInit, Le32, Le64}; +use base::Event; +use cros_async::select2; +use cros_async::select6; +use cros_async::AsyncError; +use cros_async::EventAsync; +use cros_async::Executor; +use cros_async::SelectResult; +use data_model::DataInit; +use data_model::Le32; +use data_model::Le64; use futures::channel::mpsc; +use futures::pin_mut; use futures::stream::FuturesUnordered; -use futures::{pin_mut, FutureExt, SinkExt, StreamExt}; +use futures::FutureExt; +use futures::SinkExt; +use futures::StreamExt; +use remain::sorted; +use sync::Mutex; +use thiserror::Error as ThisError; use vm_memory::GuestMemory; -use crate::virtio::{ - copy_config, virtio_vsock_config, virtio_vsock_event, virtio_vsock_hdr, vsock_op, - DescriptorError, DeviceType, Interrupt, Queue, Reader, SignalableInterrupt, VirtioDevice, - Writer, TYPE_STREAM_SOCKET, -}; -use std::fmt::Display; -use sync::Mutex; +use crate::virtio::copy_config; +use crate::virtio::virtio_vsock_config; +use crate::virtio::virtio_vsock_event; +use crate::virtio::virtio_vsock_hdr; +use crate::virtio::vsock_op; +use crate::virtio::DescriptorError; +use crate::virtio::DeviceType; +use crate::virtio::Interrupt; +use crate::virtio::Queue; +use crate::virtio::Reader; +use crate::virtio::SignalableInterrupt; +use crate::virtio::VirtioDevice; +use crate::virtio::Writer; +use crate::virtio::TYPE_STREAM_SOCKET; #[sorted] #[derive(ThisError, Debug)] diff --git a/devices/src/virtio/wl.rs b/devices/src/virtio/wl.rs index 617541bf6..60e058256 100644 --- a/devices/src/virtio/wl.rs +++ b/devices/src/virtio/wl.rs @@ -30,57 +30,107 @@ use std::cell::RefCell; use std::collections::btree_map::Entry; -use std::collections::{BTreeMap as Map, BTreeSet as Set, VecDeque}; +use std::collections::BTreeMap as Map; +use std::collections::BTreeSet as Set; +use std::collections::VecDeque; use std::convert::From; use std::error::Error as StdError; use std::fmt; use std::fs::File; -use std::io::{self, IoSliceMut, Read, Seek, SeekFrom, Write}; +use std::io::IoSliceMut; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::Write; +use std::io::{self}; use std::mem::size_of; #[cfg(feature = "minigbm")] -use std::os::raw::{c_uint, c_ulonglong}; +use std::os::raw::c_uint; +#[cfg(feature = "minigbm")] +use std::os::raw::c_ulonglong; use std::os::unix::net::UnixStream; -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::path::PathBuf; use std::rc::Rc; use std::result; use std::thread; use std::time::Duration; -#[cfg(feature = "minigbm")] -use libc::{EBADF, EINVAL}; - use anyhow::Context; -use data_model::*; - +use base::error; #[cfg(feature = "minigbm")] use base::ioctl_iow_nr; +use base::ioctl_iowr_nr; +use base::ioctl_with_ref; +use base::pagesize; +use base::pipe; +use base::round_up_to_page_size; +use base::warn; +use base::AsRawDescriptor; +use base::Error; +use base::Event; +use base::EventToken; +use base::EventType; +use base::FileFlags; +use base::FromRawDescriptor; #[cfg(feature = "gpu")] use base::IntoRawDescriptor; -use base::{ - error, ioctl_iowr_nr, ioctl_with_ref, pagesize, pipe, round_up_to_page_size, warn, - AsRawDescriptor, Error, Event, EventToken, EventType, FileFlags, FromRawDescriptor, Protection, - RawDescriptor, Result, SafeDescriptor, ScmSocket, SharedMemory, SharedMemoryUnix, Tube, - TubeError, WaitContext, -}; -use remain::sorted; -use resources::{address_allocator::AddressAllocator, AddressRange, Alloc}; +use base::Protection; +use base::RawDescriptor; +use base::Result; +use base::SafeDescriptor; +use base::ScmSocket; +use base::SharedMemory; +use base::SharedMemoryUnix; +use base::Tube; +use base::TubeError; +use base::WaitContext; +use data_model::*; #[cfg(feature = "minigbm")] -use rutabaga_gfx::{ - DrmFormat, ImageAllocationInfo, ImageMemoryRequirements, RutabagaError, RutabagaGralloc, - RutabagaGrallocFlags, -}; +use libc::EBADF; +#[cfg(feature = "minigbm")] +use libc::EINVAL; +use remain::sorted; +use resources::address_allocator::AddressAllocator; +use resources::AddressRange; +use resources::Alloc; +#[cfg(feature = "minigbm")] +use rutabaga_gfx::DrmFormat; +#[cfg(feature = "minigbm")] +use rutabaga_gfx::ImageAllocationInfo; +#[cfg(feature = "minigbm")] +use rutabaga_gfx::ImageMemoryRequirements; +#[cfg(feature = "minigbm")] +use rutabaga_gfx::RutabagaError; +#[cfg(feature = "minigbm")] +use rutabaga_gfx::RutabagaGralloc; +#[cfg(feature = "minigbm")] +use rutabaga_gfx::RutabagaGrallocFlags; use thiserror::Error as ThisError; -use vm_memory::{GuestAddress, GuestMemory, GuestMemoryError}; +use vm_control::VmMemorySource; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +use vm_memory::GuestMemoryError; #[cfg(feature = "gpu")] -use super::resource_bridge::{ - get_resource_info, BufferInfo, ResourceBridgeError, ResourceInfo, ResourceRequest, -}; -use super::{ - DeviceType, Interrupt, Queue, Reader, SharedMemoryMapper, SharedMemoryRegion, - SignalableInterrupt, VirtioDevice, Writer, -}; -use vm_control::VmMemorySource; +use super::resource_bridge::get_resource_info; +#[cfg(feature = "gpu")] +use super::resource_bridge::BufferInfo; +#[cfg(feature = "gpu")] +use super::resource_bridge::ResourceBridgeError; +#[cfg(feature = "gpu")] +use super::resource_bridge::ResourceInfo; +#[cfg(feature = "gpu")] +use super::resource_bridge::ResourceRequest; +use super::DeviceType; +use super::Interrupt; +use super::Queue; +use super::Reader; +use super::SharedMemoryMapper; +use super::SharedMemoryRegion; +use super::SignalableInterrupt; +use super::VirtioDevice; +use super::Writer; const VIRTWL_SEND_MAX_ALLOCS: usize = 28; const VIRTIO_WL_CMD_VFD_NEW: u32 = 256; diff --git a/devices/src/vmwdt.rs b/devices/src/vmwdt.rs index d89dae41d..49513ff65 100644 --- a/devices/src/vmwdt.rs +++ b/devices/src/vmwdt.rs @@ -6,24 +6,36 @@ //! on the vCPUs and resets the guest when no 'pet' events are received. //! -use crate::pci::CrosvmDeviceId; -use crate::DeviceId; -use crate::{BusAccessInfo, BusDevice}; -use base::{ - debug, error, gettid, warn, AsRawDescriptor, Descriptor, Error as SysError, Event, EventToken, - SendTube, Timer, VmEventType, WaitContext, -}; - -use remain::sorted; use std::convert::TryFrom; +use std::fs; use std::io::Error as IoError; use std::process; use std::sync::Arc; +use std::thread; use std::time::Duration; -use std::{fs, thread}; + +use base::debug; +use base::error; +use base::gettid; +use base::warn; +use base::AsRawDescriptor; +use base::Descriptor; +use base::Error as SysError; +use base::Event; +use base::EventToken; +use base::SendTube; +use base::Timer; +use base::VmEventType; +use base::WaitContext; +use remain::sorted; use sync::Mutex; use thiserror::Error; +use crate::pci::CrosvmDeviceId; +use crate::BusAccessInfo; +use crate::BusDevice; +use crate::DeviceId; + // Registers offsets const VMWDT_REG_STATUS: u32 = 0x00; const VMWDT_REG_LOAD_CNT: u32 = 0x04; diff --git a/devices/src/vtpm_proxy.rs b/devices/src/vtpm_proxy.rs index 70c3ee54a..411844a3f 100644 --- a/devices/src/vtpm_proxy.rs +++ b/devices/src/vtpm_proxy.rs @@ -6,16 +6,13 @@ use std::time::Duration; -use { - base::error, - protobuf::Message, - remain::sorted, - system_api::{ - client::OrgChromiumVtpm, - vtpm_interface::{SendCommandRequest, SendCommandResponse}, - }, - thiserror::Error, -}; +use base::error; +use protobuf::Message; +use remain::sorted; +use system_api::client::OrgChromiumVtpm; +use system_api::vtpm_interface::SendCommandRequest; +use system_api::vtpm_interface::SendCommandResponse; +use thiserror::Error; use super::virtio::TpmBackend; diff --git a/disk/src/android_sparse.rs b/disk/src/android_sparse.rs index aad0814a4..34425ef14 100644 --- a/disk/src/android_sparse.rs +++ b/disk/src/android_sparse.rs @@ -6,18 +6,30 @@ use std::collections::BTreeMap; use std::fs::File; -use std::io::{self, ErrorKind, Read, Seek, SeekFrom}; +use std::io::ErrorKind; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::{self}; use std::mem; -use crate::DiskGetLen; -use base::{ - AsRawDescriptor, FileAllocate, FileReadWriteAtVolatile, FileSetLen, FileSync, PunchHole, - RawDescriptor, WriteZeroesAt, -}; -use data_model::{DataInit, Le16, Le32, VolatileSlice}; +use base::AsRawDescriptor; +use base::FileAllocate; +use base::FileReadWriteAtVolatile; +use base::FileSetLen; +use base::FileSync; +use base::PunchHole; +use base::RawDescriptor; +use base::WriteZeroesAt; +use data_model::DataInit; +use data_model::Le16; +use data_model::Le32; +use data_model::VolatileSlice; use remain::sorted; use thiserror::Error; +use crate::DiskGetLen; + #[sorted] #[derive(Error, Debug)] pub enum Error { @@ -321,8 +333,10 @@ impl FileReadWriteAtVolatile for AndroidSparse { #[cfg(test)] mod tests { + use std::io::Cursor; + use std::io::Write; + use super::*; - use std::io::{Cursor, Write}; const CHUNK_SIZE: usize = mem::size_of::(); diff --git a/disk/src/composite.rs b/disk/src/composite.rs index 79975cb9c..508e551a1 100644 --- a/disk/src/composite.rs +++ b/disk/src/composite.rs @@ -2,31 +2,56 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::cmp::{max, min}; +use std::cmp::max; +use std::cmp::min; use std::collections::HashSet; use std::convert::TryInto; -use std::fs::{File, OpenOptions}; -use std::io::{self, ErrorKind, Read, Seek, SeekFrom, Write}; +use std::fs::File; +use std::fs::OpenOptions; +use std::io::ErrorKind; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::Write; +use std::io::{self}; use std::ops::Range; -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::path::PathBuf; -use base::{ - open_file, AsRawDescriptors, FileAllocate, FileReadWriteAtVolatile, FileSetLen, FileSync, - PunchHole, RawDescriptor, WriteZeroesAt, -}; +use base::open_file; +use base::AsRawDescriptors; +use base::FileAllocate; +use base::FileReadWriteAtVolatile; +use base::FileSetLen; +use base::FileSync; +use base::PunchHole; +use base::RawDescriptor; +use base::WriteZeroesAt; use crc32fast::Hasher; use data_model::VolatileSlice; use protobuf::Message; -use protos::cdisk_spec::{self, ComponentDisk, CompositeDisk, ReadWriteCapability}; +use protos::cdisk_spec::ComponentDisk; +use protos::cdisk_spec::CompositeDisk; +use protos::cdisk_spec::ReadWriteCapability; +use protos::cdisk_spec::{self}; use remain::sorted; use thiserror::Error; use uuid::Uuid; -use crate::gpt::{ - self, write_gpt_header, write_protective_mbr, GptPartitionEntry, GPT_BEGINNING_SIZE, - GPT_END_SIZE, GPT_HEADER_SIZE, GPT_NUM_PARTITIONS, GPT_PARTITION_ENTRY_SIZE, SECTOR_SIZE, -}; -use crate::{create_disk_file, DiskFile, DiskGetLen, ImageType}; +use crate::create_disk_file; +use crate::gpt::write_gpt_header; +use crate::gpt::write_protective_mbr; +use crate::gpt::GptPartitionEntry; +use crate::gpt::GPT_BEGINNING_SIZE; +use crate::gpt::GPT_END_SIZE; +use crate::gpt::GPT_HEADER_SIZE; +use crate::gpt::GPT_NUM_PARTITIONS; +use crate::gpt::GPT_PARTITION_ENTRY_SIZE; +use crate::gpt::SECTOR_SIZE; +use crate::gpt::{self}; +use crate::DiskFile; +use crate::DiskGetLen; +use crate::ImageType; /// The amount of padding needed between the last partition entry and the first partition, to align /// the partition appropriately. The two sectors are for the MBR and the GPT header. @@ -685,15 +710,15 @@ pub fn create_zero_filler>(zero_filler_path: P) -> Result<()> { #[cfg(test)] mod tests { - use super::*; - + use std::fs::OpenOptions; + use std::io::Write; use std::matches; use base::AsRawDescriptor; - use std::fs::OpenOptions; - use std::io::Write; use tempfile::tempfile; + use super::*; + #[test] fn block_duplicate_offset_disks() { let file1 = tempfile().unwrap(); diff --git a/disk/src/disk.rs b/disk/src/disk.rs index 59dded6ce..cfd3e23b3 100644 --- a/disk/src/disk.rs +++ b/disk/src/disk.rs @@ -7,41 +7,60 @@ use std::cmp::min; use std::fmt::Debug; use std::fs::File; -use std::io::{self, Read, Seek, SeekFrom}; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::{self}; use std::path::Path; use std::sync::Arc; -use base::{ - get_filesystem_type, info, AsRawDescriptors, FileAllocate, FileReadWriteAtVolatile, FileSetLen, - FileSync, PunchHole, WriteZeroesAt, -}; -use cros_async::{AllocateMode, Executor}; - use async_trait::async_trait; +use base::get_filesystem_type; +use base::info; +use base::AsRawDescriptors; +use base::FileAllocate; +use base::FileReadWriteAtVolatile; +use base::FileSetLen; +use base::FileSync; +use base::PunchHole; +use base::WriteZeroesAt; +use cros_async::AllocateMode; +use cros_async::Executor; use cros_async::IoSourceExt; use thiserror::Error as ThisError; use vm_memory::GuestMemory; mod qcow; -pub use qcow::{QcowFile, QCOW_MAGIC}; +pub use qcow::QcowFile; +pub use qcow::QCOW_MAGIC; mod sys; #[cfg(feature = "composite-disk")] mod composite; #[cfg(feature = "composite-disk")] -use composite::{CompositeDiskFile, CDISK_MAGIC, CDISK_MAGIC_LEN}; +use composite::CompositeDiskFile; +#[cfg(feature = "composite-disk")] +use composite::CDISK_MAGIC; +#[cfg(feature = "composite-disk")] +use composite::CDISK_MAGIC_LEN; #[cfg(feature = "composite-disk")] mod gpt; #[cfg(feature = "composite-disk")] -pub use composite::{ - create_composite_disk, create_zero_filler, Error as CompositeError, ImagePartitionType, - PartitionInfo, -}; +pub use composite::create_composite_disk; +#[cfg(feature = "composite-disk")] +pub use composite::create_zero_filler; +#[cfg(feature = "composite-disk")] +pub use composite::Error as CompositeError; +#[cfg(feature = "composite-disk")] +pub use composite::ImagePartitionType; +#[cfg(feature = "composite-disk")] +pub use composite::PartitionInfo; #[cfg(feature = "composite-disk")] pub use gpt::Error as GptError; mod android_sparse; -use android_sparse::{AndroidSparse, SPARSE_HEADER_MAGIC}; +use android_sparse::AndroidSparse; +use android_sparse::SPARSE_HEADER_MAGIC; /// Nesting depth limit for disk formats that can open other disk files. pub const MAX_NESTING_DEPTH: u32 = 10; diff --git a/disk/src/gpt.rs b/disk/src/gpt.rs index 39e6d590c..8d1694f3f 100644 --- a/disk/src/gpt.rs +++ b/disk/src/gpt.rs @@ -5,7 +5,8 @@ //! Functions for writing GUID Partition Tables for use in a composite disk image. use std::convert::TryInto; -use std::io::{self, Write}; +use std::io::Write; +use std::io::{self}; use std::num::TryFromIntError; use crc32fast::Hasher; diff --git a/disk/src/qcow/mod.rs b/disk/src/qcow/mod.rs index c005c1abf..861850ca0 100644 --- a/disk/src/qcow/mod.rs +++ b/disk/src/qcow/mod.rs @@ -6,26 +6,46 @@ mod qcow_raw_file; mod refcount; mod vec_cache; -use base::{ - error, open_file, AsRawDescriptor, AsRawDescriptors, FileAllocate, FileReadWriteAtVolatile, - FileSetLen, FileSync, PunchHole, RawDescriptor, WriteZeroesAt, -}; -use data_model::{VolatileMemory, VolatileSlice}; -use libc::{EINVAL, ENOSPC, ENOTSUP}; -use remain::sorted; -use thiserror::Error; - -use std::cmp::{max, min}; -use std::fs::{File, OpenOptions}; -use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::cmp::max; +use std::cmp::min; +use std::fs::File; +use std::fs::OpenOptions; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::Write; +use std::io::{self}; use std::mem::size_of; use std::path::Path; use std::str; +use base::error; +use base::open_file; +use base::AsRawDescriptor; +use base::AsRawDescriptors; +use base::FileAllocate; +use base::FileReadWriteAtVolatile; +use base::FileSetLen; +use base::FileSync; +use base::PunchHole; +use base::RawDescriptor; +use base::WriteZeroesAt; +use data_model::VolatileMemory; +use data_model::VolatileSlice; +use libc::EINVAL; +use libc::ENOSPC; +use libc::ENOTSUP; +use remain::sorted; +use thiserror::Error; + +use crate::create_disk_file; use crate::qcow::qcow_raw_file::QcowRawFile; use crate::qcow::refcount::RefCount; -use crate::qcow::vec_cache::{CacheMap, Cacheable, VecCache}; -use crate::{create_disk_file, DiskFile, DiskGetLen}; +use crate::qcow::vec_cache::CacheMap; +use crate::qcow::vec_cache::Cacheable; +use crate::qcow::vec_cache::VecCache; +use crate::DiskFile; +use crate::DiskGetLen; #[sorted] #[derive(Error, Debug)] @@ -1598,11 +1618,17 @@ fn div_round_up_u32(dividend: u32, divisor: u32) -> u32 { #[cfg(test)] mod tests { + use std::fs::OpenOptions; + use std::io::Read; + use std::io::Seek; + use std::io::SeekFrom; + use std::io::Write; + + use tempfile::tempfile; + use tempfile::TempDir; + use super::*; use crate::MAX_NESTING_DEPTH; - use std::fs::OpenOptions; - use std::io::{Read, Seek, SeekFrom, Write}; - use tempfile::{tempfile, TempDir}; fn valid_header() -> Vec { vec![ diff --git a/disk/src/qcow/qcow_raw_file.rs b/disk/src/qcow/qcow_raw_file.rs index 467f7961b..700c8087a 100644 --- a/disk/src/qcow/qcow_raw_file.rs +++ b/disk/src/qcow/qcow_raw_file.rs @@ -3,10 +3,16 @@ // found in the LICENSE file. use std::fs::File; -use std::io::{self, BufWriter, Read, Seek, SeekFrom, Write}; +use std::io::BufWriter; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::Write; +use std::io::{self}; use std::mem::size_of; -use base::{FileReadWriteAtVolatile, WriteZeroesAt}; +use base::FileReadWriteAtVolatile; +use base::WriteZeroesAt; use data_model::VolatileSlice; /// A qcow file. Allows reading/writing clusters and appending clusters. diff --git a/disk/src/qcow/refcount.rs b/disk/src/qcow/refcount.rs index 90cd95f83..2e71612d7 100644 --- a/disk/src/qcow/refcount.rs +++ b/disk/src/qcow/refcount.rs @@ -9,7 +9,9 @@ use remain::sorted; use thiserror::Error; use crate::qcow::qcow_raw_file::QcowRawFile; -use crate::qcow::vec_cache::{CacheMap, Cacheable, VecCache}; +use crate::qcow::vec_cache::CacheMap; +use crate::qcow::vec_cache::Cacheable; +use crate::qcow::vec_cache::VecCache; #[sorted] #[derive(Error, Debug)] diff --git a/disk/src/qcow/vec_cache.rs b/disk/src/qcow/vec_cache.rs index b5f6db2d3..4c6fd1ca7 100644 --- a/disk/src/qcow/vec_cache.rs +++ b/disk/src/qcow/vec_cache.rs @@ -5,7 +5,8 @@ use std::collections::hash_map::IterMut; use std::collections::HashMap; use std::io; -use std::ops::{Index, IndexMut}; +use std::ops::Index; +use std::ops::IndexMut; use std::slice::SliceIndex; /// Trait that allows for checking if an implementor is dirty. Useful for types that are cached so diff --git a/disk/src/sys/unix.rs b/disk/src/sys/unix.rs index 87cd23c12..0b6aac387 100644 --- a/disk/src/sys/unix.rs +++ b/disk/src/sys/unix.rs @@ -13,13 +13,16 @@ pub fn apply_raw_disk_file_options(_raw_image: &File, _is_sparse_file: bool) -> #[cfg(test)] mod tests { - use crate::*; - - use std::fs::{File, OpenOptions}; + use std::fs::File; + use std::fs::OpenOptions; use std::io::Write; - use cros_async::{Executor, MemRegion}; - use vm_memory::{GuestAddress, GuestMemory}; + use cros_async::Executor; + use cros_async::MemRegion; + use vm_memory::GuestAddress; + use vm_memory::GuestMemory; + + use crate::*; #[test] fn read_async() { diff --git a/disk/src/sys/windows.rs b/disk/src/sys/windows.rs index 23caf7237..49d44b1a7 100644 --- a/disk/src/sys/windows.rs +++ b/disk/src/sys/windows.rs @@ -5,9 +5,12 @@ use std::fs::File; use cros_async::sys::windows::HandleSource; -use cros_async::{Executor, IoSourceExt}; +use cros_async::Executor; +use cros_async::IoSourceExt; -use crate::{Error, Result, SingleFileDisk}; +use crate::Error; +use crate::Result; +use crate::SingleFileDisk; impl SingleFileDisk { pub fn new_from_files(disk_files: Vec, _ex: &Executor) -> Result { diff --git a/fuse/src/filesystem.rs b/fuse/src/filesystem.rs index 8050309ff..f063369d1 100644 --- a/fuse/src/filesystem.rs +++ b/fuse/src/filesystem.rs @@ -9,12 +9,15 @@ use std::io; use std::mem; use std::time::Duration; -use crate::sys; - use crate::server::Mapper; -pub use crate::sys::{ - FsOptions, IoctlFlags, IoctlIovec, OpenOptions, RemoveMappingOne, SetattrValid, ROOT_ID, -}; +use crate::sys; +pub use crate::sys::FsOptions; +pub use crate::sys::IoctlFlags; +pub use crate::sys::IoctlIovec; +pub use crate::sys::OpenOptions; +pub use crate::sys::RemoveMappingOne; +pub use crate::sys::SetattrValid; +pub use crate::sys::ROOT_ID; const MAX_BUFFER_SIZE: u32 = 1 << 20; diff --git a/fuse/src/fuzzing.rs b/fuse/src/fuzzing.rs index bbfde8e31..1120bee47 100644 --- a/fuse/src/fuzzing.rs +++ b/fuse/src/fuzzing.rs @@ -2,12 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::filesystem::{DirEntry, DirectoryIterator, FileSystem, ZeroCopyReader, ZeroCopyWriter}; -use crate::server::{Mapper, Reader, Server, Writer}; - use std::io; use std::os::unix::io::AsRawFd; +use crate::filesystem::DirEntry; +use crate::filesystem::DirectoryIterator; +use crate::filesystem::FileSystem; +use crate::filesystem::ZeroCopyReader; +use crate::filesystem::ZeroCopyWriter; +use crate::server::Mapper; +use crate::server::Reader; +use crate::server::Server; +use crate::server::Writer; + // Use a file system that does nothing since we are fuzzing the server implementation. struct NullFs; impl FileSystem for NullFs { diff --git a/fuse/src/lib.rs b/fuse/src/lib.rs index 5ce6aee7d..38d86bcb4 100644 --- a/fuse/src/lib.rs +++ b/fuse/src/lib.rs @@ -20,10 +20,12 @@ mod server; pub mod sys; pub mod worker; -pub use mount::mount; -pub use server::{Mapper, Reader, Server, Writer}; - use filesystem::FileSystem; +pub use mount::mount; +pub use server::Mapper; +pub use server::Reader; +pub use server::Server; +pub use server::Writer; /// Errors that may occur during the creation or operation of an Fs device. #[sorted] diff --git a/fuse/src/mount.rs b/fuse/src/mount.rs index 427f69670..99645f459 100644 --- a/fuse/src/mount.rs +++ b/fuse/src/mount.rs @@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::ffi::{CString, OsStr}; +use std::ffi::CString; +use std::ffi::OsStr; use std::fmt; use std::io; use std::os::unix::ffi::OsStrExt; diff --git a/fuse/src/server.rs b/fuse/src/server.rs index 4a6362e66..305a68ff2 100644 --- a/fuse/src/server.rs +++ b/fuse/src/server.rs @@ -2,23 +2,33 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::cmp::{max, min}; +use std::cmp::max; +use std::cmp::min; use std::convert::TryInto; use std::ffi::CStr; use std::io; -use std::mem::{size_of, MaybeUninit}; +use std::mem::size_of; +use std::mem::MaybeUninit; use std::os::unix::io::AsRawFd; use std::time::Duration; -use base::{error, pagesize}; +use base::error; +use base::pagesize; use data_model::DataInit; -use crate::filesystem::{ - Context, DirEntry, DirectoryIterator, Entry, FileSystem, GetxattrReply, IoctlReply, - ListxattrReply, ZeroCopyReader, ZeroCopyWriter, -}; +use crate::filesystem::Context; +use crate::filesystem::DirEntry; +use crate::filesystem::DirectoryIterator; +use crate::filesystem::Entry; +use crate::filesystem::FileSystem; +use crate::filesystem::GetxattrReply; +use crate::filesystem::IoctlReply; +use crate::filesystem::ListxattrReply; +use crate::filesystem::ZeroCopyReader; +use crate::filesystem::ZeroCopyWriter; use crate::sys::*; -use crate::{Error, Result}; +use crate::Error; +use crate::Result; const DIRENT_PADDING: [u8; 8] = [0; 8]; diff --git a/fuse/src/worker.rs b/fuse/src/worker.rs index 6574d20de..cc4537314 100644 --- a/fuse/src/worker.rs +++ b/fuse/src/worker.rs @@ -3,16 +3,27 @@ // found in the LICENSE file. use std::fs::File; -use std::io::{self, BufRead, BufReader, Cursor, Read, Write}; +use std::io::BufRead; +use std::io::BufReader; +use std::io::Cursor; +use std::io::Read; +use std::io::Write; +use std::io::{self}; use std::mem::size_of; use std::os::unix::fs::FileExt; use std::os::unix::io::AsRawFd; use std::sync::Arc; -use crate::filesystem::{FileSystem, ZeroCopyReader, ZeroCopyWriter}; -use crate::server::{Mapper, Reader, Server, Writer}; +use crate::filesystem::FileSystem; +use crate::filesystem::ZeroCopyReader; +use crate::filesystem::ZeroCopyWriter; +use crate::server::Mapper; +use crate::server::Reader; +use crate::server::Server; +use crate::server::Writer; use crate::sys; -use crate::{Error, Result}; +use crate::Error; +use crate::Result; struct DevFuseReader { // File representing /dev/fuse for reading, with sufficient buffer to accommodate a FUSE read @@ -195,9 +206,10 @@ fn do_start_message_loop( // TODO: Remove worker and this namespace from public pub mod internal { - use super::*; use crossbeam_utils::thread; + use super::*; + /// Start the FUSE message handling loops in multiple threads. Returns when an error happens. /// /// # Arguments diff --git a/gpu_display/examples/simple_open.rs b/gpu_display/examples/simple_open.rs index cc38b8bf5..ae7c8aab7 100644 --- a/gpu_display/examples/simple_open.rs +++ b/gpu_display/examples/simple_open.rs @@ -1,4 +1,5 @@ -use gpu_display::{GpuDisplay, SurfaceType}; +use gpu_display::GpuDisplay; +use gpu_display::SurfaceType; fn main() { let mut disp = GpuDisplay::open_x(None::<&str>).unwrap(); diff --git a/gpu_display/src/event_device.rs b/gpu_display/src/event_device.rs index 3bf384ab0..0b9ead6ad 100644 --- a/gpu_display/src/event_device.rs +++ b/gpu_display/src/event_device.rs @@ -2,18 +2,26 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::{AsRawDescriptor, RawDescriptor}; -use data_model::DataInit; -use linux_input_sys::{ - virtio_input_event, InputEventDecoder, ABS_MT_POSITION_X, ABS_MT_POSITION_Y, ABS_MT_SLOT, - ABS_MT_TRACKING_ID, -}; use std::cmp::max; use std::collections::VecDeque; -use std::io::{self, Error, ErrorKind, Read, Write}; +use std::io::Error; +use std::io::ErrorKind; +use std::io::Read; +use std::io::Write; +use std::io::{self}; use std::iter::ExactSizeIterator; use std::os::unix::net::UnixStream; +use base::AsRawDescriptor; +use base::RawDescriptor; +use data_model::DataInit; +use linux_input_sys::virtio_input_event; +use linux_input_sys::InputEventDecoder; +use linux_input_sys::ABS_MT_POSITION_X; +use linux_input_sys::ABS_MT_POSITION_Y; +use linux_input_sys::ABS_MT_SLOT; +use linux_input_sys::ABS_MT_TRACKING_ID; + const EVENT_SIZE: usize = virtio_input_event::SIZE; const EVENT_BUFFER_LEN_MAX: usize = 64 * EVENT_SIZE; diff --git a/gpu_display/src/gpu_display_stub.rs b/gpu_display/src/gpu_display_stub.rs index 32106eb9e..7e056efca 100644 --- a/gpu_display/src/gpu_display_stub.rs +++ b/gpu_display/src/gpu_display_stub.rs @@ -2,14 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{ - DisplayT, GpuDisplayError, GpuDisplayFramebuffer, GpuDisplayResult, GpuDisplaySurface, - SurfaceType, -}; - -use base::{AsRawDescriptor, Event, RawDescriptor}; +use base::AsRawDescriptor; +use base::Event; +use base::RawDescriptor; use data_model::VolatileSlice; +use crate::DisplayT; +use crate::GpuDisplayError; +use crate::GpuDisplayFramebuffer; +use crate::GpuDisplayResult; +use crate::GpuDisplaySurface; +use crate::SurfaceType; + #[allow(dead_code)] struct Buffer { width: u32, diff --git a/gpu_display/src/gpu_display_wl.rs b/gpu_display/src/gpu_display_wl.rs index 2638eabf7..d1a16d275 100644 --- a/gpu_display/src/gpu_display_wl.rs +++ b/gpu_display/src/gpu_display_wl.rs @@ -10,26 +10,34 @@ extern crate data_model; #[path = "dwl.rs"] mod dwl; -use dwl::*; - -use crate::{ - DisplayT, EventDeviceKind, GpuDisplayError, GpuDisplayEvents, GpuDisplayFramebuffer, - GpuDisplayImport, GpuDisplayResult, GpuDisplaySurface, SurfaceType, -}; - -use linux_input_sys::virtio_input_event; use std::cell::Cell; use std::cmp::max; -use std::ffi::{CStr, CString}; +use std::ffi::CStr; +use std::ffi::CString; use std::mem::zeroed; use std::path::Path; use std::ptr::null; -use base::{ - error, round_up_to_page_size, AsRawDescriptor, MemoryMapping, MemoryMappingBuilder, - RawDescriptor, SharedMemory, -}; +use base::error; +use base::round_up_to_page_size; +use base::AsRawDescriptor; +use base::MemoryMapping; +use base::MemoryMappingBuilder; +use base::RawDescriptor; +use base::SharedMemory; use data_model::VolatileMemory; +use dwl::*; +use linux_input_sys::virtio_input_event; + +use crate::DisplayT; +use crate::EventDeviceKind; +use crate::GpuDisplayError; +use crate::GpuDisplayEvents; +use crate::GpuDisplayFramebuffer; +use crate::GpuDisplayImport; +use crate::GpuDisplayResult; +use crate::GpuDisplaySurface; +use crate::SurfaceType; const BUFFER_COUNT: usize = 3; const BYTES_PER_PIXEL: u32 = 4; diff --git a/gpu_display/src/gpu_display_x.rs b/gpu_display/src/gpu_display_x.rs index 82a654e3e..99f32c534 100644 --- a/gpu_display/src/gpu_display_x.rs +++ b/gpu_display/src/gpu_display_x.rs @@ -11,24 +11,40 @@ )] mod xlib; -use linux_input_sys::virtio_input_event; use std::cmp::max; -use std::ffi::{c_void, CStr, CString}; -use std::mem::{transmute_copy, zeroed}; +use std::ffi::c_void; +use std::ffi::CStr; +use std::ffi::CString; +use std::mem::transmute_copy; +use std::mem::zeroed; use std::os::raw::c_ulong; -use std::ptr::{null, null_mut, NonNull}; +use std::ptr::null; +use std::ptr::null_mut; +use std::ptr::NonNull; use std::rc::Rc; -use libc::{shmat, shmctl, shmdt, shmget, IPC_CREAT, IPC_PRIVATE, IPC_RMID}; - -use crate::{ - keycode_converter::KeycodeTranslator, keycode_converter::KeycodeTypes, DisplayT, - EventDeviceKind, GpuDisplayError, GpuDisplayEvents, GpuDisplayFramebuffer, GpuDisplayResult, - GpuDisplaySurface, SurfaceType, -}; - -use base::{AsRawDescriptor, RawDescriptor}; +use base::AsRawDescriptor; +use base::RawDescriptor; use data_model::VolatileSlice; +use libc::shmat; +use libc::shmctl; +use libc::shmdt; +use libc::shmget; +use libc::IPC_CREAT; +use libc::IPC_PRIVATE; +use libc::IPC_RMID; +use linux_input_sys::virtio_input_event; + +use crate::keycode_converter::KeycodeTranslator; +use crate::keycode_converter::KeycodeTypes; +use crate::DisplayT; +use crate::EventDeviceKind; +use crate::GpuDisplayError; +use crate::GpuDisplayEvents; +use crate::GpuDisplayFramebuffer; +use crate::GpuDisplayResult; +use crate::GpuDisplaySurface; +use crate::SurfaceType; const BUFFER_COUNT: usize = 2; diff --git a/gpu_display/src/keycode_converter/mod.rs b/gpu_display/src/keycode_converter/mod.rs index 00549ed04..f9b5a04c4 100644 --- a/gpu_display/src/keycode_converter/mod.rs +++ b/gpu_display/src/keycode_converter/mod.rs @@ -4,9 +4,11 @@ mod data; -use data::{MapEntry, KEYCODE_MAP}; use std::collections::HashMap; +use data::MapEntry; +use data::KEYCODE_MAP; + /// Specifies which type of scancode to convert *from* in the KeycodeTranslator. #[allow(dead_code)] pub enum KeycodeTypes { diff --git a/gpu_display/src/lib.rs b/gpu_display/src/lib.rs index 9b2a2e64c..4c745e2b1 100644 --- a/gpu_display/src/lib.rs +++ b/gpu_display/src/lib.rs @@ -10,9 +10,12 @@ use std::io::Error as IoError; use std::path::Path; use std::time::Duration; -use base::{ - AsRawDescriptor, Error as BaseError, EventToken, EventType, RawDescriptor, WaitContext, -}; +use base::AsRawDescriptor; +use base::Error as BaseError; +use base::EventToken; +use base::EventType; +use base::RawDescriptor; +use base::WaitContext; use data_model::VolatileSlice; use remain::sorted; use thiserror::Error; @@ -25,7 +28,8 @@ mod gpu_display_x; #[cfg(feature = "x")] mod keycode_converter; -pub use event_device::{EventDevice, EventDeviceKind}; +pub use event_device::EventDevice; +pub use event_device::EventDeviceKind; use linux_input_sys::virtio_input_event; /// An error generated by `GpuDisplay`. diff --git a/hypervisor/src/aarch64.rs b/hypervisor/src/aarch64.rs index edbcfdb68..63db4a199 100644 --- a/hypervisor/src/aarch64.rs +++ b/hypervisor/src/aarch64.rs @@ -4,12 +4,18 @@ use std::convert::TryFrom; -use base::{Error, Result}; +use base::Error; +use base::Result; use downcast_rs::impl_downcast; use libc::EINVAL; use vm_memory::GuestAddress; -use crate::{Hypervisor, IrqRoute, IrqSource, IrqSourceChip, Vcpu, Vm}; +use crate::Hypervisor; +use crate::IrqRoute; +use crate::IrqSource; +use crate::IrqSourceChip; +use crate::Vcpu; +use crate::Vm; /// Represents a version of Power State Coordination Interface (PSCI). #[derive(Eq, Ord, PartialEq, PartialOrd)] diff --git a/hypervisor/src/haxm.rs b/hypervisor/src/haxm.rs index 63dab5fd9..d61adc242 100644 --- a/hypervisor/src/haxm.rs +++ b/hypervisor/src/haxm.rs @@ -2,19 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::arch::x86_64::{CpuidResult, __cpuid}; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::arch::x86_64::CpuidResult; +use std::arch::x86_64::__cpuid; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; -use base::{AsRawDescriptor, RawDescriptor, Result, SafeDescriptor}; +use base::AsRawDescriptor; +use base::RawDescriptor; +use base::Result; +use base::SafeDescriptor; -use crate::{CpuId, CpuIdEntry, Hypervisor, HypervisorCap, HypervisorX86_64}; +use crate::CpuId; +use crate::CpuIdEntry; +use crate::Hypervisor; +use crate::HypervisorCap; +use crate::HypervisorX86_64; mod haxm_sys; -use haxm_sys::*; // This is a HAXM-specific capability, so it's not present in the VmCap enum, and the // register_vm_log function does not exist on the Vm trait. But windows.rs will use it when // creating Haxm Vm instances, so we expose the cap constant here. pub use haxm_sys::HAX_CAP_VM_LOG; +use haxm_sys::*; mod vcpu; pub use vcpu::*; diff --git a/hypervisor/src/haxm/haxm_sys/posix.rs b/hypervisor/src/haxm/haxm_sys/posix.rs index 14bbc3795..e0c9aa994 100644 --- a/hypervisor/src/haxm/haxm_sys/posix.rs +++ b/hypervisor/src/haxm/haxm_sys/posix.rs @@ -2,7 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::{ioctl_io_nr, ioctl_ior_nr, ioctl_iow_nr, ioctl_iowr_nr}; +use base::ioctl_io_nr; +use base::ioctl_ior_nr; +use base::ioctl_iow_nr; +use base::ioctl_iowr_nr; use super::*; diff --git a/hypervisor/src/haxm/unix.rs b/hypervisor/src/haxm/unix.rs index 3f7faa726..07ba28462 100644 --- a/hypervisor/src/haxm/unix.rs +++ b/hypervisor/src/haxm/unix.rs @@ -2,14 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use libc::{open, EBUSY, O_CLOEXEC, O_RDWR}; use std::cell::RefCell; -use std::os::raw::{c_char, c_int}; +use std::os::raw::c_char; +use std::os::raw::c_int; -use base::{errno_result, Error, FromRawDescriptor, MappedRegion, Result, SafeDescriptor}; +use base::errno_result; +use base::Error; +use base::FromRawDescriptor; +use base::MappedRegion; +use base::Result; +use base::SafeDescriptor; +use libc::open; +use libc::EBUSY; +use libc::O_CLOEXEC; +use libc::O_RDWR; use super::haxm_sys::hax_tunnel; -use super::{HaxmVcpu, HAX_EXIT_PAUSED}; +use super::HaxmVcpu; +use super::HAX_EXIT_PAUSED; use crate::VcpuRunHandle; pub(super) fn open_haxm_device(_use_ghaxm: bool) -> Result { diff --git a/hypervisor/src/haxm/vcpu.rs b/hypervisor/src/haxm/vcpu.rs index 9563d53bb..424e7fef3 100644 --- a/hypervisor/src/haxm/vcpu.rs +++ b/hypervisor/src/haxm/vcpu.rs @@ -3,29 +3,54 @@ // found in the LICENSE file. use core::ffi::c_void; -use libc::{EINVAL, ENOENT, ENOSPC, ENXIO}; use std::arch::x86_64::CpuidResult; use std::cmp::min; use std::intrinsics::copy_nonoverlapping; -use std::mem::{size_of, ManuallyDrop}; +use std::mem::size_of; +use std::mem::ManuallyDrop; use std::os::raw::c_int; use std::sync::atomic::AtomicU64; use std::sync::Arc; -use base::{ - errno_result, ioctl, ioctl_with_mut_ref, ioctl_with_ptr_sized, ioctl_with_ref, warn, - AsRawDescriptor, Error, MappedRegion, MemoryMapping, RawDescriptor, Result, SafeDescriptor, -}; +use base::errno_result; +use base::ioctl; +use base::ioctl_with_mut_ref; +use base::ioctl_with_ptr_sized; +use base::ioctl_with_ref; +use base::warn; +use base::AsRawDescriptor; +use base::Error; +use base::MappedRegion; +use base::MemoryMapping; +use base::RawDescriptor; +use base::Result; +use base::SafeDescriptor; use data_model::vec_with_array_field; +use libc::EINVAL; +use libc::ENOENT; +use libc::ENOSPC; +use libc::ENXIO; use vm_memory::GuestAddress; use super::*; - -use crate::{ - get_tsc_offset_from_msr, set_tsc_offset_via_msr, CpuId, CpuIdEntry, DebugRegs, DescriptorTable, - Fpu, HypervHypercall, IoOperation, IoParams, Register, Regs, Segment, Sregs, Vcpu, VcpuExit, - VcpuRunHandle, VcpuX86_64, -}; +use crate::get_tsc_offset_from_msr; +use crate::set_tsc_offset_via_msr; +use crate::CpuId; +use crate::CpuIdEntry; +use crate::DebugRegs; +use crate::DescriptorTable; +use crate::Fpu; +use crate::HypervHypercall; +use crate::IoOperation; +use crate::IoParams; +use crate::Register; +use crate::Regs; +use crate::Segment; +use crate::Sregs; +use crate::Vcpu; +use crate::VcpuExit; +use crate::VcpuRunHandle; +use crate::VcpuX86_64; // from HAXM code's IOS_MAX_BUFFER pub(crate) const HAXM_IO_BUFFER_SIZE: usize = 64; @@ -975,9 +1000,11 @@ impl From<&Register> for vmx_msr { #[cfg(test)] mod tests { + use vm_memory::GuestAddress; + use vm_memory::GuestMemory; + use super::*; use crate::VmX86_64; - use vm_memory::{GuestAddress, GuestMemory}; // EFER Bits const EFER_SCE: u64 = 0x00000001; diff --git a/hypervisor/src/haxm/vm.rs b/hypervisor/src/haxm/vm.rs index 31ce09c22..edb75a978 100644 --- a/hypervisor/src/haxm/vm.rs +++ b/hypervisor/src/haxm/vm.rs @@ -3,27 +3,55 @@ // found in the LICENSE file. use core::ffi::c_void; -use fnv::FnvHashMap; -use libc::{E2BIG, EEXIST, EFAULT, EINVAL, EIO, ENOENT, ENOSPC, ENOTSUP, EOVERFLOW}; use std::cmp::Reverse; -use std::collections::{BTreeMap, BinaryHeap}; +use std::collections::BTreeMap; +use std::collections::BinaryHeap; use std::mem::ManuallyDrop; use std::sync::Arc; -use crate::{ - host_phys_addr_bits, ClockState, Datamatch, DeviceKind, Hypervisor, IoEventAddress, MemSlot, - VcpuX86_64, Vm, VmCap, VmX86_64, -}; -use base::{ - errno_result, error, ioctl_with_mut_ref, ioctl_with_ref, warn, AsRawDescriptor, Error, Event, - MappedRegion, MemoryMapping, MmapError, Protection, RawDescriptor, Result, SafeDescriptor, -}; +use base::errno_result; +use base::error; +use base::ioctl_with_mut_ref; +use base::ioctl_with_ref; +use base::warn; +use base::AsRawDescriptor; +use base::Error; +use base::Event; +use base::MappedRegion; +use base::MemoryMapping; +use base::MmapError; +use base::Protection; +use base::RawDescriptor; +use base::Result; +use base::SafeDescriptor; +use fnv::FnvHashMap; +use libc::E2BIG; +use libc::EEXIST; +use libc::EFAULT; +use libc::EINVAL; +use libc::EIO; +use libc::ENOENT; +use libc::ENOSPC; +use libc::ENOTSUP; +use libc::EOVERFLOW; use sync::Mutex; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; #[cfg(windows)] use win_util::win32_wide_string; use super::*; +use crate::host_phys_addr_bits; +use crate::ClockState; +use crate::Datamatch; +use crate::DeviceKind; +use crate::Hypervisor; +use crate::IoEventAddress; +use crate::MemSlot; +use crate::VcpuX86_64; +use crate::Vm; +use crate::VmCap; +use crate::VmX86_64; /// A wrapper around creating and using a HAXM VM. pub struct HaxmVm { @@ -457,10 +485,14 @@ impl VmX86_64 for HaxmVm { #[cfg(test)] mod tests { - use super::*; - use base::{EventReadResult, MemoryMappingBuilder, SharedMemory}; use std::time::Duration; + use base::EventReadResult; + use base::MemoryMappingBuilder; + use base::SharedMemory; + + use super::*; + #[test] fn create_vm() { let haxm = Haxm::new().expect("failed to instantiate HAXM"); diff --git a/hypervisor/src/haxm/win.rs b/hypervisor/src/haxm/win.rs index 2ead3964c..68e81dd73 100644 --- a/hypervisor/src/haxm/win.rs +++ b/hypervisor/src/haxm/win.rs @@ -5,13 +5,19 @@ use std::os::raw::c_int; use std::ptr::null_mut; +use base::errno_result; +use base::Error; +use base::FromRawDescriptor; +use base::Result; +use base::SafeDescriptor; use libc::EBUSY; -use winapi::um::fileapi::{CreateFileW, CREATE_ALWAYS}; -use winapi::um::handleapi::INVALID_HANDLE_VALUE; -use winapi::um::winnt::{FILE_ATTRIBUTE_NORMAL, GENERIC_READ, GENERIC_WRITE}; - -use base::{errno_result, Error, FromRawDescriptor, Result, SafeDescriptor}; use win_util::win32_wide_string; +use winapi::um::fileapi::CreateFileW; +use winapi::um::fileapi::CREATE_ALWAYS; +use winapi::um::handleapi::INVALID_HANDLE_VALUE; +use winapi::um::winnt::FILE_ATTRIBUTE_NORMAL; +use winapi::um::winnt::GENERIC_READ; +use winapi::um::winnt::GENERIC_WRITE; use super::HaxmVcpu; use crate::VcpuRunHandle; diff --git a/hypervisor/src/kvm/aarch64.rs b/hypervisor/src/kvm/aarch64.rs index b2c42d996..cf157a112 100644 --- a/hypervisor/src/kvm/aarch64.rs +++ b/hypervisor/src/kvm/aarch64.rs @@ -4,20 +4,40 @@ use std::convert::TryFrom; -use libc::{EINVAL, ENOMEM, ENOTSUP, ENXIO}; - -use base::{ - errno_result, error, ioctl_with_mut_ref, ioctl_with_ref, ioctl_with_val, warn, Error, - MemoryMappingBuilder, Result, -}; +use base::errno_result; +use base::error; +use base::ioctl_with_mut_ref; +use base::ioctl_with_ref; +use base::ioctl_with_val; +use base::warn; +use base::Error; +use base::MemoryMappingBuilder; +use base::Result; use kvm_sys::*; +use libc::EINVAL; +use libc::ENOMEM; +use libc::ENOTSUP; +use libc::ENXIO; use vm_memory::GuestAddress; -use super::{Kvm, KvmCap, KvmVcpu, KvmVm}; -use crate::{ - ClockState, DeviceKind, Hypervisor, IrqSourceChip, ProtectionType, PsciVersion, VcpuAArch64, - VcpuExit, VcpuFeature, VcpuRegAArch64, Vm, VmAArch64, VmCap, PSCI_0_2, -}; +use super::Kvm; +use super::KvmCap; +use super::KvmVcpu; +use super::KvmVm; +use crate::ClockState; +use crate::DeviceKind; +use crate::Hypervisor; +use crate::IrqSourceChip; +use crate::ProtectionType; +use crate::PsciVersion; +use crate::VcpuAArch64; +use crate::VcpuExit; +use crate::VcpuFeature; +use crate::VcpuRegAArch64; +use crate::Vm; +use crate::VmAArch64; +use crate::VmCap; +use crate::PSCI_0_2; /// Gives the ID for a register to be used with `set_one_reg`. /// @@ -466,10 +486,14 @@ pub(super) fn chip_to_kvm_chip(chip: IrqSourceChip) -> u32 { #[cfg(test)] mod tests { + use vm_memory::GuestAddress; + use vm_memory::GuestMemory; + use super::super::Kvm; use super::*; - use crate::{IrqRoute, IrqSource, IrqSourceChip}; - use vm_memory::{GuestAddress, GuestMemory}; + use crate::IrqRoute; + use crate::IrqSource; + use crate::IrqSourceChip; #[test] fn set_gsi_routing() { diff --git a/hypervisor/src/kvm/mod.rs b/hypervisor/src/kvm/mod.rs index d9873a299..52155b93c 100644 --- a/hypervisor/src/kvm/mod.rs +++ b/hypervisor/src/kvm/mod.rs @@ -9,42 +9,86 @@ use aarch64::*; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] mod x86_64; -#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use x86_64::*; - use std::cell::RefCell; -use std::cmp::{min, Reverse}; -use std::collections::{BTreeMap, BinaryHeap}; +use std::cmp::min; +use std::cmp::Reverse; +use std::collections::BTreeMap; +use std::collections::BinaryHeap; use std::convert::TryFrom; use std::ffi::CString; -use std::mem::{size_of, ManuallyDrop}; -use std::os::raw::{c_int, c_ulong, c_void}; +use std::mem::size_of; +use std::mem::ManuallyDrop; +use std::os::raw::c_int; +use std::os::raw::c_ulong; +use std::os::raw::c_void; use std::os::unix::prelude::OsStrExt; -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::path::PathBuf; use std::ptr::copy_nonoverlapping; use std::sync::atomic::AtomicU64; use std::sync::Arc; -use libc::{ - open, sigset_t, EBUSY, EFAULT, EINVAL, EIO, ENOENT, ENOSPC, EOVERFLOW, O_CLOEXEC, O_RDWR, -}; - -use base::{ - block_signal, errno_result, error, ioctl, ioctl_with_mut_ref, ioctl_with_ref, ioctl_with_val, - pagesize, signal, unblock_signal, AsRawDescriptor, Error, Event, FromRawDescriptor, - MappedRegion, MemoryMapping, MemoryMappingBuilder, MemoryMappingBuilderUnix, MmapError, - Protection, RawDescriptor, Result, SafeDescriptor, -}; +use base::block_signal; +use base::errno_result; +use base::error; +use base::ioctl; +use base::ioctl_with_mut_ref; +use base::ioctl_with_ref; +use base::ioctl_with_val; +use base::pagesize; +use base::signal; +use base::unblock_signal; +use base::AsRawDescriptor; +use base::Error; +use base::Event; +use base::FromRawDescriptor; +use base::MappedRegion; +use base::MemoryMapping; +use base::MemoryMappingBuilder; +use base::MemoryMappingBuilderUnix; +use base::MmapError; +use base::Protection; +use base::RawDescriptor; +use base::Result; +use base::SafeDescriptor; use data_model::vec_with_array_field; use kvm_sys::*; +use libc::open; +use libc::sigset_t; +use libc::EBUSY; +use libc::EFAULT; +use libc::EINVAL; +use libc::EIO; +use libc::ENOENT; +use libc::ENOSPC; +use libc::EOVERFLOW; +use libc::O_CLOEXEC; +use libc::O_RDWR; use sync::Mutex; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use x86_64::*; -use crate::{ - ClockState, Datamatch, DeviceKind, HypervHypercall, Hypervisor, HypervisorCap, IoEventAddress, - IoOperation, IoParams, IrqRoute, IrqSource, MPState, MemSlot, ProtectionType, Vcpu, VcpuExit, - VcpuRunHandle, Vm, VmCap, -}; +use crate::ClockState; +use crate::Datamatch; +use crate::DeviceKind; +use crate::HypervHypercall; +use crate::Hypervisor; +use crate::HypervisorCap; +use crate::IoEventAddress; +use crate::IoOperation; +use crate::IoParams; +use crate::IrqRoute; +use crate::IrqSource; +use crate::MPState; +use crate::MemSlot; +use crate::ProtectionType; +use crate::Vcpu; +use crate::VcpuExit; +use crate::VcpuRunHandle; +use crate::Vm; +use crate::VmCap; // Wrapper around KVM_SET_USER_MEMORY_REGION ioctl, which creates, modifies, or deletes a mapping // from guest physical to host user pages. @@ -1248,11 +1292,16 @@ impl From<&MPState> for kvm_mp_state { #[cfg(test)] mod tests { - use super::*; - use base::{pagesize, FromRawDescriptor, MemoryMappingArena, MemoryMappingBuilder}; use std::thread; + + use base::pagesize; + use base::FromRawDescriptor; + use base::MemoryMappingArena; + use base::MemoryMappingBuilder; use vm_memory::GuestAddress; + use super::*; + #[test] fn dirty_log_size() { let page_size = pagesize(); diff --git a/hypervisor/src/kvm/x86_64.rs b/hypervisor/src/kvm/x86_64.rs index adad6d95f..0158906e1 100644 --- a/hypervisor/src/kvm/x86_64.rs +++ b/hypervisor/src/kvm/x86_64.rs @@ -2,27 +2,60 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::IoctlNr; - -use libc::{E2BIG, ENXIO}; use std::arch::x86_64::CpuidResult; -use base::{ - errno_result, error, ioctl, ioctl_with_mut_ptr, ioctl_with_mut_ref, ioctl_with_ptr, - ioctl_with_ref, ioctl_with_val, AsRawDescriptor, Error, MappedRegion, Result, -}; +use base::errno_result; +use base::error; +use base::ioctl; +use base::ioctl_with_mut_ptr; +use base::ioctl_with_mut_ref; +use base::ioctl_with_ptr; +use base::ioctl_with_ref; +use base::ioctl_with_val; +use base::AsRawDescriptor; +use base::Error; +use base::IoctlNr; +use base::MappedRegion; +use base::Result; use data_model::vec_with_array_field; use kvm_sys::*; +use libc::E2BIG; +use libc::ENXIO; use vm_memory::GuestAddress; -use super::{Kvm, KvmVcpu, KvmVm}; -use crate::{ - get_tsc_offset_from_msr, host_phys_addr_bits, set_tsc_offset_via_msr, ClockState, CpuId, - CpuIdEntry, DebugRegs, DescriptorTable, DeviceKind, Fpu, HypervisorX86_64, - IoapicRedirectionTableEntry, IoapicState, IrqSourceChip, LapicState, PicSelect, PicState, - PitChannelState, PitState, ProtectionType, Register, Regs, Segment, Sregs, VcpuExit, - VcpuX86_64, VmCap, VmX86_64, MAX_IOAPIC_PINS, NUM_IOAPIC_PINS, -}; +use super::Kvm; +use super::KvmVcpu; +use super::KvmVm; +use crate::get_tsc_offset_from_msr; +use crate::host_phys_addr_bits; +use crate::set_tsc_offset_via_msr; +use crate::ClockState; +use crate::CpuId; +use crate::CpuIdEntry; +use crate::DebugRegs; +use crate::DescriptorTable; +use crate::DeviceKind; +use crate::Fpu; +use crate::HypervisorX86_64; +use crate::IoapicRedirectionTableEntry; +use crate::IoapicState; +use crate::IrqSourceChip; +use crate::LapicState; +use crate::PicSelect; +use crate::PicState; +use crate::PitChannelState; +use crate::PitState; +use crate::ProtectionType; +use crate::Register; +use crate::Regs; +use crate::Segment; +use crate::Sregs; +use crate::VcpuExit; +use crate::VcpuX86_64; +use crate::VmCap; +use crate::VmX86_64; +use crate::MAX_IOAPIC_PINS; +use crate::NUM_IOAPIC_PINS; type KvmCpuId = kvm::CpuId; @@ -1346,15 +1379,32 @@ fn to_kvm_msrs(vec: &[Register]) -> Vec { #[cfg(test)] mod tests { - use super::*; - use crate::{ - DeliveryMode, DeliveryStatus, DestinationMode, Hypervisor, HypervisorCap, HypervisorX86_64, - IoapicRedirectionTableEntry, IoapicState, IrqRoute, IrqSource, IrqSourceChip, LapicState, - PicInitState, PicState, PitChannelState, PitRWMode, PitRWState, PitState, TriggerMode, - Vcpu, Vm, - }; use libc::EINVAL; - use vm_memory::{GuestAddress, GuestMemory}; + use vm_memory::GuestAddress; + use vm_memory::GuestMemory; + + use super::*; + use crate::DeliveryMode; + use crate::DeliveryStatus; + use crate::DestinationMode; + use crate::Hypervisor; + use crate::HypervisorCap; + use crate::HypervisorX86_64; + use crate::IoapicRedirectionTableEntry; + use crate::IoapicState; + use crate::IrqRoute; + use crate::IrqSource; + use crate::IrqSourceChip; + use crate::LapicState; + use crate::PicInitState; + use crate::PicState; + use crate::PitChannelState; + use crate::PitRWMode; + use crate::PitRWState; + use crate::PitState; + use crate::TriggerMode; + use crate::Vcpu; + use crate::Vm; #[test] fn get_supported_cpuid() { diff --git a/hypervisor/src/lib.rs b/hypervisor/src/lib.rs index 562c166ea..c8ff612b9 100644 --- a/hypervisor/src/lib.rs +++ b/hypervisor/src/lib.rs @@ -18,10 +18,16 @@ pub mod x86_64; use std::os::raw::c_int; -use serde::{Deserialize, Serialize}; - -use base::{AsRawDescriptor, Event, MappedRegion, Protection, Result, SafeDescriptor}; -use vm_memory::{GuestAddress, GuestMemory}; +use base::AsRawDescriptor; +use base::Event; +use base::MappedRegion; +use base::Protection; +use base::Result; +use base::SafeDescriptor; +use serde::Deserialize; +use serde::Serialize; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] pub use crate::aarch64::*; @@ -213,7 +219,8 @@ impl VcpuRunHandle { /// `drop_fn`. pub fn new(drop_fn: fn()) -> Self { // Creates a probably unique number with a hash of the current thread id and epoch time. - use std::hash::{Hash, Hasher}; + use std::hash::Hash; + use std::hash::Hasher; let mut hasher = std::collections::hash_map::DefaultHasher::new(); std::time::Instant::now().hash(&mut hasher); std::thread::current().id().hash(&mut hasher); diff --git a/hypervisor/src/whpx.rs b/hypervisor/src/whpx.rs index 07363e6af..1de0cde2b 100644 --- a/hypervisor/src/whpx.rs +++ b/hypervisor/src/whpx.rs @@ -7,12 +7,20 @@ use core::ffi::c_void; use std::arch::x86_64::__cpuid_count; -use crate::{CpuId, CpuIdEntry, Hypervisor, HypervisorCap, HypervisorX86_64}; -use base::{error, warn, Error, Result}; +use base::error; +use base::warn; +use base::Error; +use base::Result; use once_cell::sync::Lazy; use thiserror::Error as ThisError; use winapi::shared::winerror::S_OK; +use crate::CpuId; +use crate::CpuIdEntry; +use crate::Hypervisor; +use crate::HypervisorCap; +use crate::HypervisorX86_64; + #[macro_export] macro_rules! check_whpx { ($x: expr) => {{ diff --git a/hypervisor/src/whpx/types.rs b/hypervisor/src/whpx/types.rs index a252c6217..a37da4b1d 100644 --- a/hypervisor/src/whpx/types.rs +++ b/hypervisor/src/whpx/types.rs @@ -7,7 +7,14 @@ use std::collections::HashMap; use once_cell::sync::Lazy; use super::whpx_sys::*; -use crate::{CpuIdEntry, DebugRegs, DescriptorTable, Fpu, LapicState, Regs, Segment, Sregs}; +use crate::CpuIdEntry; +use crate::DebugRegs; +use crate::DescriptorTable; +use crate::Fpu; +use crate::LapicState; +use crate::Regs; +use crate::Segment; +use crate::Sregs; #[derive(Default)] pub(super) struct WhpxRegs { diff --git a/hypervisor/src/whpx/vcpu.rs b/hypervisor/src/whpx/vcpu.rs index 90c751a37..907f600e9 100644 --- a/hypervisor/src/whpx/vcpu.rs +++ b/hypervisor/src/whpx/vcpu.rs @@ -3,7 +3,6 @@ // found in the LICENSE file. use core::ffi::c_void; -use libc::{EBUSY, EINVAL, ENOENT, ENXIO}; use std::arch::x86_64::CpuidResult; use std::cell::RefCell; use std::convert::TryInto; @@ -11,19 +10,34 @@ use std::mem::size_of; use std::os::raw::c_int; use std::sync::atomic::AtomicU64; use std::sync::Arc; -use winapi::shared::winerror::E_UNEXPECTED; -use base::{Error, Result}; +use base::Error; +use base::Result; +use libc::EBUSY; +use libc::EINVAL; +use libc::ENOENT; +use libc::ENXIO; use vm_memory::GuestAddress; +use winapi::shared::winerror::E_UNEXPECTED; use super::types::*; use super::*; - -use crate::{ - get_tsc_offset_from_msr, set_tsc_offset_via_msr, CpuId, CpuIdEntry, DebugRegs, Fpu, - HypervHypercall, IoOperation, IoParams, Register, Regs, Sregs, Vcpu, VcpuExit, VcpuRunHandle, - VcpuX86_64, -}; +use crate::get_tsc_offset_from_msr; +use crate::set_tsc_offset_via_msr; +use crate::CpuId; +use crate::CpuIdEntry; +use crate::DebugRegs; +use crate::Fpu; +use crate::HypervHypercall; +use crate::IoOperation; +use crate::IoParams; +use crate::Register; +use crate::Regs; +use crate::Sregs; +use crate::Vcpu; +use crate::VcpuExit; +use crate::VcpuRunHandle; +use crate::VcpuX86_64; const WHPX_EXIT_DIRECTION_MMIO_READ: u8 = 0; const WHPX_EXIT_DIRECTION_MMIO_WRITE: u8 = 1; @@ -1280,9 +1294,11 @@ fn get_msr_names(msrs: &[Register]) -> Vec { // run calls are tested with the integration tests since the full vcpu needs to be setup for it. #[cfg(test)] mod tests { + use vm_memory::GuestAddress; + use vm_memory::GuestMemory; + use super::*; use crate::VmX86_64; - use vm_memory::{GuestAddress, GuestMemory}; fn new_vm(cpu_count: usize, mem: GuestMemory) -> WhpxVm { let whpx = Whpx::new().expect("failed to instantiate whpx"); diff --git a/hypervisor/src/whpx/vm.rs b/hypervisor/src/whpx/vm.rs index 47d90b25d..284c282cd 100644 --- a/hypervisor/src/whpx/vm.rs +++ b/hypervisor/src/whpx/vm.rs @@ -2,31 +2,62 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::{ - error, info, pagesize, AsRawDescriptor, Error, Event, MappedRegion, MmapError, Protection, - RawDescriptor, Result, SafeDescriptor, -}; use core::ffi::c_void; -use fnv::FnvHashMap; -use libc::{EEXIST, EFAULT, EINVAL, EIO, ENODEV, ENOENT, ENOSPC, ENOTSUP, EOVERFLOW}; use std::cmp::Reverse; -use std::collections::{BTreeMap, BinaryHeap}; +use std::collections::BTreeMap; +use std::collections::BinaryHeap; use std::convert::TryInto; use std::sync::Arc; + +use base::error; +use base::info; +use base::pagesize; +use base::AsRawDescriptor; +use base::Error; +use base::Event; +use base::MappedRegion; +use base::MmapError; +use base::Protection; +use base::RawDescriptor; +use base::Result; +use base::SafeDescriptor; +use fnv::FnvHashMap; +use libc::EEXIST; +use libc::EFAULT; +use libc::EINVAL; +use libc::EIO; +use libc::ENODEV; +use libc::ENOENT; +use libc::ENOSPC; +use libc::ENOTSUP; +use libc::EOVERFLOW; use sync::Mutex; -use vm_memory::{GuestAddress, GuestMemory}; -use winapi::shared::winerror::{ERROR_BUSY, ERROR_SUCCESS}; -use winapi::um::memoryapi::{OfferVirtualMemory, ReclaimVirtualMemory, VmOfferPriorityBelowNormal}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +use winapi::shared::winerror::ERROR_BUSY; +use winapi::shared::winerror::ERROR_SUCCESS; +use winapi::um::memoryapi::OfferVirtualMemory; +use winapi::um::memoryapi::ReclaimVirtualMemory; +use winapi::um::memoryapi::VmOfferPriorityBelowNormal; use winapi::um::winnt::RtlZeroMemory; use super::types::*; use super::*; - +use crate::host_phys_addr_bits; use crate::whpx::whpx_sys::*; -use crate::{ - host_phys_addr_bits, ClockState, Datamatch, DeliveryMode, DestinationMode, DeviceKind, - IoEventAddress, LapicState, MemSlot, TriggerMode, VcpuX86_64, Vm, VmCap, VmX86_64, -}; +use crate::ClockState; +use crate::Datamatch; +use crate::DeliveryMode; +use crate::DestinationMode; +use crate::DeviceKind; +use crate::IoEventAddress; +use crate::LapicState; +use crate::MemSlot; +use crate::TriggerMode; +use crate::VcpuX86_64; +use crate::Vm; +use crate::VmCap; +use crate::VmX86_64; pub struct WhpxVm { whpx: Whpx, @@ -725,11 +756,15 @@ impl VmX86_64 for WhpxVm { // NOTE: WHPX Tests need to be run serially as otherwise it barfs unless we map new regions of guest memory. #[cfg(test)] mod tests { - use super::*; - use base::{EventReadResult, MemoryMappingBuilder, SharedMemory}; use std::thread; use std::time::Duration; + use base::EventReadResult; + use base::MemoryMappingBuilder; + use base::SharedMemory; + + use super::*; + fn new_vm(cpu_count: usize, mem: GuestMemory) -> WhpxVm { let whpx = Whpx::new().expect("failed to instantiate whpx"); let local_apic_supported = Whpx::check_whpx_feature(WhpxFeature::LocalApicEmulation) diff --git a/hypervisor/src/x86_64.rs b/hypervisor/src/x86_64.rs index 1cf85d427..feab14358 100644 --- a/hypervisor/src/x86_64.rs +++ b/hypervisor/src/x86_64.rs @@ -4,17 +4,25 @@ use std::arch::x86_64::CpuidResult; #[cfg(any(unix, feature = "haxm", feature = "whpx"))] -use std::arch::x86_64::{__cpuid, _rdtsc}; +use std::arch::x86_64::__cpuid; +#[cfg(any(unix, feature = "haxm", feature = "whpx"))] +use std::arch::x86_64::_rdtsc; -use serde::{Deserialize, Serialize}; - -use base::{error, Result}; +use base::error; +use base::Result; use bit_field::*; use downcast_rs::impl_downcast; - -use crate::{Hypervisor, IrqRoute, IrqSource, IrqSourceChip, Vcpu, Vm}; +use serde::Deserialize; +use serde::Serialize; use vm_memory::GuestAddress; +use crate::Hypervisor; +use crate::IrqRoute; +use crate::IrqSource; +use crate::IrqSourceChip; +use crate::Vcpu; +use crate::Vm; + /// A trait for managing cpuids for an x86_64 hypervisor and for checking its capabilities. pub trait HypervisorX86_64: Hypervisor { /// Get the system supported CPUID values. diff --git a/hypervisor/tests/dirty_log.rs b/hypervisor/tests/dirty_log.rs index 509a70d84..ee4ea4d35 100644 --- a/hypervisor/tests/dirty_log.rs +++ b/hypervisor/tests/dirty_log.rs @@ -6,9 +6,11 @@ #![cfg(unix)] #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use base::{MemoryMappingBuilder, SharedMemory}; +use base::MemoryMappingBuilder; +use base::SharedMemory; use hypervisor::*; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; #[test] #[cfg(unix)] diff --git a/hypervisor/tests/mmio_and_pio.rs b/hypervisor/tests/mmio_and_pio.rs index f74b5d37c..736947203 100644 --- a/hypervisor/tests/mmio_and_pio.rs +++ b/hypervisor/tests/mmio_and_pio.rs @@ -6,10 +6,12 @@ #![cfg(unix)] #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use std::sync::atomic::{AtomicU16, Ordering}; +use std::sync::atomic::AtomicU16; +use std::sync::atomic::Ordering; use hypervisor::*; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; #[test] #[cfg(unix)] diff --git a/hypervisor/tests/mmio_fetch_memory.rs b/hypervisor/tests/mmio_fetch_memory.rs index 2278d1e19..929500e18 100644 --- a/hypervisor/tests/mmio_fetch_memory.rs +++ b/hypervisor/tests/mmio_fetch_memory.rs @@ -6,10 +6,12 @@ // Test applies to whpx only. #![cfg(feature = "whpx")] -use std::sync::atomic::{AtomicU16, Ordering}; +use std::sync::atomic::AtomicU16; +use std::sync::atomic::Ordering; use hypervisor::*; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; // This test case is for the following scenario: // Test sets up a guest memory instruction page, such that an instruction diff --git a/hypervisor/tests/read_only_memory.rs b/hypervisor/tests/read_only_memory.rs index e6cefa765..22ace063b 100644 --- a/hypervisor/tests/read_only_memory.rs +++ b/hypervisor/tests/read_only_memory.rs @@ -6,11 +6,14 @@ #![cfg(unix)] #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use std::sync::atomic::{AtomicU16, Ordering}; +use std::sync::atomic::AtomicU16; +use std::sync::atomic::Ordering; -use base::{MemoryMappingBuilder, SharedMemory}; +use base::MemoryMappingBuilder; +use base::SharedMemory; use hypervisor::*; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; #[test] #[cfg(unix)] diff --git a/hypervisor/tests/real_run_addr.rs b/hypervisor/tests/real_run_addr.rs index 3bf7d9749..23d9f4566 100644 --- a/hypervisor/tests/real_run_addr.rs +++ b/hypervisor/tests/real_run_addr.rs @@ -6,10 +6,10 @@ #![cfg(unix)] #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use sync::Mutex; - use hypervisor::*; -use vm_memory::{GuestAddress, GuestMemory}; +use sync::Mutex; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; #[test] #[cfg(unix)] diff --git a/hypervisor/tests/remove_memory.rs b/hypervisor/tests/remove_memory.rs index ab4fc260b..3af62149d 100644 --- a/hypervisor/tests/remove_memory.rs +++ b/hypervisor/tests/remove_memory.rs @@ -6,9 +6,11 @@ #![cfg(unix)] #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use base::{MemoryMappingBuilder, SharedMemory}; +use base::MemoryMappingBuilder; +use base::SharedMemory; use hypervisor::*; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; #[test] #[cfg(unix)] diff --git a/hypervisor/tests/tsc_offsets.rs b/hypervisor/tests/tsc_offsets.rs index 8bc09c90f..c26b476d3 100644 --- a/hypervisor/tests/tsc_offsets.rs +++ b/hypervisor/tests/tsc_offsets.rs @@ -9,7 +9,8 @@ use std::arch::x86_64::_rdtsc; use hypervisor::*; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; macro_rules! assert_wrapping_close { ($value:expr, $expected: expr, $threshold: expr, $type: expr) => { diff --git a/integration_tests/guest_under_test/delegate.rs b/integration_tests/guest_under_test/delegate.rs index dd2f77ef7..ed57df727 100644 --- a/integration_tests/guest_under_test/delegate.rs +++ b/integration_tests/guest_under_test/delegate.rs @@ -8,7 +8,8 @@ use std::fs::File; use std::io; use std::io::prelude::*; use std::path::Path; -use std::process::{Command, Stdio}; +use std::process::Command; +use std::process::Stdio; use std::str; /// Device file to read from and write to. diff --git a/integration_tests/tests/boot.rs b/integration_tests/tests/boot.rs index cbf6b1f9f..8659f117b 100644 --- a/integration_tests/tests/boot.rs +++ b/integration_tests/tests/boot.rs @@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. mod fixture; -use fixture::{Config, TestVm}; +use fixture::Config; +use fixture::TestVm; #[test] fn boot_test_vm() { diff --git a/integration_tests/tests/fixture.rs b/integration_tests/tests/fixture.rs index bf6b73059..4cbf1f80e 100644 --- a/integration_tests/tests/fixture.rs +++ b/integration_tests/tests/fixture.rs @@ -2,21 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::env; use std::ffi::CString; use std::fs::File; use std::fs::OpenOptions; -use std::io::{self, BufRead, BufReader, Write}; +use std::io::BufRead; +use std::io::BufReader; +use std::io::Write; +use std::io::{self}; use std::os::unix::fs::OpenOptionsExt; -use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; +use std::path::Path; +use std::path::PathBuf; +use std::process::Child; +use std::process::Command; +use std::process::Stdio; use std::str::from_utf8; use std::sync::mpsc::sync_channel; use std::sync::Once; use std::thread; use std::time::Duration; -use std::{env, process::Child}; -use anyhow::{anyhow, Result}; +use anyhow::anyhow; +use anyhow::Result; use base::syslog; use libc::O_DIRECT; use tempfile::TempDir; diff --git a/io_uring/src/syscalls.rs b/io_uring/src/syscalls.rs index f3a3b41a0..94652507f 100644 --- a/io_uring/src/syscalls.rs +++ b/io_uring/src/syscalls.rs @@ -6,7 +6,12 @@ use std::io::Error; use std::os::unix::io::RawFd; use std::ptr::null_mut; -use libc::{c_int, c_long, c_void, syscall, SYS_io_uring_enter, SYS_io_uring_setup}; +use libc::c_int; +use libc::c_long; +use libc::c_void; +use libc::syscall; +use libc::SYS_io_uring_enter; +use libc::SYS_io_uring_setup; use crate::bindings::*; diff --git a/io_uring/src/uring.rs b/io_uring/src/uring.rs index 588985547..483311188 100644 --- a/io_uring/src/uring.rs +++ b/io_uring/src/uring.rs @@ -9,14 +9,23 @@ use std::collections::BTreeMap; use std::fs::File; use std::io; -use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::FromRawFd; +use std::os::unix::io::RawFd; use std::pin::Pin; -use std::sync::atomic::{AtomicPtr, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::AtomicPtr; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; -use base::{ - AsRawDescriptor, EventType, MappedRegion, MemoryMapping, MemoryMappingBuilder, Protection, - RawDescriptor, -}; +use base::AsRawDescriptor; +use base::EventType; +use base::MappedRegion; +use base::MemoryMapping; +use base::MemoryMappingBuilder; +use base::Protection; +use base::RawDescriptor; use data_model::IoBufMut; use remain::sorted; use sync::Mutex; @@ -902,18 +911,27 @@ impl QueuePointers { mod tests { use std::collections::BTreeSet; use std::fs::OpenOptions; - use std::io::{IoSlice, IoSliceMut}; - use std::io::{Read, Seek, SeekFrom, Write}; + use std::io::IoSlice; + use std::io::IoSliceMut; + use std::io::Read; + use std::io::Seek; + use std::io::SeekFrom; + use std::io::Write; use std::mem; - use std::path::{Path, PathBuf}; + use std::path::Path; + use std::path::PathBuf; use std::sync::mpsc::channel; - use std::sync::{Arc, Barrier}; + use std::sync::Arc; + use std::sync::Barrier; use std::thread; use std::time::Duration; - use base::{pipe, WaitContext}; - use sync::{Condvar, Mutex}; - use tempfile::{tempfile, TempDir}; + use base::pipe; + use base::WaitContext; + use sync::Condvar; + use sync::Mutex; + use tempfile::tempfile; + use tempfile::TempDir; use super::*; diff --git a/kernel_cmdline/src/kernel_cmdline.rs b/kernel_cmdline/src/kernel_cmdline.rs index 589fccf4f..be6d618fa 100644 --- a/kernel_cmdline/src/kernel_cmdline.rs +++ b/kernel_cmdline/src/kernel_cmdline.rs @@ -139,9 +139,10 @@ impl From for Vec { #[cfg(test)] mod tests { - use super::*; use std::ffi::CString; + use super::*; + #[test] fn insert_hello_world() { let mut cl = Cmdline::new(100); diff --git a/kernel_loader/src/lib.rs b/kernel_loader/src/lib.rs index c3b176880..bdbb9bc50 100644 --- a/kernel_loader/src/lib.rs +++ b/kernel_loader/src/lib.rs @@ -5,7 +5,9 @@ //! Linux kernel ELF file loader. use std::ffi::CStr; -use std::io::{Read, Seek, SeekFrom}; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; use std::mem; use base::AsRawDescriptor; @@ -13,7 +15,8 @@ use data_model::DataInit; use remain::sorted; use resources::AddressRange; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; #[allow(dead_code)] #[allow(non_camel_case_types)] @@ -380,11 +383,14 @@ impl From for elf::Elf64_Phdr { #[cfg(test)] mod test { - use super::*; use std::fs::File; use std::io::Write; + use tempfile::tempfile; - use vm_memory::{GuestAddress, GuestMemory}; + use vm_memory::GuestAddress; + use vm_memory::GuestMemory; + + use super::*; const MEM_SIZE: u64 = 0x40_0000; diff --git a/kvm/src/lib.rs b/kvm/src/lib.rs index 91a3f0a0a..fa93d544c 100644 --- a/kvm/src/lib.rs +++ b/kvm/src/lib.rs @@ -9,37 +9,81 @@ mod cap; use std::cell::RefCell; -use std::cmp::{min, Ordering}; -use std::collections::{BTreeMap, BinaryHeap}; +use std::cmp::min; +use std::cmp::Ordering; +use std::collections::BTreeMap; +use std::collections::BinaryHeap; use std::ffi::CString; use std::fs::File; use std::mem::size_of; -use std::ops::{Deref, DerefMut}; +use std::ops::Deref; +use std::ops::DerefMut; use std::os::raw::*; use std::os::unix::prelude::OsStrExt; -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::path::PathBuf; use std::ptr::copy_nonoverlapping; use std::sync::Arc; -use sync::Mutex; - -use base::{AsRawDescriptor, FromRawDescriptor, RawDescriptor}; -use data_model::vec_with_array_field; - -#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use data_model::FlexibleArrayWrapper; - -use libc::sigset_t; -use libc::{open, EBUSY, EINVAL, ENOENT, ENOSPC, EOVERFLOW, O_CLOEXEC, O_RDWR}; - -use kvm_sys::*; #[allow(unused_imports)] -use base::{ - block_signal, ioctl, ioctl_with_mut_ptr, ioctl_with_mut_ref, ioctl_with_ptr, ioctl_with_ref, - ioctl_with_val, pagesize, signal, unblock_signal, warn, Error, Event, IoctlNr, MappedRegion, - MemoryMapping, MemoryMappingBuilder, MmapError, Result, SIGRTMIN, -}; -use vm_memory::{GuestAddress, GuestMemory}; +use base::block_signal; +#[allow(unused_imports)] +use base::ioctl; +#[allow(unused_imports)] +use base::ioctl_with_mut_ptr; +#[allow(unused_imports)] +use base::ioctl_with_mut_ref; +#[allow(unused_imports)] +use base::ioctl_with_ptr; +#[allow(unused_imports)] +use base::ioctl_with_ref; +#[allow(unused_imports)] +use base::ioctl_with_val; +#[allow(unused_imports)] +use base::pagesize; +#[allow(unused_imports)] +use base::signal; +#[allow(unused_imports)] +use base::unblock_signal; +#[allow(unused_imports)] +use base::warn; +use base::AsRawDescriptor; +#[allow(unused_imports)] +use base::Error; +#[allow(unused_imports)] +use base::Event; +use base::FromRawDescriptor; +#[allow(unused_imports)] +use base::IoctlNr; +#[allow(unused_imports)] +use base::MappedRegion; +#[allow(unused_imports)] +use base::MemoryMapping; +#[allow(unused_imports)] +use base::MemoryMappingBuilder; +#[allow(unused_imports)] +use base::MmapError; +use base::RawDescriptor; +#[allow(unused_imports)] +use base::Result; +#[allow(unused_imports)] +use base::SIGRTMIN; +use data_model::vec_with_array_field; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use data_model::FlexibleArrayWrapper; +use kvm_sys::*; +use libc::open; +use libc::sigset_t; +use libc::EBUSY; +use libc::EINVAL; +use libc::ENOENT; +use libc::ENOSPC; +use libc::EOVERFLOW; +use libc::O_CLOEXEC; +use libc::O_RDWR; +use sync::Mutex; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; pub use crate::cap::*; diff --git a/kvm/tests/dirty_log.rs b/kvm/tests/dirty_log.rs index bfd0ec59a..347e68c58 100644 --- a/kvm/tests/dirty_log.rs +++ b/kvm/tests/dirty_log.rs @@ -4,10 +4,12 @@ #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use base::{MemoryMappingBuilder, SharedMemory}; +use base::MemoryMappingBuilder; +use base::SharedMemory; use kvm::*; use kvm_sys::kvm_regs; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; #[test] fn test_run() { diff --git a/kvm/tests/read_only_memory.rs b/kvm/tests/read_only_memory.rs index 91dc8728b..e205e9fe1 100644 --- a/kvm/tests/read_only_memory.rs +++ b/kvm/tests/read_only_memory.rs @@ -4,10 +4,12 @@ #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use base::{MemoryMappingBuilder, SharedMemory}; +use base::MemoryMappingBuilder; +use base::SharedMemory; use kvm::*; use kvm_sys::kvm_regs; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; #[test] fn test_run() { diff --git a/kvm/tests/real_run_adder.rs b/kvm/tests/real_run_adder.rs index a87e2586d..645963b1f 100644 --- a/kvm/tests/real_run_adder.rs +++ b/kvm/tests/real_run_adder.rs @@ -6,7 +6,8 @@ use kvm::*; use kvm_sys::kvm_regs; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; #[test] fn test_run() { diff --git a/kvm_sys/src/lib.rs b/kvm_sys/src/lib.rs index dd0271914..908d3b10b 100644 --- a/kvm_sys/src/lib.rs +++ b/kvm_sys/src/lib.rs @@ -8,7 +8,10 @@ #![allow(non_camel_case_types)] #![allow(non_snake_case)] -use base::{ioctl_io_nr, ioctl_ior_nr, ioctl_iow_nr, ioctl_iowr_nr}; +use base::ioctl_io_nr; +use base::ioctl_ior_nr; +use base::ioctl_iow_nr; +use base::ioctl_iowr_nr; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use data_model::flexible_array_impl; // Each of the below modules defines ioctls specific to their platform. @@ -23,8 +26,11 @@ pub mod x86 { // generated with bindgen /usr/include/linux/kvm.h --no-unstable-rust --constified-enum '*' --with-derive-default #[allow(clippy::all)] pub mod bindings; + use base::ioctl_ior_nr; + use base::ioctl_iow_nr; + use base::ioctl_iowr_nr; + pub use crate::bindings::*; - use base::{ioctl_ior_nr, ioctl_iow_nr, ioctl_iowr_nr}; ioctl_iowr_nr!(KVM_GET_MSR_INDEX_LIST, KVMIO, 0x02, kvm_msr_list); ioctl_iowr_nr!(KVM_GET_SUPPORTED_CPUID, KVMIO, 0x05, kvm_cpuid2); @@ -58,7 +64,8 @@ pub mod x86 { pub mod aarch64 { // generated with bindgen /usr/include/linux/kvm.h --no-unstable-rust --constified-enum '*' --with-derive-default -- -I/usr/include pub mod bindings; - use base::{ioctl_ior_nr, ioctl_iow_nr}; + use base::ioctl_ior_nr; + use base::ioctl_iow_nr; pub use bindings::*; ioctl_iow_nr!(KVM_ARM_SET_DEVICE_ADDR, KVMIO, 0xab, kvm_arm_device_addr); diff --git a/kvm_sys/tests/basic.rs b/kvm_sys/tests/basic.rs index d50ddc56e..a163159ec 100644 --- a/kvm_sys/tests/basic.rs +++ b/kvm_sys/tests/basic.rs @@ -4,9 +4,11 @@ #![cfg(not(any(target_os = "windows", target_arch = "arm")))] -use libc::{c_char, ioctl, open, O_RDWR}; - use kvm_sys::*; +use libc::c_char; +use libc::ioctl; +use libc::open; +use libc::O_RDWR; const KVM_PATH: &str = "/dev/kvm\0"; diff --git a/linux_input_sys/src/lib.rs b/linux_input_sys/src/lib.rs index d032a2abf..c1159e3f3 100644 --- a/linux_input_sys/src/lib.rs +++ b/linux_input_sys/src/lib.rs @@ -4,9 +4,12 @@ //! Linux input system bindings. -use data_model::{DataInit, Le16, SLe32}; use std::mem::size_of; +use data_model::DataInit; +use data_model::Le16; +use data_model::SLe32; + pub const EV_SYN: u16 = 0x00; pub const EV_KEY: u16 = 0x01; pub const EV_REL: u16 = 0x02; diff --git a/media/ffmpeg/src/avcodec.rs b/media/ffmpeg/src/avcodec.rs index 3fd124595..4b91b3369 100644 --- a/media/ffmpeg/src/avcodec.rs +++ b/media/ffmpeg/src/avcodec.rs @@ -6,9 +6,13 @@ //! designed to concentrate all calls to unsafe methods in one place, while providing the same //! low-level access as the libavcodec functions do. -use std::{ffi::CStr, fmt::Display, marker::PhantomData, ops::Deref}; +use std::ffi::CStr; +use std::fmt::Display; +use std::marker::PhantomData; +use std::ops::Deref; -use libc::{c_char, c_int}; +use libc::c_char; +use libc::c_int; use thiserror::Error as ThisError; use super::*; diff --git a/media/ffmpeg/src/lib.rs b/media/ffmpeg/src/lib.rs index 8082405e7..b444341dc 100644 --- a/media/ffmpeg/src/lib.rs +++ b/media/ffmpeg/src/lib.rs @@ -11,9 +11,7 @@ mod ffi; pub mod swscale; pub use ffi::AVPixelFormat_AV_PIX_FMT_NV12; - pub use ffi::AV_CODEC_CAP_DR1; - pub use ffi::FF_PROFILE_H264_BASELINE; pub use ffi::FF_PROFILE_H264_EXTENDED; pub use ffi::FF_PROFILE_H264_HIGH; @@ -23,12 +21,10 @@ pub use ffi::FF_PROFILE_H264_HIGH_444_PREDICTIVE; pub use ffi::FF_PROFILE_H264_MAIN; pub use ffi::FF_PROFILE_H264_MULTIVIEW_HIGH; pub use ffi::FF_PROFILE_H264_STEREO_HIGH; - +pub use ffi::FF_PROFILE_HEVC_MAIN; +pub use ffi::FF_PROFILE_HEVC_MAIN_10; +pub use ffi::FF_PROFILE_HEVC_MAIN_STILL_PICTURE; pub use ffi::FF_PROFILE_VP9_0; pub use ffi::FF_PROFILE_VP9_1; pub use ffi::FF_PROFILE_VP9_2; pub use ffi::FF_PROFILE_VP9_3; - -pub use ffi::FF_PROFILE_HEVC_MAIN; -pub use ffi::FF_PROFILE_HEVC_MAIN_10; -pub use ffi::FF_PROFILE_HEVC_MAIN_STILL_PICTURE; diff --git a/media/ffmpeg/src/swscale.rs b/media/ffmpeg/src/swscale.rs index 383e01b05..c6b502934 100644 --- a/media/ffmpeg/src/swscale.rs +++ b/media/ffmpeg/src/swscale.rs @@ -6,7 +6,9 @@ //! `libswscale`. It is designed to concentrate all calls to unsafe methods in one place, while //! providing a higher-level interface for converting decoded frames from one format to another. -use base::{MappedRegion, MemoryMappingArena, MmapError}; +use base::MappedRegion; +use base::MemoryMappingArena; +use base::MmapError; use thiserror::Error as ThisError; use crate::avcodec::AvFrame; diff --git a/media/libva/src/buffer.rs b/media/libva/src/buffer.rs index 3fb2f3a7c..05405e59f 100644 --- a/media/libva/src/buffer.rs +++ b/media/libva/src/buffer.rs @@ -7,10 +7,13 @@ use std::rc::Rc; use anyhow::Result; use base::error; -use crate::{ - bindings, buffer_type::BufferType, status::Status, Context, IQMatrix, PictureParameter, - SliceParameter, -}; +use crate::bindings; +use crate::buffer_type::BufferType; +use crate::status::Status; +use crate::Context; +use crate::IQMatrix; +use crate::PictureParameter; +use crate::SliceParameter; /// A wrapper type representing a buffer created with vaCreateBuffer pub struct Buffer { diff --git a/media/libva/src/config.rs b/media/libva/src/config.rs index 44ae8f17d..d06973c23 100644 --- a/media/libva/src/config.rs +++ b/media/libva/src/config.rs @@ -7,7 +7,10 @@ use std::rc::Rc; use anyhow::Result; use base::error; -use crate::{bindings, display::Display, generic_value::GenericValue, status::Status}; +use crate::bindings; +use crate::display::Display; +use crate::generic_value::GenericValue; +use crate::status::Status; /// An owned VAConfig that is tied to the lifetime of a particular VADisplay pub struct Config { diff --git a/media/libva/src/context.rs b/media/libva/src/context.rs index d2e8655ca..2536b466e 100644 --- a/media/libva/src/context.rs +++ b/media/libva/src/context.rs @@ -7,10 +7,13 @@ use std::rc::Rc; use anyhow::Result; use base::error; -use crate::{ - bindings, buffer::Buffer, buffer_type::BufferType, display::Display, status::Status, Config, - Surface, -}; +use crate::bindings; +use crate::buffer::Buffer; +use crate::buffer_type::BufferType; +use crate::display::Display; +use crate::status::Status; +use crate::Config; +use crate::Surface; /// An owned Context that is tied to the lifetime of a particular Display pub struct Context { diff --git a/media/libva/src/display.rs b/media/libva/src/display.rs index 2bac52cb8..ba981967b 100644 --- a/media/libva/src/display.rs +++ b/media/libva/src/display.rs @@ -2,15 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ffi::CStr, fs::File, rc::Rc}; +use std::ffi::CStr; +use std::fs::File; +use std::rc::Rc; +use anyhow::anyhow; use anyhow::Context as AnyhowContext; -use anyhow::{anyhow, Result}; +use anyhow::Result; use base::AsRawDescriptor; -use crate::{ - bindings, config::Config, context::Context, status::Status, surface::Surface, UsageHint, -}; +use crate::bindings; +use crate::config::Config; +use crate::context::Context; +use crate::status::Status; +use crate::surface::Surface; +use crate::UsageHint; /// An owned VADisplay pub struct Display { diff --git a/media/libva/src/generic_value.rs b/media/libva/src/generic_value.rs index 48a26eaca..794619e3b 100644 --- a/media/libva/src/generic_value.rs +++ b/media/libva/src/generic_value.rs @@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use anyhow::{anyhow, Result}; +use anyhow::anyhow; +use anyhow::Result; use crate::bindings; diff --git a/media/libva/src/image.rs b/media/libva/src/image.rs index 3192c443c..d5c3d129b 100644 --- a/media/libva/src/image.rs +++ b/media/libva/src/image.rs @@ -4,11 +4,10 @@ use anyhow::Result; -use crate::{ - bindings, - picture::{Picture, PictureSync}, - status::Status, -}; +use crate::bindings; +use crate::picture::Picture; +use crate::picture::PictureSync; +use crate::status::Status; /// An owned VAImage that is tied to the lifetime of a given Picture. /// A VAImage is used to either get the surface data to client memory, or diff --git a/media/libva/src/picture.rs b/media/libva/src/picture.rs index c23f37141..01c9e4b00 100644 --- a/media/libva/src/picture.rs +++ b/media/libva/src/picture.rs @@ -2,11 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{marker::PhantomData, rc::Rc}; +use std::marker::PhantomData; +use std::rc::Rc; use anyhow::Result; -use crate::{bindings, buffer::Buffer, context::Context, status::Status, surface::Surface}; +use crate::bindings; +use crate::buffer::Buffer; +use crate::context::Context; +use crate::status::Status; +use crate::surface::Surface; // Use the sealed trait pattern to make sure that new states are not created in // caller code. More information about the sealed trait pattern can be found at diff --git a/media/libva/src/status.rs b/media/libva/src/status.rs index 9844e1546..68093823f 100644 --- a/media/libva/src/status.rs +++ b/media/libva/src/status.rs @@ -4,7 +4,8 @@ use std::ffi::CStr; -use anyhow::{anyhow, Result}; +use anyhow::anyhow; +use anyhow::Result; use crate::bindings; diff --git a/media/libva/src/surface.rs b/media/libva/src/surface.rs index b4222141c..ebc220c24 100644 --- a/media/libva/src/surface.rs +++ b/media/libva/src/surface.rs @@ -6,7 +6,10 @@ use std::rc::Rc; use anyhow::Result; -use crate::{bindings, display::Display, status::Status, UsageHint}; +use crate::bindings; +use crate::display::Display; +use crate::status::Status; +use crate::UsageHint; /// An owned VASurface that is tied to the lifetime of a particular VADisplay pub struct Surface { diff --git a/media/libvda/src/decode/event.rs b/media/libvda/src/decode/event.rs index 4e365b741..3a4658564 100644 --- a/media/libvda/src/decode/event.rs +++ b/media/libvda/src/decode/event.rs @@ -4,8 +4,10 @@ //! Events reported by VDA over pipe FD. +use std::fmt::Display; +use std::fmt::{self}; + use enumn::N; -use std::fmt::{self, Display}; use super::bindings; use crate::error::*; diff --git a/media/libvda/src/decode/session.rs b/media/libvda/src/decode/session.rs index dada37b5e..0a8f018d6 100644 --- a/media/libvda/src/decode/session.rs +++ b/media/libvda/src/decode/session.rs @@ -2,15 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::fs::File; use std::io::Read; use std::mem; use std::os::unix::io::FromRawFd; -use std::{fs::File, rc::Rc}; +use std::rc::Rc; +use super::bindings; use super::event::*; -use super::{bindings, VdaConnection}; +use super::VdaConnection; use crate::error::*; -use crate::format::{BufferFd, FramePlane, PixelFormat, Profile}; +use crate::format::BufferFd; +use crate::format::FramePlane; +use crate::format::PixelFormat; +use crate::format::Profile; /// Represents a decode session. pub struct Session { diff --git a/media/libvda/src/decode/vda_instance.rs b/media/libvda/src/decode/vda_instance.rs index 1789677d5..e0a0b375c 100644 --- a/media/libvda/src/decode/vda_instance.rs +++ b/media/libvda/src/decode/vda_instance.rs @@ -5,7 +5,8 @@ //! This module provides type safe interfaces for each operation exposed by Chrome's //! VideoDecodeAccelerator. -use std::{os::raw::c_void, rc::Rc}; +use std::os::raw::c_void; +use std::rc::Rc; use super::bindings; use super::format::*; diff --git a/media/libvda/src/encode/event.rs b/media/libvda/src/encode/event.rs index 93c8aa11c..24b4b0dad 100644 --- a/media/libvda/src/encode/event.rs +++ b/media/libvda/src/encode/event.rs @@ -4,12 +4,15 @@ //! Events reported by VDA encode API over pipe FD. -use enumn::N; use std::error; -use std::fmt::{self, Display}; +use std::fmt::Display; +use std::fmt::{self}; + +use enumn::N; use super::bindings; -use super::session::{VeaInputBufferId, VeaOutputBufferId}; +use super::session::VeaInputBufferId; +use super::session::VeaOutputBufferId; use crate::error::*; /// Represents an error from a libvda encode session. diff --git a/media/libvda/src/encode/format.rs b/media/libvda/src/encode/format.rs index 7b802f1db..3d2c9c569 100644 --- a/media/libvda/src/encode/format.rs +++ b/media/libvda/src/encode/format.rs @@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use enumn::N; + use super::bindings; use crate::error::Result; use crate::format::*; -use enumn::N; /// Represents an output profile for VEA. #[derive(Debug, Clone, Copy)] diff --git a/media/libvda/src/encode/session.rs b/media/libvda/src/encode/session.rs index 7e5168aac..df7b443ef 100644 --- a/media/libvda/src/encode/session.rs +++ b/media/libvda/src/encode/session.rs @@ -2,17 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::fs::File; use std::io::Read; use std::mem; use std::os::unix::io::FromRawFd; -use std::{fs::File, rc::Rc}; +use std::rc::Rc; +use super::bindings; use super::event::*; use super::format::Bitrate; use super::vea_instance::Config; -use super::{bindings, VeaConnection}; +use super::VeaConnection; use crate::error::*; -use crate::format::{BufferFd, FramePlane}; +use crate::format::BufferFd; +use crate::format::FramePlane; pub type VeaInputBufferId = bindings::vea_input_buffer_id_t; pub type VeaOutputBufferId = bindings::vea_output_buffer_id_t; diff --git a/media/libvda/src/encode/vea_instance.rs b/media/libvda/src/encode/vea_instance.rs index c628e7a3d..d371cadf6 100644 --- a/media/libvda/src/encode/vea_instance.rs +++ b/media/libvda/src/encode/vea_instance.rs @@ -2,10 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{os::raw::c_void, rc::Rc}; +use std::os::raw::c_void; +use std::rc::Rc; use super::bindings; -use super::format::{Bitrate, OutputProfile}; +use super::format::Bitrate; +use super::format::OutputProfile; use super::session::*; use crate::error::*; use crate::format::*; diff --git a/media/libvda/src/error.rs b/media/libvda/src/error.rs index 791ca396a..d1236f717 100644 --- a/media/libvda/src/error.rs +++ b/media/libvda/src/error.rs @@ -5,7 +5,8 @@ //! Errors that can happen in LibVDA. use std::error; -use std::fmt::{self, Display}; +use std::fmt::Display; +use std::fmt::{self}; use super::format; use crate::decode; diff --git a/media/libvda/src/format.rs b/media/libvda/src/format.rs index 6a77cf953..c7e114c48 100644 --- a/media/libvda/src/format.rs +++ b/media/libvda/src/format.rs @@ -4,9 +4,10 @@ //! Data structures representing coded/raw formats. -use enumn::N; use std::os::unix::io::RawFd; +use enumn::N; + use super::bindings; use super::error::*; diff --git a/media/vp8/src/bool_decoder.rs b/media/vp8/src/bool_decoder.rs index 51bce6ac7..a41c5ac51 100644 --- a/media/vp8/src/bool_decoder.rs +++ b/media/vp8/src/bool_decoder.rs @@ -3,9 +3,12 @@ // found in the LICENSE file. /// A VP8 boolean decoder based on the implementation in Chromium and GStreamer. -use std::{convert::TryFrom, io::Cursor}; +use std::convert::TryFrom; +/// A VP8 boolean decoder based on the implementation in Chromium and GStreamer. +use std::io::Cursor; -use anyhow::{anyhow, Result}; +use anyhow::anyhow; +use anyhow::Result; use bytes::Buf; const LOTS_OF_BITS: u32 = 0x40000000; diff --git a/media/vp8/src/parser.rs b/media/vp8/src/parser.rs index 8b9a2adf3..ba638cdcc 100644 --- a/media/vp8/src/parser.rs +++ b/media/vp8/src/parser.rs @@ -5,15 +5,20 @@ use std::convert::TryFrom; use std::io::Cursor; -use anyhow::{anyhow, Result}; +use anyhow::anyhow; +use anyhow::Result; use bytes::Buf; use log::debug; use crate::bool_decoder::BoolDecoder; -use crate::probs::{ - COEFF_DEFAULT_PROBS, COEFF_UPDATE_PROBS, KF_UV_MODE_PROBS, KF_Y_MODE_PROBS, MV_DEFAULT_PROBS, - MV_UPDATE_PROBS, NK_UV_MODE_PROBS, NK_Y_MODE_PROBS, -}; +use crate::probs::COEFF_DEFAULT_PROBS; +use crate::probs::COEFF_UPDATE_PROBS; +use crate::probs::KF_UV_MODE_PROBS; +use crate::probs::KF_Y_MODE_PROBS; +use crate::probs::MV_DEFAULT_PROBS; +use crate::probs::MV_UPDATE_PROBS; +use crate::probs::NK_UV_MODE_PROBS; +use crate::probs::NK_Y_MODE_PROBS; /// Dequantization indices as parsed from the quant_indices() syntax. #[derive(Clone, Default)] diff --git a/metrics/build.rs b/metrics/build.rs index 039686e84..b74e07698 100644 --- a/metrics/build.rs +++ b/metrics/build.rs @@ -2,11 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use protoc_rust::{Codegen, Customize}; +use std::env; +use std::fs; use std::fs::File; use std::io::Write; use std::path::PathBuf; -use std::{env, fs}; + +use protoc_rust::Codegen; +use protoc_rust::Customize; fn main() { build_protos(); diff --git a/metrics/src/controller.rs b/metrics/src/controller.rs index 27f9ef8f3..f7b05c665 100644 --- a/metrics/src/controller.rs +++ b/metrics/src/controller.rs @@ -4,10 +4,14 @@ //! Encapsulate the main runtime loop of a metrics process. +use anyhow::Result; +use base::info; +use base::warn; +use base::EventToken; +use base::Tube; + use crate::metrics_requests::MetricsRequest; use crate::RequestHandler; -use anyhow::Result; -use base::{info, warn, EventToken, Tube}; /// Handles incoming requests to log metrics pub(crate) trait MetricsRequestHandler { diff --git a/metrics/src/event_types.rs b/metrics/src/event_types.rs index 7dd834b85..5ec233a52 100644 --- a/metrics/src/event_types.rs +++ b/metrics/src/event_types.rs @@ -2,11 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use anyhow::Error; -use serde::{Deserialize, Serialize}; use std::convert::From; use std::convert::TryFrom; +use anyhow::Error; +use serde::Deserialize; +use serde::Serialize; + // TODO(mikehoyle): Create a way to generate these directly from the // proto for a single source-of-truth. #[derive(Copy, Clone, Debug, Serialize, Deserialize)] diff --git a/metrics/src/metrics_requests.rs b/metrics/src/metrics_requests.rs index 4f536df9e..de4b9d519 100644 --- a/metrics/src/metrics_requests.rs +++ b/metrics/src/metrics_requests.rs @@ -4,8 +4,10 @@ //! Structs used to transport log requests between client processes and the logging controller +use serde::Deserialize; +use serde::Serialize; + use crate::MetricEventType; -use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub struct LogMetric { diff --git a/metrics/src/noop/client.rs b/metrics/src/noop/client.rs index 16d87795d..c170bd176 100644 --- a/metrics/src/noop/client.rs +++ b/metrics/src/noop/client.rs @@ -2,9 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{event_details_proto::RecordDetails, MetricEventType, MetricsClientDestructor}; use base::Tube; +use crate::event_details_proto::RecordDetails; +use crate::MetricEventType; +use crate::MetricsClientDestructor; + /// This interface exists to be used and re-implemented by downstream forks. Updates shouldn't be /// done without ensuring they won't cause breakages in dependent codebases. pub fn initialize(_: Tube) {} diff --git a/metrics/src/noop/periodic_logger.rs b/metrics/src/noop/periodic_logger.rs index 3870f0961..0ec4be5d4 100644 --- a/metrics/src/noop/periodic_logger.rs +++ b/metrics/src/noop/periodic_logger.rs @@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::MetricEventType; use std::result::Result; use std::time::Duration; +use crate::MetricEventType; + /// A logging struct meant for use in tracking and periodically /// logging a single metric. The metric is aggregated over the /// designated time period. Intended for use with high-frequency metrics. diff --git a/metrics/src/sys/unix/controller.rs b/metrics/src/sys/unix/controller.rs index 3de41e487..42a5043a2 100644 --- a/metrics/src/sys/unix/controller.rs +++ b/metrics/src/sys/unix/controller.rs @@ -2,9 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::controller::{MetricsController, MetricsControllerToken}; use anyhow::Result; -use base::{ReadNotifier, WaitContext}; +use base::ReadNotifier; +use base::WaitContext; + +use crate::controller::MetricsController; +use crate::controller::MetricsControllerToken; impl MetricsController { pub(crate) fn run_internal(&mut self) -> Result<()> { diff --git a/metrics/src/sys/windows/controller.rs b/metrics/src/sys/windows/controller.rs index e2fe757f3..18c9be459 100644 --- a/metrics/src/sys/windows/controller.rs +++ b/metrics/src/sys/windows/controller.rs @@ -2,9 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::controller::{MetricsController, MetricsControllerToken}; use anyhow::Result; -use base::{CloseNotifier, ReadNotifier, WaitContext}; +use base::CloseNotifier; +use base::ReadNotifier; +use base::WaitContext; + +use crate::controller::MetricsController; +use crate::controller::MetricsControllerToken; impl MetricsController { pub(crate) fn run_internal(&mut self) -> Result<()> { diff --git a/metrics/src/sys/windows/gpu_metrics.rs b/metrics/src/sys/windows/gpu_metrics.rs index e2310ec0f..cefa7186c 100644 --- a/metrics/src/sys/windows/gpu_metrics.rs +++ b/metrics/src/sys/windows/gpu_metrics.rs @@ -2,11 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::windows::system_metrics::CoreWinMetrics; -use crate::windows::{Error, Result}; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; use std::sync::Arc; +use crate::windows::system_metrics::CoreWinMetrics; +use crate::windows::Error; +use crate::windows::Result; + static INSTANCE_EXISTS: AtomicBool = AtomicBool::new(false); /// Used by gpu_display to show metrics in the CrosVm performance overlay. diff --git a/metrics/src/sys/windows/system_metrics.rs b/metrics/src/sys/windows/system_metrics.rs index ff57168ab..19964be70 100644 --- a/metrics/src/sys/windows/system_metrics.rs +++ b/metrics/src/sys/windows/system_metrics.rs @@ -2,32 +2,46 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::windows::{Error, Result, METRIC_UPLOAD_INTERVAL_SECONDS}; -use crate::{log_metric, MetricEventType}; - -use base::{ - error, AsRawDescriptor, Error as SysError, Event, EventToken, FromRawDescriptor, - SafeDescriptor, WaitContext, -}; - -use chrono::{DateTime, Local}; use std::fmt; use std::mem; -use std::sync::{Arc, Mutex, Weak}; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::Weak; use std::thread; use std::thread::JoinHandle; use std::time::Duration; -use winapi::shared::minwindef::{DWORD, FILETIME}; -use winapi::um::processthreadsapi::{GetProcessTimes, GetSystemTimes, OpenProcess}; -use winapi::um::psapi::{ - GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, PROCESS_MEMORY_COUNTERS_EX, -}; +use base::error; +use base::AsRawDescriptor; +use base::Error as SysError; +use base::Event; +use base::EventToken; +use base::FromRawDescriptor; +use base::SafeDescriptor; +use base::WaitContext; +use chrono::DateTime; +use chrono::Local; +use winapi::shared::minwindef::DWORD; +use winapi::shared::minwindef::FILETIME; +use winapi::um::processthreadsapi::GetProcessTimes; +use winapi::um::processthreadsapi::GetSystemTimes; +use winapi::um::processthreadsapi::OpenProcess; +use winapi::um::psapi::GetProcessMemoryInfo; +use winapi::um::psapi::PROCESS_MEMORY_COUNTERS; +use winapi::um::psapi::PROCESS_MEMORY_COUNTERS_EX; use winapi::um::winbase::GetProcessIoCounters; -use winapi::um::winnt::{ - IO_COUNTERS, LARGE_INTEGER, LONGLONG, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_VM_READ, - SYNCHRONIZE, -}; +use winapi::um::winnt::IO_COUNTERS; +use winapi::um::winnt::LARGE_INTEGER; +use winapi::um::winnt::LONGLONG; +use winapi::um::winnt::PROCESS_QUERY_LIMITED_INFORMATION; +use winapi::um::winnt::PROCESS_VM_READ; +use winapi::um::winnt::SYNCHRONIZE; + +use crate::log_metric; +use crate::windows::Error; +use crate::windows::Result; +use crate::windows::METRIC_UPLOAD_INTERVAL_SECONDS; +use crate::MetricEventType; const BYTES_PER_MB: usize = 1024 * 1024; const WORKER_REPORT_INTERVAL: Duration = Duration::from_secs(1); diff --git a/metrics/src/sys/windows/wmi.rs b/metrics/src/sys/windows/wmi.rs index 9d45ffea2..5ba50ec05 100644 --- a/metrics/src/sys/windows/wmi.rs +++ b/metrics/src/sys/windows/wmi.rs @@ -9,12 +9,16 @@ interface and conform to the windows naming convension. #![allow(non_camel_case_types)] #![allow(non_snake_case)] -use serde::{de::DeserializeOwned, Deserialize}; -use { - base::warn, - std::{collections::HashMap, error::Error, rc::Rc}, - wmi::{query::FilterValue, COMLibrary, WMIConnection}, -}; +use std::collections::HashMap; +use std::error::Error; +use std::rc::Rc; + +use base::warn; +use serde::de::DeserializeOwned; +use serde::Deserialize; +use wmi::query::FilterValue; +use wmi::COMLibrary; +use wmi::WMIConnection; const VIDEO_CONTROLLER_AVAILABILITY_ENABLED: i64 = 3; diff --git a/net_sys/src/lib.rs b/net_sys/src/lib.rs index d7be6440d..baac2a8c8 100644 --- a/net_sys/src/lib.rs +++ b/net_sys/src/lib.rs @@ -8,16 +8,24 @@ #![allow(non_camel_case_types)] #![allow(non_snake_case)] -use base::{ioctl_ior_nr, ioctl_iow_nr}; +use base::ioctl_ior_nr; +use base::ioctl_iow_nr; pub mod if_tun; pub mod iff; // Named "iff" to avoid conflicting with "if" keyword. pub mod sockios; -pub use crate::if_tun::{ - sock_fprog, IFF_MULTI_QUEUE, IFF_NO_PI, IFF_TAP, IFF_VNET_HDR, TUN_F_CSUM, TUN_F_TSO4, - TUN_F_TSO6, TUN_F_TSO_ECN, TUN_F_UFO, -}; -pub use crate::iff::{ifreq, net_device_flags}; +pub use crate::if_tun::sock_fprog; +pub use crate::if_tun::IFF_MULTI_QUEUE; +pub use crate::if_tun::IFF_NO_PI; +pub use crate::if_tun::IFF_TAP; +pub use crate::if_tun::IFF_VNET_HDR; +pub use crate::if_tun::TUN_F_CSUM; +pub use crate::if_tun::TUN_F_TSO4; +pub use crate::if_tun::TUN_F_TSO6; +pub use crate::if_tun::TUN_F_TSO_ECN; +pub use crate::if_tun::TUN_F_UFO; +pub use crate::iff::ifreq; +pub use crate::iff::net_device_flags; pub const TUNTAP: ::std::os::raw::c_uint = 84; diff --git a/net_util/src/lib.rs b/net_util/src/lib.rs index c93ba5025..0c2b4e3da 100644 --- a/net_util/src/lib.rs +++ b/net_util/src/lib.rs @@ -15,18 +15,22 @@ //! Captures packets in a ring buffer and dumps them to a pcap file on exit. pub mod sys; -use std::fmt::{self, Display}; -use std::io::{Read, Write}; +use std::fmt::Display; +use std::fmt::{self}; +use std::io::Read; +use std::io::Write; use std::net; use std::num::ParseIntError; use std::os::raw::*; use std::str::FromStr; -pub use sys::TapT; +use base::AsRawDescriptor; use base::Error as SysError; -use base::{AsRawDescriptor, RawDescriptor}; +use base::RawDescriptor; use remain::sorted; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; +pub use sys::TapT; use thiserror::Error as ThisError; #[sorted] diff --git a/net_util/src/slirp/packet_ring_buffer.rs b/net_util/src/slirp/packet_ring_buffer.rs index 583e0eeae..ab33baa0f 100644 --- a/net_util/src/slirp/packet_ring_buffer.rs +++ b/net_util/src/slirp/packet_ring_buffer.rs @@ -2,11 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use pcap_file::pcap::PacketHeader; use std::collections::VecDeque; -use std::fmt::{self, Display}; +use std::fmt::Display; +use std::fmt::{self}; use std::time::Duration; +use pcap_file::pcap::PacketHeader; + const PACKET_HEADER_SIZE_IN_BYTES: usize = std::mem::size_of::(); /// A wrapper around a ringer buffer that stores packet information. diff --git a/net_util/src/slirp/sys.rs b/net_util/src/slirp/sys.rs index e4f068385..feaed4046 100644 --- a/net_util/src/slirp/sys.rs +++ b/net_util/src/slirp/sys.rs @@ -11,4 +11,5 @@ cfg_if::cfg_if! { } } -pub use platform::{handler, Slirp}; +pub use platform::handler; +pub use platform::Slirp; diff --git a/net_util/src/slirp/sys/windows.rs b/net_util/src/slirp/sys/windows.rs index 3fed7442d..3125fe3c1 100644 --- a/net_util/src/slirp/sys/windows.rs +++ b/net_util/src/slirp/sys/windows.rs @@ -4,21 +4,37 @@ pub mod handler; -use crate::{slirp::ETHERNET_FRAME_SIZE, Error, MacAddress, Result, TapT, TapTCommon}; -use std::io::{Read, Result as IoResult, Write}; +use std::io::Read; +use std::io::Result as IoResult; +use std::io::Write; use std::net; use std::os::raw::*; use std::os::windows::io::AsRawHandle; use std::thread; -use base::named_pipes::{ - self, BlockingMode, FramingMode, OverlappedWrapper, PipeConnection, ReadOverlapped, - WriteOverlapped, -}; -use base::{warn, AsRawDescriptor, Event, RawDescriptor}; -use base::{Error as SysError, ReadNotifier}; +use base::named_pipes::BlockingMode; +use base::named_pipes::FramingMode; +use base::named_pipes::OverlappedWrapper; +use base::named_pipes::PipeConnection; +use base::named_pipes::ReadOverlapped; +use base::named_pipes::WriteOverlapped; +use base::named_pipes::{self}; +use base::warn; +use base::AsRawDescriptor; +use base::Error as SysError; +use base::Event; +use base::RawDescriptor; +use base::ReadNotifier; use cros_async::IntoAsync; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; + +use crate::slirp::ETHERNET_FRAME_SIZE; +use crate::Error; +use crate::MacAddress; +use crate::Result; +use crate::TapT; +use crate::TapTCommon; // Size of the buffer for packets in transit between the the virtio-net backend & Slirp. pub const SLIRP_BUFFER_SIZE: usize = 1000 * ETHERNET_FRAME_SIZE; diff --git a/net_util/src/slirp/sys/windows/handler.rs b/net_util/src/slirp/sys/windows/handler.rs index a19b4a899..0e905e176 100644 --- a/net_util/src/slirp/sys/windows/handler.rs +++ b/net_util/src/slirp/sys/windows/handler.rs @@ -2,38 +2,68 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::slirp::context::{CallbackHandler, Context, PollEvents}; -#[cfg(feature = "slirp-ring-capture")] -use crate::slirp::packet_ring_buffer::PacketRingBuffer; -use crate::{slirp::ETHERNET_FRAME_SIZE, Error, Result}; - -use base::named_pipes::{OverlappedWrapper, PipeConnection}; -use base::{ - error, warn, AsRawDescriptor, Descriptor, Event, EventToken, EventWindows, RawDescriptor, - WaitContext, -}; -use base::{Error as SysError, Timer}; -use data_model::{DataInit, Le16}; -use metrics::{MetricEventType, PeriodicLogger}; -#[cfg(any(feature = "slirp-ring-capture", feature = "slirp-debug"))] -use pcap_file::pcap::PcapWriter; -use smallvec::SmallVec; use std::collections::HashMap; #[cfg(any(feature = "slirp-ring-capture", feature = "slirp-debug"))] use std::fs::File; use std::io; #[cfg(any(feature = "slirp-ring-capture", feature = "slirp-debug"))] use std::io::BufWriter; -use std::net::{Ipv4Addr, Ipv6Addr}; +use std::net::Ipv4Addr; +use std::net::Ipv6Addr; use std::time::Duration; use std::time::Instant; -use virtio_sys::{virtio_net_hdr, virtio_net_hdr_mrg_rxbuf}; + +use base::error; +use base::named_pipes::OverlappedWrapper; +use base::named_pipes::PipeConnection; +use base::warn; +use base::AsRawDescriptor; +use base::Descriptor; +use base::Error as SysError; +use base::Event; +use base::EventToken; +use base::EventWindows; +use base::RawDescriptor; +use base::Timer; +use base::WaitContext; +use data_model::DataInit; +use data_model::Le16; +use metrics::MetricEventType; +use metrics::PeriodicLogger; +#[cfg(any(feature = "slirp-ring-capture", feature = "slirp-debug"))] +use pcap_file::pcap::PcapWriter; +use smallvec::SmallVec; +use virtio_sys::virtio_net_hdr; +use virtio_sys::virtio_net_hdr_mrg_rxbuf; use winapi::shared::minwindef::MAKEWORD; -use winapi::um::winnt::{LONG, SHORT}; -use winapi::um::winsock2::{ - WSACleanup, WSAEventSelect, WSAGetLastError, WSAPoll, WSAStartup, FD_CLOSE, FD_READ, FD_WRITE, - POLLERR, POLLHUP, POLLRDBAND, POLLRDNORM, POLLWRNORM, SOCKET, SOCKET_ERROR, WSADATA, WSAPOLLFD, -}; +use winapi::um::winnt::LONG; +use winapi::um::winnt::SHORT; +use winapi::um::winsock2::WSACleanup; +use winapi::um::winsock2::WSAEventSelect; +use winapi::um::winsock2::WSAGetLastError; +use winapi::um::winsock2::WSAPoll; +use winapi::um::winsock2::WSAStartup; +use winapi::um::winsock2::FD_CLOSE; +use winapi::um::winsock2::FD_READ; +use winapi::um::winsock2::FD_WRITE; +use winapi::um::winsock2::POLLERR; +use winapi::um::winsock2::POLLHUP; +use winapi::um::winsock2::POLLRDBAND; +use winapi::um::winsock2::POLLRDNORM; +use winapi::um::winsock2::POLLWRNORM; +use winapi::um::winsock2::SOCKET; +use winapi::um::winsock2::SOCKET_ERROR; +use winapi::um::winsock2::WSADATA; +use winapi::um::winsock2::WSAPOLLFD; + +use crate::slirp::context::CallbackHandler; +use crate::slirp::context::Context; +use crate::slirp::context::PollEvents; +#[cfg(feature = "slirp-ring-capture")] +use crate::slirp::packet_ring_buffer::PacketRingBuffer; +use crate::slirp::ETHERNET_FRAME_SIZE; +use crate::Error; +use crate::Result; #[cfg(any(feature = "slirp-ring-capture", feature = "slirp-debug"))] const SLIRP_CAPTURE_FILE_NAME: &str = "slirp_capture.pcap"; @@ -666,13 +696,16 @@ fn create_slirp_context( #[cfg(test)] mod tests { - use super::super::SLIRP_BUFFER_SIZE; - use super::*; - use base::named_pipes; - use base::named_pipes::{BlockingMode, FramingMode}; use std::net::UdpSocket; use std::os::windows::io::AsRawSocket; + use base::named_pipes; + use base::named_pipes::BlockingMode; + use base::named_pipes::FramingMode; + + use super::super::SLIRP_BUFFER_SIZE; + use super::*; + fn create_socket() -> (UdpSocket, WSAPOLLFD) { let socket = UdpSocket::bind("127.0.0.1:0").unwrap(); socket diff --git a/net_util/src/sys/unix.rs b/net_util/src/sys/unix.rs index 4b5a907bb..0f2eabdd7 100644 --- a/net_util/src/sys/unix.rs +++ b/net_util/src/sys/unix.rs @@ -3,10 +3,10 @@ // found in the LICENSE file. pub mod tap; +use base::FileReadWriteVolatile; pub use tap::Tap; use crate::TapTCommon; -use base::FileReadWriteVolatile; // TODO(b/159159958) implement FileReadWriteVolatile for slirp pub trait TapT: FileReadWriteVolatile + TapTCommon {} diff --git a/net_util/src/sys/unix/tap.rs b/net_util/src/sys/unix/tap.rs index c5f19ceb2..2e8636825 100644 --- a/net_util/src/sys/unix/tap.rs +++ b/net_util/src/sys/unix/tap.rs @@ -3,21 +3,35 @@ // found in the LICENSE file. use std::fs::File; -use std::io::{Read, Result as IoResult, Write}; +use std::io::Read; +use std::io::Result as IoResult; +use std::io::Write; use std::mem; use std::net; use std::os::raw::*; -use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::FromRawFd; +use std::os::unix::io::RawFd; +use base::ioctl_with_mut_ref; +use base::ioctl_with_ref; +use base::ioctl_with_val; +use base::volatile_impl; +use base::AsRawDescriptor; +use base::Error as SysError; +use base::FileReadWriteVolatile; +use base::FromRawDescriptor; +use base::IoctlNr; +use base::RawDescriptor; +use base::ReadNotifier; +use cros_async::IntoAsync; use libc::EPERM; -use crate::{Error, MacAddress, Result, TapT, TapTCommon}; -use base::Error as SysError; -use base::{ - ioctl_with_mut_ref, ioctl_with_ref, ioctl_with_val, volatile_impl, AsRawDescriptor, - FileReadWriteVolatile, FromRawDescriptor, IoctlNr, RawDescriptor, ReadNotifier, -}; -use cros_async::IntoAsync; +use crate::Error; +use crate::MacAddress; +use crate::Result; +use crate::TapT; +use crate::TapTCommon; /// Handle for a network tap interface. /// @@ -455,10 +469,11 @@ impl IntoAsync for Tap {} volatile_impl!(Tap); pub mod fakes { - use super::*; use std::fs::remove_file; use std::fs::OpenOptions; + use super::*; + const TMP_FILE: &str = "/tmp/crosvm_tap_test_file"; pub struct FakeTap { diff --git a/net_util/src/sys/windows.rs b/net_util/src/sys/windows.rs index 8bcdaab33..906930c07 100644 --- a/net_util/src/sys/windows.rs +++ b/net_util/src/sys/windows.rs @@ -2,8 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::TapTCommon; -use base::named_pipes::{ReadOverlapped, WriteOverlapped}; +use base::named_pipes::ReadOverlapped; +use base::named_pipes::WriteOverlapped; use base::ReadNotifier; +use crate::TapTCommon; + pub trait TapT: TapTCommon + ReadNotifier + ReadOverlapped + WriteOverlapped {} diff --git a/power_monitor/build.rs b/power_monitor/build.rs index 2241929f9..1f7ed59d9 100644 --- a/power_monitor/build.rs +++ b/power_monitor/build.rs @@ -11,7 +11,8 @@ fn main() { use std::fmt::Write as FmtWrite; use std::fs; use std::io::Write; - use std::path::{Path, PathBuf}; + use std::path::Path; + use std::path::PathBuf; fn paths_to_strs>(paths: &[P]) -> Vec<&str> { paths diff --git a/power_monitor/src/powerd/mod.rs b/power_monitor/src/powerd/mod.rs index ce008d91d..57bc7e777 100644 --- a/power_monitor/src/powerd/mod.rs +++ b/power_monitor/src/powerd/mod.rs @@ -2,23 +2,27 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{BatteryData, BatteryStatus, PowerData, PowerMonitor}; +use crate::BatteryData; +use crate::BatteryStatus; +use crate::PowerData; +use crate::PowerMonitor; mod proto; -use proto::system_api::power_supply_properties::{ - PowerSupplyProperties, PowerSupplyProperties_BatteryState, PowerSupplyProperties_ExternalPower, -}; - -use dbus::ffidisp::{BusType, Connection, ConnectionItem, WatchEvent}; +use std::error::Error; +use std::os::unix::io::RawFd; +use dbus::ffidisp::BusType; +use dbus::ffidisp::Connection; +use dbus::ffidisp::ConnectionItem; +use dbus::ffidisp::WatchEvent; +use proto::system_api::power_supply_properties::PowerSupplyProperties; +use proto::system_api::power_supply_properties::PowerSupplyProperties_BatteryState; +use proto::system_api::power_supply_properties::PowerSupplyProperties_ExternalPower; use protobuf::error::ProtobufError; use protobuf::Message; use remain::sorted; use thiserror::Error; -use std::error::Error; -use std::os::unix::io::RawFd; - // Interface name from power_manager/dbus_bindings/org.chromium.PowerManager.xml. const POWER_INTERFACE_NAME: &str = "org.chromium.PowerManager"; diff --git a/protos/build.rs b/protos/build.rs index 5aa3ca255..e45f6fbd6 100644 --- a/protos/build.rs +++ b/protos/build.rs @@ -4,9 +4,11 @@ use std::env; use std::error::Error; -use std::fs::{self, File}; +use std::fs::File; +use std::fs::{self}; use std::io::Write; -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::path::PathBuf; type Result = std::result::Result>; diff --git a/qcow_utils/src/qcow_utils.rs b/qcow_utils/src/qcow_utils.rs index aeb322f86..973a834b4 100644 --- a/qcow_utils/src/qcow_utils.rs +++ b/qcow_utils/src/qcow_utils.rs @@ -4,13 +4,20 @@ //! Exported interface to basic qcow functionality to be used from C. -use libc::{EINVAL, EIO, ENOSYS}; use std::ffi::CStr; use std::fs::OpenOptions; -use std::os::raw::{c_char, c_int}; +use std::os::raw::c_char; +use std::os::raw::c_int; -use base::{flock, FlockOperation}; -use disk::{self, DiskFile, ImageType, QcowFile}; +use base::flock; +use base::FlockOperation; +use disk::DiskFile; +use disk::ImageType; +use disk::QcowFile; +use disk::{self}; +use libc::EINVAL; +use libc::EIO; +use libc::ENOSYS; #[no_mangle] pub unsafe extern "C" fn create_qcow_with_size(path: *const c_char, virtual_size: u64) -> c_int { diff --git a/resources/src/address_allocator.rs b/resources/src/address_allocator.rs index 7f0dd5a60..851a8eae7 100644 --- a/resources/src/address_allocator.rs +++ b/resources/src/address_allocator.rs @@ -3,9 +3,13 @@ // found in the LICENSE file. use std::cmp; -use std::collections::{BTreeSet, HashMap}; +use std::collections::BTreeSet; +use std::collections::HashMap; -use crate::{AddressRange, Alloc, Error, Result}; +use crate::AddressRange; +use crate::Alloc; +use crate::Error; +use crate::Result; /// Manages allocating address ranges. /// Use `AddressAllocator` whenever an address range needs to be allocated to different users. diff --git a/resources/src/address_range.rs b/resources/src/address_range.rs index 8dc37dbf8..fb70528ae 100644 --- a/resources/src/address_range.rs +++ b/resources/src/address_range.rs @@ -5,7 +5,8 @@ use std::cmp; use std::ops::RangeInclusive; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; /// Represents a range of addresses from `start` to `end`, inclusive. /// diff --git a/resources/src/lib.rs b/resources/src/lib.rs index d0f859b29..446b5a335 100644 --- a/resources/src/lib.rs +++ b/resources/src/lib.rs @@ -5,11 +5,14 @@ //! Manages system resources that can be allocated to VMs and their devices. use remain::sorted; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; use thiserror::Error; pub use crate::address_range::AddressRange; -pub use crate::system_allocator::{MmioType, SystemAllocator, SystemAllocatorConfig}; +pub use crate::system_allocator::MmioType; +pub use crate::system_allocator::SystemAllocator; +pub use crate::system_allocator::SystemAllocatorConfig; pub mod address_allocator; mod address_range; diff --git a/resources/src/system_allocator.rs b/resources/src/system_allocator.rs index 764e7d25c..c8c91d5f3 100644 --- a/resources/src/system_allocator.rs +++ b/resources/src/system_allocator.rs @@ -6,8 +6,12 @@ use std::collections::BTreeMap; use base::pagesize; -use crate::address_allocator::{AddressAllocator, AddressAllocatorSet}; -use crate::{AddressRange, Alloc, Error, Result}; +use crate::address_allocator::AddressAllocator; +use crate::address_allocator::AddressAllocatorSet; +use crate::AddressRange; +use crate::Alloc; +use crate::Error; +use crate::Result; /// Manages allocating system resources such as address space and interrupt numbers. diff --git a/rutabaga_gfx/build.rs b/rutabaga_gfx/build.rs index 98690ece7..1dac77301 100644 --- a/rutabaga_gfx/build.rs +++ b/rutabaga_gfx/build.rs @@ -2,10 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use anyhow::Result; - -#[cfg(feature = "virgl_renderer")] -use anyhow::bail; #[cfg(feature = "virgl_renderer")] use std::env; #[cfg(feature = "virgl_renderer")] @@ -17,6 +13,10 @@ use std::path::PathBuf; #[cfg(feature = "virgl_renderer")] use std::process::Command; +#[cfg(feature = "virgl_renderer")] +use anyhow::bail; +use anyhow::Result; + #[cfg(feature = "virgl_renderer")] const MINIGBM_SRC: &str = "../third_party/minigbm"; #[cfg(feature = "virgl_renderer")] diff --git a/rutabaga_gfx/ffi/src/lib.rs b/rutabaga_gfx/ffi/src/lib.rs index f4d4bcf67..2befd8c36 100644 --- a/rutabaga_gfx/ffi/src/lib.rs +++ b/rutabaga_gfx/ffi/src/lib.rs @@ -8,16 +8,22 @@ extern crate rutabaga_gfx; use std::convert::TryInto; use std::ffi::CStr; use std::os::raw::c_char; -use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::panic::catch_unwind; +use std::panic::AssertUnwindSafe; use std::path::PathBuf; -use std::ptr::{copy_nonoverlapping, null_mut}; -use std::slice::{from_raw_parts, from_raw_parts_mut}; +use std::ptr::copy_nonoverlapping; +use std::ptr::null_mut; +use std::slice::from_raw_parts; +use std::slice::from_raw_parts_mut; -use base::{error, FromRawDescriptor, IntoRawDescriptor, SafeDescriptor}; +use base::error; +use base::FromRawDescriptor; +use base::IntoRawDescriptor; +use base::SafeDescriptor; use data_model::VolatileSlice; - -use libc::{iovec, EINVAL, ESRCH}; - +use libc::iovec; +use libc::EINVAL; +use libc::ESRCH; use rutabaga_gfx::*; const NO_ERROR: i32 = 0; diff --git a/rutabaga_gfx/src/cross_domain/cross_domain.rs b/rutabaga_gfx/src/cross_domain/cross_domain.rs index a3f9798f9..ce8d4f8a3 100644 --- a/rutabaga_gfx/src/cross_domain/cross_domain.rs +++ b/rutabaga_gfx/src/cross_domain/cross_domain.rs @@ -14,20 +14,30 @@ use std::ptr::copy_nonoverlapping; use std::sync::Arc; use std::thread; -use base::{error, Event, EventToken, FileReadWriteVolatile, SafeDescriptor, WaitContext}; +use base::error; +use base::Event; +use base::EventToken; +use base::FileReadWriteVolatile; +use base::SafeDescriptor; +use base::WaitContext; +use data_model::DataInit; +use data_model::VolatileMemory; +use data_model::VolatileSlice; +use sync::Condvar; +use sync::Mutex; +use super::sys::descriptor_analysis; +use super::sys::SystemStream; use crate::cross_domain::cross_domain_protocol::*; -use crate::rutabaga_core::{RutabagaComponent, RutabagaContext, RutabagaResource}; +use crate::rutabaga_core::RutabagaComponent; +use crate::rutabaga_core::RutabagaContext; +use crate::rutabaga_core::RutabagaResource; use crate::rutabaga_utils::*; -use crate::{ - DrmFormat, ImageAllocationInfo, ImageMemoryRequirements, RutabagaGralloc, RutabagaGrallocFlags, -}; - -use super::sys::{descriptor_analysis, SystemStream}; - -use data_model::{DataInit, VolatileMemory, VolatileSlice}; - -use sync::{Condvar, Mutex}; +use crate::DrmFormat; +use crate::ImageAllocationInfo; +use crate::ImageMemoryRequirements; +use crate::RutabagaGralloc; +use crate::RutabagaGrallocFlags; const CROSS_DOMAIN_DEFAULT_BUFFER_SIZE: usize = 4096; const CROSS_DOMAIN_MAX_SEND_RECV_SIZE: usize = diff --git a/rutabaga_gfx/src/cross_domain/sys.rs b/rutabaga_gfx/src/cross_domain/sys.rs index cc7fb786d..9102ae428 100644 --- a/rutabaga_gfx/src/cross_domain/sys.rs +++ b/rutabaga_gfx/src/cross_domain/sys.rs @@ -14,4 +14,5 @@ cfg_if::cfg_if! { } } -pub(crate) use platform::{descriptor_analysis, SystemStream}; +pub(crate) use platform::descriptor_analysis; +pub(crate) use platform::SystemStream; diff --git a/rutabaga_gfx/src/cross_domain/sys/unix.rs b/rutabaga_gfx/src/cross_domain/sys/unix.rs index eb252ec82..585167cfb 100644 --- a/rutabaga_gfx/src/cross_domain/sys/unix.rs +++ b/rutabaga_gfx/src/cross_domain/sys/unix.rs @@ -2,24 +2,32 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{ - fs::File, - io::{IoSliceMut, Seek, SeekFrom}, -}; +use std::fs::File; +use std::io::IoSliceMut; +use std::io::Seek; +use std::io::SeekFrom; -use base::{pipe, AsRawDescriptor, FileFlags, FromRawDescriptor, RawDescriptor, ScmSocket}; +use base::pipe; +use base::AsRawDescriptor; +use base::FileFlags; +use base::FromRawDescriptor; +use base::RawDescriptor; +use base::ScmSocket; use data_model::VolatileSlice; -use super::super::{ - cross_domain::{ - add_item, CrossDomainContext, CrossDomainItem, CrossDomainJob, CrossDomainState, - }, - cross_domain_protocol::{ - CrossDomainSendReceive, CROSS_DOMAIN_ID_TYPE_READ_PIPE, CROSS_DOMAIN_ID_TYPE_VIRTGPU_BLOB, - CROSS_DOMAIN_ID_TYPE_WRITE_PIPE, CROSS_DOMAIN_MAX_IDENTIFIERS, - }, -}; -use crate::{cross_domain::cross_domain_protocol::CrossDomainInit, RutabagaError, RutabagaResult}; +use super::super::cross_domain::add_item; +use super::super::cross_domain::CrossDomainContext; +use super::super::cross_domain::CrossDomainItem; +use super::super::cross_domain::CrossDomainJob; +use super::super::cross_domain::CrossDomainState; +use super::super::cross_domain_protocol::CrossDomainSendReceive; +use super::super::cross_domain_protocol::CROSS_DOMAIN_ID_TYPE_READ_PIPE; +use super::super::cross_domain_protocol::CROSS_DOMAIN_ID_TYPE_VIRTGPU_BLOB; +use super::super::cross_domain_protocol::CROSS_DOMAIN_ID_TYPE_WRITE_PIPE; +use super::super::cross_domain_protocol::CROSS_DOMAIN_MAX_IDENTIFIERS; +use crate::cross_domain::cross_domain_protocol::CrossDomainInit; +use crate::RutabagaError; +use crate::RutabagaResult; // TODO(b:231309513): The alias can be moved to base crate for wider use. pub(crate) type SystemStream = std::os::unix::net::UnixStream; diff --git a/rutabaga_gfx/src/cross_domain/sys/windows.rs b/rutabaga_gfx/src/cross_domain/sys/windows.rs index 7c78adffc..a48849130 100644 --- a/rutabaga_gfx/src/cross_domain/sys/windows.rs +++ b/rutabaga_gfx/src/cross_domain/sys/windows.rs @@ -7,12 +7,11 @@ use std::fs::File; use base::AsRawDescriptor; use data_model::VolatileSlice; -use super::super::{ - cross_domain::{CrossDomainContext, CrossDomainState}, - cross_domain_protocol::{ - CrossDomainInit, CrossDomainSendReceive, CROSS_DOMAIN_MAX_IDENTIFIERS, - }, -}; +use super::super::cross_domain::CrossDomainContext; +use super::super::cross_domain::CrossDomainState; +use super::super::cross_domain_protocol::CrossDomainInit; +use super::super::cross_domain_protocol::CrossDomainSendReceive; +use super::super::cross_domain_protocol::CROSS_DOMAIN_MAX_IDENTIFIERS; use crate::RutabagaResult; // SystemStream is never constructed on windows. This is a placeholder to make more code diff --git a/rutabaga_gfx/src/gfxstream.rs b/rutabaga_gfx/src/gfxstream.rs index 755637a2c..b63ffd3a9 100644 --- a/rutabaga_gfx/src/gfxstream.rs +++ b/rutabaga_gfx/src/gfxstream.rs @@ -10,27 +10,34 @@ use std::cell::RefCell; use std::convert::TryInto; -use std::mem::{size_of, transmute}; -use std::os::raw::{c_char, c_int, c_uint, c_void}; -use std::ptr::{null, null_mut}; +use std::mem::size_of; +use std::mem::transmute; +use std::os::raw::c_char; +use std::os::raw::c_int; +use std::os::raw::c_uint; +use std::os::raw::c_void; +use std::ptr::null; +use std::ptr::null_mut; use std::rc::Rc; use std::sync::Arc; -use base::{ - ExternalMapping, ExternalMappingError, ExternalMappingResult, FromRawDescriptor, - IntoRawDescriptor, SafeDescriptor, -}; - -use crate::generated::virgl_renderer_bindings::{ - iovec, virgl_box, virgl_renderer_resource_create_args, -}; - -use crate::renderer_utils::*; -use crate::rutabaga_core::{RutabagaComponent, RutabagaContext, RutabagaResource}; -use crate::rutabaga_utils::*; - +use base::ExternalMapping; +use base::ExternalMappingError; +use base::ExternalMappingResult; +use base::FromRawDescriptor; +use base::IntoRawDescriptor; +use base::SafeDescriptor; use data_model::VolatileSlice; +use crate::generated::virgl_renderer_bindings::iovec; +use crate::generated::virgl_renderer_bindings::virgl_box; +use crate::generated::virgl_renderer_bindings::virgl_renderer_resource_create_args; +use crate::renderer_utils::*; +use crate::rutabaga_core::RutabagaComponent; +use crate::rutabaga_core::RutabagaContext; +use crate::rutabaga_core::RutabagaResource; +use crate::rutabaga_utils::*; + #[repr(C)] pub struct VirglRendererGlCtxParam { pub version: c_int, diff --git a/rutabaga_gfx/src/lib.rs b/rutabaga_gfx/src/lib.rs index 104466eee..915acef1c 100644 --- a/rutabaga_gfx/src/lib.rs +++ b/rutabaga_gfx/src/lib.rs @@ -18,8 +18,12 @@ mod rutabaga_gralloc; mod rutabaga_utils; mod virgl_renderer; -pub use crate::rutabaga_core::{calculate_context_mask, Rutabaga, RutabagaBuilder}; -pub use crate::rutabaga_gralloc::{ - DrmFormat, ImageAllocationInfo, ImageMemoryRequirements, RutabagaGralloc, RutabagaGrallocFlags, -}; +pub use crate::rutabaga_core::calculate_context_mask; +pub use crate::rutabaga_core::Rutabaga; +pub use crate::rutabaga_core::RutabagaBuilder; +pub use crate::rutabaga_gralloc::DrmFormat; +pub use crate::rutabaga_gralloc::ImageAllocationInfo; +pub use crate::rutabaga_gralloc::ImageMemoryRequirements; +pub use crate::rutabaga_gralloc::RutabagaGralloc; +pub use crate::rutabaga_gralloc::RutabagaGrallocFlags; pub use crate::rutabaga_utils::*; diff --git a/rutabaga_gfx/src/renderer_utils.rs b/rutabaga_gfx/src/renderer_utils.rs index 1a08ecaff..a39c29f88 100644 --- a/rutabaga_gfx/src/renderer_utils.rs +++ b/rutabaga_gfx/src/renderer_utils.rs @@ -5,17 +5,20 @@ //! renderer_utils: Utility functions and structs used by virgl_renderer and gfxstream. use std::cell::RefCell; -use std::os::raw::{c_int, c_void}; +use std::os::raw::c_int; +use std::os::raw::c_void; use std::panic::catch_unwind; use std::process::abort; use std::rc::Rc; -use base::{IntoRawDescriptor, SafeDescriptor}; - -use crate::rutabaga_utils::{ - RutabagaError, RutabagaFence, RutabagaFenceHandler, RutabagaResult, RUTABAGA_FLAG_FENCE, -}; +use base::IntoRawDescriptor; +use base::SafeDescriptor; +use crate::rutabaga_utils::RutabagaError; +use crate::rutabaga_utils::RutabagaFence; +use crate::rutabaga_utils::RutabagaFenceHandler; +use crate::rutabaga_utils::RutabagaResult; +use crate::rutabaga_utils::RUTABAGA_FLAG_FENCE; #[cfg(feature = "gfxstream")] use crate::rutabaga_utils::RUTABAGA_FLAG_INFO_RING_IDX; diff --git a/rutabaga_gfx/src/rutabaga_2d.rs b/rutabaga_gfx/src/rutabaga_2d.rs index cf9a8bacd..563de4d33 100644 --- a/rutabaga_gfx/src/rutabaga_2d.rs +++ b/rutabaga_gfx/src/rutabaga_2d.rs @@ -4,11 +4,15 @@ //! rutabaga_2d: Handles 2D virtio-gpu hypercalls. -use std::cmp::{max, min, Ordering}; +use std::cmp::max; +use std::cmp::min; +use std::cmp::Ordering; use data_model::*; -use crate::rutabaga_core::{Rutabaga2DInfo, RutabagaComponent, RutabagaResource}; +use crate::rutabaga_core::Rutabaga2DInfo; +use crate::rutabaga_core::RutabagaComponent; +use crate::rutabaga_core::RutabagaResource; use crate::rutabaga_utils::*; /// Transfers a resource from potentially many chunked src VolatileSlices to a dst VolatileSlice. diff --git a/rutabaga_gfx/src/rutabaga_core.rs b/rutabaga_gfx/src/rutabaga_core.rs index a0b51da81..a9b9cf122 100644 --- a/rutabaga_gfx/src/rutabaga_core.rs +++ b/rutabaga_gfx/src/rutabaga_core.rs @@ -7,17 +7,15 @@ use std::collections::BTreeMap as Map; use std::sync::Arc; -use base::{ExternalMapping, SafeDescriptor}; +use base::ExternalMapping; +use base::SafeDescriptor; use data_model::VolatileSlice; use crate::cross_domain::CrossDomain; - #[cfg(feature = "gfxstream")] use crate::gfxstream::Gfxstream; - use crate::rutabaga_2d::Rutabaga2D; use crate::rutabaga_utils::*; - #[cfg(feature = "virgl_renderer")] use crate::virgl_renderer::VirglRenderer; diff --git a/rutabaga_gfx/src/rutabaga_gralloc/formats.rs b/rutabaga_gfx/src/rutabaga_gralloc/formats.rs index 8bb93f7e1..d5866d555 100644 --- a/rutabaga_gfx/src/rutabaga_gralloc/formats.rs +++ b/rutabaga_gfx/src/rutabaga_gralloc/formats.rs @@ -7,16 +7,16 @@ use std::fmt; -use crate::checked_arithmetic; -use crate::rutabaga_gralloc::gralloc::{ImageAllocationInfo, ImageMemoryRequirements}; -use crate::rutabaga_utils::*; - #[cfg(feature = "vulkano")] use vulkano::format::Format as VulkanFormat; - #[cfg(feature = "vulkano")] use vulkano::image::ImageAspect as VulkanImageAspect; +use crate::checked_arithmetic; +use crate::rutabaga_gralloc::gralloc::ImageAllocationInfo; +use crate::rutabaga_gralloc::gralloc::ImageMemoryRequirements; +use crate::rutabaga_utils::*; + /* * This list is based on Sommelier / cros_gralloc guest userspace. Formats that are never * used by guest userspace (i.e, DRM_FORMAT_RGB332) are left out for simplicity. @@ -259,9 +259,10 @@ pub fn canonical_image_requirements( #[cfg(test)] mod tests { + use std::fmt::Write; + use super::*; use crate::rutabaga_gralloc::RutabagaGrallocFlags; - use std::fmt::Write; #[test] fn format_debug() { diff --git a/rutabaga_gfx/src/rutabaga_gralloc/gralloc.rs b/rutabaga_gfx/src/rutabaga_gralloc/gralloc.rs index 0d0d33523..45e18602d 100644 --- a/rutabaga_gfx/src/rutabaga_gralloc/gralloc.rs +++ b/rutabaga_gfx/src/rutabaga_gralloc/gralloc.rs @@ -7,17 +7,16 @@ use std::collections::BTreeMap as Map; -use base::{round_up_to_page_size, MappedRegion}; +use base::round_up_to_page_size; +use base::MappedRegion; use crate::rutabaga_gralloc::formats::*; -use crate::rutabaga_gralloc::system_gralloc::SystemGralloc; -use crate::rutabaga_utils::*; - #[cfg(feature = "minigbm")] use crate::rutabaga_gralloc::minigbm::MinigbmDevice; - +use crate::rutabaga_gralloc::system_gralloc::SystemGralloc; #[cfg(feature = "vulkano")] use crate::rutabaga_gralloc::vulkano_gralloc::VulkanoGralloc; +use crate::rutabaga_utils::*; /* * Rutabaga gralloc flags are copied from minigbm, but redundant legacy flags are left out. diff --git a/rutabaga_gfx/src/rutabaga_gralloc/minigbm.rs b/rutabaga_gfx/src/rutabaga_gralloc/minigbm.rs index 40b5d9e82..3717e47b1 100644 --- a/rutabaga_gfx/src/rutabaga_gralloc/minigbm.rs +++ b/rutabaga_gfx/src/rutabaga_gralloc/minigbm.rs @@ -10,14 +10,20 @@ use std::ffi::CStr; use std::fs::File; -use std::io::{Seek, SeekFrom}; +use std::io::Seek; +use std::io::SeekFrom; use std::os::raw::c_char; use std::sync::Arc; -use base::{AsRawDescriptor, Error as BaseError, FromRawDescriptor, RawDescriptor}; +use base::AsRawDescriptor; +use base::Error as BaseError; +use base::FromRawDescriptor; +use base::RawDescriptor; use crate::rutabaga_gralloc::formats::DrmFormat; -use crate::rutabaga_gralloc::gralloc::{Gralloc, ImageAllocationInfo, ImageMemoryRequirements}; +use crate::rutabaga_gralloc::gralloc::Gralloc; +use crate::rutabaga_gralloc::gralloc::ImageAllocationInfo; +use crate::rutabaga_gralloc::gralloc::ImageMemoryRequirements; use crate::rutabaga_gralloc::minigbm_bindings::*; use crate::rutabaga_gralloc::rendernode; use crate::rutabaga_utils::*; diff --git a/rutabaga_gfx/src/rutabaga_gralloc/minigbm_bindings.rs b/rutabaga_gfx/src/rutabaga_gralloc/minigbm_bindings.rs index 366b3ad74..6c5fa820f 100644 --- a/rutabaga_gfx/src/rutabaga_gralloc/minigbm_bindings.rs +++ b/rutabaga_gfx/src/rutabaga_gralloc/minigbm_bindings.rs @@ -10,7 +10,10 @@ #![allow(dead_code, non_camel_case_types)] /* Added below line manually */ -use std::os::raw::{c_char, c_int, c_uint, c_void}; +use std::os::raw::c_char; +use std::os::raw::c_int; +use std::os::raw::c_uint; +use std::os::raw::c_void; #[repr(C)] #[derive(Debug, Copy, Clone)] diff --git a/rutabaga_gfx/src/rutabaga_gralloc/mod.rs b/rutabaga_gfx/src/rutabaga_gralloc/mod.rs index 560a193e4..3ff1af370 100644 --- a/rutabaga_gfx/src/rutabaga_gralloc/mod.rs +++ b/rutabaga_gfx/src/rutabaga_gralloc/mod.rs @@ -17,6 +17,7 @@ mod system_gralloc; mod vulkano_gralloc; pub use formats::DrmFormat; -pub use gralloc::{ - ImageAllocationInfo, ImageMemoryRequirements, RutabagaGralloc, RutabagaGrallocFlags, -}; +pub use gralloc::ImageAllocationInfo; +pub use gralloc::ImageMemoryRequirements; +pub use gralloc::RutabagaGralloc; +pub use gralloc::RutabagaGrallocFlags; diff --git a/rutabaga_gfx/src/rutabaga_gralloc/rendernode.rs b/rutabaga_gfx/src/rutabaga_gralloc/rendernode.rs index d7fe1d37a..88f49c941 100644 --- a/rutabaga_gfx/src/rutabaga_gralloc/rendernode.rs +++ b/rutabaga_gfx/src/rutabaga_gralloc/rendernode.rs @@ -5,17 +5,21 @@ #![cfg(feature = "minigbm")] use std::ffi::CString; -use std::fs::{File, OpenOptions}; - +use std::fs::File; +use std::fs::OpenOptions; +use std::os::raw::c_char; +use std::os::raw::c_int; +use std::os::raw::c_uint; #[cfg(target_pointer_width = "64")] use std::os::raw::c_ulong; -use std::os::raw::{c_char, c_int, c_uint}; use std::path::Path; use std::ptr::null_mut; -use base::{ioctl_iowr_nr, ioctl_with_mut_ref}; +use base::ioctl_iowr_nr; +use base::ioctl_with_mut_ref; -use crate::rutabaga_utils::{RutabagaError, RutabagaResult}; +use crate::rutabaga_utils::RutabagaError; +use crate::rutabaga_utils::RutabagaResult; // Consistent with __kernel_size_t in include/uapi/asm-generic/posix_types.h. #[cfg(not(target_pointer_width = "64"))] diff --git a/rutabaga_gfx/src/rutabaga_gralloc/system_gralloc.rs b/rutabaga_gfx/src/rutabaga_gralloc/system_gralloc.rs index 06a03e681..2b57ca7f8 100644 --- a/rutabaga_gfx/src/rutabaga_gralloc/system_gralloc.rs +++ b/rutabaga_gfx/src/rutabaga_gralloc/system_gralloc.rs @@ -8,7 +8,9 @@ use base::SharedMemory; use crate::rutabaga_gralloc::formats::canonical_image_requirements; -use crate::rutabaga_gralloc::gralloc::{Gralloc, ImageAllocationInfo, ImageMemoryRequirements}; +use crate::rutabaga_gralloc::gralloc::Gralloc; +use crate::rutabaga_gralloc::gralloc::ImageAllocationInfo; +use crate::rutabaga_gralloc::gralloc::ImageMemoryRequirements; use crate::rutabaga_utils::*; /// A gralloc implementation capable of allocation from system memory. diff --git a/rutabaga_gfx/src/rutabaga_gralloc/vulkano_gralloc.rs b/rutabaga_gfx/src/rutabaga_gralloc/vulkano_gralloc.rs index 874ba66db..2c1fb005c 100644 --- a/rutabaga_gfx/src/rutabaga_gralloc/vulkano_gralloc.rs +++ b/rutabaga_gfx/src/rutabaga_gralloc/vulkano_gralloc.rs @@ -9,29 +9,47 @@ #![cfg(feature = "vulkano")] -use std::{collections::BTreeMap as Map, convert::TryInto, sync::Arc}; +use std::collections::BTreeMap as Map; +use std::convert::TryInto; +use std::sync::Arc; use base::MappedRegion; +use vulkano::device::physical::MemoryType; +use vulkano::device::physical::PhysicalDevice; +use vulkano::device::physical::PhysicalDeviceType; +use vulkano::device::Device; +use vulkano::device::DeviceCreateInfo; +use vulkano::device::DeviceCreationError; +use vulkano::device::DeviceExtensions; +use vulkano::device::QueueCreateInfo; +use vulkano::image::sys; +use vulkano::image::ImageCreationError; +use vulkano::image::ImageDimensions; +use vulkano::image::ImageUsage; +use vulkano::image::SampleCount; +use vulkano::instance::Instance; +use vulkano::instance::InstanceCreateInfo; +use vulkano::instance::InstanceCreationError; +use vulkano::instance::InstanceExtensions; +use vulkano::instance::Version; +use vulkano::memory::pool::AllocFromRequirementsFilter; +use vulkano::memory::DedicatedAllocation; +use vulkano::memory::DeviceMemory; +use vulkano::memory::DeviceMemoryAllocationError; +use vulkano::memory::DeviceMemoryExportError; +use vulkano::memory::ExternalMemoryHandleType; +use vulkano::memory::ExternalMemoryHandleTypes; +use vulkano::memory::MappedDeviceMemory; +use vulkano::memory::MemoryAllocateInfo; +use vulkano::memory::MemoryMapError; +use vulkano::memory::MemoryRequirements; +use vulkano::sync::Sharing; -use crate::rutabaga_gralloc::gralloc::{Gralloc, ImageAllocationInfo, ImageMemoryRequirements}; +use crate::rutabaga_gralloc::gralloc::Gralloc; +use crate::rutabaga_gralloc::gralloc::ImageAllocationInfo; +use crate::rutabaga_gralloc::gralloc::ImageMemoryRequirements; use crate::rutabaga_utils::*; -use vulkano::{ - device::{ - physical::{MemoryType, PhysicalDevice, PhysicalDeviceType}, - Device, DeviceCreateInfo, DeviceCreationError, DeviceExtensions, QueueCreateInfo, - }, - image::{sys, ImageCreationError, ImageDimensions, ImageUsage, SampleCount}, - instance::{Instance, InstanceCreateInfo, InstanceCreationError, InstanceExtensions, Version}, - memory::{ - pool::AllocFromRequirementsFilter, DedicatedAllocation, DeviceMemory, - DeviceMemoryAllocationError, DeviceMemoryExportError, ExternalMemoryHandleType, - ExternalMemoryHandleTypes, MappedDeviceMemory, MemoryAllocateInfo, MemoryMapError, - MemoryRequirements, - }, - sync::Sharing, -}; - /// A gralloc implementation capable of allocation `VkDeviceMemory`. pub struct VulkanoGralloc { devices: Map>, diff --git a/rutabaga_gfx/src/rutabaga_utils.rs b/rutabaga_gfx/src/rutabaga_utils.rs index be862012b..f525cd4db 100644 --- a/rutabaga_gfx/src/rutabaga_utils.rs +++ b/rutabaga_gfx/src/rutabaga_utils.rs @@ -10,12 +10,14 @@ use std::os::raw::c_void; use std::path::PathBuf; use std::str::Utf8Error; -use base::{Error as BaseError, ExternalMappingError, SafeDescriptor}; +use base::Error as BaseError; +use base::ExternalMappingError; +use base::SafeDescriptor; use data_model::VolatileMemoryError; use remain::sorted; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; use thiserror::Error; - #[cfg(feature = "vulkano")] use vulkano::device::DeviceCreationError; #[cfg(feature = "vulkano")] diff --git a/rutabaga_gfx/src/virgl_renderer.rs b/rutabaga_gfx/src/virgl_renderer.rs index c07ac0a6e..6ac38cd4e 100644 --- a/rutabaga_gfx/src/virgl_renderer.rs +++ b/rutabaga_gfx/src/virgl_renderer.rs @@ -10,29 +10,36 @@ use std::cell::RefCell; use std::cmp::min; use std::convert::TryFrom; -use std::mem::{size_of, transmute}; -use std::os::raw::{c_char, c_void}; +use std::mem::size_of; +use std::mem::transmute; +use std::os::raw::c_char; +use std::os::raw::c_void; use std::os::unix::io::AsRawFd; use std::panic::catch_unwind; use std::process::abort; use std::ptr::null_mut; use std::rc::Rc; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; use std::sync::Arc; -use base::{ - warn, Error as SysError, ExternalMapping, ExternalMappingError, ExternalMappingResult, - FromRawDescriptor, SafeDescriptor, -}; +use base::warn; +use base::Error as SysError; +use base::ExternalMapping; +use base::ExternalMappingError; +use base::ExternalMappingResult; +use base::FromRawDescriptor; +use base::SafeDescriptor; +use data_model::VolatileSlice; use crate::generated::virgl_debug_callback_bindings::*; use crate::generated::virgl_renderer_bindings::*; use crate::renderer_utils::*; -use crate::rutabaga_core::{RutabagaComponent, RutabagaContext, RutabagaResource}; +use crate::rutabaga_core::RutabagaComponent; +use crate::rutabaga_core::RutabagaContext; +use crate::rutabaga_core::RutabagaResource; use crate::rutabaga_utils::*; -use data_model::VolatileSlice; - type Query = virgl_renderer_export_query; /// The virtio-gpu backend state tracker which supports accelerated rendering. diff --git a/serde_keyvalue/serde_keyvalue_derive/src/lib.rs b/serde_keyvalue/serde_keyvalue_derive/src/lib.rs index dfb605250..8496e6c91 100644 --- a/serde_keyvalue/serde_keyvalue_derive/src/lib.rs +++ b/serde_keyvalue/serde_keyvalue_derive/src/lib.rs @@ -3,7 +3,8 @@ // found in the LICENSE file. use quote::quote; -use syn::{parse_macro_input, DeriveInput}; +use syn::parse_macro_input; +use syn::DeriveInput; /// Implement `argh`'s `FromArgValue` trait for a struct or enum using `from_key_values`. #[proc_macro_derive(FromKeyValues)] diff --git a/serde_keyvalue/src/key_values.rs b/serde_keyvalue/src/key_values.rs index 1c2818f68..7b0fc3698 100644 --- a/serde_keyvalue/src/key_values.rs +++ b/serde_keyvalue/src/key_values.rs @@ -3,8 +3,11 @@ // found in the LICENSE file. use std::borrow::Cow; -use std::fmt::{self, Debug, Display}; -use std::num::{IntErrorKind, ParseIntError}; +use std::fmt::Debug; +use std::fmt::Display; +use std::fmt::{self}; +use std::num::IntErrorKind; +use std::num::ParseIntError; use std::str::FromStr; use num_traits::Num; diff --git a/serde_keyvalue/src/lib.rs b/serde_keyvalue/src/lib.rs index 51d9d37f2..6bb8d17f9 100644 --- a/serde_keyvalue/src/lib.rs +++ b/serde_keyvalue/src/lib.rs @@ -287,9 +287,10 @@ mod key_values; -pub use key_values::{from_key_values, ErrorKind, ParseError}; - #[cfg(feature = "argh_derive")] pub use argh; +pub use key_values::from_key_values; +pub use key_values::ErrorKind; +pub use key_values::ParseError; #[cfg(feature = "argh_derive")] pub use serde_keyvalue_derive::FromKeyValues; diff --git a/src/crosvm/argument.rs b/src/crosvm/argument.rs index faba878f2..775d8e2e4 100644 --- a/src/crosvm/argument.rs +++ b/src/crosvm/argument.rs @@ -49,7 +49,8 @@ use std::result; use std::str::FromStr; use remain::sorted; -use terminal_size::{terminal_size, Width}; +use terminal_size::terminal_size; +use terminal_size::Width; use thiserror::Error; /// An error with argument parsing. diff --git a/src/crosvm/cmdline.rs b/src/crosvm/cmdline.rs index 65678b873..1581b5d44 100644 --- a/src/crosvm/cmdline.rs +++ b/src/crosvm/cmdline.rs @@ -26,13 +26,6 @@ cfg_if::cfg_if! { use std::collections::BTreeMap; use std::path::PathBuf; -#[cfg(all(feature = "gpu", feature = "virgl_renderer_next"))] -use super::sys::config::parse_gpu_render_server_options; -#[cfg(all(feature = "gpu", feature = "virgl_renderer_next"))] -use super::sys::GpuRenderServerParameters; - -#[cfg(any(feature = "video-decoder", feature = "video-encoder"))] -use super::config::parse_video_options; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use arch::MsrConfig; use arch::Pstore; @@ -55,26 +48,54 @@ use hypervisor::ProtectionType; use resources::AddressRange; use vm_control::BatteryType; +#[cfg(any(feature = "video-decoder", feature = "video-encoder"))] +use super::config::parse_video_options; #[cfg(feature = "gpu")] use super::sys::config::parse_gpu_options; +#[cfg(all(feature = "gpu", feature = "virgl_renderer_next"))] +use super::sys::config::parse_gpu_render_server_options; +#[cfg(all(feature = "gpu", feature = "virgl_renderer_next"))] +use super::sys::GpuRenderServerParameters; +use crate::crosvm::config::numbered_disk_option; #[cfg(feature = "audio")] use crate::crosvm::config::parse_ac97_options; -use crate::crosvm::config::{ - numbered_disk_option, parse_battery_options, parse_bus_id_addr, parse_cpu_affinity, - parse_cpu_capacity, parse_cpu_set, parse_file_backed_mapping, parse_mmio_address_range, - parse_pflash_parameters, parse_pstore, parse_serial_options, parse_stub_pci_parameters, - Executable, FileBackedMappingParameters, HypervisorKind, TouchDeviceOption, VhostUserFsOption, - VhostUserOption, VhostUserWlOption, VvuOption, -}; +use crate::crosvm::config::parse_battery_options; +use crate::crosvm::config::parse_bus_id_addr; +use crate::crosvm::config::parse_cpu_affinity; +use crate::crosvm::config::parse_cpu_capacity; +use crate::crosvm::config::parse_cpu_set; #[cfg(feature = "direct")] -use crate::crosvm::config::{ - parse_direct_io_options, parse_pcie_root_port_params, DirectIoOption, - HostPcieRootPortParameters, -}; +use crate::crosvm::config::parse_direct_io_options; +use crate::crosvm::config::parse_file_backed_mapping; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use crate::crosvm::config::{parse_memory_region, parse_userspace_msr_options}; +use crate::crosvm::config::parse_memory_region; +use crate::crosvm::config::parse_mmio_address_range; +#[cfg(feature = "direct")] +use crate::crosvm::config::parse_pcie_root_port_params; +use crate::crosvm::config::parse_pflash_parameters; #[cfg(feature = "plugin")] -use crate::crosvm::config::{parse_plugin_mount_option, BindMount, GidMap}; +use crate::crosvm::config::parse_plugin_mount_option; +use crate::crosvm::config::parse_pstore; +use crate::crosvm::config::parse_serial_options; +use crate::crosvm::config::parse_stub_pci_parameters; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use crate::crosvm::config::parse_userspace_msr_options; +#[cfg(feature = "plugin")] +use crate::crosvm::config::BindMount; +#[cfg(feature = "direct")] +use crate::crosvm::config::DirectIoOption; +use crate::crosvm::config::Executable; +use crate::crosvm::config::FileBackedMappingParameters; +#[cfg(feature = "plugin")] +use crate::crosvm::config::GidMap; +#[cfg(feature = "direct")] +use crate::crosvm::config::HostPcieRootPortParameters; +use crate::crosvm::config::HypervisorKind; +use crate::crosvm::config::TouchDeviceOption; +use crate::crosvm::config::VhostUserFsOption; +use crate::crosvm::config::VhostUserOption; +use crate::crosvm::config::VhostUserWlOption; +use crate::crosvm::config::VvuOption; #[derive(FromArgs)] /// crosvm diff --git a/src/crosvm/config.rs b/src/crosvm/config.rs index 2bbc0868f..9fbf340c8 100644 --- a/src/crosvm/config.rs +++ b/src/crosvm/config.rs @@ -4,16 +4,24 @@ use std::collections::BTreeMap; use std::net; -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::path::PathBuf; use std::str::FromStr; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; -use arch::{ - set_default_serial_parameters, MsrAction, MsrConfig, MsrFilter, MsrRWType, MsrValueFrom, - Pstore, VcpuAffinity, -}; -use base::{debug, pagesize}; -use devices::serial_device::{SerialHardware, SerialParameters}; +use arch::set_default_serial_parameters; +use arch::MsrAction; +use arch::MsrConfig; +use arch::MsrFilter; +use arch::MsrRWType; +use arch::MsrValueFrom; +use arch::Pstore; +use arch::VcpuAffinity; +use base::debug; +use base::pagesize; +use devices::serial_device::SerialHardware; +use devices::serial_device::SerialParameters; use devices::virtio::block::block::DiskOption; #[cfg(feature = "gpu")] use devices::virtio::gpu::GpuParameters; @@ -21,22 +29,30 @@ use devices::virtio::gpu::GpuParameters; use devices::virtio::snd::parameters::Parameters as SndParameters; #[cfg(any(feature = "video-decoder", feature = "video-encoder"))] use devices::virtio::VideoBackendType; +#[cfg(feature = "audio")] +use devices::Ac97Backend; +#[cfg(feature = "audio")] +use devices::Ac97Parameters; #[cfg(feature = "direct")] use devices::BusRange; -use devices::{PciAddress, PciClassCode, PflashParameters, StubPciParameters}; +use devices::PciAddress; +use devices::PciClassCode; +use devices::PflashParameters; +use devices::StubPciParameters; use hypervisor::ProtectionType; use resources::AddressRange; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; use uuid::Uuid; use vm_control::BatteryType; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use x86_64::{set_enable_pnp_data_msr_config, set_itmt_msr_config}; - -#[cfg(feature = "audio")] -use devices::{Ac97Backend, Ac97Parameters}; +use x86_64::set_enable_pnp_data_msr_config; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use x86_64::set_itmt_msr_config; +use super::argument::parse_hex_or_decimal; +use super::check_opt_path; pub(crate) use super::sys::HypervisorKind; -use super::{argument::parse_hex_or_decimal, check_opt_path}; cfg_if::cfg_if! { if #[cfg(unix)] { @@ -1198,10 +1214,13 @@ pub fn parse_pflash_parameters(s: &str) -> Result { // BTreeMaps serialize fine, as long as their keys are trivial types. A tuple does not // work, hence the need to convert to/from a vector form. mod serde_serial_params { - use super::*; - use serde::{Deserializer, Serializer}; use std::iter::FromIterator; + use serde::Deserializer; + use serde::Serializer; + + use super::*; + pub fn serialize( params: &BTreeMap<(SerialHardware, u8), SerialParameters>, ser: S, @@ -1795,9 +1814,10 @@ pub fn validate_config(cfg: &mut Config) -> std::result::Result<(), String> { #[cfg(test)] mod tests { - use super::*; use argh::FromArgs; + use super::*; + #[test] fn parse_cpu_set_single() { assert_eq!(parse_cpu_set("123").expect("parse failed"), vec![123]); diff --git a/src/crosvm/gdb.rs b/src/crosvm/gdb.rs index 8ade45c1d..e078239fe 100644 --- a/src/crosvm/gdb.rs +++ b/src/crosvm/gdb.rs @@ -6,33 +6,42 @@ use std::net::TcpListener; use std::sync::mpsc; use std::time::Duration; -use base::{error, info, Tube, TubeError}; - -use sync::Mutex; -use vm_control::{ - VcpuControl, VcpuDebug, VcpuDebugStatus, VcpuDebugStatusMessage, VmRequest, VmResponse, -}; -use vm_memory::GuestAddress; - +use base::error; +use base::info; +use base::Tube; +use base::TubeError; use gdbstub::arch::Arch; use gdbstub::common::Signal; -use gdbstub::conn::{Connection, ConnectionExt}; +use gdbstub::conn::Connection; +use gdbstub::conn::ConnectionExt; +use gdbstub::stub::run_blocking; use gdbstub::stub::run_blocking::BlockingEventLoop; -use gdbstub::stub::{run_blocking, SingleThreadStopReason}; -use gdbstub::target::ext::base::singlethread::{ - SingleThreadBase, SingleThreadResume, SingleThreadResumeOps, SingleThreadSingleStep, - SingleThreadSingleStepOps, -}; +use gdbstub::stub::SingleThreadStopReason; +use gdbstub::target::ext::base::singlethread::SingleThreadBase; +use gdbstub::target::ext::base::singlethread::SingleThreadResume; +use gdbstub::target::ext::base::singlethread::SingleThreadResumeOps; +use gdbstub::target::ext::base::singlethread::SingleThreadSingleStep; +use gdbstub::target::ext::base::singlethread::SingleThreadSingleStepOps; use gdbstub::target::ext::base::BaseOps; -use gdbstub::target::ext::breakpoints::{ - Breakpoints, BreakpointsOps, HwBreakpoint, HwBreakpointOps, -}; +use gdbstub::target::ext::breakpoints::Breakpoints; +use gdbstub::target::ext::breakpoints::BreakpointsOps; +use gdbstub::target::ext::breakpoints::HwBreakpoint; +use gdbstub::target::ext::breakpoints::HwBreakpointOps; +use gdbstub::target::Target; use gdbstub::target::TargetError::NonFatal; -use gdbstub::target::{Target, TargetResult}; +use gdbstub::target::TargetResult; #[cfg(target_arch = "x86_64")] use gdbstub_arch::x86::X86_64_SSE as GdbArch; use remain::sorted; +use sync::Mutex; use thiserror::Error as ThisError; +use vm_control::VcpuControl; +use vm_control::VcpuDebug; +use vm_control::VcpuDebugStatus; +use vm_control::VcpuDebugStatusMessage; +use vm_control::VmRequest; +use vm_control::VmResponse; +use vm_memory::GuestAddress; #[cfg(target_arch = "x86_64")] type ArchUsize = u64; diff --git a/src/crosvm/plugin/mod.rs b/src/crosvm/plugin/mod.rs index 5bc3b2427..3d4a9cdc0 100644 --- a/src/crosvm/plugin/mod.rs +++ b/src/crosvm/plugin/mod.rs @@ -7,39 +7,93 @@ mod vcpu; use std::fs::File; use std::io::Read; -use std::io::{self, Write}; +use std::io::Write; +use std::io::{self}; use std::os::unix::net::UnixDatagram; use std::path::Path; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Barrier}; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::sync::Barrier; use std::thread; -use std::time::{Duration, Instant}; +use std::time::Duration; +use std::time::Instant; -use libc::{ - c_int, c_ulong, fcntl, ioctl, socketpair, AF_UNIX, EAGAIN, EBADF, EDEADLK, EEXIST, EINTR, - EINVAL, ENOENT, EOVERFLOW, EPERM, FIOCLEX, F_SETPIPE_SZ, MS_NODEV, MS_NOEXEC, MS_NOSUID, - MS_RDONLY, O_NONBLOCK, SIGCHLD, SOCK_SEQPACKET, -}; - -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; +use base::add_fd_flags; +use base::block_signal; +use base::clear_signal; +use base::drop_capabilities; +use base::enable_core_scheduling; +use base::error; +use base::getegid; +use base::geteuid; +use base::info; +use base::pipe; +use base::register_rt_signal_handler; +use base::validate_raw_descriptor; +use base::warn; +use base::AsRawDescriptor; +use base::Descriptor; +use base::Error as SysError; +use base::Event; +use base::EventToken; +use base::FromRawDescriptor; +use base::Killable; +use base::MmapError; +use base::RawDescriptor; +use base::Result as SysResult; +use base::SignalFd; +use base::WaitContext; +use base::SIGRTMIN; +use kvm::Cap; +use kvm::Datamatch; +use kvm::IoeventAddress; +use kvm::Kvm; +use kvm::Vcpu; +use kvm::VcpuExit; +use kvm::Vm; +use libc::c_int; +use libc::c_ulong; +use libc::fcntl; +use libc::ioctl; +use libc::socketpair; +use libc::AF_UNIX; +use libc::EAGAIN; +use libc::EBADF; +use libc::EDEADLK; +use libc::EEXIST; +use libc::EINTR; +use libc::EINVAL; +use libc::ENOENT; +use libc::EOVERFLOW; +use libc::EPERM; +use libc::FIOCLEX; +use libc::F_SETPIPE_SZ; +use libc::MS_NODEV; +use libc::MS_NOEXEC; +use libc::MS_NOSUID; +use libc::MS_RDONLY; +use libc::O_NONBLOCK; +use libc::SIGCHLD; +use libc::SOCK_SEQPACKET; +use minijail::Minijail; +use minijail::{self}; +use net_util::sys::unix::Tap; +use net_util::TapTCommon; use protobuf::ProtobufError; use remain::sorted; use thiserror::Error; - -use base::{ - add_fd_flags, block_signal, clear_signal, drop_capabilities, enable_core_scheduling, error, - getegid, geteuid, info, pipe, register_rt_signal_handler, validate_raw_descriptor, warn, - AsRawDescriptor, Descriptor, Error as SysError, Event, EventToken, FromRawDescriptor, Killable, - MmapError, RawDescriptor, Result as SysResult, SignalFd, WaitContext, SIGRTMIN, -}; -use kvm::{Cap, Datamatch, IoeventAddress, Kvm, Vcpu, VcpuExit, Vm}; -use minijail::{self, Minijail}; -use net_util::{sys::unix::Tap, TapTCommon}; -use vm_memory::{GuestMemory, MemoryPolicy}; +use vm_memory::GuestMemory; +use vm_memory::MemoryPolicy; use self::process::*; use self::vcpu::*; -use crate::{crosvm::config::Executable, Config}; +use crate::crosvm::config::Executable; +use crate::Config; const MAX_DATAGRAM_SIZE: usize = 4096; const MAX_VCPU_DATAGRAM_SIZE: usize = 0x40000; diff --git a/src/crosvm/plugin/process.rs b/src/crosvm/plugin/process.rs index 4976a0b53..075d333e5 100644 --- a/src/crosvm/plugin/process.rs +++ b/src/crosvm/plugin/process.rs @@ -2,42 +2,68 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::collections::hash_map::{Entry, HashMap, VacantEntry}; +use std::collections::hash_map::Entry; +use std::collections::hash_map::HashMap; +use std::collections::hash_map::VacantEntry; use std::env::set_var; use std::fs::File; -use std::io::{IoSlice, IoSliceMut, Write}; +use std::io::IoSlice; +use std::io::IoSliceMut; +use std::io::Write; use std::mem::transmute; use std::os::unix::net::UnixDatagram; use std::path::Path; use std::process::Command; use std::result; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use std::sync::RwLock; use std::thread::JoinHandle; -use net_util::{Error as NetError, TapTCommon}; - -use libc::{ - pid_t, waitpid, EINVAL, ENODATA, ENOTTY, STDERR_FILENO, WEXITSTATUS, WIFEXITED, WNOHANG, - WTERMSIG, -}; - -use protobuf::Message; - -use base::{ - error, AsRawDescriptor, Descriptor, Error as SysError, Event, IntoRawDescriptor, Killable, - MemoryMappingBuilder, Result as SysResult, ScmSocket, SharedMemory, SharedMemoryUnix, SIGRTMIN, -}; -use kvm::{dirty_log_bitmap_size, Datamatch, IoeventAddress, IrqRoute, IrqSource, PicId, Vm}; -use kvm_sys::{kvm_clock_data, kvm_ioapic_state, kvm_pic_state, kvm_pit_state2}; +use base::error; +use base::AsRawDescriptor; +use base::Descriptor; +use base::Error as SysError; +use base::Event; +use base::IntoRawDescriptor; +use base::Killable; +use base::MemoryMappingBuilder; +use base::Result as SysResult; +use base::ScmSocket; +use base::SharedMemory; +use base::SharedMemoryUnix; +use base::SIGRTMIN; +// Wrapper types to make the kvm state structs DataInit +use data_model::DataInit; +use kvm::dirty_log_bitmap_size; +use kvm::Datamatch; +use kvm::IoeventAddress; +use kvm::IrqRoute; +use kvm::IrqSource; +use kvm::PicId; +use kvm::Vm; +use kvm_sys::kvm_clock_data; +use kvm_sys::kvm_ioapic_state; +use kvm_sys::kvm_pic_state; +use kvm_sys::kvm_pit_state2; +use libc::pid_t; +use libc::waitpid; +use libc::EINVAL; +use libc::ENODATA; +use libc::ENOTTY; +use libc::STDERR_FILENO; +use libc::WEXITSTATUS; +use libc::WIFEXITED; +use libc::WNOHANG; +use libc::WTERMSIG; use minijail::Minijail; +use net_util::Error as NetError; +use net_util::TapTCommon; +use protobuf::Message; use protos::plugin::*; use sync::Mutex; use vm_memory::GuestAddress; use super::*; - -// Wrapper types to make the kvm state structs DataInit -use data_model::DataInit; #[derive(Copy, Clone)] struct VmPicState(kvm_pic_state); unsafe impl DataInit for VmPicState {} diff --git a/src/crosvm/plugin/vcpu.rs b/src/crosvm/plugin/vcpu.rs index ef5eea5fa..335be67cf 100644 --- a/src/crosvm/plugin/vcpu.rs +++ b/src/crosvm/plugin/vcpu.rs @@ -3,26 +3,46 @@ // found in the LICENSE file. use std::alloc::Layout; -use std::cell::{Cell, RefCell}; +use std::cell::Cell; +use std::cell::RefCell; use std::cmp::min; -use std::cmp::{self, Ord, PartialEq, PartialOrd}; +use std::cmp::Ord; +use std::cmp::PartialEq; +use std::cmp::PartialOrd; +use std::cmp::{self}; use std::collections::btree_set::BTreeSet; -use std::io::{Read, Write}; +use std::io::Read; +use std::io::Write; use std::mem; -use std::sync::{Arc, RwLock}; - -use libc::{EINVAL, ENOENT, ENOTTY, EPERM, EPIPE, EPROTO}; - -use protobuf::{CodedOutputStream, Message}; +use std::sync::Arc; +use std::sync::RwLock; use assertions::const_assert; -use base::{error, LayoutAllocation}; +use base::error; +use base::LayoutAllocation; use data_model::DataInit; -use kvm::{CpuId, Vcpu}; -use kvm_sys::{ - kvm_debugregs, kvm_enable_cap, kvm_fpu, kvm_lapic_state, kvm_mp_state, kvm_msr_entry, kvm_msrs, - kvm_regs, kvm_sregs, kvm_vcpu_events, kvm_xcrs, KVM_CPUID_FLAG_SIGNIFCANT_INDEX, -}; +use kvm::CpuId; +use kvm::Vcpu; +use kvm_sys::kvm_debugregs; +use kvm_sys::kvm_enable_cap; +use kvm_sys::kvm_fpu; +use kvm_sys::kvm_lapic_state; +use kvm_sys::kvm_mp_state; +use kvm_sys::kvm_msr_entry; +use kvm_sys::kvm_msrs; +use kvm_sys::kvm_regs; +use kvm_sys::kvm_sregs; +use kvm_sys::kvm_vcpu_events; +use kvm_sys::kvm_xcrs; +use kvm_sys::KVM_CPUID_FLAG_SIGNIFCANT_INDEX; +use libc::EINVAL; +use libc::ENOENT; +use libc::ENOTTY; +use libc::EPERM; +use libc::EPIPE; +use libc::EPROTO; +use protobuf::CodedOutputStream; +use protobuf::Message; use protos::plugin::*; use sync::Mutex; diff --git a/src/crosvm/sys.rs b/src/crosvm/sys.rs index 2ade3d9c9..7d6c4a3ff 100644 --- a/src/crosvm/sys.rs +++ b/src/crosvm/sys.rs @@ -19,11 +19,10 @@ cfg_if::cfg_if! { } } -pub(crate) use platform::cmdline; -pub(crate) use platform::config; - #[cfg(feature = "crash-report")] pub(crate) use platform::broker::setup_emulator_crash_reporting; +pub(crate) use platform::cmdline; +pub(crate) use platform::config; #[cfg(feature = "gpu")] pub(crate) use platform::config::validate_gpu_config; pub(crate) use platform::config::HypervisorKind; diff --git a/src/crosvm/sys/unix.rs b/src/crosvm/sys/unix.rs index e93b04f06..508263f59 100644 --- a/src/crosvm/sys/unix.rs +++ b/src/crosvm/sys/unix.rs @@ -12,10 +12,13 @@ pub(crate) mod gpu; pub(crate) mod jail_helpers; mod vcpu; -use std::cmp::{max, Reverse}; -use std::collections::{BTreeMap, BTreeSet}; +use std::cmp::max; +use std::cmp::Reverse; +use std::collections::BTreeMap; +use std::collections::BTreeSet; use std::convert::TryInto; -use std::fs::{File, OpenOptions}; +use std::fs::File; +use std::fs::OpenOptions; use std::io::prelude::*; use std::io::stdin; use std::iter; @@ -25,87 +28,133 @@ use std::ops::RangeInclusive; use std::os::unix::net::UnixStream; use std::os::unix::prelude::OpenOptionsExt; use std::path::Path; +use std::process; use std::str::FromStr; -use std::sync::{mpsc, Arc, Barrier}; +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Barrier; +#[cfg(all(target_arch = "x86_64", feature = "gdb"))] +use std::thread; #[cfg(feature = "balloon")] use std::time::Duration; -use std::process; -#[cfg(all(target_arch = "x86_64", feature = "gdb"))] -use std::thread; - +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use aarch64::AArch64 as Arch; +use acpi_tables::sdt::SDT; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; +use arch::LinuxArch; +use arch::RunnableLinuxVm; +use arch::VcpuAffinity; +use arch::VirtioDeviceStub; +use arch::VmComponents; +use arch::VmImage; +use arch::{self}; +use base::UnixSeqpacket; +use base::UnixSeqpacketListener; +use base::UnlinkUnixSeqpacketListener; +use base::*; +use device_helpers::*; +use devices::serial_device::SerialHardware; +use devices::vfio::VfioCommonSetup; +use devices::vfio::VfioCommonTrait; +use devices::virtio::memory_mapper::MemoryMapper; +use devices::virtio::memory_mapper::MemoryMapperTrait; +use devices::virtio::vhost::vsock::VhostVsockConfig; #[cfg(feature = "balloon")] use devices::virtio::BalloonMode; -use libc; - -use acpi_tables::sdt::SDT; - -use anyhow::{anyhow, bail, Context, Result}; -use base::*; -use base::{UnixSeqpacket, UnixSeqpacketListener, UnlinkUnixSeqpacketListener}; -use devices::serial_device::SerialHardware; -use devices::vfio::{VfioCommonSetup, VfioCommonTrait}; -use devices::virtio::memory_mapper::{MemoryMapper, MemoryMapperTrait}; -use devices::virtio::vhost::vsock::VhostVsockConfig; #[cfg(feature = "gpu")] -use devices::virtio::{self, EventDevice}; +use devices::virtio::EventDevice; +#[cfg(feature = "gpu")] +use devices::virtio::{self}; #[cfg(feature = "audio")] use devices::Ac97Dev; -use devices::{ - self, BusDeviceObj, HostHotPlugKey, HotPlugBus, IrqEventIndex, IrqEventSource, - KvmKernelIrqChip, PciAddress, PciDevice, PvPanicCode, PvPanicPciDevice, StubPciDevice, - VirtioPciDevice, -}; -use devices::{CoIommuDev, IommuDevType}; +use devices::BusDeviceObj; +use devices::CoIommuDev; #[cfg(feature = "usb")] -use devices::{HostBackendDeviceProvider, XhciController}; -use hypervisor::kvm::{Kvm, KvmVcpu, KvmVm}; -use hypervisor::{HypervisorCap, ProtectionType, Vm, VmCap}; -use minijail::{self, Minijail}; -#[cfg(feature = "direct")] -use resources::Error as ResourceError; -use resources::{AddressRange, Alloc, SystemAllocator}; -use rutabaga_gfx::RutabagaGralloc; -use sync::{Condvar, Mutex}; -use vm_control::*; -use vm_memory::{GuestAddress, GuestMemory, MemoryPolicy}; - -#[cfg(all(target_arch = "x86_64", feature = "gdb"))] -use crate::crosvm::gdb::{gdb_thread, GdbStub}; -use crate::crosvm::{ - config::{ - Config, Executable, FileBackedMappingParameters, HypervisorKind, SharedDir, SharedDirKind, - }, - sys::config::VfioType, -}; -use arch::{ - self, LinuxArch, RunnableLinuxVm, VcpuAffinity, VirtioDeviceStub, VmComponents, VmImage, -}; - -#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use { - crate::crosvm::config::HostPcieRootPortParameters, - devices::{ - IrqChipX86_64 as IrqChipArch, KvmSplitIrqChip, PciBridge, PcieHostPort, PcieRootPort, - }, - hypervisor::{VcpuX86_64 as VcpuArch, VmX86_64 as VmArch}, - x86_64::msr::get_override_msr_list, - x86_64::X8664arch as Arch, -}; +use devices::HostBackendDeviceProvider; +use devices::HostHotPlugKey; +use devices::HotPlugBus; +use devices::IommuDevType; #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] -use { - aarch64::AArch64 as Arch, - devices::IrqChipAArch64 as IrqChipArch, - hypervisor::{VcpuAArch64 as VcpuArch, VmAArch64 as VmArch}, -}; - -use device_helpers::*; -use jail_helpers::*; - +use devices::IrqChipAArch64 as IrqChipArch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use devices::IrqChipX86_64 as IrqChipArch; +use devices::IrqEventIndex; +use devices::IrqEventSource; +use devices::KvmKernelIrqChip; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use devices::KvmSplitIrqChip; +use devices::PciAddress; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use devices::PciBridge; +use devices::PciDevice; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use devices::PcieHostPort; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use devices::PcieRootPort; +use devices::PvPanicCode; +use devices::PvPanicPciDevice; +use devices::StubPciDevice; +use devices::VirtioPciDevice; +#[cfg(feature = "usb")] +use devices::XhciController; +use devices::{self}; #[cfg(feature = "gpu")] pub use gpu::GpuRenderServerParameters; #[cfg(feature = "gpu")] use gpu::*; +use hypervisor::kvm::Kvm; +use hypervisor::kvm::KvmVcpu; +use hypervisor::kvm::KvmVm; +use hypervisor::HypervisorCap; +use hypervisor::ProtectionType; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use hypervisor::VcpuAArch64 as VcpuArch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use hypervisor::VcpuX86_64 as VcpuArch; +use hypervisor::Vm; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use hypervisor::VmAArch64 as VmArch; +use hypervisor::VmCap; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use hypervisor::VmX86_64 as VmArch; +use jail_helpers::*; +use libc; +use minijail::Minijail; +use minijail::{self}; +use resources::AddressRange; +use resources::Alloc; +#[cfg(feature = "direct")] +use resources::Error as ResourceError; +use resources::SystemAllocator; +use rutabaga_gfx::RutabagaGralloc; +use sync::Condvar; +use sync::Mutex; +use vm_control::*; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +use vm_memory::MemoryPolicy; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use x86_64::msr::get_override_msr_list; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use x86_64::X8664arch as Arch; + +use crate::crosvm::config::Config; +use crate::crosvm::config::Executable; +use crate::crosvm::config::FileBackedMappingParameters; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use crate::crosvm::config::HostPcieRootPortParameters; +use crate::crosvm::config::HypervisorKind; +use crate::crosvm::config::SharedDir; +use crate::crosvm::config::SharedDirKind; +#[cfg(all(target_arch = "x86_64", feature = "gdb"))] +use crate::crosvm::gdb::gdb_thread; +#[cfg(all(target_arch = "x86_64", feature = "gdb"))] +use crate::crosvm::gdb::GdbStub; +use crate::crosvm::sys::config::VfioType; // gpu_device_tube is not used when GPU support is disabled. #[cfg_attr(not(feature = "gpu"), allow(unused_variables))] @@ -2465,9 +2514,10 @@ fn run_control( #[cfg(test)] mod tests { - use super::*; use std::path::PathBuf; + use super::*; + // Create a file-backed mapping parameters struct with the given `address` and `size` and other // parameters set to default values. fn test_file_backed_mapping(address: u64, size: u64) -> FileBackedMappingParameters { diff --git a/src/crosvm/sys/unix/android.rs b/src/crosvm/sys/unix/android.rs index c18e760b4..6cfc07515 100644 --- a/src/crosvm/sys/unix/android.rs +++ b/src/crosvm/sys/unix/android.rs @@ -4,9 +4,12 @@ #![cfg(target_os = "android")] -use anyhow::{anyhow, Result}; +use std::ffi::CStr; +use std::ffi::CString; + +use anyhow::anyhow; +use anyhow::Result; use libc; -use std::ffi::{CStr, CString}; #[link(name = "processgroup")] extern "C" { diff --git a/src/crosvm/sys/unix/cmdline.rs b/src/crosvm/sys/unix/cmdline.rs index 4cd50d6d1..42dacfb9f 100644 --- a/src/crosvm/sys/unix/cmdline.rs +++ b/src/crosvm/sys/unix/cmdline.rs @@ -2,9 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use devices::virtio::vhost::user::device; - use argh::FromArgs; +use devices::virtio::vhost::user::device; #[derive(FromArgs)] #[argh(subcommand)] diff --git a/src/crosvm/sys/unix/config.rs b/src/crosvm/sys/unix/config.rs index 559acacf8..7aa0e7472 100644 --- a/src/crosvm/sys/unix/config.rs +++ b/src/crosvm/sys/unix/config.rs @@ -2,19 +2,31 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{collections::BTreeMap, path::PathBuf, str::FromStr, time::Duration}; - -use devices::{IommuDevType, PciAddress, SerialParameters}; -use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::str::FromStr; +use std::time::Duration; #[cfg(feature = "gpu")] -use devices::virtio::{ - GpuDisplayParameters, GpuParameters, DEFAULT_DISPLAY_HEIGHT, DEFAULT_DISPLAY_WIDTH, -}; - -use crate::crosvm::config::{invalid_value_err, Config}; +use devices::virtio::GpuDisplayParameters; #[cfg(feature = "gpu")] -use crate::crosvm::{argument, argument::parse_hex_or_decimal}; +use devices::virtio::GpuParameters; +#[cfg(feature = "gpu")] +use devices::virtio::DEFAULT_DISPLAY_HEIGHT; +#[cfg(feature = "gpu")] +use devices::virtio::DEFAULT_DISPLAY_WIDTH; +use devices::IommuDevType; +use devices::PciAddress; +use devices::SerialParameters; +use serde::Deserialize; +use serde::Serialize; + +#[cfg(feature = "gpu")] +use crate::crosvm::argument; +#[cfg(feature = "gpu")] +use crate::crosvm::argument::parse_hex_or_decimal; +use crate::crosvm::config::invalid_value_err; +use crate::crosvm::config::Config; #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub enum HypervisorKind { @@ -671,15 +683,16 @@ impl VfioCommand { #[cfg(test)] mod tests { - use super::*; - use crate::crosvm::config::{DEFAULT_TOUCH_DEVICE_HEIGHT, DEFAULT_TOUCH_DEVICE_WIDTH}; - - use argh::FromArgs; use std::path::PathBuf; + use argh::FromArgs; + + use super::*; #[cfg(feature = "audio")] use crate::crosvm::config::parse_ac97_options; use crate::crosvm::config::BindMount; + use crate::crosvm::config::DEFAULT_TOUCH_DEVICE_HEIGHT; + use crate::crosvm::config::DEFAULT_TOUCH_DEVICE_WIDTH; #[cfg(feature = "audio_cras")] #[test] diff --git a/src/crosvm/sys/unix/device_helpers.rs b/src/crosvm/sys/unix/device_helpers.rs index f76fe72e5..28a94b5ec 100644 --- a/src/crosvm/sys/unix/device_helpers.rs +++ b/src/crosvm/sys/unix/device_helpers.rs @@ -4,60 +4,86 @@ use std::collections::BTreeMap; use std::convert::TryFrom; -use std::fs::{File, OpenOptions}; +use std::fs::File; +use std::fs::OpenOptions; use std::net::Ipv4Addr; use std::ops::RangeInclusive; use std::os::unix::net::UnixListener; -use std::os::unix::{net::UnixStream, prelude::OpenOptionsExt}; -use std::path::{Path, PathBuf}; +use std::os::unix::net::UnixStream; +use std::os::unix::prelude::OpenOptionsExt; +use std::path::Path; +use std::path::PathBuf; use std::str; use std::sync::Arc; -use crate::crosvm::config::{ - JailConfig, TouchDeviceOption, VhostUserFsOption, VhostUserOption, VhostUserWlOption, VvuOption, -}; -use anyhow::{anyhow, bail, Context, Result}; -use arch::{self, VirtioDeviceStub}; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; +use arch::VirtioDeviceStub; +use arch::{self}; use base::*; -use devices::serial_device::{SerialParameters, SerialType}; -use devices::vfio::{VfioCommonSetup, VfioCommonTrait}; +use devices::serial_device::SerialParameters; +use devices::serial_device::SerialType; +use devices::vfio::VfioCommonSetup; +use devices::vfio::VfioCommonTrait; use devices::virtio::block::block::DiskOption; use devices::virtio::console::asynchronous::AsyncConsole; -use devices::virtio::ipc_memory_mapper::{create_ipc_mapper, CreateIpcMapperRet}; -use devices::virtio::memory_mapper::{BasicMemoryMapper, MemoryMapperTrait}; +use devices::virtio::ipc_memory_mapper::create_ipc_mapper; +use devices::virtio::ipc_memory_mapper::CreateIpcMapperRet; +use devices::virtio::memory_mapper::BasicMemoryMapper; +use devices::virtio::memory_mapper::MemoryMapperTrait; #[cfg(feature = "audio")] use devices::virtio::snd::parameters::Parameters as SndParameters; use devices::virtio::vfio_wrapper::VfioWrapper; use devices::virtio::vhost::user::proxy::VirtioVhostUser; +use devices::virtio::vhost::user::vmm::Block as VhostUserBlock; +use devices::virtio::vhost::user::vmm::Console as VhostUserConsole; +use devices::virtio::vhost::user::vmm::Fs as VhostUserFs; +use devices::virtio::vhost::user::vmm::Mac80211Hwsim as VhostUserMac80211Hwsim; +use devices::virtio::vhost::user::vmm::Net as VhostUserNet; #[cfg(feature = "audio")] use devices::virtio::vhost::user::vmm::Snd as VhostUserSnd; -use devices::virtio::vhost::user::vmm::{ - Block as VhostUserBlock, Console as VhostUserConsole, Fs as VhostUserFs, - Mac80211Hwsim as VhostUserMac80211Hwsim, Net as VhostUserNet, Vsock as VhostUserVsock, - Wl as VhostUserWl, -}; +use devices::virtio::vhost::user::vmm::Vsock as VhostUserVsock; +use devices::virtio::vhost::user::vmm::Wl as VhostUserWl; use devices::virtio::vhost::vsock::VhostVsockConfig; #[cfg(feature = "balloon")] use devices::virtio::BalloonMode; #[cfg(any(feature = "video-decoder", feature = "video-encoder"))] use devices::virtio::VideoBackendType; -use devices::virtio::{self, VirtioDevice}; +use devices::virtio::VirtioDevice; +use devices::virtio::{self}; +use devices::BusDeviceObj; use devices::IommuDevType; +use devices::PciAddress; +use devices::PciDevice; #[cfg(feature = "tpm")] use devices::SoftwareTpm; +use devices::VfioDevice; +use devices::VfioPciDevice; +use devices::VfioPlatformDevice; #[cfg(all(feature = "tpm", feature = "chromeos", target_arch = "x86_64"))] use devices::VtpmProxy; -use devices::{ - self, BusDeviceObj, PciAddress, PciDevice, VfioDevice, VfioPciDevice, VfioPlatformDevice, -}; -use hypervisor::{ProtectionType, Vm}; -use minijail::{self, Minijail}; -use net_util::{sys::unix::Tap, MacAddress}; -use resources::{Alloc, MmioType, SystemAllocator}; +use devices::{self}; +use hypervisor::ProtectionType; +use hypervisor::Vm; +use minijail::Minijail; +use minijail::{self}; +use net_util::sys::unix::Tap; +use net_util::MacAddress; +use resources::Alloc; +use resources::MmioType; +use resources::SystemAllocator; use sync::Mutex; use vm_memory::GuestAddress; use super::jail_helpers::*; +use crate::crosvm::config::JailConfig; +use crate::crosvm::config::TouchDeviceOption; +use crate::crosvm::config::VhostUserFsOption; +use crate::crosvm::config::VhostUserOption; +use crate::crosvm::config::VhostUserWlOption; +use crate::crosvm::config::VvuOption; pub enum TaggedControlTube { Fs(Tube), diff --git a/src/crosvm/sys/unix/gpu.rs b/src/crosvm/sys/unix/gpu.rs index c38d3707a..9a2035296 100644 --- a/src/crosvm/sys/unix/gpu.rs +++ b/src/crosvm/sys/unix/gpu.rs @@ -9,11 +9,12 @@ use std::env; use std::path::PathBuf; use devices::virtio::vhost::user::vmm::Gpu as VhostUserGpu; -use serde::{Deserialize, Serialize}; - -use crate::crosvm::config::{Config, VhostUserOption}; +use serde::Deserialize; +use serde::Serialize; use super::*; +use crate::crosvm::config::Config; +use crate::crosvm::config::VhostUserOption; pub fn create_vhost_user_gpu_device( cfg: &Config, diff --git a/src/crosvm/sys/unix/jail_helpers.rs b/src/crosvm/sys/unix/jail_helpers.rs index 3d05fdeec..5397bac37 100644 --- a/src/crosvm/sys/unix/jail_helpers.rs +++ b/src/crosvm/sys/unix/jail_helpers.rs @@ -5,11 +5,16 @@ use std::path::Path; use std::str; -use libc::{self, c_ulong, gid_t, uid_t}; - -use anyhow::{bail, Context, Result}; +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; use base::*; -use minijail::{self, Minijail}; +use libc::c_ulong; +use libc::gid_t; +use libc::uid_t; +use libc::{self}; +use minijail::Minijail; +use minijail::{self}; use crate::crosvm::config::JailConfig; diff --git a/src/crosvm/sys/unix/vcpu.rs b/src/crosvm/sys/unix/vcpu.rs index cd74d04ff..9eee56210 100644 --- a/src/crosvm/sys/unix/vcpu.rs +++ b/src/crosvm/sys/unix/vcpu.rs @@ -7,35 +7,58 @@ use std::fs::File; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use std::fs::OpenOptions; use std::io::prelude::*; -use std::sync::{mpsc, Arc, Barrier}; -use sync::{Condvar, Mutex}; - +use std::sync::mpsc; +use std::sync::Arc; +use std::sync::Barrier; use std::thread; use std::thread::JoinHandle; -use libc::{self, c_int}; - -use anyhow::{Context, Result}; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use aarch64::AArch64 as Arch; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use aarch64::MsrHandlers; +use anyhow::Context; +use anyhow::Result; +use arch::LinuxArch; +use arch::MsrConfig; +use arch::{self}; use base::*; -use devices::{self, Bus, IrqChip, VcpuRunState}; -use hypervisor::{IoOperation, IoParams, Vcpu, VcpuExit, VcpuRunHandle}; +use devices::Bus; +use devices::IrqChip; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use devices::IrqChipAArch64 as IrqChipArch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use devices::IrqChipX86_64 as IrqChipArch; +use devices::VcpuRunState; +use devices::{self}; +use hypervisor::IoOperation; +use hypervisor::IoParams; +use hypervisor::Vcpu; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use hypervisor::VcpuAArch64 as VcpuArch; +use hypervisor::VcpuExit; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use hypervisor::VcpuInitAArch64 as VcpuInitArch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use hypervisor::VcpuInitX86_64 as VcpuInitArch; +use hypervisor::VcpuRunHandle; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use hypervisor::VcpuX86_64 as VcpuArch; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use hypervisor::VmAArch64 as VmArch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use hypervisor::VmX86_64 as VmArch; +use libc::c_int; +use libc::{self}; +use sync::Condvar; +use sync::Mutex; use vm_control::*; #[cfg(all(target_arch = "x86_64", feature = "gdb"))] use vm_memory::GuestMemory; - -use arch::{self, LinuxArch, MsrConfig}; -#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] -use { - aarch64::{AArch64 as Arch, MsrHandlers}, - devices::IrqChipAArch64 as IrqChipArch, - hypervisor::{VcpuAArch64 as VcpuArch, VcpuInitAArch64 as VcpuInitArch, VmAArch64 as VmArch}, -}; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use { - devices::IrqChipX86_64 as IrqChipArch, - hypervisor::{VcpuInitX86_64 as VcpuInitArch, VcpuX86_64 as VcpuArch, VmX86_64 as VmArch}, - x86_64::{msr::MsrHandlers, X8664arch as Arch}, -}; +use x86_64::msr::MsrHandlers; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use x86_64::X8664arch as Arch; use super::ExitState; diff --git a/src/crosvm/sys/windows/broker.rs b/src/crosvm/sys/windows/broker.rs index b8038f37c..092ae7abc 100644 --- a/src/crosvm/sys/windows/broker.rs +++ b/src/crosvm/sys/windows/broker.rs @@ -5,47 +5,83 @@ //! Contains the multi-process broker for crosvm. This is a work in progress, and some example //! structs here are dead code. #![allow(dead_code)] -use crate::crosvm::sys::windows::exit::{ - to_process_type_error, Exit, ExitCode, ExitCodeWrapper, ExitContext, ExitContextAnyhow, -}; -#[cfg(feature = "crash-report")] -use crash_report::CrashReportAttributes; - -use crate::{bail_exit_code, crosvm::sys::config::ProcessType, ensure_exit_code, Config}; -use anyhow::{anyhow, Context, Result}; -use base::named_pipes::{self, BlockingMode, FramingMode}; -use base::{ - error, info, syslog, warn, AsRawDescriptor, Descriptor, DuplicateHandleRequest, - DuplicateHandleResponse, Event, EventToken, RawDescriptor, ReadNotifier, SafeDescriptor, Timer, - Tube, WaitContext, -}; - -use base::enable_high_res_timers; -use broker_ipc::CommonChildStartupArgs; -#[cfg(feature = "process-invariants")] -use broker_ipc::{init_broker_process_invariants, EmulatorProcessInvariants}; -use devices::virtio::vhost::user::device::NetBackendConfig; -#[cfg(feature = "gpu")] -use gpu_display::EventDevice; -use metrics::event_details_proto::{EmulatorChildProcessExitDetails, RecordDetails}; -use metrics::{self, MetricEventType}; -use net_util::slirp::sys::windows::{SlirpStartupConfig, SLIRP_BUFFER_SIZE}; use std::boxed::Box; use std::collections::HashMap; use std::env::current_exe; use std::ffi::OsStr; -use std::fmt::{self, Debug, Display, Formatter}; +use std::fmt::Debug; +use std::fmt::Display; +use std::fmt::Formatter; +use std::fmt::{self}; use std::fs::OpenOptions; -use std::os::windows::io::{AsRawHandle, RawHandle}; -use std::path::{Path, PathBuf}; -use std::process::{self, Command}; +use std::os::windows::io::AsRawHandle; +use std::os::windows::io::RawHandle; +use std::path::Path; +use std::path::PathBuf; +use std::process::Command; +use std::process::{self}; use std::time::Duration; -use tube_transporter::{TubeToken, TubeTransferData, TubeTransporter}; + +use anyhow::anyhow; +use anyhow::Context; +use anyhow::Result; +use base::enable_high_res_timers; +use base::error; +#[cfg(feature = "crash-report")] +use base::generate_uuid; +use base::info; +use base::named_pipes::BlockingMode; +use base::named_pipes::FramingMode; +use base::named_pipes::{self}; +use base::syslog; +use base::warn; +use base::AsRawDescriptor; +use base::Descriptor; +use base::DuplicateHandleRequest; +use base::DuplicateHandleResponse; +use base::Event; +use base::EventToken; +use base::RawDescriptor; +use base::ReadNotifier; +use base::SafeDescriptor; +use base::Timer; +use base::Tube; +use base::WaitContext; +#[cfg(feature = "process-invariants")] +use broker_ipc::init_broker_process_invariants; +use broker_ipc::CommonChildStartupArgs; +#[cfg(feature = "process-invariants")] +use broker_ipc::EmulatorProcessInvariants; +#[cfg(feature = "crash-report")] +use crash_report::product_type; +#[cfg(feature = "crash-report")] +use crash_report::CrashReportAttributes; +use devices::virtio::vhost::user::device::NetBackendConfig; +#[cfg(feature = "gpu")] +use gpu_display::EventDevice; +use metrics::event_details_proto::EmulatorChildProcessExitDetails; +use metrics::event_details_proto::RecordDetails; +use metrics::MetricEventType; +use metrics::{self}; +use net_util::slirp::sys::windows::SlirpStartupConfig; +use net_util::slirp::sys::windows::SLIRP_BUFFER_SIZE; +use tube_transporter::TubeToken; +use tube_transporter::TubeTransferData; +use tube_transporter::TubeTransporter; use win_util::get_exit_code_process; use winapi::shared::winerror::ERROR_ACCESS_DENIED; use winapi::um::processthreadsapi::TerminateProcess; -#[cfg(feature = "crash-report")] -use {base::generate_uuid, crash_report::product_type}; + +use crate::bail_exit_code; +use crate::crosvm::sys::config::ProcessType; +use crate::crosvm::sys::windows::exit::to_process_type_error; +use crate::crosvm::sys::windows::exit::Exit; +use crate::crosvm::sys::windows::exit::ExitCode; +use crate::crosvm::sys::windows::exit::ExitCodeWrapper; +use crate::crosvm::sys::windows::exit::ExitContext; +use crate::crosvm::sys::windows::exit::ExitContextAnyhow; +use crate::ensure_exit_code; +use crate::Config; const KILL_CHILD_EXIT_CODE: u32 = 1; @@ -1500,9 +1536,10 @@ where #[cfg(test)] mod tests { - use super::*; use base::thread::spawn_with_timeout; + use super::*; + /// Verifies that the supervisor loop exits normally with a single child that exits. #[test] fn smoke_test() { diff --git a/src/crosvm/sys/windows/cmdline.rs b/src/crosvm/sys/windows/cmdline.rs index 699336a49..e8711cfa8 100644 --- a/src/crosvm/sys/windows/cmdline.rs +++ b/src/crosvm/sys/windows/cmdline.rs @@ -3,7 +3,6 @@ // found in the LICENSE file. use argh::FromArgs; - use argh_helpers::generate_catchall_args; #[derive(Debug, FromArgs)] #[argh(subcommand)] diff --git a/src/crosvm/sys/windows/config.rs b/src/crosvm/sys/windows/config.rs index a5c1eed6d..23fb30d97 100644 --- a/src/crosvm/sys/windows/config.rs +++ b/src/crosvm/sys/windows/config.rs @@ -9,15 +9,25 @@ use base::info; #[cfg(all(feature = "prod-build", feature = "kiwi"))] use devices::serial_device::SerialType; #[cfg(feature = "gpu")] -use devices::virtio::{GpuDisplayMode, GpuDisplayParameters, GpuMode, GpuParameters}; +use devices::virtio::GpuDisplayMode; +#[cfg(feature = "gpu")] +use devices::virtio::GpuDisplayParameters; +#[cfg(feature = "gpu")] +use devices::virtio::GpuMode; +#[cfg(feature = "gpu")] +use devices::virtio::GpuParameters; use devices::Ac97Parameters; use devices::SerialParameters; use metrics::event_details_proto::EmulatorProcessType; #[cfg(feature = "gpu")] -use rutabaga_gfx::{calculate_context_mask, RutabagaWsi}; -use serde::{Deserialize, Serialize}; +use rutabaga_gfx::calculate_context_mask; +#[cfg(feature = "gpu")] +use rutabaga_gfx::RutabagaWsi; +use serde::Deserialize; +use serde::Serialize; -use crate::crosvm::{argument, config::Config}; +use crate::crosvm::argument; +use crate::crosvm::config::Config; #[cfg(feature = "audio")] pub fn parse_ac97_options( @@ -552,11 +562,12 @@ impl FromStr for HypervisorKind { #[cfg(test)] mod tests { + #[cfg(feature = "gpu")] + use devices::virtio::gpu::GpuDisplayMode; + use super::*; #[cfg(feature = "gpu")] use crate::crosvm::sys::config::parse_gpu_options; - #[cfg(feature = "gpu")] - use devices::virtio::gpu::GpuDisplayMode; #[cfg(all(feature = "gpu", feature = "gfxstream"))] #[test] diff --git a/src/crosvm/sys/windows/exit.rs b/src/crosvm/sys/windows/exit.rs index c5e82ed35..2319fd5cc 100644 --- a/src/crosvm/sys/windows/exit.rs +++ b/src/crosvm/sys/windows/exit.rs @@ -4,10 +4,13 @@ //! Enum and Anyhow helpers to set the process exit code. -use std::fmt::{self, Display, Formatter}; +use std::fmt::Display; +use std::fmt::Formatter; +use std::fmt::{self}; + +use anyhow::Context; use crate::crosvm::sys::config::ProcessType; -use anyhow::Context; pub type ExitCode = i32; @@ -427,9 +430,10 @@ pub fn to_process_type_error(error_code: u32, cmd_type: ProcessType) -> u32 { #[cfg(test)] mod tests { - use super::*; use winapi::shared::ntstatus::STATUS_BAD_INITIAL_PC; + use super::*; + #[test] fn test_to_process_type_error_ntstatus_vendor() { let e = to_process_type_error(Exit::InvalidRunArgs as u32, ProcessType::Main); diff --git a/src/crosvm/sys/windows/stats.rs b/src/crosvm/sys/windows/stats.rs index 259852d17..cf1790102 100644 --- a/src/crosvm/sys/windows/stats.rs +++ b/src/crosvm/sys/windows/stats.rs @@ -4,7 +4,8 @@ use std::cmp::Reverse; use std::fmt; -use std::time::{Duration, Instant}; +use std::time::Duration; +use std::time::Instant; use devices::BusStatistics; use hypervisor::VcpuExit; diff --git a/src/main.rs b/src/main.rs index 3b6ce75b1..f2766420f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,38 +7,56 @@ use std::fs::OpenOptions; use std::path::Path; -use anyhow::{anyhow, Result}; +use anyhow::anyhow; +use anyhow::Result; use argh::FromArgs; +use base::error; +use base::info; +use base::syslog; use base::syslog::LogConfig; -use base::{error, info, syslog}; -use cmdline::{RunCommand, UsbAttachCommand}; +use cmdline::RunCommand; +use cmdline::UsbAttachCommand; mod crosvm; use crosvm::cmdline; #[cfg(feature = "plugin")] use crosvm::config::executable_is_plugin; use crosvm::config::Config; -use devices::virtio::vhost::user::device::{run_block_device, run_net_device}; -use disk::QcowFile; +use devices::virtio::vhost::user::device::run_block_device; +use devices::virtio::vhost::user::device::run_net_device; #[cfg(feature = "composite-disk")] -use disk::{ - create_composite_disk, create_disk_file, create_zero_filler, ImagePartitionType, PartitionInfo, -}; +use disk::create_composite_disk; +#[cfg(feature = "composite-disk")] +use disk::create_disk_file; +#[cfg(feature = "composite-disk")] +use disk::create_zero_filler; +#[cfg(feature = "composite-disk")] +use disk::ImagePartitionType; +#[cfg(feature = "composite-disk")] +use disk::PartitionInfo; +use disk::QcowFile; mod sys; -use vm_control::{ - client::{ - do_modify_battery, do_usb_attach, do_usb_detach, do_usb_list, handle_request, vms_request, - ModifyUsbResult, - }, - DiskControlCommand, UsbControlResult, VmRequest, -}; +use crosvm::cmdline::Command; +use crosvm::cmdline::CrossPlatformCommands; +use crosvm::cmdline::CrossPlatformDevicesCommands; +#[cfg(windows)] +use sys::windows::metrics; +use vm_control::client::do_modify_battery; +use vm_control::client::do_usb_attach; +use vm_control::client::do_usb_detach; +use vm_control::client::do_usb_list; +use vm_control::client::handle_request; +use vm_control::client::vms_request; +use vm_control::client::ModifyUsbResult; #[cfg(feature = "balloon")] -use vm_control::{BalloonControlCommand, VmResponse}; +use vm_control::BalloonControlCommand; +use vm_control::DiskControlCommand; +use vm_control::UsbControlResult; +use vm_control::VmRequest; +#[cfg(feature = "balloon")] +use vm_control::VmResponse; use crate::sys::error_to_exit_code; use crate::sys::init_log; -use crosvm::cmdline::{Command, CrossPlatformCommands, CrossPlatformDevicesCommands}; -#[cfg(windows)] -use sys::windows::metrics; #[cfg(feature = "scudo")] #[global_allocator] @@ -203,7 +221,8 @@ fn modify_vfio(cmd: cmdline::VfioCrosvmCommand) -> std::result::Result<(), ()> { #[cfg(feature = "composite-disk")] fn create_composite(cmd: cmdline::CreateCompositeCommand) -> std::result::Result<(), ()> { - use std::{fs::File, path::PathBuf}; + use std::fs::File; + use std::path::PathBuf; let composite_image_path = &cmd.path; let zero_filler_path = format!("{}.filler", composite_image_path); diff --git a/src/sys.rs b/src/sys.rs index 0ea17bf64..e0842305e 100644 --- a/src/sys.rs +++ b/src/sys.rs @@ -17,12 +17,13 @@ cfg_if::cfg_if! { } } -pub(crate) use platform::main::{ - cleanup, error_to_exit_code, get_library_watcher, init_log, run_command, start_device, -}; - +pub(crate) use platform::main::cleanup; +pub(crate) use platform::main::error_to_exit_code; +pub(crate) use platform::main::get_library_watcher; +pub(crate) use platform::main::init_log; +pub(crate) use platform::main::run_command; #[cfg(feature = "kiwi")] pub(crate) use platform::main::sandbox_lower_token; - +pub(crate) use platform::main::start_device; #[cfg(not(feature = "crash-report"))] pub(crate) use platform::set_panic_hook; diff --git a/src/sys/unix/main.rs b/src/sys/unix/main.rs index 4f9a9d6be..e5a8d4b04 100644 --- a/src/sys/unix/main.rs +++ b/src/sys/unix/main.rs @@ -2,22 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{thread::sleep, time::Duration}; +use std::thread::sleep; +use std::time::Duration; use anyhow::anyhow; -use base::{kill_process_group, reap_child, syslog, syslog::LogConfig, warn}; +use base::kill_process_group; +use base::reap_child; +use base::syslog; +use base::syslog::LogConfig; +use base::warn; +use devices::virtio::vhost::user::device::run_console_device; +use devices::virtio::vhost::user::device::run_fs_device; #[cfg(feature = "gpu")] use devices::virtio::vhost::user::device::run_gpu_device; #[cfg(feature = "audio_cras")] use devices::virtio::vhost::user::device::run_snd_device; -use devices::virtio::vhost::user::device::{ - run_console_device, run_fs_device, run_vsock_device, run_wl_device, -}; +use devices::virtio::vhost::user::device::run_vsock_device; +use devices::virtio::vhost::user::device::run_wl_device; -use crate::{ - crosvm::sys::cmdline::{Commands, DevicesSubcommand}, - CommandStatus, Config, -}; +use crate::crosvm::sys::cmdline::Commands; +use crate::crosvm::sys::cmdline::DevicesSubcommand; +use crate::CommandStatus; +use crate::Config; pub(crate) fn start_device(command: DevicesSubcommand) -> anyhow::Result<()> { match command { diff --git a/src/sys/unix/panic_hook.rs b/src/sys/unix/panic_hook.rs index f6625ef21..aa362c036 100644 --- a/src/sys/unix/panic_hook.rs +++ b/src/sys/unix/panic_hook.rs @@ -4,13 +4,22 @@ use std::env; use std::fs::File; -use std::io::{stderr, Read}; -use std::panic::{self, PanicInfo}; +use std::io::stderr; +use std::io::Read; +use std::panic::PanicInfo; +use std::panic::{self}; use std::process::abort; use std::string::String; -use base::{error, FromRawDescriptor, IntoRawDescriptor}; -use libc::{close, dup, dup2, pipe2, O_NONBLOCK, STDERR_FILENO}; +use base::error; +use base::FromRawDescriptor; +use base::IntoRawDescriptor; +use libc::close; +use libc::dup; +use libc::dup2; +use libc::pipe2; +use libc::O_NONBLOCK; +use libc::STDERR_FILENO; // Opens a pipe and puts the write end into the stderr FD slot. On success, returns the read end of // the pipe and the old stderr as a pair of files. diff --git a/src/sys/windows.rs b/src/sys/windows.rs index 4026e31e9..a494ff169 100644 --- a/src/sys/windows.rs +++ b/src/sys/windows.rs @@ -9,113 +9,201 @@ pub(crate) mod metrics; mod panic_hook; pub(crate) mod run_vcpu; -use irq_wait::IrqWaitWorker; -#[cfg(not(feature = "crash-report"))] -pub(crate) use panic_hook::set_panic_hook; -use run_vcpu::{run_all_vcpus, VcpuRunMode}; +#[cfg(feature = "whpx")] +use std::arch::x86_64::__cpuid; +#[cfg(feature = "whpx")] +use std::arch::x86_64::__cpuid_count; +#[cfg(feature = "gpu")] +use std::collections::BTreeMap; +#[cfg(feature = "kiwi")] +use std::convert::TryInto; +use std::fs::File; +use std::fs::OpenOptions; +use std::iter; +use std::mem; +#[cfg(feature = "gpu")] +use std::num::NonZeroU8; +use std::os::windows::fs::OpenOptionsExt; +use std::sync::Arc; -use crate::crosvm::config::{Config, Executable}; -use crate::crosvm::sys::windows::exit::{Exit, ExitContext, ExitContextAnyhow}; -use crate::crosvm::sys::windows::stats::StatisticsCollector; - -use crate::sys::windows::metrics::{log_descriptor, MetricEventType}; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use aarch64::AArch64 as Arch; use acpi_tables::sdt::SDT; #[cfg(all(feature = "kiwi", feature = "anti-tamper",))] use anti_tamper::spawn_dedicated_anti_tamper_thread; +use anyhow::anyhow; +use anyhow::bail; #[cfg(feature = "kiwi")] use anyhow::ensure; -use anyhow::{anyhow, bail, Context, Result}; -use arch::{self, LinuxArch, RunnableLinuxVm, VirtioDeviceStub, VmComponents, VmImage}; +use anyhow::Context; +use anyhow::Result; +use arch::LinuxArch; +use arch::RunnableLinuxVm; +use arch::VirtioDeviceStub; +use arch::VmComponents; +use arch::VmImage; +use arch::{self}; +use base::enable_high_res_timers; +use base::error; #[cfg(feature = "kiwi")] use base::give_foregrounding_permission; -use base::{ - self, enable_high_res_timers, error, info, warn, Event, EventToken, ExternalMapping, - FromRawDescriptor, RawDescriptor, ReadNotifier, RecvTube, SendTube, Tube, TubeError, - VmEventType, WaitContext, -}; -use devices::serial_device::{SerialHardware, SerialParameters}; +use base::info; +use base::warn; +#[cfg(feature = "gpu")] +use base::BlockingMode; +use base::Event; +use base::EventToken; +use base::ExternalMapping; +#[cfg(feature = "gpu")] +use base::FramingMode; +use base::FromRawDescriptor; +use base::RawDescriptor; +use base::ReadNotifier; +use base::RecvTube; +use base::SendTube; +#[cfg(feature = "gpu")] +use base::StreamChannel; +use base::Tube; +use base::TubeError; +use base::VmEventType; +use base::WaitContext; +use base::{self}; +use broker_ipc::common_child_setup; +use broker_ipc::CommonChildStartupArgs; +use devices::serial_device::SerialHardware; +use devices::serial_device::SerialParameters; +use devices::tsc::get_tsc_sync_mitigations; +use devices::tsc::standard_deviation; +use devices::tsc::TscSyncMitigations; use devices::virtio::block::block::DiskOption; -use devices::virtio::{self, BalloonMode, Console, PvClock}; +use devices::virtio::BalloonMode; +use devices::virtio::Console; +use devices::virtio::PvClock; +use devices::virtio::{self}; +use devices::Ac97Dev; +use devices::BusDeviceObj; +#[cfg(feature = "gvm")] +use devices::GvmIrqChip; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use devices::IrqChip; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use devices::IrqChipAArch64 as IrqChipArch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use devices::IrqChipX86_64 as IrqChipArch; use devices::Minijail; -use devices::{ - self, - tsc::{get_tsc_sync_mitigations, standard_deviation, TscSyncMitigations}, - Ac97Dev, BusDeviceObj, UserspaceIrqChip, VirtioPciDevice, -}; +use devices::UserspaceIrqChip; +use devices::VirtioPciDevice; +#[cfg(feature = "whpx")] +use devices::WhpxSplitIrqChip; +use devices::{self}; +#[cfg(feature = "gpu")] +use gpu_display::EventDevice; +#[cfg(feature = "gvm")] +use hypervisor::gvm::Gvm; +#[cfg(feature = "gvm")] +use hypervisor::gvm::GvmVcpu; +#[cfg(feature = "gvm")] +use hypervisor::gvm::GvmVersion; +#[cfg(feature = "gvm")] +use hypervisor::gvm::GvmVm; #[cfg(feature = "haxm")] -use hypervisor::haxm::{get_use_ghaxm, set_use_ghaxm, Haxm, HaxmVcpu, HaxmVm}; -use hypervisor::{ProtectionType, Vm}; +use hypervisor::haxm::get_use_ghaxm; +#[cfg(feature = "haxm")] +use hypervisor::haxm::set_use_ghaxm; +#[cfg(feature = "haxm")] +use hypervisor::haxm::Haxm; +#[cfg(feature = "haxm")] +use hypervisor::haxm::HaxmVcpu; +#[cfg(feature = "haxm")] +use hypervisor::haxm::HaxmVm; +#[cfg(feature = "whpx")] +use hypervisor::whpx::Whpx; +#[cfg(feature = "whpx")] +use hypervisor::whpx::WhpxFeature; +#[cfg(feature = "whpx")] +use hypervisor::whpx::WhpxVcpu; +#[cfg(feature = "whpx")] +use hypervisor::whpx::WhpxVm; +#[cfg(feature = "whpx")] +use hypervisor::Hypervisor; +#[cfg(feature = "whpx")] +use hypervisor::HypervisorCap; +#[cfg(feature = "whpx")] +use hypervisor::HypervisorX86_64; +use hypervisor::ProtectionType; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use hypervisor::VcpuAArch64 as VcpuArch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use hypervisor::VcpuX86_64 as VcpuArch; +use hypervisor::Vm; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use hypervisor::VmAArch64 as VmArch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use hypervisor::VmX86_64 as VmArch; +use irq_wait::IrqWaitWorker; +#[cfg(not(feature = "crash-report"))] +pub(crate) use panic_hook::set_panic_hook; use resources::SystemAllocator; +use run_vcpu::run_all_vcpus; +use run_vcpu::VcpuRunMode; use rutabaga_gfx::RutabagaGralloc; #[cfg(feature = "kiwi")] -use std::convert::TryInto; -use std::fs::{File, OpenOptions}; -use std::iter; -use std::mem; -use std::os::windows::fs::OpenOptionsExt; -use std::sync::Arc; -use sync::Mutex; -use tracing; +use service_ipc::get_balloon_size; #[cfg(feature = "kiwi")] -use vm_control::{ - Ac97Control, BalloonControlCommand, - GpuSendToMain::{self, MuteAc97, SendToService}, - PvClockCommand, PvClockCommandResponse, ServiceSendToGpu, -}; -#[cfg(feature = "gvm")] -use { - devices::GvmIrqChip, - hypervisor::gvm::{Gvm, GvmVcpu, GvmVersion, GvmVm}, -}; - -use vm_control::{VmMemoryRequest, VmRunMode}; -use vm_memory::GuestMemory; -use winapi::um::winnt::FILE_SHARE_READ; -#[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), feature = "haxm"))] -use x86_64::{get_cpu_manufacturer, CpuManufacturer}; - -#[cfg(feature = "gpu")] -use { - crate::crosvm::config::TouchDeviceOption, - base::{BlockingMode, FramingMode, StreamChannel}, - gpu_display::EventDevice, - std::collections::BTreeMap, - std::num::NonZeroU8, -}; -#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] -use { - aarch64::AArch64 as Arch, - devices::{IrqChip, IrqChipAArch64 as IrqChipArch}, - hypervisor::{VcpuAArch64 as VcpuArch, VmAArch64 as VmArch}, -}; -#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use { - devices::IrqChipX86_64 as IrqChipArch, - hypervisor::{VcpuX86_64 as VcpuArch, VmX86_64 as VmArch}, - x86_64::X8664arch as Arch, -}; - -#[cfg(feature = "whpx")] -use { - devices::WhpxSplitIrqChip, - hypervisor::whpx::{Whpx, WhpxFeature, WhpxVcpu, WhpxVm}, - hypervisor::Hypervisor, - hypervisor::HypervisorCap, - hypervisor::HypervisorX86_64, - std::arch::x86_64::{__cpuid, __cpuid_count}, - x86_64::cpuid::{adjust_cpuid, CpuIdContext}, -}; - -use crate::crosvm::sys::config::{HypervisorKind, IrqChipKind}; -use broker_ipc::{common_child_setup, CommonChildStartupArgs}; +use service_ipc::request_utilities::prod::MessageFromService; #[cfg(all(feature = "kiwi", feature = "anti-tamper"))] use service_ipc::request_utilities::prod::MessageToService; #[cfg(feature = "kiwi")] -use service_ipc::{ - get_balloon_size, request_utilities::prod::MessageFromService, - service_vm_state::ServiceVmState, ServiceIpc, -}; -use tube_transporter::{TubeToken, TubeTransporterReader}; +use service_ipc::service_vm_state::ServiceVmState; +#[cfg(feature = "kiwi")] +use service_ipc::ServiceIpc; +use sync::Mutex; +use tracing; +use tube_transporter::TubeToken; +use tube_transporter::TubeTransporterReader; +#[cfg(feature = "kiwi")] +use vm_control::Ac97Control; +#[cfg(feature = "kiwi")] +use vm_control::BalloonControlCommand; +#[cfg(feature = "kiwi")] +use vm_control::GpuSendToMain::MuteAc97; +#[cfg(feature = "kiwi")] +use vm_control::GpuSendToMain::SendToService; +#[cfg(feature = "kiwi")] +use vm_control::GpuSendToMain::{self}; +#[cfg(feature = "kiwi")] +use vm_control::PvClockCommand; +#[cfg(feature = "kiwi")] +use vm_control::PvClockCommandResponse; +#[cfg(feature = "kiwi")] +use vm_control::ServiceSendToGpu; +use vm_control::VmMemoryRequest; +use vm_control::VmRunMode; +use vm_memory::GuestMemory; +use winapi::um::winnt::FILE_SHARE_READ; +#[cfg(feature = "whpx")] +use x86_64::cpuid::adjust_cpuid; +#[cfg(feature = "whpx")] +use x86_64::cpuid::CpuIdContext; +#[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), feature = "haxm"))] +use x86_64::get_cpu_manufacturer; +#[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), feature = "haxm"))] +use x86_64::CpuManufacturer; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use x86_64::X8664arch as Arch; + +use crate::crosvm::config::Config; +use crate::crosvm::config::Executable; +#[cfg(feature = "gpu")] +use crate::crosvm::config::TouchDeviceOption; +use crate::crosvm::sys::config::HypervisorKind; +use crate::crosvm::sys::config::IrqChipKind; +use crate::crosvm::sys::windows::exit::Exit; +use crate::crosvm::sys::windows::exit::ExitContext; +use crate::crosvm::sys::windows::exit::ExitContextAnyhow; +use crate::crosvm::sys::windows::stats::StatisticsCollector; +use crate::sys::windows::metrics::log_descriptor; +use crate::sys::windows::metrics::MetricEventType; const DEFAULT_GUEST_CID: u64 = 3; @@ -2034,9 +2122,10 @@ where #[cfg(test)] mod tests { - use super::*; use tempfile::TempDir; + use super::*; + fn create_config(test_dir: &TempDir) -> Config { let mut config = Config::default(); diff --git a/src/sys/windows/irq_wait.rs b/src/sys/windows/irq_wait.rs index 8fe773c30..fb86df5fc 100644 --- a/src/sys/windows/irq_wait.rs +++ b/src/sys/windows/irq_wait.rs @@ -5,23 +5,37 @@ //! Handles the main wait loop for IRQs. //! Should be started on a background thread. -use base::{ - error, info, warn, Event, EventToken, ReadNotifier, Result, Tube, TubeError, WaitContext, - MAXIMUM_WAIT_OBJECTS, -}; +use std::collections::HashMap; +use std::sync::Arc; +use std::thread::JoinHandle; +use std::thread::{self}; +use std::time::Duration; +use std::time::Instant; + +use base::error; +use base::info; +use base::warn; +use base::Event; +use base::EventToken; +use base::ReadNotifier; +use base::Result; +use base::Tube; +use base::TubeError; +use base::WaitContext; +use base::MAXIMUM_WAIT_OBJECTS; #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] use devices::IrqChipAArch64 as IrqChipArch; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use devices::IrqChipX86_64 as IrqChipArch; -use devices::{IrqEdgeEvent, IrqEventIndex, IrqEventSource}; -use metrics::{log_high_frequency_descriptor_event, MetricEventType}; +use devices::IrqEdgeEvent; +use devices::IrqEventIndex; +use devices::IrqEventSource; +use metrics::log_high_frequency_descriptor_event; +use metrics::MetricEventType; use resources::SystemAllocator; -use std::collections::HashMap; -use std::sync::Arc; -use std::thread::{self, JoinHandle}; -use std::time::{Duration, Instant}; use sync::Mutex; -use vm_control::{IrqSetup, VmIrqRequest}; +use vm_control::IrqSetup; +use vm_control::VmIrqRequest; pub struct IrqWaitWorker { exit_evt: Event, diff --git a/src/sys/windows/main.rs b/src/sys/windows/main.rs index 9fba29c30..8c4b495d5 100644 --- a/src/sys/windows/main.rs +++ b/src/sys/windows/main.rs @@ -2,38 +2,42 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use anyhow::{anyhow, Result}; -use argh::FromArgs; -use base::{ - info, - syslog::{self, LogConfig}, - FromRawDescriptor, RawDescriptor, -}; -use broker_ipc::{common_child_setup, CommonChildStartupArgs}; -use metrics::{ - self, - event_details_proto::{EmulatorDllDetails, RecordDetails}, - MetricEventType, -}; -#[cfg(all(feature = "slirp"))] -use net_util::slirp::sys::windows::SlirpStartupConfig; -use tube_transporter::{TubeToken, TubeTransporterReader}; -use win_util::{DllNotificationData, DllWatcher}; - use std::collections::HashSet; use std::ffi::OsString; use std::fs::OpenOptions; -use crate::{ - crosvm::{ - argument::{self, Argument}, - cmdline::RunCommand, - sys::cmdline::{Commands, DevicesSubcommand}, - sys::windows::exit::{Exit, ExitContext, ExitContextAnyhow}, - }, - metrics::run_metrics, - CommandStatus, Config, -}; +use anyhow::anyhow; +use anyhow::Result; +use argh::FromArgs; +use base::info; +use base::syslog::LogConfig; +use base::syslog::{self}; +use base::FromRawDescriptor; +use base::RawDescriptor; +use broker_ipc::common_child_setup; +use broker_ipc::CommonChildStartupArgs; +use metrics::event_details_proto::EmulatorDllDetails; +use metrics::event_details_proto::RecordDetails; +use metrics::MetricEventType; +use metrics::{self}; +#[cfg(all(feature = "slirp"))] +use net_util::slirp::sys::windows::SlirpStartupConfig; +use tube_transporter::TubeToken; +use tube_transporter::TubeTransporterReader; +use win_util::DllNotificationData; +use win_util::DllWatcher; + +use crate::crosvm::argument::Argument; +use crate::crosvm::argument::{self}; +use crate::crosvm::cmdline::RunCommand; +use crate::crosvm::sys::cmdline::Commands; +use crate::crosvm::sys::cmdline::DevicesSubcommand; +use crate::crosvm::sys::windows::exit::Exit; +use crate::crosvm::sys::windows::exit::ExitContext; +use crate::crosvm::sys::windows::exit::ExitContextAnyhow; +use crate::metrics::run_metrics; +use crate::CommandStatus; +use crate::Config; #[cfg(all(feature = "slirp"))] pub(crate) fn run_slirp(args: Vec) -> Result<()> { diff --git a/src/sys/windows/metrics.rs b/src/sys/windows/metrics.rs index 3a29a3bbd..9cbb88595 100644 --- a/src/sys/windows/metrics.rs +++ b/src/sys/windows/metrics.rs @@ -17,13 +17,16 @@ cfg_if::cfg_if! { } } +use anyhow::Result; +pub(crate) use metrics::get_destructor; +pub(crate) use metrics::log_descriptor; +pub(crate) use metrics::merge_session_invariants; +pub(crate) use metrics::set_auth_token; +pub(crate) use metrics::set_package_name; +pub(crate) use metrics::MetricEventType; + #[cfg(feature = "kiwi")] use crate::crosvm::argument::Argument; -use anyhow::Result; -pub(crate) use metrics::{ - get_destructor, log_descriptor, merge_session_invariants, set_auth_token, set_package_name, - MetricEventType, -}; pub(crate) fn run_metrics(#[allow(unused_variables)] args: Vec) -> Result<()> { #[cfg(not(feature = "kiwi"))] diff --git a/src/sys/windows/run_vcpu.rs b/src/sys/windows/run_vcpu.rs index 54aa5076e..79888a7e1 100644 --- a/src/sys/windows/run_vcpu.rs +++ b/src/sys/windows/run_vcpu.rs @@ -2,54 +2,92 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use anyhow::{anyhow, Result}; -use arch::{self, LinuxArch, RunnableLinuxVm, VcpuAffinity}; -use base::{ - self, error, info, set_audio_thread_priorities, set_cpu_affinity, warn, Event, - Result as BaseResult, SafeMultimediaHandle, SendTube, Timer, Tube, VmEventType, -}; -use std::{ - arch::x86_64::{__cpuid, __cpuid_count}, - fmt::Display, -}; +use std::arch::x86_64::__cpuid; +use std::arch::x86_64::__cpuid_count; +use std::convert::TryInto; +use std::fmt; +use std::fmt::Display; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::sync::Barrier; +use std::thread; +use std::thread::JoinHandle; +use std::time::Duration; +use std::time::Instant; #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] -use { - aarch64::AArch64 as Arch, - devices::{IrqChip, IrqChipAArch64 as IrqChipArch}, - hypervisor::{VcpuAArch64 as VcpuArch, VmAArch64 as VmArch}, -}; +use aarch64::AArch64 as Arch; +use anyhow::anyhow; +use anyhow::Result; +use arch::LinuxArch; +use arch::RunnableLinuxVm; +use arch::VcpuAffinity; +use arch::{self}; +use base::error; +use base::info; +use base::set_audio_thread_priorities; +use base::set_cpu_affinity; +use base::warn; +use base::Event; +use base::Result as BaseResult; +use base::SafeMultimediaHandle; +use base::SendTube; +use base::Timer; +use base::Tube; +use base::VmEventType; +use base::{self}; +use cros_async::select2; +use cros_async::EventAsync; +use cros_async::Executor; +use cros_async::SelectResult; +use cros_async::TimerAsync; +use devices::tsc::TscSyncMitigations; +use devices::Bus; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use devices::IrqChip; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use devices::IrqChipAArch64 as IrqChipArch; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use { - devices::IrqChipX86_64 as IrqChipArch, - hypervisor::{VcpuX86_64 as VcpuArch, VmX86_64 as VmArch}, - x86_64::cpuid::{adjust_cpuid, CpuIdContext}, - x86_64::X8664arch as Arch, -}; - -use crate::bail_exit_code; -use crate::crosvm::sys::windows::exit::{Exit, ExitContext, ExitContextAnyhow}; -use crate::crosvm::sys::windows::stats::{StatisticsCollector, VmExitStatistics}; -use crate::sys::windows::save_vcpu_tsc_offset; -use cros_async::{select2, EventAsync, Executor, SelectResult, TimerAsync}; -use devices::{tsc::TscSyncMitigations, Bus, VcpuRunState}; +use devices::IrqChipX86_64 as IrqChipArch; +use devices::VcpuRunState; use futures::pin_mut; #[cfg(feature = "whpx")] use hypervisor::whpx::WhpxVcpu; -use hypervisor::{ - HypervisorCap, IoEventAddress, IoOperation, IoParams, VcpuExit, VcpuInitX86_64, VcpuRunHandle, -}; -use std::convert::TryInto; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Barrier}; -use std::thread::JoinHandle; -use std::time::{Duration, Instant}; -use std::{fmt, thread}; -use sync::{Condvar, Mutex}; +use hypervisor::HypervisorCap; +use hypervisor::IoEventAddress; +use hypervisor::IoOperation; +use hypervisor::IoParams; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use hypervisor::VcpuAArch64 as VcpuArch; +use hypervisor::VcpuExit; +use hypervisor::VcpuInitX86_64; +use hypervisor::VcpuRunHandle; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use hypervisor::VcpuX86_64 as VcpuArch; +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +use hypervisor::VmAArch64 as VmArch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use hypervisor::VmX86_64 as VmArch; +use sync::Condvar; +use sync::Mutex; use tracing::trace_event; use vm_control::VmRunMode; use winapi::shared::winerror::ERROR_RETRY; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use x86_64::cpuid::adjust_cpuid; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use x86_64::cpuid::CpuIdContext; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use x86_64::X8664arch as Arch; +use crate::bail_exit_code; +use crate::crosvm::sys::windows::exit::Exit; +use crate::crosvm::sys::windows::exit::ExitContext; +use crate::crosvm::sys::windows::exit::ExitContextAnyhow; +use crate::crosvm::sys::windows::stats::StatisticsCollector; +use crate::crosvm::sys::windows::stats::VmExitStatistics; +use crate::sys::windows::save_vcpu_tsc_offset; use crate::sys::windows::ExitState; const ERROR_RETRY_I32: i32 = ERROR_RETRY as i32; diff --git a/tests/plugins.rs b/tests/plugins.rs index 1cc628e7d..63442b2ae 100644 --- a/tests/plugins.rs +++ b/tests/plugins.rs @@ -4,17 +4,23 @@ #![cfg(feature = "plugin")] -use std::env::{current_exe, var_os}; +use std::env::current_exe; +use std::env::var_os; use std::ffi::OsString; use std::fs::remove_file; -use std::io::{Read, Write}; -use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::io::Read; +use std::io::Write; +use std::path::Path; +use std::path::PathBuf; +use std::process::Command; +use std::process::Stdio; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; use std::thread::sleep; use std::time::Duration; -use base::{ioctl, AsRawDescriptor}; +use base::ioctl; +use base::AsRawDescriptor; use net_util::TapTCommon; use once_cell::sync::Lazy; use tempfile::tempfile; diff --git a/third_party/libslirp-rs/src/context.rs b/third_party/libslirp-rs/src/context.rs index b7d87648e..2965b2d2c 100644 --- a/third_party/libslirp-rs/src/context.rs +++ b/third_party/libslirp-rs/src/context.rs @@ -35,15 +35,25 @@ // Some bindings of the libslirp API are used, but we want to keep them for completeness #![allow(dead_code)] +use std::ffi::CStr; +use std::ffi::CString; +use std::fmt; +use std::io; +use std::net::Ipv4Addr; +use std::net::Ipv6Addr; +use std::ops; +use std::os::raw::c_char; +use std::os::raw::c_int; +use std::os::raw::c_void; +use std::slice; +use std::str; + +use base::error; +use base::RawDescriptor; use libslirp_sys::*; -use crate::{Error, Result}; - -use base::{error, RawDescriptor}; -use std::ffi::{CStr, CString}; -use std::net::{Ipv4Addr, Ipv6Addr}; -use std::os::raw::{c_char, c_int, c_void}; -use std::{fmt, io, ops, slice, str}; +use crate::Error; +use crate::Result; /// An instance of libslirp is represented by a Context, which provides methods that consumers use /// to interact with Slirp. The Context is also where consumers register their CallbackHandler, diff --git a/tools/examples/baremetal/src/main.rs b/tools/examples/baremetal/src/main.rs index 0b063ed0d..38333b7d8 100644 --- a/tools/examples/baremetal/src/main.rs +++ b/tools/examples/baremetal/src/main.rs @@ -5,7 +5,8 @@ #![no_std] // don't link the Rust standard library #![no_main] // disable all Rust-level entry points -use core::arch::{asm, global_asm}; +use core::arch::asm; +use core::arch::global_asm; use core::panic::PanicInfo; use log::*; diff --git a/tpm2-sys/build.rs b/tpm2-sys/build.rs index d8c3fc796..f2a78ad52 100644 --- a/tpm2-sys/build.rs +++ b/tpm2-sys/build.rs @@ -2,12 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use anyhow::{bail, Result}; use std::env; use std::path::Path; use std::path::PathBuf; use std::process::Command; +use anyhow::bail; +use anyhow::Result; + /// Returns the target triplet prefix for gcc commands. No prefix is required /// for native builds. fn get_cross_compile_prefix() -> String { diff --git a/tpm2-sys/src/lib.rs b/tpm2-sys/src/lib.rs index 089ba10b6..5f50698b9 100644 --- a/tpm2-sys/src/lib.rs +++ b/tpm2-sys/src/lib.rs @@ -4,7 +4,9 @@ //! Bindings for the TPM2 simulator library. -use std::os::raw::{c_int, c_uchar, c_uint}; +use std::os::raw::c_int; +use std::os::raw::c_uchar; +use std::os::raw::c_uint; extern "C" { pub fn TPM_Manufacture(firstTime: c_int) -> c_int; diff --git a/tpm2/src/lib.rs b/tpm2/src/lib.rs index 468f889ec..617d54197 100644 --- a/tpm2/src/lib.rs +++ b/tpm2/src/lib.rs @@ -4,10 +4,12 @@ //! TPM2 (Trusted Platform Module 2.0) simulator. -use std::os::raw::{c_int, c_uint}; +use std::os::raw::c_int; +use std::os::raw::c_uint; use std::ptr; use std::slice; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; static SIMULATOR_EXISTS: AtomicBool = AtomicBool::new(false); diff --git a/tube_transporter/src/lib.rs b/tube_transporter/src/lib.rs index 34d22353e..fe1867684 100644 --- a/tube_transporter/src/lib.rs +++ b/tube_transporter/src/lib.rs @@ -8,14 +8,23 @@ //! This IPC crate is used by the broker process to send boot data across the //! different CrosVm child processes on Windows. -use base::named_pipes::{BlockingMode, FramingMode}; -use base::{ - deserialize_and_recv, named_pipes::PipeConnection, serialize_and_send, set_alias_pid, - set_duplicate_handle_tube, DuplicateHandleTube, FromRawDescriptor, RawDescriptor, Tube, - TubeError, -}; -use serde::{Deserialize, Serialize}; -use std::fmt::{self, Display}; +use std::fmt::Display; +use std::fmt::{self}; + +use base::deserialize_and_recv; +use base::named_pipes::BlockingMode; +use base::named_pipes::FramingMode; +use base::named_pipes::PipeConnection; +use base::serialize_and_send; +use base::set_alias_pid; +use base::set_duplicate_handle_tube; +use base::DuplicateHandleTube; +use base::FromRawDescriptor; +use base::RawDescriptor; +use base::Tube; +use base::TubeError; +use serde::Deserialize; +use serde::Serialize; use thiserror::Error as ThisError; pub type TransportTubeResult = std::result::Result; @@ -174,14 +183,17 @@ impl TubeTransferDataList { #[cfg(test)] mod tests { - use super::*; - use base::{ - named_pipes::{pair, BlockingMode, FramingMode}, - Event, EventReadResult, - }; use std::thread; + + use base::named_pipes::pair; + use base::named_pipes::BlockingMode; + use base::named_pipes::FramingMode; + use base::Event; + use base::EventReadResult; use winapi::um::processthreadsapi::GetCurrentProcessId; + use super::*; + #[test] fn test_send_tubes_through_tube_transporter() { let (broker_pipe_connection_server, child_process_pipe) = pair( diff --git a/usb_sys/src/lib.rs b/usb_sys/src/lib.rs index 5539ae4b8..f9aeb6665 100644 --- a/usb_sys/src/lib.rs +++ b/usb_sys/src/lib.rs @@ -10,9 +10,16 @@ #![allow(non_camel_case_types)] #![allow(non_snake_case)] -use std::os::raw::{c_char, c_int, c_uchar, c_uint, c_void}; +use std::os::raw::c_char; +use std::os::raw::c_int; +use std::os::raw::c_uchar; +use std::os::raw::c_uint; +use std::os::raw::c_void; -use base::{ioctl_io_nr, ioctl_ior_nr, ioctl_iow_nr, ioctl_iowr_nr}; +use base::ioctl_io_nr; +use base::ioctl_ior_nr; +use base::ioctl_iow_nr; +use base::ioctl_iowr_nr; #[repr(C)] #[derive(Default)] diff --git a/usb_util/src/descriptor.rs b/usb_util/src/descriptor.rs index adf48d83a..7784b2715 100644 --- a/usb_util/src/descriptor.rs +++ b/usb_util/src/descriptor.rs @@ -2,14 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::types::{self, Descriptor, DescriptorHeader, EndpointDescriptor}; -use crate::{Error, Result}; -use base::warn; -use data_model::DataInit; use std::collections::BTreeMap; use std::mem::size_of; use std::ops::Deref; +use base::warn; +use data_model::DataInit; + +use crate::types::Descriptor; +use crate::types::DescriptorHeader; +use crate::types::EndpointDescriptor; +use crate::types::{self}; +use crate::Error; +use crate::Result; + #[derive(Clone)] pub struct DeviceDescriptorTree { // Full descriptor tree in the original format returned by the device. diff --git a/usb_util/src/device.rs b/usb_util/src/device.rs index d07d3ccd9..381bc095a 100644 --- a/usb_util/src/device.rs +++ b/usb_util/src/device.rs @@ -2,21 +2,38 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::{ - control_request_type, descriptor, ConfigDescriptorTree, - ControlRequestDataPhaseTransferDirection, ControlRequestRecipient, ControlRequestType, - DeviceDescriptor, DeviceDescriptorTree, Error, Result, StandardControlRequest, -}; -use base::{handle_eintr_errno, AsRawDescriptor, IoctlNr, RawDescriptor}; -use data_model::vec_with_array_field; -use libc::{EAGAIN, ENODEV, ENOENT}; use std::convert::TryInto; use std::fs::File; -use std::io::{Read, Seek, SeekFrom}; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; use std::mem::size_of_val; -use std::os::raw::{c_int, c_uint, c_void}; +use std::os::raw::c_int; +use std::os::raw::c_uint; +use std::os::raw::c_void; use std::sync::Arc; +use base::handle_eintr_errno; +use base::AsRawDescriptor; +use base::IoctlNr; +use base::RawDescriptor; +use data_model::vec_with_array_field; +use libc::EAGAIN; +use libc::ENODEV; +use libc::ENOENT; + +use crate::control_request_type; +use crate::descriptor; +use crate::ConfigDescriptorTree; +use crate::ControlRequestDataPhaseTransferDirection; +use crate::ControlRequestRecipient; +use crate::ControlRequestType; +use crate::DeviceDescriptor; +use crate::DeviceDescriptorTree; +use crate::Error; +use crate::Result; +use crate::StandardControlRequest; + /// Device represents a USB device. pub struct Device { fd: Arc, diff --git a/usb_util/src/error.rs b/usb_util/src/error.rs index b24fccd36..5aa5192f7 100644 --- a/usb_util/src/error.rs +++ b/usb_util/src/error.rs @@ -2,10 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::IoctlNr; -use remain::sorted; use std::io; use std::num; + +use base::IoctlNr; +use remain::sorted; use thiserror::Error; #[sorted] diff --git a/usb_util/src/lib.rs b/usb_util/src/lib.rs index 21342c96f..9d27bc230 100644 --- a/usb_util/src/lib.rs +++ b/usb_util/src/lib.rs @@ -9,14 +9,27 @@ mod device; mod error; mod types; -pub use self::descriptor::{ - parse_usbfs_descriptors, ConfigDescriptorTree, DeviceDescriptorTree, InterfaceDescriptorTree, -}; -pub use self::device::{Device, Transfer, TransferStatus}; -pub use self::error::{Error, Result}; -pub use self::types::{ - control_request_type, ConfigDescriptor, ControlRequestDataPhaseTransferDirection, - ControlRequestRecipient, ControlRequestType, DescriptorHeader, DescriptorType, - DeviceDescriptor, EndpointDescriptor, EndpointDirection, EndpointType, InterfaceDescriptor, - StandardControlRequest, UsbRequestSetup, ENDPOINT_DIRECTION_OFFSET, -}; +pub use self::descriptor::parse_usbfs_descriptors; +pub use self::descriptor::ConfigDescriptorTree; +pub use self::descriptor::DeviceDescriptorTree; +pub use self::descriptor::InterfaceDescriptorTree; +pub use self::device::Device; +pub use self::device::Transfer; +pub use self::device::TransferStatus; +pub use self::error::Error; +pub use self::error::Result; +pub use self::types::control_request_type; +pub use self::types::ConfigDescriptor; +pub use self::types::ControlRequestDataPhaseTransferDirection; +pub use self::types::ControlRequestRecipient; +pub use self::types::ControlRequestType; +pub use self::types::DescriptorHeader; +pub use self::types::DescriptorType; +pub use self::types::DeviceDescriptor; +pub use self::types::EndpointDescriptor; +pub use self::types::EndpointDirection; +pub use self::types::EndpointType; +pub use self::types::InterfaceDescriptor; +pub use self::types::StandardControlRequest; +pub use self::types::UsbRequestSetup; +pub use self::types::ENDPOINT_DIRECTION_OFFSET; diff --git a/usb_util/src/types.rs b/usb_util/src/types.rs index 7eb94ca2b..316f8316a 100644 --- a/usb_util/src/types.rs +++ b/usb_util/src/types.rs @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::mem::size_of; + use assertions::const_assert; use data_model::DataInit; -use std::mem::size_of; - /// Standard USB descriptor types. pub enum DescriptorType { Device = 0x01, diff --git a/vhost/src/lib.rs b/vhost/src/lib.rs index 0cb470115..f5ba5d234 100644 --- a/vhost/src/lib.rs +++ b/vhost/src/lib.rs @@ -8,20 +8,29 @@ pub mod net; mod vsock; -#[cfg(unix)] -pub use crate::net::{Net, NetT}; -pub use crate::vsock::Vsock; - use std::alloc::Layout; use std::io::Error as IoError; use std::ptr::null; use assertions::const_assert; -use base::{ioctl, ioctl_with_mut_ref, ioctl_with_ptr, ioctl_with_ref}; -use base::{AsRawDescriptor, Event, LayoutAllocation}; +use base::ioctl; +use base::ioctl_with_mut_ref; +use base::ioctl_with_ptr; +use base::ioctl_with_ref; +use base::AsRawDescriptor; +use base::Event; +use base::LayoutAllocation; use remain::sorted; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory, GuestMemoryError}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +use vm_memory::GuestMemoryError; + +#[cfg(unix)] +pub use crate::net::Net; +#[cfg(unix)] +pub use crate::net::NetT; +pub use crate::vsock::Vsock; #[sorted] #[derive(Error, Debug)] @@ -390,12 +399,16 @@ pub trait Vhost: AsRawDescriptor + std::marker::Sized { #[cfg(unix)] #[cfg(test)] mod tests { - use super::*; + use std::path::PathBuf; + use std::result; - use crate::net::fakes::FakeNet; use net_util::sys::unix::fakes::FakeTap; - use std::{path::PathBuf, result}; - use vm_memory::{GuestAddress, GuestMemory, GuestMemoryError}; + use vm_memory::GuestAddress; + use vm_memory::GuestMemory; + use vm_memory::GuestMemoryError; + + use super::*; + use crate::net::fakes::FakeNet; fn create_guest_memory() -> result::Result { let start_addr1 = GuestAddress(0x0); diff --git a/vhost/src/net.rs b/vhost/src/net.rs index 3c521d2f6..b6e5f1bea 100644 --- a/vhost/src/net.rs +++ b/vhost/src/net.rs @@ -2,17 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use net_util::TapT; +use std::fs::File; +use std::fs::OpenOptions; use std::marker::PhantomData; use std::os::unix::fs::OpenOptionsExt; -use std::{ - fs::{File, OpenOptions}, - path::Path, -}; +use std::path::Path; -use base::{ioctl_with_ref, AsRawDescriptor, RawDescriptor}; +use base::ioctl_with_ref; +use base::AsRawDescriptor; +use base::RawDescriptor; +use net_util::TapT; -use super::{ioctl_result, Error, Result, Vhost}; +use super::ioctl_result; +use super::Error; +use super::Result; +use super::Vhost; /// Handle to run VHOST_NET ioctls. /// @@ -89,10 +93,11 @@ impl AsRawDescriptor for Net { } pub mod fakes { - use super::*; use std::fs::remove_file; use std::fs::OpenOptions; + use super::*; + const TMP_FILE: &str = "/tmp/crosvm_vhost_test_file"; pub struct FakeNet { diff --git a/vhost/src/vsock.rs b/vhost/src/vsock.rs index b690c54b3..6480e5d8c 100644 --- a/vhost/src/vsock.rs +++ b/vhost/src/vsock.rs @@ -4,10 +4,15 @@ use std::fs::File; -use base::{ioctl_with_ref, AsRawDescriptor, RawDescriptor}; -use virtio_sys::{VHOST_VSOCK_SET_GUEST_CID, VHOST_VSOCK_SET_RUNNING}; +use base::ioctl_with_ref; +use base::AsRawDescriptor; +use base::RawDescriptor; +use virtio_sys::VHOST_VSOCK_SET_GUEST_CID; +use virtio_sys::VHOST_VSOCK_SET_RUNNING; -use super::{ioctl_result, Result, Vhost}; +use super::ioctl_result; +use super::Result; +use super::Vhost; /// Handle for running VHOST_VSOCK ioctls. pub struct Vsock { diff --git a/virtio_sys/src/lib.rs b/virtio_sys/src/lib.rs index 7928fa8a8..c0fcb15fd 100644 --- a/virtio_sys/src/lib.rs +++ b/virtio_sys/src/lib.rs @@ -8,7 +8,10 @@ #![allow(non_camel_case_types)] #![allow(non_snake_case)] -use base::{ioctl_io_nr, ioctl_ior_nr, ioctl_iow_nr, ioctl_iowr_nr}; +use base::ioctl_io_nr; +use base::ioctl_ior_nr; +use base::ioctl_iow_nr; +use base::ioctl_iowr_nr; pub mod vhost; pub mod virtio_config; diff --git a/vm_control/src/client.rs b/vm_control/src/client.rs index 2a50e24d2..e48842c87 100644 --- a/vm_control/src/client.rs +++ b/vm_control/src/client.rs @@ -3,13 +3,16 @@ // found in the LICENSE file. use std::fs::OpenOptions; -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::path::PathBuf; -use base::{info, open_file}; +use base::info; +use base::open_file; use remain::sorted; use thiserror::Error; -pub use crate::{sys::handle_request, *}; +pub use crate::sys::handle_request; +pub use crate::*; #[sorted] #[derive(Error, Debug)] diff --git a/vm_control/src/display.rs b/vm_control/src/display.rs index aad1d5632..f7c00c2a2 100644 --- a/vm_control/src/display.rs +++ b/vm_control/src/display.rs @@ -5,10 +5,14 @@ use std::convert::TryFrom; use std::result::Result as StdResult; use std::slice::Iter; -use std::time::{SystemTime, UNIX_EPOCH}; +use std::time::SystemTime; +use std::time::UNIX_EPOCH; -use anyhow::{anyhow, Error as AnyError, Result as AnyResult}; -use serde::{Deserialize, Serialize}; +use anyhow::anyhow; +use anyhow::Error as AnyError; +use anyhow::Result as AnyResult; +use serde::Deserialize; +use serde::Serialize; #[derive(PartialEq, Clone, Copy, Serialize, Deserialize, Debug)] pub enum WindowVisibility { diff --git a/vm_control/src/lib.rs b/vm_control/src/lib.rs index 921fc1c83..0c0a3cd6f 100644 --- a/vm_control/src/lib.rs +++ b/vm_control/src/lib.rs @@ -23,49 +23,76 @@ pub mod display; pub mod sys; use std::convert::TryInto; -use std::fmt::{self, Display}; +use std::fmt::Display; +use std::fmt::{self}; use std::fs::File; use std::path::PathBuf; use std::result::Result as StdResult; use std::str::FromStr; -use std::sync::{mpsc, Arc}; - +use std::sync::mpsc; +use std::sync::Arc; use std::thread::JoinHandle; -use remain::sorted; -use thiserror::Error; - -use libc::{EINVAL, EIO, ENODEV, ENOTSUP, ERANGE}; -use serde::{Deserialize, Serialize}; - pub use balloon_control::BalloonStats; #[cfg(feature = "balloon")] -use balloon_control::{BalloonTubeCommand, BalloonTubeResult}; - -use base::{ - error, info, warn, with_as_descriptor, AsRawDescriptor, Error as SysError, Event, - ExternalMapping, MappedRegion, MemoryMappingBuilder, MmapError, Protection, Result, - SafeDescriptor, SharedMemory, Tube, -}; - -use hypervisor::{IrqRoute, IrqSource, Vm}; -use resources::{Alloc, MmioType, SystemAllocator}; -use rutabaga_gfx::{RutabagaGralloc, RutabagaHandle, VulkanInfo}; -use sync::{Condvar, Mutex}; -use vm_memory::GuestAddress; - -use crate::display::{ - AspectRatio, DisplaySize, GuestDisplayDensity, MouseMode, WindowEvent, WindowMode, - WindowVisibility, -}; - +use balloon_control::BalloonTubeCommand; +#[cfg(feature = "balloon")] +use balloon_control::BalloonTubeResult; +use base::error; +use base::info; +use base::warn; +use base::with_as_descriptor; +use base::AsRawDescriptor; +use base::Error as SysError; +use base::Event; +use base::ExternalMapping; +use base::MappedRegion; +use base::MemoryMappingBuilder; +use base::MmapError; +use base::Protection; +use base::Result; +use base::SafeDescriptor; +use base::SharedMemory; +use base::Tube; +use hypervisor::IrqRoute; +use hypervisor::IrqSource; +pub use hypervisor::MemSlot; +use hypervisor::Vm; +use libc::EINVAL; +use libc::EIO; +use libc::ENODEV; +use libc::ENOTSUP; +use libc::ERANGE; +use remain::sorted; +use resources::Alloc; +use resources::MmioType; +use resources::SystemAllocator; +use rutabaga_gfx::RutabagaGralloc; +use rutabaga_gfx::RutabagaHandle; +use rutabaga_gfx::VulkanInfo; +use serde::Deserialize; +use serde::Serialize; +use sync::Condvar; +use sync::Mutex; use sys::kill_handle; #[cfg(unix)] -pub use sys::{FsMappingRequest, VmMsyncRequest, VmMsyncResponse}; +pub use sys::FsMappingRequest; +#[cfg(unix)] +pub use sys::VmMsyncRequest; +#[cfg(unix)] +pub use sys::VmMsyncResponse; +use thiserror::Error; +use vm_memory::GuestAddress; +use crate::display::AspectRatio; +use crate::display::DisplaySize; +use crate::display::GuestDisplayDensity; +use crate::display::MouseMode; +use crate::display::WindowEvent; +use crate::display::WindowMode; +use crate::display::WindowVisibility; #[cfg(all(target_arch = "x86_64", feature = "gdb"))] pub use crate::gdb::*; -pub use hypervisor::MemSlot; /// Control the state of a particular VM CPU. #[derive(Clone, Debug)] @@ -1172,9 +1199,10 @@ pub enum ServiceSendToGpu { #[cfg(test)] mod tests { - use super::*; use base::Event; + use super::*; + #[test] fn sock_send_recv_event() { let (req, res) = Tube::pair().unwrap(); diff --git a/vm_control/src/sys/unix.rs b/vm_control/src/sys/unix.rs index a88b75bb3..2fb571e9a 100644 --- a/vm_control/src/sys/unix.rs +++ b/vm_control/src/sys/unix.rs @@ -2,19 +2,35 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use libc::{EINVAL, ERANGE}; -use std::{path::Path, thread::JoinHandle}; +use std::path::Path; +use std::thread::JoinHandle; -use base::{ - error, AsRawDescriptor, Descriptor, Error as SysError, Killable, MemoryMappingArena, MmapError, - Protection, SafeDescriptor, Tube, UnixSeqpacket, SIGRTMIN, -}; -use hypervisor::{MemSlot, Vm}; -use resources::{Alloc, MmioType, SystemAllocator}; -use serde::{Deserialize, Serialize}; +use base::error; +use base::AsRawDescriptor; +use base::Descriptor; +use base::Error as SysError; +use base::Killable; +use base::MemoryMappingArena; +use base::MmapError; +use base::Protection; +use base::SafeDescriptor; +use base::Tube; +use base::UnixSeqpacket; +use base::SIGRTMIN; +use hypervisor::MemSlot; +use hypervisor::Vm; +use libc::EINVAL; +use libc::ERANGE; +use resources::Alloc; +use resources::MmioType; +use resources::SystemAllocator; +use serde::Deserialize; +use serde::Serialize; use vm_memory::GuestAddress; -use crate::{client::HandleRequestResult, VmRequest, VmResponse}; +use crate::client::HandleRequestResult; +use crate::VmRequest; +use crate::VmResponse; pub fn handle_request + std::fmt::Debug>( request: &VmRequest, diff --git a/vm_control/src/sys/windows.rs b/vm_control/src/sys/windows.rs index 21e8ce74f..b31435ed6 100644 --- a/vm_control/src/sys/windows.rs +++ b/vm_control/src/sys/windows.rs @@ -5,7 +5,8 @@ use std::path::Path; use std::thread::JoinHandle; -use crate::{client::HandleRequestResult, VmRequest}; +use crate::client::HandleRequestResult; +use crate::VmRequest; // TODO(b/145563346): Make this work on Windows pub fn handle_request + std::fmt::Debug>( diff --git a/vm_memory/src/guest_address.rs b/vm_memory/src/guest_address.rs index c9d56e44c..2cadc5106 100644 --- a/vm_memory/src/guest_address.rs +++ b/vm_memory/src/guest_address.rs @@ -4,11 +4,18 @@ //! Represents an address in the guest's memory space. -use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; -use std::fmt::{self, Display}; -use std::ops::{BitAnd, BitOr}; +use std::cmp::Eq; +use std::cmp::Ord; +use std::cmp::Ordering; +use std::cmp::PartialEq; +use std::cmp::PartialOrd; +use std::fmt::Display; +use std::fmt::{self}; +use std::ops::BitAnd; +use std::ops::BitOr; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; +use serde::Serialize; /// Represents an Address in the guest's memory. #[derive(Clone, Copy, Debug, Deserialize, Serialize)] diff --git a/vm_memory/src/guest_memory.rs b/vm_memory/src/guest_memory.rs index 852631cb2..64fe8a8a7 100644 --- a/vm_memory/src/guest_memory.rs +++ b/vm_memory/src/guest_memory.rs @@ -4,22 +4,29 @@ //! Track memory regions that are mapped to the guest VM. -use std::convert::{AsRef, TryFrom}; +use std::convert::AsRef; +use std::convert::TryFrom; use std::fs::File; -use std::io::{Read, Write}; -use std::marker::{Send, Sync}; +use std::io::Read; +use std::io::Write; +use std::marker::Send; +use std::marker::Sync; use std::mem::size_of; use std::result; use std::sync::Arc; -use base::{pagesize, Error as SysError}; -use base::{ - AsRawDescriptor, AsRawDescriptors, MappedRegion, MemoryMapping, MemoryMappingBuilder, - MmapError, RawDescriptor, SharedMemory, -}; - -use cros_async::{mem, BackingMemory}; - +use base::pagesize; +use base::AsRawDescriptor; +use base::AsRawDescriptors; +use base::Error as SysError; +use base::MappedRegion; +use base::MemoryMapping; +use base::MemoryMappingBuilder; +use base::MmapError; +use base::RawDescriptor; +use base::SharedMemory; +use cros_async::mem; +use cros_async::BackingMemory; use data_model::volatile_memory::*; use data_model::DataInit; use remain::sorted; @@ -827,10 +834,11 @@ unsafe impl BackingMemory for GuestMemory { #[cfg(test)] mod tests { - use super::*; #[cfg(unix)] use base::kernel_has_memfd; + use super::*; + #[test] fn test_alignment() { let start_addr1 = GuestAddress(0x0); diff --git a/vm_memory/src/guest_memory/sys/unix.rs b/vm_memory/src/guest_memory/sys/unix.rs index 555c9ef43..527fc3f49 100644 --- a/vm_memory/src/guest_memory/sys/unix.rs +++ b/vm_memory/src/guest_memory/sys/unix.rs @@ -2,11 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use base::MemfdSeals; +use base::MemoryMappingUnix; +use base::SharedMemory; +use base::SharedMemoryUnix; use bitflags::bitflags; -use base::{MemfdSeals, MemoryMappingUnix, SharedMemory, SharedMemoryUnix}; - -use crate::{Error, GuestAddress, GuestMemory, Result}; +use crate::Error; +use crate::GuestAddress; +use crate::GuestMemory; +use crate::Result; bitflags! { pub struct MemoryPolicy: u32 { diff --git a/vm_memory/src/guest_memory/sys/windows.rs b/vm_memory/src/guest_memory/sys/windows.rs index ed911702d..55b228f91 100644 --- a/vm_memory/src/guest_memory/sys/windows.rs +++ b/vm_memory/src/guest_memory/sys/windows.rs @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use base::SharedMemory; use bitflags::bitflags; -use base::SharedMemory; - -use crate::{GuestMemory, Result}; +use crate::GuestMemory; +use crate::Result; bitflags! { pub struct MemoryPolicy: u32 { diff --git a/vm_memory/src/udmabuf.rs b/vm_memory/src/udmabuf.rs index 41c717751..e016106de 100644 --- a/vm_memory/src/udmabuf.rs +++ b/vm_memory/src/udmabuf.rs @@ -4,24 +4,27 @@ #![allow(dead_code)] -use std::fs::{File, OpenOptions}; -use std::os::raw::c_uint; - +use std::fs::File; +use std::fs::OpenOptions; use std::io; +use std::os::raw::c_uint; use std::path::Path; -use base::{ - ioctl_iow_nr, ioctl_with_ptr, pagesize, FromRawDescriptor, MappedRegion, SafeDescriptor, -}; - -use data_model::{flexible_array_impl, FlexibleArrayWrapper}; - -use super::udmabuf_bindings::*; - +use base::ioctl_iow_nr; +use base::ioctl_with_ptr; +use base::pagesize; +use base::FromRawDescriptor; +use base::MappedRegion; +use base::SafeDescriptor; +use data_model::flexible_array_impl; +use data_model::FlexibleArrayWrapper; use remain::sorted; use thiserror::Error; -use crate::{GuestAddress, GuestMemory, GuestMemoryError}; +use super::udmabuf_bindings::*; +use crate::GuestAddress; +use crate::GuestMemory; +use crate::GuestMemoryError; const UDMABUF_IOCTL_BASE: c_uint = 0x75; @@ -143,9 +146,10 @@ impl UdmabufDriver { #[cfg(test)] mod tests { + use base::kernel_has_memfd; + use super::*; use crate::GuestAddress; - use base::kernel_has_memfd; #[test] fn test_memory_offsets() { diff --git a/win_audio/src/intermediate_resampler_buffer.rs b/win_audio/src/intermediate_resampler_buffer.rs index 2612670fa..ac368f7c3 100644 --- a/win_audio/src/intermediate_resampler_buffer.rs +++ b/win_audio/src/intermediate_resampler_buffer.rs @@ -2,16 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::collections::VecDeque; + +use audio_streams::BoxError; +use base::info; +use base::warn; +use winapi::shared::mmreg::SPEAKER_FRONT_LEFT; +use winapi::shared::mmreg::SPEAKER_FRONT_RIGHT; + use crate::r8b_create; use crate::r8b_delete; use crate::r8b_process; use crate::win_audio_impl; use crate::CR8BResampler; use crate::ER8BResamplerRes_r8brr24; -use audio_streams::BoxError; -use base::{info, warn}; -use std::collections::VecDeque; -use winapi::shared::mmreg::{SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT}; // Increasing this constant won't do much now. In the future, we may want to read from the shm // buffer mulitple times in a row to prevent the chance of us running out of audio frames to write @@ -248,11 +252,14 @@ impl Drop for IntermediateResamplerBuffer { #[cfg(test)] mod test { + use winapi::shared::mmreg::SPEAKER_BACK_LEFT; + use winapi::shared::mmreg::SPEAKER_BACK_RIGHT; + use winapi::shared::mmreg::SPEAKER_FRONT_CENTER; + use winapi::shared::mmreg::SPEAKER_LOW_FREQUENCY; + use winapi::shared::mmreg::SPEAKER_SIDE_LEFT; + use winapi::shared::mmreg::SPEAKER_SIDE_RIGHT; + use super::*; - use winapi::shared::mmreg::{ - SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT, SPEAKER_FRONT_CENTER, SPEAKER_LOW_FREQUENCY, - SPEAKER_SIDE_LEFT, SPEAKER_SIDE_RIGHT, - }; #[test] fn test_copy_every_other_and_convert_to_float() { diff --git a/win_audio/src/lib.rs b/win_audio/src/lib.rs index 8d0128a64..4271c6a51 100644 --- a/win_audio/src/lib.rs +++ b/win_audio/src/lib.rs @@ -22,14 +22,17 @@ macro_rules! check_hresult { pub mod intermediate_resampler_buffer; mod win_audio_impl; use std::error; -use win_audio_impl::*; - -use audio_streams::{ - NoopStream, NoopStreamSource, PlaybackBufferStream, SampleFormat, StreamSource, -}; -use base::{info, warn}; use std::sync::Arc; + +use audio_streams::NoopStream; +use audio_streams::NoopStreamSource; +use audio_streams::PlaybackBufferStream; +use audio_streams::SampleFormat; +use audio_streams::StreamSource; +use base::info; +use base::warn; use sync::Mutex; +use win_audio_impl::*; pub type BoxError = Box; diff --git a/win_audio/src/win_audio_impl/completion_handler.rs b/win_audio/src/win_audio_impl/completion_handler.rs index 36538c371..a4a2ac645 100644 --- a/win_audio/src/win_audio_impl/completion_handler.rs +++ b/win_audio/src/win_audio_impl/completion_handler.rs @@ -2,15 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use base::{error, info, Event, EventExt}; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering::SeqCst; + +use base::error; +use base::info; +use base::Event; +use base::EventExt; use libc::c_void; -use std::sync::atomic::{AtomicU32, Ordering::SeqCst}; -use winapi::shared::guiddef::{IsEqualGUID, REFIID}; +use winapi::shared::guiddef::IsEqualGUID; +use winapi::shared::guiddef::REFIID; use winapi::shared::minwindef::ULONG; -use winapi::shared::winerror::{E_INVALIDARG, E_NOINTERFACE, NOERROR, S_OK}; +use winapi::shared::winerror::E_INVALIDARG; +use winapi::shared::winerror::E_NOINTERFACE; +use winapi::shared::winerror::NOERROR; +use winapi::shared::winerror::S_OK; use winapi::um::mmdeviceapi::*; use winapi::um::objidlbase::IAgileObject; -use winapi::um::unknwnbase::{IUnknown, IUnknownVtbl}; +use winapi::um::unknwnbase::IUnknown; +use winapi::um::unknwnbase::IUnknownVtbl; use winapi::um::winnt::HRESULT; use winapi::Interface; use wio::com::ComPtr; diff --git a/win_audio/src/win_audio_impl/mod.rs b/win_audio/src/win_audio_impl/mod.rs index f7c2818af..9b202abb2 100644 --- a/win_audio/src/win_audio_impl/mod.rs +++ b/win_audio/src/win_audio_impl/mod.rs @@ -2,40 +2,58 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::AudioSharedFormat; -use audio_streams::{ - BoxError, BufferCommit, NoopStream, NoopStreamControl, PlaybackBuffer, PlaybackBufferError, - PlaybackBufferStream, SampleFormat, StreamControl, StreamSource, -}; -use base::{error, info, warn, AsRawDescriptor, Error, Event, EventExt, EventReadResult}; -use completion_handler::{ - WinAudioActivateAudioInterfaceCompletionHandler, ACTIVATE_AUDIO_INTERFACE_COMPLETION_EVENT, -}; -use metrics::event_details_proto::RecordDetails; -use metrics::{self, MetricEventType}; use std::convert::From; use std::fmt::Debug; use std::mem::MaybeUninit; use std::os::raw::c_void; use std::ptr::null_mut; -use std::sync::{Arc, Once}; +use std::sync::Arc; +use std::sync::Once; use std::thread_local; use std::time::Duration; + +use audio_streams::BoxError; +use audio_streams::BufferCommit; +use audio_streams::NoopStream; +use audio_streams::NoopStreamControl; +use audio_streams::PlaybackBuffer; +use audio_streams::PlaybackBufferError; +use audio_streams::PlaybackBufferStream; +use audio_streams::SampleFormat; +use audio_streams::StreamControl; +use audio_streams::StreamSource; +use base::error; +use base::info; +use base::warn; +use base::AsRawDescriptor; +use base::Error; +use base::Event; +use base::EventExt; +use base::EventReadResult; +use completion_handler::WinAudioActivateAudioInterfaceCompletionHandler; +use completion_handler::ACTIVATE_AUDIO_INTERFACE_COMPLETION_EVENT; +use metrics::event_details_proto::RecordDetails; +use metrics::MetricEventType; +use metrics::{self}; use sync::Mutex; use thiserror::Error as ThisError; use wave_format::*; -use winapi::shared::guiddef::{GUID, REFCLSID}; +use winapi::shared::guiddef::GUID; +use winapi::shared::guiddef::REFCLSID; use winapi::shared::ksmedia::KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; use winapi::shared::mmreg::WAVEFORMATEX; -use winapi::shared::winerror::{S_FALSE, S_OK}; +use winapi::shared::winerror::S_FALSE; +use winapi::shared::winerror::S_OK; use winapi::um::audioclient::*; -use winapi::um::audiosessiontypes::{AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK}; +use winapi::um::audiosessiontypes::AUDCLNT_SHAREMODE_SHARED; +use winapi::um::audiosessiontypes::AUDCLNT_STREAMFLAGS_EVENTCALLBACK; use winapi::um::combaseapi::*; use winapi::um::coml2api::STGM_READ; use winapi::um::functiondiscoverykeys_devpkey::PKEY_Device_FriendlyName; use winapi::um::mmdeviceapi::*; use winapi::um::objbase::COINIT_APARTMENTTHREADED; -use winapi::um::propidl::{PropVariantClear, PROPVARIANT}; +use winapi::um::propidl::PropVariantClear; +use winapi::um::propidl::PROPVARIANT; use winapi::um::propsys::IPropertyStore; use winapi::um::synchapi::WaitForSingleObject; use winapi::um::unknwnbase::IUnknown; @@ -43,6 +61,8 @@ use winapi::um::winbase::WAIT_OBJECT_0; use winapi::Interface; use wio::com::ComPtr; +use crate::AudioSharedFormat; + mod completion_handler; mod wave_format; @@ -818,11 +838,14 @@ impl From for RenderError { // be found. Just put it in the appropriate spot in the `target` directory. #[cfg(test)] mod tests { - use super::*; - use once_cell::sync::Lazy; use std::thread; - use winapi::shared::mmreg::{WAVEFORMATEXTENSIBLE, WAVE_FORMAT_EXTENSIBLE}; + + use once_cell::sync::Lazy; + use winapi::shared::mmreg::WAVEFORMATEXTENSIBLE; + use winapi::shared::mmreg::WAVE_FORMAT_EXTENSIBLE; use winapi::shared::winerror::S_OK; + + use super::*; // These tests needs to be ran serially because there is a chance that two different tests // running on different threads could open the same event named // ACTIVATE_AUDIO_INTERFACE_COMPLETION_EVENT. diff --git a/win_audio/src/win_audio_impl/wave_format.rs b/win_audio/src/win_audio_impl/wave_format.rs index 156005db0..ba23ecc5a 100644 --- a/win_audio/src/win_audio_impl/wave_format.rs +++ b/win_audio/src/win_audio_impl/wave_format.rs @@ -2,26 +2,39 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use crate::AudioSharedFormat; -use crate::{MONO_CHANNEL_COUNT, STEREO_CHANNEL_COUNT}; -use base::warn; -use metrics::event_details_proto::{WaveFormat, WaveFormatDetails, WaveFormat_WaveFormatSubFormat}; use std::convert::TryInto; -use std::fmt::{self, Debug, Formatter}; -use winapi::shared::guiddef::{IsEqualGUID, GUID}; +use std::fmt::Debug; +use std::fmt::Formatter; +use std::fmt::{self}; + +use base::warn; +use metrics::event_details_proto::WaveFormat; +use metrics::event_details_proto::WaveFormatDetails; +use metrics::event_details_proto::WaveFormat_WaveFormatSubFormat; +use winapi::shared::guiddef::IsEqualGUID; +use winapi::shared::guiddef::GUID; +use winapi::shared::ksmedia::KSDATAFORMAT_SUBTYPE_ADPCM; +use winapi::shared::ksmedia::KSDATAFORMAT_SUBTYPE_ALAW; +use winapi::shared::ksmedia::KSDATAFORMAT_SUBTYPE_ANALOG; +use winapi::shared::ksmedia::KSDATAFORMAT_SUBTYPE_DRM; use winapi::shared::ksmedia::KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; -use winapi::shared::ksmedia::{ - KSDATAFORMAT_SUBTYPE_ADPCM, KSDATAFORMAT_SUBTYPE_ALAW, KSDATAFORMAT_SUBTYPE_ANALOG, - KSDATAFORMAT_SUBTYPE_DRM, KSDATAFORMAT_SUBTYPE_MPEG, KSDATAFORMAT_SUBTYPE_MULAW, - KSDATAFORMAT_SUBTYPE_PCM, -}; -use winapi::shared::mmreg::{ - SPEAKER_FRONT_CENTER, SPEAKER_FRONT_LEFT, SPEAKER_FRONT_RIGHT, WAVEFORMATEX, - WAVEFORMATEXTENSIBLE, WAVE_FORMAT_EXTENSIBLE, WAVE_FORMAT_IEEE_FLOAT, -}; +use winapi::shared::ksmedia::KSDATAFORMAT_SUBTYPE_MPEG; +use winapi::shared::ksmedia::KSDATAFORMAT_SUBTYPE_MULAW; +use winapi::shared::ksmedia::KSDATAFORMAT_SUBTYPE_PCM; +use winapi::shared::mmreg::SPEAKER_FRONT_CENTER; +use winapi::shared::mmreg::SPEAKER_FRONT_LEFT; +use winapi::shared::mmreg::SPEAKER_FRONT_RIGHT; +use winapi::shared::mmreg::WAVEFORMATEX; +use winapi::shared::mmreg::WAVEFORMATEXTENSIBLE; +use winapi::shared::mmreg::WAVE_FORMAT_EXTENSIBLE; +use winapi::shared::mmreg::WAVE_FORMAT_IEEE_FLOAT; #[cfg(not(test))] use winapi::um::combaseapi::CoTaskMemFree; +use crate::AudioSharedFormat; +use crate::MONO_CHANNEL_COUNT; +use crate::STEREO_CHANNEL_COUNT; + pub type WaveFormatDetailsProto = WaveFormatDetails; pub type WaveFormatProto = WaveFormat; pub type SubFormatProto = WaveFormat_WaveFormatSubFormat; @@ -439,12 +452,15 @@ impl<'a> From> for SubFormatProto { #[cfg(test)] mod tests { - use super::*; use winapi::shared::ksmedia::KSDATAFORMAT_SUBTYPE_PCM; - use winapi::shared::mmreg::{ - SPEAKER_BACK_LEFT, SPEAKER_BACK_RIGHT, SPEAKER_LOW_FREQUENCY, SPEAKER_SIDE_LEFT, - SPEAKER_SIDE_RIGHT, WAVE_FORMAT_PCM, - }; + use winapi::shared::mmreg::SPEAKER_BACK_LEFT; + use winapi::shared::mmreg::SPEAKER_BACK_RIGHT; + use winapi::shared::mmreg::SPEAKER_LOW_FREQUENCY; + use winapi::shared::mmreg::SPEAKER_SIDE_LEFT; + use winapi::shared::mmreg::SPEAKER_SIDE_RIGHT; + use winapi::shared::mmreg::WAVE_FORMAT_PCM; + + use super::*; #[test] fn test_modify_mix_format() { diff --git a/win_util/src/dll_notification.rs b/win_util/src/dll_notification.rs index 1ea747926..d8cd7bdaf 100644 --- a/win_util/src/dll_notification.rs +++ b/win_util/src/dll_notification.rs @@ -2,8 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::ffi::{c_void, OsString}; -use std::{io, ptr}; +use std::ffi::c_void; +use std::ffi::OsString; +use std::io; +use std::ptr; use winapi::shared::minwindef::ULONG; use winapi::um::winnt::PVOID; @@ -20,10 +22,13 @@ mod dll_notification_sys { use std::io; use winapi::shared::minwindef::ULONG; - use winapi::shared::ntdef::{NTSTATUS, PCUNICODE_STRING}; + use winapi::shared::ntdef::NTSTATUS; + use winapi::shared::ntdef::PCUNICODE_STRING; use winapi::shared::ntstatus::STATUS_SUCCESS; - use winapi::um::libloaderapi::{GetModuleHandleA, GetProcAddress}; - use winapi::um::winnt::{CHAR, PVOID}; + use winapi::um::libloaderapi::GetModuleHandleA; + use winapi::um::libloaderapi::GetProcAddress; + use winapi::um::winnt::CHAR; + use winapi::um::winnt::PVOID; #[repr(C)] pub union _LDR_DLL_NOTIFICATION_DATA { @@ -336,9 +341,14 @@ where #[cfg(test)] mod tests { + use std::collections::HashSet; + use std::ffi::CString; + use std::io; + + use winapi::um::libloaderapi::FreeLibrary; + use winapi::um::libloaderapi::LoadLibraryA; + use super::*; - use std::{collections::HashSet, ffi::CString, io}; - use winapi::um::libloaderapi::{FreeLibrary, LoadLibraryA}; // Arbitrarily chosen DLL for load/unload test. Chosen because it's // hopefully esoteric enough that it's probably not already loaded in diff --git a/win_util/src/large_integer.rs b/win_util/src/large_integer.rs index 3126b806e..0d619d946 100644 --- a/win_util/src/large_integer.rs +++ b/win_util/src/large_integer.rs @@ -3,6 +3,7 @@ // found in the LICENSE file. use std::ops::Deref; + use winapi::um::winnt::LARGE_INTEGER; pub struct LargeInteger { diff --git a/win_util/src/lib.rs b/win_util/src/lib.rs index b0c3d2c29..94ca89f12 100644 --- a/win_util/src/lib.rs +++ b/win_util/src/lib.rs @@ -17,29 +17,43 @@ mod security_attributes; pub use crate::security_attributes::*; mod dll_notification; -pub use crate::dll_notification::*; - -use std::ffi::{CString, OsStr, OsString}; +use std::ffi::CString; +use std::ffi::OsStr; +use std::ffi::OsString; +use std::io; use std::iter::once; use std::mem::MaybeUninit; -use std::os::windows::ffi::{OsStrExt, OsStringExt}; +use std::os::windows::ffi::OsStrExt; +use std::os::windows::ffi::OsStringExt; use std::os::windows::io::RawHandle; +use std::ptr; +use std::slice; use std::sync::Once; -use std::{io, ptr, slice}; use libc::c_ulong; -use winapi::shared::minwindef::{DWORD, FALSE, TRUE}; +use winapi::shared::minwindef::DWORD; +use winapi::shared::minwindef::FALSE; +use winapi::shared::minwindef::TRUE; use winapi::shared::ntdef::UNICODE_STRING; -use winapi::um::handleapi::{ - CloseHandle, DuplicateHandle, SetHandleInformation, INVALID_HANDLE_VALUE, -}; +use winapi::um::handleapi::CloseHandle; +use winapi::um::handleapi::DuplicateHandle; +use winapi::um::handleapi::SetHandleInformation; +use winapi::um::handleapi::INVALID_HANDLE_VALUE; use winapi::um::minwinbase::STILL_ACTIVE; -use winapi::um::processthreadsapi::{ - GetCurrentProcess, GetExitCodeProcess, OpenProcess, ResumeThread, -}; -use winapi::um::sysinfoapi::{GetNativeSystemInfo, SYSTEM_INFO}; -use winapi::um::winbase::{CreateFileMappingA, HANDLE_FLAG_INHERIT}; -use winapi::um::winnt::{DUPLICATE_SAME_ACCESS, HRESULT, PROCESS_DUP_HANDLE, WCHAR}; +use winapi::um::processthreadsapi::GetCurrentProcess; +use winapi::um::processthreadsapi::GetExitCodeProcess; +use winapi::um::processthreadsapi::OpenProcess; +use winapi::um::processthreadsapi::ResumeThread; +use winapi::um::sysinfoapi::GetNativeSystemInfo; +use winapi::um::sysinfoapi::SYSTEM_INFO; +use winapi::um::winbase::CreateFileMappingA; +use winapi::um::winbase::HANDLE_FLAG_INHERIT; +use winapi::um::winnt::DUPLICATE_SAME_ACCESS; +use winapi::um::winnt::HRESULT; +use winapi::um::winnt::PROCESS_DUP_HANDLE; +use winapi::um::winnt::WCHAR; + +pub use crate::dll_notification::*; #[macro_export] macro_rules! syscall_bail { diff --git a/win_util/src/security_attributes.rs b/win_util/src/security_attributes.rs index 9a9641fda..74e702f52 100644 --- a/win_util/src/security_attributes.rs +++ b/win_util/src/security_attributes.rs @@ -2,32 +2,53 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::alloc::{alloc_zeroed, dealloc, handle_alloc_error, Layout}; -use std::convert::{TryFrom, TryInto}; +use std::alloc::alloc_zeroed; +use std::alloc::dealloc; +use std::alloc::handle_alloc_error; +use std::alloc::Layout; +use std::convert::TryFrom; +use std::convert::TryInto; +use std::io; use std::mem::size_of; use std::os::windows::io::RawHandle; -use std::{io, ptr}; -use winapi::shared::minwindef::{FALSE, HLOCAL, LPDWORD, LPVOID, TRUE}; -use winapi::shared::winerror::{ERROR_INSUFFICIENT_BUFFER, ERROR_SUCCESS}; -use winapi::um::accctrl::{ - EXPLICIT_ACCESS_A, NO_INHERITANCE, NO_MULTIPLE_TRUSTEE, PEXPLICIT_ACCESSA, SET_ACCESS, - TRUSTEE_A, TRUSTEE_IS_SID, TRUSTEE_IS_USER, -}; +use std::ptr; + +use once_cell::sync::OnceCell; +use winapi::shared::minwindef::FALSE; +use winapi::shared::minwindef::HLOCAL; +use winapi::shared::minwindef::LPDWORD; +use winapi::shared::minwindef::LPVOID; +use winapi::shared::minwindef::TRUE; +use winapi::shared::winerror::ERROR_INSUFFICIENT_BUFFER; +use winapi::shared::winerror::ERROR_SUCCESS; +use winapi::um::accctrl::EXPLICIT_ACCESS_A; +use winapi::um::accctrl::NO_INHERITANCE; +use winapi::um::accctrl::NO_MULTIPLE_TRUSTEE; +use winapi::um::accctrl::PEXPLICIT_ACCESSA; +use winapi::um::accctrl::SET_ACCESS; +use winapi::um::accctrl::TRUSTEE_A; +use winapi::um::accctrl::TRUSTEE_IS_SID; +use winapi::um::accctrl::TRUSTEE_IS_USER; use winapi::um::aclapi::SetEntriesInAclA; use winapi::um::handleapi::CloseHandle; use winapi::um::minwinbase::SECURITY_ATTRIBUTES; -use winapi::um::processthreadsapi::{GetCurrentProcess, OpenProcessToken}; -use winapi::um::securitybaseapi::{ - GetTokenInformation, InitializeSecurityDescriptor, MakeSelfRelativeSD, - SetSecurityDescriptorDacl, -}; +use winapi::um::processthreadsapi::GetCurrentProcess; +use winapi::um::processthreadsapi::OpenProcessToken; +use winapi::um::securitybaseapi::GetTokenInformation; +use winapi::um::securitybaseapi::InitializeSecurityDescriptor; +use winapi::um::securitybaseapi::MakeSelfRelativeSD; +use winapi::um::securitybaseapi::SetSecurityDescriptorDacl; use winapi::um::winbase::LocalFree; -use winapi::um::winnt::{ - TokenUser, ACL, GENERIC_ALL, PACL, PSECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR, - SECURITY_DESCRIPTOR_REVISION, TOKEN_ALL_ACCESS, TOKEN_INFORMATION_CLASS, TOKEN_USER, -}; - -use once_cell::sync::OnceCell; +use winapi::um::winnt::TokenUser; +use winapi::um::winnt::ACL; +use winapi::um::winnt::GENERIC_ALL; +use winapi::um::winnt::PACL; +use winapi::um::winnt::PSECURITY_DESCRIPTOR; +use winapi::um::winnt::SECURITY_DESCRIPTOR; +use winapi::um::winnt::SECURITY_DESCRIPTOR_REVISION; +use winapi::um::winnt::TOKEN_ALL_ACCESS; +use winapi::um::winnt::TOKEN_INFORMATION_CLASS; +use winapi::um::winnt::TOKEN_USER; /// Struct for wrapping `SECURITY_ATTRIBUTES` and `SECURITY_DESCRIPTOR`. pub struct SecurityAttributes { diff --git a/x86_64/src/acpi.rs b/x86_64/src/acpi.rs index 8cacc78cb..c235f85df 100644 --- a/x86_64/src/acpi.rs +++ b/x86_64/src/acpi.rs @@ -2,17 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::arch::x86_64::{CpuidResult, __cpuid, __cpuid_count}; +use std::arch::x86_64::CpuidResult; +use std::arch::x86_64::__cpuid; +use std::arch::x86_64::__cpuid_count; use std::collections::BTreeMap; - -use acpi_tables::{facs::FACS, rsdp::RSDP, sdt::SDT}; -use arch::VcpuAffinity; -use base::{error, warn}; -use data_model::DataInit; -use devices::{ACPIPMResource, PciAddress, PciInterruptPin}; use std::sync::Arc; + +use acpi_tables::facs::FACS; +use acpi_tables::rsdp::RSDP; +use acpi_tables::sdt::SDT; +use arch::VcpuAffinity; +use base::error; +use base::warn; +use data_model::DataInit; +use devices::ACPIPMResource; +use devices::PciAddress; +use devices::PciInterruptPin; use sync::Mutex; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; pub struct AcpiDevResource { pub amls: Vec, diff --git a/x86_64/src/bzimage.rs b/x86_64/src/bzimage.rs index db9bd8965..4a42fa615 100644 --- a/x86_64/src/bzimage.rs +++ b/x86_64/src/bzimage.rs @@ -5,13 +5,16 @@ // Loader for bzImage-format Linux kernels as described in // https://www.kernel.org/doc/Documentation/x86/boot.txt -use std::io::{Read, Seek, SeekFrom}; +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; use base::AsRawDescriptor; use data_model::DataInit; use remain::sorted; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; use crate::bootparam::boot_params; diff --git a/x86_64/src/cpuid.rs b/x86_64/src/cpuid.rs index 07f44c304..d98a99016 100644 --- a/x86_64/src/cpuid.rs +++ b/x86_64/src/cpuid.rs @@ -2,17 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::arch::x86_64::{CpuidResult, __cpuid, __cpuid_count}; +use std::arch::x86_64::CpuidResult; +use std::arch::x86_64::__cpuid; +use std::arch::x86_64::__cpuid_count; use std::cmp; use std::result; -use devices::{Apic, IrqChipCap, IrqChipX86_64}; -use hypervisor::{CpuIdEntry, HypervisorCap, HypervisorX86_64, VcpuX86_64}; - -use crate::CpuManufacturer; +use devices::Apic; +use devices::IrqChipCap; +use devices::IrqChipX86_64; +use hypervisor::CpuIdEntry; +use hypervisor::HypervisorCap; +use hypervisor::HypervisorX86_64; +use hypervisor::VcpuX86_64; use remain::sorted; use thiserror::Error; +use crate::CpuManufacturer; + #[sorted] #[derive(Error, Debug, PartialEq)] pub enum Error { @@ -391,10 +398,11 @@ pub fn cpu_manufacturer() -> CpuManufacturer { #[cfg(test)] mod tests { - use super::*; #[cfg(unix)] use hypervisor::ProtectionType; + use super::*; + #[test] fn cpu_manufacturer_test() { // this should be amd or intel. We don't support other processors for virtualization. diff --git a/x86_64/src/fdt.rs b/x86_64/src/fdt.rs index 67fa497be..3a75ff8eb 100644 --- a/x86_64/src/fdt.rs +++ b/x86_64/src/fdt.rs @@ -2,15 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use arch::android::create_android_fdt; -use arch::fdt::{Error, FdtWriter}; -use data_model::DataInit; use std::fs::File; use std::mem; -use vm_memory::{GuestAddress, GuestMemory}; + +use arch::android::create_android_fdt; +use arch::fdt::Error; +use arch::fdt::FdtWriter; +use data_model::DataInit; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; use crate::bootparam::setup_data; -use crate::{SETUP_DTB, X86_64_FDT_MAX_SIZE}; +use crate::SETUP_DTB; +use crate::X86_64_FDT_MAX_SIZE; // Like `setup_data` without the incomplete array field at the end, which allows us to safely // implement Copy, Clone, and DataInit. diff --git a/x86_64/src/lib.rs b/x86_64/src/lib.rs index 9e8767440..76555b0e9 100644 --- a/x86_64/src/lib.rs +++ b/x86_64/src/lib.rs @@ -50,52 +50,90 @@ mod mptable; mod regs; mod smbios; -use once_cell::sync::OnceCell; use std::arch::x86_64::__cpuid; use std::collections::BTreeMap; -use std::ffi::{CStr, CString}; +use std::ffi::CStr; +use std::ffi::CString; use std::fs::File; -use std::io::{self, Seek}; +use std::io::Seek; +use std::io::{self}; use std::mem; use std::sync::Arc; -use crate::bootparam::boot_params; +use acpi_tables::aml; +use acpi_tables::aml::Aml; use acpi_tables::sdt::SDT; -use acpi_tables::{aml, aml::Aml}; -use arch::{ - get_serial_cmdline, GetSerialCmdlineError, MsrAction, MsrConfig, MsrFilter, MsrRWType, - MsrValueFrom, RunnableLinuxVm, VmComponents, VmImage, -}; +use arch::get_serial_cmdline; +use arch::GetSerialCmdlineError; +use arch::MsrAction; +use arch::MsrConfig; +use arch::MsrFilter; +use arch::MsrRWType; +use arch::MsrValueFrom; +use arch::RunnableLinuxVm; +use arch::VmComponents; +use arch::VmImage; +use base::warn; #[cfg(unix)] use base::AsRawDescriptors; -use base::{warn, Event, SendTube, TubeError}; -pub use cpuid::{adjust_cpuid, CpuIdContext}; +use base::Event; +use base::SendTube; +use base::TubeError; +pub use cpuid::adjust_cpuid; +pub use cpuid::CpuIdContext; +use devices::BusDevice; +use devices::BusDeviceObj; +use devices::BusResumeDevice; +use devices::Debugcon; +use devices::IrqChip; +use devices::IrqChipX86_64; +use devices::IrqEventSource; #[cfg(windows)] use devices::Minijail; +use devices::PciAddress; +use devices::PciConfigIo; +use devices::PciConfigMmio; +use devices::PciDevice; +use devices::PciVirtualConfigMmio; +use devices::Pflash; #[cfg(unix)] use devices::ProxyDevice; -use devices::{ - BusDevice, BusDeviceObj, BusResumeDevice, Debugcon, IrqChip, IrqChipX86_64, IrqEventSource, - PciAddress, PciConfigIo, PciConfigMmio, PciDevice, PciVirtualConfigMmio, Pflash, Serial, - SerialHardware, SerialParameters, -}; -use hypervisor::{ - HypervisorX86_64, ProtectionType, VcpuInitX86_64, VcpuX86_64, Vm, VmCap, VmX86_64, -}; +use devices::Serial; +use devices::SerialHardware; +use devices::SerialParameters; +#[cfg(all(target_arch = "x86_64", feature = "gdb"))] +use gdbstub_arch::x86::reg::X86SegmentRegs; +#[cfg(all(target_arch = "x86_64", feature = "gdb"))] +use gdbstub_arch::x86::reg::X86_64CoreRegs; +#[cfg(all(target_arch = "x86_64", feature = "gdb"))] +use gdbstub_arch::x86::reg::X87FpuInternalRegs; +#[cfg(all(target_arch = "x86_64", feature = "gdb"))] +use hypervisor::x86_64::Regs; +#[cfg(all(target_arch = "x86_64", feature = "gdb"))] +use hypervisor::x86_64::Sregs; +use hypervisor::HypervisorX86_64; +use hypervisor::ProtectionType; +use hypervisor::VcpuInitX86_64; +use hypervisor::VcpuX86_64; +use hypervisor::Vm; +use hypervisor::VmCap; +use hypervisor::VmX86_64; #[cfg(unix)] use minijail::Minijail; +use once_cell::sync::OnceCell; use remain::sorted; -use resources::{AddressRange, SystemAllocator, SystemAllocatorConfig}; +use resources::AddressRange; +use resources::SystemAllocator; +use resources::SystemAllocatorConfig; use sync::Mutex; use thiserror::Error; -use vm_control::{BatControl, BatteryType}; -use vm_memory::{GuestAddress, GuestMemory, GuestMemoryError}; -#[cfg(all(target_arch = "x86_64", feature = "gdb"))] -use { - gdbstub_arch::x86::reg::{X86SegmentRegs, X86_64CoreRegs, X87FpuInternalRegs}, - hypervisor::x86_64::{Regs, Sregs}, -}; +use vm_control::BatControl; +use vm_control::BatteryType; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; +use vm_memory::GuestMemoryError; +use crate::bootparam::boot_params; use crate::msr_index::*; #[sorted] diff --git a/x86_64/src/mptable.rs b/x86_64/src/mptable.rs index 2b392d456..46a334d15 100644 --- a/x86_64/src/mptable.rs +++ b/x86_64/src/mptable.rs @@ -7,12 +7,13 @@ use std::mem; use std::result; use std::slice; +use devices::PciAddress; +use devices::PciInterruptPin; use libc::c_char; use remain::sorted; use thiserror::Error; - -use devices::{PciAddress, PciInterruptPin}; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; use crate::mpspec::*; @@ -363,9 +364,10 @@ pub fn setup_mptable( #[cfg(test)] mod tests { - use super::*; use base::pagesize; + use super::*; + fn compute_page_aligned_mp_size(num_cpus: u8) -> u64 { let mp_size = compute_mp_size(num_cpus); let pg_size = pagesize(); diff --git a/x86_64/src/msr.rs b/x86_64/src/msr.rs index 82c2a68d0..354dc67f5 100644 --- a/x86_64/src/msr.rs +++ b/x86_64/src/msr.rs @@ -4,15 +4,20 @@ use std::cell::RefCell; use std::collections::BTreeMap; -use std::fs::{File, OpenOptions}; +use std::fs::File; +use std::fs::OpenOptions; use std::os::unix::fs::FileExt; use std::rc::Rc; use anyhow::Context; - -use arch::{MsrAction, MsrConfig, MsrExitHandlerError, MsrFilter, MsrRWType, MsrValueFrom}; -use base::{debug, error}; - +use arch::MsrAction; +use arch::MsrConfig; +use arch::MsrExitHandlerError; +use arch::MsrFilter; +use arch::MsrRWType; +use arch::MsrValueFrom; +use base::debug; +use base::error; use remain::sorted; use thiserror::Error as ThisError; diff --git a/x86_64/src/regs.rs b/x86_64/src/regs.rs index 0182099fb..4125fc0bd 100644 --- a/x86_64/src/regs.rs +++ b/x86_64/src/regs.rs @@ -2,13 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{mem, result}; +use std::mem; +use std::result; -use base::{self, warn}; -use hypervisor::{Register, Sregs, VcpuX86_64, Vm}; +use base::warn; +use base::{self}; +use hypervisor::Register; +use hypervisor::Sregs; +use hypervisor::VcpuX86_64; +use hypervisor::Vm; use remain::sorted; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; use crate::gdt; @@ -308,8 +314,10 @@ pub fn setup_page_tables(mem: &GuestMemory, sregs: &mut Sregs) -> Result<()> { #[cfg(test)] mod tests { + use vm_memory::GuestAddress; + use vm_memory::GuestMemory; + use super::*; - use vm_memory::{GuestAddress, GuestMemory}; fn create_guest_mem() -> GuestMemory { GuestMemory::new(&[(GuestAddress(0), 0x10000)]).unwrap() diff --git a/x86_64/src/smbios.rs b/x86_64/src/smbios.rs index 09fd5a2c5..1e2382b1a 100644 --- a/x86_64/src/smbios.rs +++ b/x86_64/src/smbios.rs @@ -2,18 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::mem; -use std::result; -use std::slice; - use std::fs::OpenOptions; use std::io::prelude::*; -use std::path::{Path, PathBuf}; +use std::mem; +use std::path::Path; +use std::path::PathBuf; +use std::result; +use std::slice; use data_model::DataInit; use remain::sorted; use thiserror::Error; -use vm_memory::{GuestAddress, GuestMemory}; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; #[sorted] #[derive(Error, Debug)] diff --git a/x86_64/src/test_integration.rs b/x86_64/src/test_integration.rs index 4b4bd5dd7..2bcd17efc 100644 --- a/x86_64/src/test_integration.rs +++ b/x86_64/src/test_integration.rs @@ -10,37 +10,51 @@ mod sys; -use arch::LinuxArch; -use devices::IrqChipX86_64; -use hypervisor::{ - HypervisorX86_64, IoOperation, IoParams, ProtectionType, Regs, VcpuExit, VcpuX86_64, VmCap, - VmX86_64, -}; -use resources::{AddressRange, SystemAllocator}; -use vm_memory::{GuestAddress, GuestMemory}; - -use super::cpuid::setup_cpuid; -use super::interrupts::set_lint; -use super::regs::{configure_segments_and_sregs, long_mode_msrs, mtrr_msrs, setup_page_tables}; -use super::X8664arch; -use super::{ - acpi, arch_memory_regions, bootparam, init_low_memory_layout, mptable, - read_pci_mmio_before_32bit, read_pcie_cfg_mmio, smbios, -}; -use super::{ - BOOT_STACK_POINTER, KERNEL_64BIT_ENTRY_OFFSET, KERNEL_START_OFFSET, X86_64_SCI_IRQ, - ZERO_PAGE_OFFSET, -}; - -use base::{Event, Tube}; - use std::collections::BTreeMap; use std::ffi::CString; use std::sync::Arc; use std::thread; -use sync::Mutex; +use arch::LinuxArch; +use base::Event; +use base::Tube; +use devices::IrqChipX86_64; use devices::PciConfigIo; +use hypervisor::HypervisorX86_64; +use hypervisor::IoOperation; +use hypervisor::IoParams; +use hypervisor::ProtectionType; +use hypervisor::Regs; +use hypervisor::VcpuExit; +use hypervisor::VcpuX86_64; +use hypervisor::VmCap; +use hypervisor::VmX86_64; +use resources::AddressRange; +use resources::SystemAllocator; +use sync::Mutex; +use vm_memory::GuestAddress; +use vm_memory::GuestMemory; + +use super::acpi; +use super::arch_memory_regions; +use super::bootparam; +use super::cpuid::setup_cpuid; +use super::init_low_memory_layout; +use super::interrupts::set_lint; +use super::mptable; +use super::read_pci_mmio_before_32bit; +use super::read_pcie_cfg_mmio; +use super::regs::configure_segments_and_sregs; +use super::regs::long_mode_msrs; +use super::regs::mtrr_msrs; +use super::regs::setup_page_tables; +use super::smbios; +use super::X8664arch; +use super::BOOT_STACK_POINTER; +use super::KERNEL_64BIT_ENTRY_OFFSET; +use super::KERNEL_START_OFFSET; +use super::X86_64_SCI_IRQ; +use super::ZERO_PAGE_OFFSET; enum TaggedControlTube { VmMemory(Tube),