misc: Automatically fix cargo clippy issues added in 1.65 (stable)

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
This commit is contained in:
Rob Bradford 2022-12-14 11:41:15 +00:00
parent 8b59316718
commit 5e52729453
57 changed files with 448 additions and 574 deletions

View File

@ -22,16 +22,16 @@ impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use Error::*; use Error::*;
match self { match self {
Socket(e) => write!(f, "Error writing to or reading from HTTP socket: {}", e), Socket(e) => write!(f, "Error writing to or reading from HTTP socket: {e}"),
SocketSendFds(e) => write!(f, "Error writing to or reading from HTTP socket: {}", e), SocketSendFds(e) => write!(f, "Error writing to or reading from HTTP socket: {e}"),
StatusCodeParsing(e) => write!(f, "Error parsing HTTP status code: {}", e), StatusCodeParsing(e) => write!(f, "Error parsing HTTP status code: {e}"),
MissingProtocol => write!(f, "HTTP output is missing protocol statement"), MissingProtocol => write!(f, "HTTP output is missing protocol statement"),
ContentLengthParsing(e) => write!(f, "Error parsing HTTP Content-Length field: {}", e), ContentLengthParsing(e) => write!(f, "Error parsing HTTP Content-Length field: {e}"),
ServerResponse(s, o) => { ServerResponse(s, o) => {
if let Some(o) = o { if let Some(o) = o {
write!(f, "Server responded with an error: {:?}: {}", s, o) write!(f, "Server responded with an error: {s:?}: {o}")
} else { } else {
write!(f, "Server responded with an error: {:?}", s) write!(f, "Server responded with an error: {s:?}")
} }
} }
} }
@ -79,7 +79,7 @@ impl StatusCode {
} }
fn get_header<'a>(res: &'a str, header: &'a str) -> Option<&'a str> { fn get_header<'a>(res: &'a str, header: &'a str) -> Option<&'a str> {
let header_str = format!("{}: ", header); let header_str = format!("{header}: ");
res.find(&header_str) res.find(&header_str)
.map(|o| &res[o + header_str.len()..o + res[o..].find('\r').unwrap()]) .map(|o| &res[o + header_str.len()..o + res[o..].find('\r').unwrap()])
} }
@ -153,8 +153,7 @@ pub fn simple_api_full_command_with_fds_and_response<T: Read + Write + ScmSocket
socket socket
.send_with_fds( .send_with_fds(
&[format!( &[format!(
"{} /api/v1/{} HTTP/1.1\r\nHost: localhost\r\nAccept: */*\r\n", "{method} /api/v1/{full_command} HTTP/1.1\r\nHost: localhost\r\nAccept: */*\r\n"
method, full_command
) )
.as_bytes()], .as_bytes()],
&request_fds, &request_fds,
@ -235,7 +234,7 @@ pub fn simple_api_command_with_fds<T: Read + Write + ScmSocket>(
) -> Result<(), Error> { ) -> Result<(), Error> {
// Create the full VM command. For VMM commands, use // Create the full VM command. For VMM commands, use
// simple_api_full_command(). // simple_api_full_command().
let full_command = format!("vm.{}", c); let full_command = format!("vm.{c}");
simple_api_full_command_with_fds(socket, method, &full_command, request_body, request_fds) simple_api_full_command_with_fds(socket, method, &full_command, request_body, request_fds)
} }

View File

@ -160,7 +160,7 @@ fn create_cpu_nodes(
let num_cpus = vcpu_mpidr.len(); let num_cpus = vcpu_mpidr.len();
for (cpu_id, mpidr) in vcpu_mpidr.iter().enumerate().take(num_cpus) { for (cpu_id, mpidr) in vcpu_mpidr.iter().enumerate().take(num_cpus) {
let cpu_name = format!("cpu@{:x}", cpu_id); let cpu_name = format!("cpu@{cpu_id:x}");
let cpu_node = fdt.begin_node(&cpu_name)?; let cpu_node = fdt.begin_node(&cpu_name)?;
fdt.property_string("device_type", "cpu")?; fdt.property_string("device_type", "cpu")?;
fdt.property_string("compatible", "arm,arm-v8")?; fdt.property_string("compatible", "arm,arm-v8")?;
@ -192,15 +192,15 @@ fn create_cpu_nodes(
// Create device tree nodes with regard of above mapping. // Create device tree nodes with regard of above mapping.
for cluster_idx in 0..packages { for cluster_idx in 0..packages {
let cluster_name = format!("cluster{:x}", cluster_idx); let cluster_name = format!("cluster{cluster_idx:x}");
let cluster_node = fdt.begin_node(&cluster_name)?; let cluster_node = fdt.begin_node(&cluster_name)?;
for core_idx in 0..cores_per_package { for core_idx in 0..cores_per_package {
let core_name = format!("core{:x}", core_idx); let core_name = format!("core{core_idx:x}");
let core_node = fdt.begin_node(&core_name)?; let core_node = fdt.begin_node(&core_name)?;
for thread_idx in 0..threads_per_core { for thread_idx in 0..threads_per_core {
let thread_name = format!("thread{:x}", thread_idx); let thread_name = format!("thread{thread_idx:x}");
let thread_node = fdt.begin_node(&thread_name)?; let thread_node = fdt.begin_node(&thread_name)?;
let cpu_idx = threads_per_core * cores_per_package * cluster_idx let cpu_idx = threads_per_core * cores_per_package * cluster_idx
+ threads_per_core * core_idx + threads_per_core * core_idx
@ -247,7 +247,7 @@ fn create_memory_node(
node_memory_addr = memory_region_start_addr; node_memory_addr = memory_region_start_addr;
} }
} }
let memory_node_name = format!("memory@{:x}", node_memory_addr); let memory_node_name = format!("memory@{node_memory_addr:x}");
let memory_node = fdt.begin_node(&memory_node_name)?; let memory_node = fdt.begin_node(&memory_node_name)?;
fdt.property_string("device_type", "memory")?; fdt.property_string("device_type", "memory")?;
fdt.property_array_u64("reg", &mem_reg_prop)?; fdt.property_array_u64("reg", &mem_reg_prop)?;
@ -667,7 +667,7 @@ fn create_pci_nodes(
// See kernel document Documentation/devicetree/bindings/virtio/iommu.txt // See kernel document Documentation/devicetree/bindings/virtio/iommu.txt
// for virtio-iommu node settings. // for virtio-iommu node settings.
let virtio_iommu_node_name = format!("virtio_iommu@{:x}", virtio_iommu_bdf); let virtio_iommu_node_name = format!("virtio_iommu@{virtio_iommu_bdf:x}");
let virtio_iommu_node = fdt.begin_node(&virtio_iommu_node_name)?; let virtio_iommu_node = fdt.begin_node(&virtio_iommu_node_name)?;
fdt.property_u32("#iommu-cells", 1)?; fdt.property_u32("#iommu-cells", 1)?;
fdt.property_string("compatible", "virtio,pci-iommu")?; fdt.property_string("compatible", "virtio,pci-iommu")?;

View File

@ -34,9 +34,7 @@ where
if uefi_size > 0x300000 { if uefi_size > 0x300000 {
return Err(Error::UefiTooBig); return Err(Error::UefiTooBig);
} }
uefi_image uefi_image.rewind().map_err(|_| Error::SeekUefiStart)?;
.seek(SeekFrom::Start(0))
.map_err(|_| Error::SeekUefiStart)?;
guest_mem guest_mem
.read_exact_from(guest_addr, uefi_image, uefi_size) .read_exact_from(guest_addr, uefi_image, uefi_size)
.map_err(|_| Error::ReadUefiImage) .map_err(|_| Error::ReadUefiImage)

View File

@ -145,7 +145,7 @@ pub const PAGE_SIZE: usize = 4096;
impl fmt::Display for DeviceType { impl fmt::Display for DeviceType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self) write!(f, "{self:?}")
} }
} }

View File

@ -1320,6 +1320,6 @@ mod tests {
add_memmap_entry(&mut memmap, 0, 0x1000, E820_RAM); add_memmap_entry(&mut memmap, 0, 0x1000, E820_RAM);
add_memmap_entry(&mut memmap, 0x10000, 0xa000, E820_RESERVED); add_memmap_entry(&mut memmap, 0x10000, 0xa000, E820_RESERVED);
assert_eq!(format!("{:?}", memmap), format!("{:?}", expected_memmap)); assert_eq!(format!("{memmap:?}"), format!("{expected_memmap:?}"));
} }
} }

View File

@ -300,7 +300,7 @@ mod tests {
mpspec::MP_IOAPIC => mem::size_of::<MpcIoapicWrapper>(), mpspec::MP_IOAPIC => mem::size_of::<MpcIoapicWrapper>(),
mpspec::MP_INTSRC => mem::size_of::<MpcIntsrcWrapper>(), mpspec::MP_INTSRC => mem::size_of::<MpcIntsrcWrapper>(),
mpspec::MP_LINTSRC => mem::size_of::<MpcLintsrcWrapper>(), mpspec::MP_LINTSRC => mem::size_of::<MpcLintsrcWrapper>(),
_ => panic!("unrecognized mpc table entry type: {}", type_), _ => panic!("unrecognized mpc table entry type: {type_}"),
} }
} }

View File

@ -48,10 +48,10 @@ impl Display for Error {
Clear => "Failure while zeroing out the memory for the SMBIOS table".to_string(), Clear => "Failure while zeroing out the memory for the SMBIOS table".to_string(),
WriteSmbiosEp => "Failure to write SMBIOS entrypoint structure".to_string(), WriteSmbiosEp => "Failure to write SMBIOS entrypoint structure".to_string(),
WriteData => "Failure to write additional data to memory".to_string(), WriteData => "Failure to write additional data to memory".to_string(),
ParseUuid(e) => format!("Failure to parse uuid: {}", e), ParseUuid(e) => format!("Failure to parse uuid: {e}"),
}; };
write!(f, "SMBIOS error: {}", description) write!(f, "SMBIOS error: {description}")
} }
} }

View File

@ -541,7 +541,7 @@ mod tests {
let mut f = std::fs::File::open("tdvf.fd").unwrap(); let mut f = std::fs::File::open("tdvf.fd").unwrap();
let (sections, _) = parse_tdvf_sections(&mut f).unwrap(); let (sections, _) = parse_tdvf_sections(&mut f).unwrap();
for section in sections { for section in sections {
eprintln!("{:x?}", section) eprintln!("{section:x?}")
} }
} }
} }

View File

@ -23,5 +23,5 @@ fn main() {
// variable BUILT_VERSION, so that it can be reused from the binary. // variable BUILT_VERSION, so that it can be reused from the binary.
// Particularly, this is used from src/main.rs to display the exact // Particularly, this is used from src/main.rs to display the exact
// version. // version.
println!("cargo:rustc-env=BUILT_VERSION={}", version); println!("cargo:rustc-env=BUILT_VERSION={version}");
} }

View File

@ -40,11 +40,11 @@ impl DebugIoPortRange {
impl fmt::Display for DebugIoPortRange { impl fmt::Display for DebugIoPortRange {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
DebugIoPortRange::Firmware => write!(f, "{}: Firmware", DEBUG_IOPORT_PREFIX), DebugIoPortRange::Firmware => write!(f, "{DEBUG_IOPORT_PREFIX}: Firmware"),
DebugIoPortRange::Bootloader => write!(f, "{}: Bootloader", DEBUG_IOPORT_PREFIX), DebugIoPortRange::Bootloader => write!(f, "{DEBUG_IOPORT_PREFIX}: Bootloader"),
DebugIoPortRange::Kernel => write!(f, "{}: Kernel", DEBUG_IOPORT_PREFIX), DebugIoPortRange::Kernel => write!(f, "{DEBUG_IOPORT_PREFIX}: Kernel"),
DebugIoPortRange::Userspace => write!(f, "{}: Userspace", DEBUG_IOPORT_PREFIX), DebugIoPortRange::Userspace => write!(f, "{DEBUG_IOPORT_PREFIX}: Userspace"),
DebugIoPortRange::Custom => write!(f, "{}: Custom", DEBUG_IOPORT_PREFIX), DebugIoPortRange::Custom => write!(f, "{DEBUG_IOPORT_PREFIX}: Custom"),
} }
} }
} }

View File

@ -51,13 +51,13 @@ pub enum Error {
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
Error::BadWriteOffset(offset) => write!(f, "Bad Write Offset: {}", offset), Error::BadWriteOffset(offset) => write!(f, "Bad Write Offset: {offset}"),
Error::GpioInterruptDisabled => write!(f, "GPIO interrupt disabled by guest driver.",), Error::GpioInterruptDisabled => write!(f, "GPIO interrupt disabled by guest driver.",),
Error::GpioInterruptFailure(ref e) => { Error::GpioInterruptFailure(ref e) => {
write!(f, "Could not trigger GPIO interrupt: {}.", e) write!(f, "Could not trigger GPIO interrupt: {e}.")
} }
Error::GpioTriggerKeyFailure(key) => { Error::GpioTriggerKeyFailure(key) => {
write!(f, "Invalid GPIO Input key triggerd: {}.", key) write!(f, "Invalid GPIO Input key triggerd: {key}.")
} }
} }
} }

View File

@ -48,8 +48,8 @@ pub enum Error {
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
Error::BadWriteOffset(offset) => write!(f, "Bad Write Offset: {}", offset), Error::BadWriteOffset(offset) => write!(f, "Bad Write Offset: {offset}"),
Error::InterruptFailure(e) => write!(f, "Failed to trigger interrupt: {}", e), Error::InterruptFailure(e) => write!(f, "Failed to trigger interrupt: {e}"),
} }
} }
} }

View File

@ -60,11 +60,11 @@ pub enum Error {
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
Error::BadWriteOffset(offset) => write!(f, "pl011_write: Bad Write Offset: {}", offset), Error::BadWriteOffset(offset) => write!(f, "pl011_write: Bad Write Offset: {offset}"),
Error::DmaNotImplemented => write!(f, "pl011: DMA not implemented."), Error::DmaNotImplemented => write!(f, "pl011: DMA not implemented."),
Error::InterruptFailure(e) => write!(f, "Failed to trigger interrupt: {}", e), Error::InterruptFailure(e) => write!(f, "Failed to trigger interrupt: {e}"),
Error::WriteAllFailure(e) => write!(f, "Failed to write: {}", e), Error::WriteAllFailure(e) => write!(f, "Failed to write: {e}"),
Error::FlushFailure(e) => write!(f, "Failed to flush: {}", e), Error::FlushFailure(e) => write!(f, "Failed to flush: {e}"),
} }
} }
} }

View File

@ -117,10 +117,7 @@ fn get_fields_map(reg: u32) -> phf::Map<&'static str, [u32; 2]> {
CRB_INTF_ID2 => CRB_INTF_ID2_FIELDS, CRB_INTF_ID2 => CRB_INTF_ID2_FIELDS,
CRB_CTRL_STS => CRB_CTRL_STS_FIELDS, CRB_CTRL_STS => CRB_CTRL_STS_FIELDS,
_ => { _ => {
panic!( panic!("Fields in '{reg:?}' register were accessed which are Invalid");
"Fields in '{:?}' register were accessed which are Invalid",
reg
);
} }
} }
} }

View File

@ -24,10 +24,10 @@ impl<T: Debug> Display for Exception<T> {
self.vector, self.vector,
self.ip, self.ip,
self.error self.error
.map(|e| format!(": error {:x}", e)) .map(|e| format!(": error {e:x}"))
.unwrap_or_else(|| "".to_owned()), .unwrap_or_else(|| "".to_owned()),
self.payload self.payload
.map(|payload| format!(": payload {:x}", payload)) .map(|payload| format!(": payload {payload:x}"))
.unwrap_or_else(|| "".to_owned()) .unwrap_or_else(|| "".to_owned())
) )
} }

View File

@ -97,8 +97,7 @@ pub fn is_system_register(regid: u64) -> bool {
assert!( assert!(
!(size != KVM_REG_SIZE_U32 && size != KVM_REG_SIZE_U64), !(size != KVM_REG_SIZE_U32 && size != KVM_REG_SIZE_U64),
"Unexpected register size for system register {}", "Unexpected register size for system register {size}"
size
); );
true true

View File

@ -125,7 +125,7 @@ impl<'de> Deserialize<'de> for MacAddr {
{ {
let s = String::deserialize(deserializer)?; let s = String::deserialize(deserializer)?;
MacAddr::parse_str(&s) MacAddr::parse_str(&s)
.map_err(|e| D::Error::custom(format!("The provided MAC address is invalid: {}", e))) .map_err(|e| D::Error::custom(format!("The provided MAC address is invalid: {e}")))
} }
} }
@ -161,7 +161,7 @@ mod tests {
let mac = MacAddr::parse_str("12:34:56:78:9a:BC").unwrap(); let mac = MacAddr::parse_str("12:34:56:78:9a:BC").unwrap();
println!("parsed MAC address: {}", mac); println!("parsed MAC address: {mac}");
let bytes = mac.get_bytes(); let bytes = mac.get_bytes();
assert_eq!(bytes, [0x12u8, 0x34, 0x56, 0x78, 0x9a, 0xbc]); assert_eq!(bytes, [0x12u8, 0x34, 0x56, 0x78, 0x9a, 0xbc]);

View File

@ -41,7 +41,7 @@ type Result<T> = std::result::Result<T, Error>;
fn check_mq_support(if_name: &Option<&str>, queue_pairs: usize) -> Result<()> { fn check_mq_support(if_name: &Option<&str>, queue_pairs: usize) -> Result<()> {
if let Some(tap_name) = if_name { if let Some(tap_name) = if_name {
let mq = queue_pairs > 1; let mq = queue_pairs > 1;
let path = format!("/sys/class/net/{}/tun_flags", tap_name); let path = format!("/sys/class/net/{tap_name}/tun_flags");
// interface does not exist, check is not required // interface does not exist, check is not required
if !Path::new(&path).exists() { if !Path::new(&path).exists() {
return Ok(()); return Ok(());

View File

@ -581,7 +581,7 @@ mod tests {
let _tap_ip_guard = TAP_IP_LOCK.lock().unwrap(); let _tap_ip_guard = TAP_IP_LOCK.lock().unwrap();
let t = Tap::new(1).unwrap(); let t = Tap::new(1).unwrap();
println!("created tap: {:?}", t); println!("created tap: {t:?}");
} }
#[test] #[test]

View File

@ -28,10 +28,10 @@ pub enum OptionParserError {
impl fmt::Display for OptionParserError { impl fmt::Display for OptionParserError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
OptionParserError::UnknownOption(s) => write!(f, "unknown option: {}", s), OptionParserError::UnknownOption(s) => write!(f, "unknown option: {s}"),
OptionParserError::InvalidSyntax(s) => write!(f, "invalid syntax:{}", s), OptionParserError::InvalidSyntax(s) => write!(f, "invalid syntax:{s}"),
OptionParserError::Conversion(field, value) => { OptionParserError::Conversion(field, value) => {
write!(f, "unable to convert {} for {}", value, field) write!(f, "unable to convert {value} for {field}")
} }
} }
} }

View File

@ -516,9 +516,9 @@ impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::Error::*; use self::Error::*;
match self { match self {
BarAddressInvalid(a, s) => write!(f, "address {} size {} too big", a, s), BarAddressInvalid(a, s) => write!(f, "address {a} size {s} too big"),
BarInUse(b) => write!(f, "bar {} already used", b), BarInUse(b) => write!(f, "bar {b} already used"),
BarInUse64(b) => write!(f, "64bit bar {} already used(requires two regs)", b), BarInUse64(b) => write!(f, "64bit bar {b} already used(requires two regs)"),
BarInvalid(b) => write!(f, "bar {} invalid, max {}", b, NUM_BAR_REGS - 1), BarInvalid(b) => write!(f, "bar {} invalid, max {}", b, NUM_BAR_REGS - 1),
BarInvalid64(b) => write!( BarInvalid64(b) => write!(
f, f,
@ -526,18 +526,18 @@ impl Display for Error {
b, b,
NUM_BAR_REGS - 1 NUM_BAR_REGS - 1
), ),
BarSizeInvalid(s) => write!(f, "bar address {} not a power of two", s), BarSizeInvalid(s) => write!(f, "bar address {s} not a power of two"),
CapabilityEmpty => write!(f, "empty capabilities are invalid"), CapabilityEmpty => write!(f, "empty capabilities are invalid"),
CapabilityLengthInvalid(l) => write!(f, "Invalid capability length {}", l), CapabilityLengthInvalid(l) => write!(f, "Invalid capability length {l}"),
CapabilitySpaceFull(s) => write!(f, "capability of size {} doesn't fit", s), CapabilitySpaceFull(s) => write!(f, "capability of size {s} doesn't fit"),
Decode32BarSize => write!(f, "failed to decode 32 bits BAR size"), Decode32BarSize => write!(f, "failed to decode 32 bits BAR size"),
Decode64BarSize => write!(f, "failed to decode 64 bits BAR size"), Decode64BarSize => write!(f, "failed to decode 64 bits BAR size"),
Encode32BarSize => write!(f, "failed to encode 32 bits BAR size"), Encode32BarSize => write!(f, "failed to encode 32 bits BAR size"),
Encode64BarSize => write!(f, "failed to encode 64 bits BAR size"), Encode64BarSize => write!(f, "failed to encode 64 bits BAR size"),
RomBarAddressInvalid(a, s) => write!(f, "address {} size {} too big", a, s), RomBarAddressInvalid(a, s) => write!(f, "address {a} size {s} too big"),
RomBarInUse(b) => write!(f, "rom bar {} already used", b), RomBarInUse(b) => write!(f, "rom bar {b} already used"),
RomBarInvalid(b) => write!(f, "rom bar {} invalid, max {}", b, NUM_BAR_REGS - 1), RomBarInvalid(b) => write!(f, "rom bar {} invalid, max {}", b, NUM_BAR_REGS - 1),
RomBarSizeInvalid(s) => write!(f, "rom bar address {} not a power of two", s), RomBarSizeInvalid(s) => write!(f, "rom bar address {s} not a power of two"),
} }
} }
} }

View File

@ -31,15 +31,15 @@ impl Display for Error {
use self::Error::*; use self::Error::*;
match self { match self {
CapabilitiesSetup(e) => write!(f, "failed to add capability {}", e), CapabilitiesSetup(e) => write!(f, "failed to add capability {e}"),
IoAllocationFailed(size) => { IoAllocationFailed(size) => {
write!(f, "failed to allocate space for an IO BAR, size={}", size) write!(f, "failed to allocate space for an IO BAR, size={size}")
} }
IoRegistrationFailed(addr, e) => { IoRegistrationFailed(addr, e) => {
write!(f, "failed to register an IO BAR, addr={} err={}", addr, e) write!(f, "failed to register an IO BAR, addr={addr} err={e}")
} }
MissingResource => write!(f, "failed to find expected resource"), MissingResource => write!(f, "failed to find expected resource"),
InvalidResource(r) => write!(f, "invalid resource {:?}", r), InvalidResource(r) => write!(f, "invalid resource {r:?}"),
} }
} }
} }

View File

@ -575,13 +575,13 @@ impl<M: GuestAddressSpace + Sync + Send> ExternalDmaMapping for VfioUserDmaMappi
.map_err(|e| { .map_err(|e| {
std::io::Error::new( std::io::Error::new(
std::io::ErrorKind::Other, std::io::ErrorKind::Other,
format!("Error mapping region: {}", e), format!("Error mapping region: {e}"),
) )
}) })
} else { } else {
Err(std::io::Error::new( Err(std::io::Error::new(
std::io::ErrorKind::Other, std::io::ErrorKind::Other,
format!("Region not found for 0x{:x}", gpa), format!("Region not found for 0x{gpa:x}"),
)) ))
} }
} }
@ -594,7 +594,7 @@ impl<M: GuestAddressSpace + Sync + Send> ExternalDmaMapping for VfioUserDmaMappi
.map_err(|e| { .map_err(|e| {
std::io::Error::new( std::io::Error::new(
std::io::ErrorKind::Other, std::io::ErrorKind::Other,
format!("Error unmapping region: {}", e), format!("Error unmapping region: {e}"),
) )
}) })
} }

View File

@ -22,5 +22,5 @@ fn main() {
// variable GIT_HUMAN_READABLE, so that it can be reused from the binary. // variable GIT_HUMAN_READABLE, so that it can be reused from the binary.
// Particularly, this is used from the main.rs to display the exact // Particularly, this is used from the main.rs to display the exact
// version information. // version information.
println!("cargo:rustc-env=GIT_HUMAN_READABLE={}", git_human_readable); println!("cargo:rustc-env=GIT_HUMAN_READABLE={git_human_readable}");
} }

View File

@ -117,7 +117,7 @@ pub struct PerformanceTestOverrides {
impl fmt::Display for PerformanceTestOverrides { impl fmt::Display for PerformanceTestOverrides {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(test_iterations) = self.test_iterations { if let Some(test_iterations) = self.test_iterations {
write!(f, "test_iterations = {}", test_iterations)?; write!(f, "test_iterations = {test_iterations}")?;
} }
Ok(()) Ok(())
@ -141,19 +141,19 @@ impl fmt::Display for PerformanceTestControl {
self.test_timeout, self.test_iterations self.test_timeout, self.test_iterations
); );
if let Some(o) = self.num_queues { if let Some(o) = self.num_queues {
output = format!("{}, num_queues = {}", output, o); output = format!("{output}, num_queues = {o}");
} }
if let Some(o) = self.queue_size { if let Some(o) = self.queue_size {
output = format!("{}, queue_size = {}", output, o); output = format!("{output}, queue_size = {o}");
} }
if let Some(o) = self.net_rx { if let Some(o) = self.net_rx {
output = format!("{}, net_rx = {}", output, o); output = format!("{output}, net_rx = {o}");
} }
if let Some(o) = &self.fio_ops { if let Some(o) = &self.fio_ops {
output = format!("{}, fio_ops = {}", output, o); output = format!("{output}, fio_ops = {o}");
} }
write!(f, "{}", output) write!(f, "{output}")
} }
} }
@ -569,7 +569,7 @@ fn main() {
metrics_report.results.push(r); metrics_report.results.push(r);
} }
Err(e) => { Err(e) => {
eprintln!("Aborting test due to error: '{:?}'", e); eprintln!("Aborting test due to error: '{e:?}'");
std::process::exit(1); std::process::exit(1);
} }
}; };
@ -583,7 +583,7 @@ fn main() {
Box::new( Box::new(
std::fs::File::create(std::path::Path::new(file)) std::fs::File::create(std::path::Path::new(file))
.map_err(|e| { .map_err(|e| {
eprintln!("Error opening report file: {}: {}", file, e); eprintln!("Error opening report file: {file}: {e}");
std::process::exit(1); std::process::exit(1);
}) })
.unwrap(), .unwrap(),
@ -599,7 +599,7 @@ fn main() {
.as_bytes(), .as_bytes(),
) )
.map_err(|e| { .map_err(|e| {
eprintln!("Error writing report file: {}", e); eprintln!("Error writing report file: {e}");
std::process::exit(1); std::process::exit(1);
}) })
.unwrap(); .unwrap();

View File

@ -37,8 +37,7 @@ pub fn init_tests() {
// The test image can not be created on tmpfs (e.g. /tmp) filesystem, // The test image can not be created on tmpfs (e.g. /tmp) filesystem,
// as tmpfs does not support O_DIRECT // as tmpfs does not support O_DIRECT
assert!(exec_host_command_output(&format!( assert!(exec_host_command_output(&format!(
"dd if=/dev/zero of={} bs=1M count=4096", "dd if=/dev/zero of={BLK_IO_TEST_IMG} bs=1M count=4096"
BLK_IO_TEST_IMG
)) ))
.status .status
.success()); .success());
@ -46,7 +45,7 @@ pub fn init_tests() {
pub fn cleanup_tests() { pub fn cleanup_tests() {
fs::remove_file(BLK_IO_TEST_IMG) fs::remove_file(BLK_IO_TEST_IMG)
.unwrap_or_else(|_| panic!("Failed to remove file '{}'.", BLK_IO_TEST_IMG)); .unwrap_or_else(|_| panic!("Failed to remove file '{BLK_IO_TEST_IMG}'."));
} }
// Performance tests are expected to be executed sequentially, so we can // Performance tests are expected to be executed sequentially, so we can
@ -92,7 +91,7 @@ pub fn performance_net_throughput(control: &PerformanceTestControl) -> f64 {
); );
let mut child = GuestCommand::new(&guest) let mut child = GuestCommand::new(&guest)
.args(["--cpus", &format!("boot={}", num_queues)]) .args(["--cpus", &format!("boot={num_queues}")])
.args(["--memory", "size=4G"]) .args(["--memory", "size=4G"])
.args(["--kernel", direct_kernel_boot_path().to_str().unwrap()]) .args(["--kernel", direct_kernel_boot_path().to_str().unwrap()])
.args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE])
@ -133,7 +132,7 @@ pub fn performance_net_latency(control: &PerformanceTestControl) -> f64 {
); );
let mut child = GuestCommand::new(&guest) let mut child = GuestCommand::new(&guest)
.args(["--cpus", &format!("boot={}", num_queues)]) .args(["--cpus", &format!("boot={num_queues}")])
.args(["--memory", "size=4G"]) .args(["--memory", "size=4G"])
.args(["--kernel", direct_kernel_boot_path().to_str().unwrap()]) .args(["--kernel", direct_kernel_boot_path().to_str().unwrap()])
.args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE])
@ -349,7 +348,7 @@ pub fn performance_block_io(control: &PerformanceTestControl) -> f64 {
.to_string(); .to_string();
let mut child = GuestCommand::new(&guest) let mut child = GuestCommand::new(&guest)
.args(["--cpus", &format!("boot={}", num_queues)]) .args(["--cpus", &format!("boot={num_queues}")])
.args(["--memory", "size=4G"]) .args(["--memory", "size=4G"])
.args(["--kernel", direct_kernel_boot_path().to_str().unwrap()]) .args(["--kernel", direct_kernel_boot_path().to_str().unwrap()])
.args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE]) .args(["--cmdline", DIRECT_KERNEL_BOOT_CMDLINE])
@ -365,7 +364,7 @@ pub fn performance_block_io(control: &PerformanceTestControl) -> f64 {
guest.disk_config.disk(DiskType::CloudInit).unwrap() guest.disk_config.disk(DiskType::CloudInit).unwrap()
) )
.as_str(), .as_str(),
format!("path={}", BLK_IO_TEST_IMG).as_str(), format!("path={BLK_IO_TEST_IMG}").as_str(),
]) ])
.default_net() .default_net()
.args(["--api-socket", &api_socket]) .args(["--api-socket", &api_socket])
@ -381,8 +380,7 @@ pub fn performance_block_io(control: &PerformanceTestControl) -> f64 {
let fio_command = format!( let fio_command = format!(
"sudo fio --filename=/dev/vdc --name=test --output-format=json \ "sudo fio --filename=/dev/vdc --name=test --output-format=json \
--direct=1 --bs=4k --ioengine=io_uring --iodepth=64 \ --direct=1 --bs=4k --ioengine=io_uring --iodepth=64 \
--rw={} --runtime={} --numjobs={}", --rw={fio_ops} --runtime={test_timeout} --numjobs={num_queues}"
fio_ops, test_timeout, num_queues
); );
let output = guest let output = guest
.ssh_command(&fio_command) .ssh_command(&fio_command)

View File

@ -80,45 +80,41 @@ impl Display for Error {
match self { match self {
BackingFilesNotSupported => write!(f, "backing files not supported"), BackingFilesNotSupported => write!(f, "backing files not supported"),
CompressedBlocksNotSupported => write!(f, "compressed blocks not supported"), CompressedBlocksNotSupported => write!(f, "compressed blocks not supported"),
EvictingCache(e) => write!(f, "failed to evict cache: {}", e), EvictingCache(e) => write!(f, "failed to evict cache: {e}"),
FileTooBig(size) => write!( FileTooBig(size) => write!(f, "file larger than max of {MAX_QCOW_FILE_SIZE}: {size}"),
f, GettingFileSize(e) => write!(f, "failed to get file size: {e}"),
"file larger than max of {}: {}", GettingRefcount(e) => write!(f, "failed to get refcount: {e}"),
MAX_QCOW_FILE_SIZE, size
),
GettingFileSize(e) => write!(f, "failed to get file size: {}", e),
GettingRefcount(e) => write!(f, "failed to get refcount: {}", e),
InvalidClusterIndex => write!(f, "invalid cluster index"), InvalidClusterIndex => write!(f, "invalid cluster index"),
InvalidClusterSize => write!(f, "invalid cluster size"), InvalidClusterSize => write!(f, "invalid cluster size"),
InvalidIndex => write!(f, "invalid index"), InvalidIndex => write!(f, "invalid index"),
InvalidL1TableOffset => write!(f, "invalid L1 table offset"), InvalidL1TableOffset => write!(f, "invalid L1 table offset"),
InvalidL1TableSize(size) => write!(f, "invalid L1 table size {}", size), InvalidL1TableSize(size) => write!(f, "invalid L1 table size {size}"),
InvalidMagic => write!(f, "invalid magic"), InvalidMagic => write!(f, "invalid magic"),
InvalidOffset(_) => write!(f, "invalid offset"), InvalidOffset(_) => write!(f, "invalid offset"),
InvalidRefcountTableOffset => write!(f, "invalid refcount table offset"), InvalidRefcountTableOffset => write!(f, "invalid refcount table offset"),
InvalidRefcountTableSize(size) => write!(f, "invalid refcount table size: {}", size), InvalidRefcountTableSize(size) => write!(f, "invalid refcount table size: {size}"),
NoFreeClusters => write!(f, "no free clusters"), NoFreeClusters => write!(f, "no free clusters"),
NoRefcountClusters => write!(f, "no refcount clusters"), NoRefcountClusters => write!(f, "no refcount clusters"),
NotEnoughSpaceForRefcounts => write!(f, "not enough space for refcounts"), NotEnoughSpaceForRefcounts => write!(f, "not enough space for refcounts"),
OpeningFile(e) => write!(f, "failed to open file: {}", e), OpeningFile(e) => write!(f, "failed to open file: {e}"),
ReadingData(e) => write!(f, "failed to read data: {}", e), ReadingData(e) => write!(f, "failed to read data: {e}"),
ReadingHeader(e) => write!(f, "failed to read header: {}", e), ReadingHeader(e) => write!(f, "failed to read header: {e}"),
ReadingPointers(e) => write!(f, "failed to read pointers: {}", e), ReadingPointers(e) => write!(f, "failed to read pointers: {e}"),
ReadingRefCountBlock(e) => write!(f, "failed to read ref count block: {}", e), ReadingRefCountBlock(e) => write!(f, "failed to read ref count block: {e}"),
ReadingRefCounts(e) => write!(f, "failed to read ref counts: {}", e), ReadingRefCounts(e) => write!(f, "failed to read ref counts: {e}"),
RebuildingRefCounts(e) => write!(f, "failed to rebuild ref counts: {}", e), RebuildingRefCounts(e) => write!(f, "failed to rebuild ref counts: {e}"),
RefcountTableOffEnd => write!(f, "refcount table offset past file end"), RefcountTableOffEnd => write!(f, "refcount table offset past file end"),
RefcountTableTooLarge => write!(f, "too many clusters specified for refcount table"), RefcountTableTooLarge => write!(f, "too many clusters specified for refcount table"),
SeekingFile(e) => write!(f, "failed to seek file: {}", e), SeekingFile(e) => write!(f, "failed to seek file: {e}"),
SettingFileSize(e) => write!(f, "failed to set file size: {}", e), SettingFileSize(e) => write!(f, "failed to set file size: {e}"),
SettingRefcountRefcount(e) => write!(f, "failed to set refcount refcount: {}", e), SettingRefcountRefcount(e) => write!(f, "failed to set refcount refcount: {e}"),
SizeTooSmallForNumberOfClusters => write!(f, "size too small for number of clusters"), SizeTooSmallForNumberOfClusters => write!(f, "size too small for number of clusters"),
TooManyL1Entries(count) => write!(f, "l1 entry table too large: {}", count), TooManyL1Entries(count) => write!(f, "l1 entry table too large: {count}"),
TooManyRefcounts(count) => write!(f, "ref count table too large: {}", count), TooManyRefcounts(count) => write!(f, "ref count table too large: {count}"),
UnsupportedRefcountOrder => write!(f, "unsupported refcount order"), UnsupportedRefcountOrder => write!(f, "unsupported refcount order"),
UnsupportedVersion(v) => write!(f, "unsupported version: {}", v), UnsupportedVersion(v) => write!(f, "unsupported version: {v}"),
WritingData(e) => write!(f, "failed to write data: {}", e), WritingData(e) => write!(f, "failed to write data: {e}"),
WritingHeader(e) => write!(f, "failed to write header: {}", e), WritingHeader(e) => write!(f, "failed to write header: {e}"),
} }
} }
} }
@ -190,7 +186,7 @@ pub struct QcowHeader {
impl QcowHeader { impl QcowHeader {
/// Creates a QcowHeader from a reference to a file. /// Creates a QcowHeader from a reference to a file.
pub fn new(f: &mut RawFile) -> Result<QcowHeader> { pub fn new(f: &mut RawFile) -> Result<QcowHeader> {
f.seek(SeekFrom::Start(0)).map_err(Error::ReadingHeader)?; f.rewind().map_err(Error::ReadingHeader)?;
let magic = f.read_u32::<BigEndian>().map_err(Error::ReadingHeader)?; let magic = f.read_u32::<BigEndian>().map_err(Error::ReadingHeader)?;
if magic != QCOW_MAGIC { if magic != QCOW_MAGIC {
return Err(Error::InvalidMagic); return Err(Error::InvalidMagic);
@ -559,7 +555,7 @@ impl QcowFile {
/// Creates a new QcowFile at the given path. /// Creates a new QcowFile at the given path.
pub fn new(mut file: RawFile, version: u32, virtual_size: u64) -> Result<QcowFile> { pub fn new(mut file: RawFile, version: u32, virtual_size: u64) -> Result<QcowFile> {
let header = QcowHeader::create_for_size(version, virtual_size); let header = QcowHeader::create_for_size(version, virtual_size);
file.seek(SeekFrom::Start(0)).map_err(Error::SeekingFile)?; file.rewind().map_err(Error::SeekingFile)?;
header.write_to(&mut file)?; header.write_to(&mut file)?;
let mut qcow = Self::from(file)?; let mut qcow = Self::from(file)?;
@ -812,10 +808,7 @@ impl QcowFile {
) -> Result<()> { ) -> Result<()> {
// Rewrite the header with lazy refcounts enabled while we are rebuilding the tables. // Rewrite the header with lazy refcounts enabled while we are rebuilding the tables.
header.compatible_features |= COMPATIBLE_FEATURES_LAZY_REFCOUNTS; header.compatible_features |= COMPATIBLE_FEATURES_LAZY_REFCOUNTS;
raw_file raw_file.file_mut().rewind().map_err(Error::SeekingFile)?;
.file_mut()
.seek(SeekFrom::Start(0))
.map_err(Error::SeekingFile)?;
header.write_to(raw_file.file_mut())?; header.write_to(raw_file.file_mut())?;
for (i, refblock_addr) in ref_table.iter().enumerate() { for (i, refblock_addr) in ref_table.iter().enumerate() {
@ -850,10 +843,7 @@ impl QcowFile {
// Rewrite the header again, now with lazy refcounts disabled. // Rewrite the header again, now with lazy refcounts disabled.
header.compatible_features &= !COMPATIBLE_FEATURES_LAZY_REFCOUNTS; header.compatible_features &= !COMPATIBLE_FEATURES_LAZY_REFCOUNTS;
raw_file raw_file.file_mut().rewind().map_err(Error::SeekingFile)?;
.file_mut()
.seek(SeekFrom::Start(0))
.map_err(Error::SeekingFile)?;
header.write_to(raw_file.file_mut())?; header.write_to(raw_file.file_mut())?;
Ok(()) Ok(())
@ -1240,7 +1230,7 @@ impl QcowFile {
.map_err(|e| { .map_err(|e| {
io::Error::new( io::Error::new(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
format!("failed to get cluster refcount: {}", e), format!("failed to get cluster refcount: {e}"),
) )
})?; })?;
if refcount == 0 { if refcount == 0 {
@ -1656,9 +1646,7 @@ where
R: Read + Seek + SeekHole, R: Read + Seek + SeekHole,
{ {
let src_size = reader.seek(SeekFrom::End(0)).map_err(Error::SeekingFile)?; let src_size = reader.seek(SeekFrom::End(0)).map_err(Error::SeekingFile)?;
reader reader.rewind().map_err(Error::SeekingFile)?;
.seek(SeekFrom::Start(0))
.map_err(Error::SeekingFile)?;
// Ensure the destination file is empty before writing to it. // Ensure the destination file is empty before writing to it.
dst_file.set_len(0).map_err(Error::SettingFileSize)?; dst_file.set_len(0).map_err(Error::SettingFileSize)?;
@ -1700,10 +1688,8 @@ pub fn convert(mut src_file: RawFile, dst_file: RawFile, dst_type: ImageType) ->
/// Detect the type of an image file by checking for a valid qcow2 header. /// Detect the type of an image file by checking for a valid qcow2 header.
pub fn detect_image_type(file: &mut RawFile) -> Result<ImageType> { pub fn detect_image_type(file: &mut RawFile) -> Result<ImageType> {
let orig_seek = file let orig_seek = file.stream_position().map_err(Error::SeekingFile)?;
.seek(SeekFrom::Current(0)) file.rewind().map_err(Error::SeekingFile)?;
.map_err(Error::SeekingFile)?;
file.seek(SeekFrom::Start(0)).map_err(Error::SeekingFile)?;
let magic = file.read_u32::<BigEndian>().map_err(Error::ReadingHeader)?; let magic = file.read_u32::<BigEndian>().map_err(Error::ReadingHeader)?;
let image_type = if magic == QCOW_MAGIC { let image_type = if magic == QCOW_MAGIC {
ImageType::Qcow2 ImageType::Qcow2
@ -1794,7 +1780,7 @@ mod tests {
let mut disk_file: RawFile = RawFile::new(TempFile::new().unwrap().into_file(), false); let mut disk_file: RawFile = RawFile::new(TempFile::new().unwrap().into_file(), false);
disk_file.write_all(header).unwrap(); disk_file.write_all(header).unwrap();
disk_file.set_len(0x1_0000_0000).unwrap(); disk_file.set_len(0x1_0000_0000).unwrap();
disk_file.seek(SeekFrom::Start(0)).unwrap(); disk_file.rewind().unwrap();
testfn(disk_file); // File closed when the function exits. testfn(disk_file); // File closed when the function exits.
} }
@ -1816,7 +1802,7 @@ mod tests {
header header
.write_to(&mut disk_file) .write_to(&mut disk_file)
.expect("Failed to write header to temporary file."); .expect("Failed to write header to temporary file.");
disk_file.seek(SeekFrom::Start(0)).unwrap(); disk_file.rewind().unwrap();
QcowFile::from(disk_file).expect("Failed to create Qcow from default Header"); QcowFile::from(disk_file).expect("Failed to create Qcow from default Header");
} }
@ -1827,7 +1813,7 @@ mod tests {
header header
.write_to(&mut disk_file) .write_to(&mut disk_file)
.expect("Failed to write header to temporary file."); .expect("Failed to write header to temporary file.");
disk_file.seek(SeekFrom::Start(0)).unwrap(); disk_file.rewind().unwrap();
QcowFile::from(disk_file).expect("Failed to create Qcow from default Header"); QcowFile::from(disk_file).expect("Failed to create Qcow from default Header");
} }
@ -1955,7 +1941,7 @@ mod tests {
q.write_all(b"test first bytes") q.write_all(b"test first bytes")
.expect("Failed to write test string."); .expect("Failed to write test string.");
let mut buf = [0u8; 4]; let mut buf = [0u8; 4];
q.seek(SeekFrom::Start(0)).expect("Failed to seek."); q.rewind().expect("Failed to seek.");
q.read_exact(&mut buf).expect("Failed to read."); q.read_exact(&mut buf).expect("Failed to read.");
assert_eq!(&buf, b"test"); assert_eq!(&buf, b"test");
}); });
@ -2007,15 +1993,15 @@ mod tests {
let mut q = QcowFile::from(disk_file).unwrap(); let mut q = QcowFile::from(disk_file).unwrap();
// Write some test data. // Write some test data.
let b = [0x55u8; CHUNK_SIZE]; let b = [0x55u8; CHUNK_SIZE];
q.seek(SeekFrom::Start(0)).expect("Failed to seek."); q.rewind().expect("Failed to seek.");
q.write_all(&b).expect("Failed to write test string."); q.write_all(&b).expect("Failed to write test string.");
// Overwrite the full cluster with zeroes. // Overwrite the full cluster with zeroes.
q.seek(SeekFrom::Start(0)).expect("Failed to seek."); q.rewind().expect("Failed to seek.");
let nwritten = q.write_zeroes(CHUNK_SIZE).expect("Failed to write zeroes."); let nwritten = q.write_zeroes(CHUNK_SIZE).expect("Failed to write zeroes.");
assert_eq!(nwritten, CHUNK_SIZE); assert_eq!(nwritten, CHUNK_SIZE);
// Verify that the data was zeroed out. // Verify that the data was zeroed out.
let mut buf = [0u8; CHUNK_SIZE]; let mut buf = [0u8; CHUNK_SIZE];
q.seek(SeekFrom::Start(0)).expect("Failed to seek."); q.rewind().expect("Failed to seek.");
q.read_exact(&mut buf).expect("Failed to read."); q.read_exact(&mut buf).expect("Failed to read.");
assert_eq!(buf[0], 0); assert_eq!(buf[0], 0);
assert_eq!(buf[CHUNK_SIZE - 1], 0); assert_eq!(buf[CHUNK_SIZE - 1], 0);
@ -2457,7 +2443,7 @@ mod tests {
} }
} }
// Check that address 0 is still zeros. // Check that address 0 is still zeros.
qcow_file.seek(SeekFrom::Start(0)).expect("Failed to seek."); qcow_file.rewind().expect("Failed to seek.");
let nread = qcow_file.read(&mut readback).expect("Failed to read."); let nread = qcow_file.read(&mut readback).expect("Failed to read.");
assert_eq!(nread, BLOCK_SIZE); assert_eq!(nread, BLOCK_SIZE);
for read in readback.iter() { for read in readback.iter() {
@ -2481,7 +2467,7 @@ mod tests {
} }
fn seek_cur(file: &mut QcowFile) -> u64 { fn seek_cur(file: &mut QcowFile) -> u64 {
file.seek(SeekFrom::Current(0)).unwrap() file.stream_position().unwrap()
} }
#[test] #[test]
@ -2545,7 +2531,7 @@ mod tests {
assert_eq!(seek_cur(&mut file), 0xFFFF); assert_eq!(seek_cur(&mut file), 0xFFFF);
// seek_hole at or after the end of the file should return None // seek_hole at or after the end of the file should return None
file.seek(SeekFrom::Start(0)).unwrap(); file.rewind().unwrap();
assert_eq!(file.seek_hole(0x30000).unwrap(), None); assert_eq!(file.seek_hole(0x30000).unwrap(), None);
assert_eq!(seek_cur(&mut file), 0); assert_eq!(seek_cur(&mut file), 0);
assert_eq!(file.seek_hole(0x30001).unwrap(), None); assert_eq!(file.seek_hole(0x30001).unwrap(), None);
@ -2563,33 +2549,33 @@ mod tests {
assert_eq!(seek_cur(&mut file), 0xFFFF); assert_eq!(seek_cur(&mut file), 0xFFFF);
// seek_hole within data should return the next hole // seek_hole within data should return the next hole
file.seek(SeekFrom::Start(0)).unwrap(); file.rewind().unwrap();
assert_eq!(file.seek_hole(0x10000).unwrap(), Some(0x20000)); assert_eq!(file.seek_hole(0x10000).unwrap(), Some(0x20000));
assert_eq!(seek_cur(&mut file), 0x20000); assert_eq!(seek_cur(&mut file), 0x20000);
file.seek(SeekFrom::Start(0)).unwrap(); file.rewind().unwrap();
assert_eq!(file.seek_hole(0x10001).unwrap(), Some(0x20000)); assert_eq!(file.seek_hole(0x10001).unwrap(), Some(0x20000));
assert_eq!(seek_cur(&mut file), 0x20000); assert_eq!(seek_cur(&mut file), 0x20000);
file.seek(SeekFrom::Start(0)).unwrap(); file.rewind().unwrap();
assert_eq!(file.seek_hole(0x1FFFF).unwrap(), Some(0x20000)); assert_eq!(file.seek_hole(0x1FFFF).unwrap(), Some(0x20000));
assert_eq!(seek_cur(&mut file), 0x20000); assert_eq!(seek_cur(&mut file), 0x20000);
file.seek(SeekFrom::Start(0)).unwrap(); file.rewind().unwrap();
assert_eq!(file.seek_hole(0xFFFF).unwrap(), Some(0xFFFF)); assert_eq!(file.seek_hole(0xFFFF).unwrap(), Some(0xFFFF));
assert_eq!(seek_cur(&mut file), 0xFFFF); assert_eq!(seek_cur(&mut file), 0xFFFF);
file.seek(SeekFrom::Start(0)).unwrap(); file.rewind().unwrap();
assert_eq!(file.seek_hole(0x10000).unwrap(), Some(0x20000)); assert_eq!(file.seek_hole(0x10000).unwrap(), Some(0x20000));
assert_eq!(seek_cur(&mut file), 0x20000); assert_eq!(seek_cur(&mut file), 0x20000);
file.seek(SeekFrom::Start(0)).unwrap(); file.rewind().unwrap();
assert_eq!(file.seek_hole(0x1FFFF).unwrap(), Some(0x20000)); assert_eq!(file.seek_hole(0x1FFFF).unwrap(), Some(0x20000));
assert_eq!(seek_cur(&mut file), 0x20000); assert_eq!(seek_cur(&mut file), 0x20000);
file.seek(SeekFrom::Start(0)).unwrap(); file.rewind().unwrap();
assert_eq!(file.seek_hole(0x20000).unwrap(), Some(0x20000)); assert_eq!(file.seek_hole(0x20000).unwrap(), Some(0x20000));
assert_eq!(seek_cur(&mut file), 0x20000); assert_eq!(seek_cur(&mut file), 0x20000);
file.seek(SeekFrom::Start(0)).unwrap(); file.rewind().unwrap();
assert_eq!(file.seek_hole(0x20001).unwrap(), Some(0x20001)); assert_eq!(file.seek_hole(0x20001).unwrap(), Some(0x20001));
assert_eq!(seek_cur(&mut file), 0x20001); assert_eq!(seek_cur(&mut file), 0x20001);
// seek_hole at EOF should return None // seek_hole at EOF should return None
file.seek(SeekFrom::Start(0)).unwrap(); file.rewind().unwrap();
assert_eq!(file.seek_hole(0x30000).unwrap(), None); assert_eq!(file.seek_hole(0x30000).unwrap(), None);
assert_eq!(seek_cur(&mut file), 0); assert_eq!(seek_cur(&mut file), 0);
@ -2600,10 +2586,10 @@ mod tests {
// seek_hole within [0x20000, 0x30000) should now find the hole at EOF // seek_hole within [0x20000, 0x30000) should now find the hole at EOF
assert_eq!(file.seek_hole(0x20000).unwrap(), Some(0x30000)); assert_eq!(file.seek_hole(0x20000).unwrap(), Some(0x30000));
assert_eq!(seek_cur(&mut file), 0x30000); assert_eq!(seek_cur(&mut file), 0x30000);
file.seek(SeekFrom::Start(0)).unwrap(); file.rewind().unwrap();
assert_eq!(file.seek_hole(0x20001).unwrap(), Some(0x30000)); assert_eq!(file.seek_hole(0x20001).unwrap(), Some(0x30000));
assert_eq!(seek_cur(&mut file), 0x30000); assert_eq!(seek_cur(&mut file), 0x30000);
file.seek(SeekFrom::Start(0)).unwrap(); file.rewind().unwrap();
assert_eq!(file.seek_hole(0x30000).unwrap(), None); assert_eq!(file.seek_hole(0x30000).unwrap(), None);
assert_eq!(seek_cur(&mut file), 0); assert_eq!(seek_cur(&mut file), 0);
}); });

View File

@ -31,16 +31,14 @@ impl Display for Error {
use self::Error::*; use self::Error::*;
match self { match self {
EvictingRefCounts(e) => write!( EvictingRefCounts(e) => {
f, write!(f, "failed to write a refblock from the cache to disk: {e}")
"failed to write a refblock from the cache to disk: {}", }
e
),
InvalidIndex => write!(f, "address requested is not within the range of the disk"), InvalidIndex => write!(f, "address requested is not within the range of the disk"),
NeedCluster(addr) => write!(f, "cluster with addr={} needs to be read", addr), NeedCluster(addr) => write!(f, "cluster with addr={addr} needs to be read"),
NeedNewCluster => write!(f, "new cluster needs to be allocated for refcounts"), NeedNewCluster => write!(f, "new cluster needs to be allocated for refcounts"),
ReadingRefCounts(e) => { ReadingRefCounts(e) => {
write!(f, "failed to read the file into the refcount cache: {}", e) write!(f, "failed to read the file into the refcount cache: {e}")
} }
} }
} }

View File

@ -889,7 +889,7 @@ pub(crate) mod tests {
fn test_rate_limiter_debug() { fn test_rate_limiter_debug() {
let l = RateLimiter::new(1, 2, 3, 4, 5, 6).unwrap(); let l = RateLimiter::new(1, 2, 3, 4, 5, 6).unwrap();
assert_eq!( assert_eq!(
format!("{:?}", l), format!("{l:?}"),
format!( format!(
"RateLimiter {{ bandwidth: {:?}, ops: {:?} }}", "RateLimiter {{ bandwidth: {:?}, ops: {:?} }}",
l.bandwidth(), l.bandwidth(),

View File

@ -42,21 +42,21 @@ impl fmt::Display for Error {
use Error::*; use Error::*;
match self { match self {
ApiClient(e) => e.fmt(f), ApiClient(e) => e.fmt(f),
Connect(e) => write!(f, "Error opening HTTP socket: {}", e), Connect(e) => write!(f, "Error opening HTTP socket: {e}"),
InvalidCpuCount(e) => write!(f, "Error parsing CPU count: {}", e), InvalidCpuCount(e) => write!(f, "Error parsing CPU count: {e}"),
InvalidMemorySize(e) => write!(f, "Error parsing memory size: {:?}", e), InvalidMemorySize(e) => write!(f, "Error parsing memory size: {e:?}"),
InvalidBalloonSize(e) => write!(f, "Error parsing balloon size: {:?}", e), InvalidBalloonSize(e) => write!(f, "Error parsing balloon size: {e:?}"),
AddDeviceConfig(e) => write!(f, "Error parsing device syntax: {}", e), AddDeviceConfig(e) => write!(f, "Error parsing device syntax: {e}"),
AddDiskConfig(e) => write!(f, "Error parsing disk syntax: {}", e), AddDiskConfig(e) => write!(f, "Error parsing disk syntax: {e}"),
AddFsConfig(e) => write!(f, "Error parsing filesystem syntax: {}", e), AddFsConfig(e) => write!(f, "Error parsing filesystem syntax: {e}"),
AddPmemConfig(e) => write!(f, "Error parsing persistent memory syntax: {}", e), AddPmemConfig(e) => write!(f, "Error parsing persistent memory syntax: {e}"),
AddNetConfig(e) => write!(f, "Error parsing network syntax: {}", e), AddNetConfig(e) => write!(f, "Error parsing network syntax: {e}"),
AddUserDeviceConfig(e) => write!(f, "Error parsing user device syntax: {}", e), AddUserDeviceConfig(e) => write!(f, "Error parsing user device syntax: {e}"),
AddVdpaConfig(e) => write!(f, "Error parsing vDPA device syntax: {}", e), AddVdpaConfig(e) => write!(f, "Error parsing vDPA device syntax: {e}"),
AddVsockConfig(e) => write!(f, "Error parsing vsock syntax: {}", e), AddVsockConfig(e) => write!(f, "Error parsing vsock syntax: {e}"),
Restore(e) => write!(f, "Error parsing restore syntax: {}", e), Restore(e) => write!(f, "Error parsing restore syntax: {e}"),
ReadingStdin(e) => write!(f, "Error reading from stdin: {}", e), ReadingStdin(e) => write!(f, "Error reading from stdin: {e}"),
ReadingFile(e) => write!(f, "Error reading from file: {}", e), ReadingFile(e) => write!(f, "Error reading from file: {e}"),
} }
} }
} }
@ -688,7 +688,7 @@ fn main() {
let matches = app.get_matches(); let matches = app.get_matches();
if let Err(e) = do_command(&matches) { if let Err(e) = do_command(&matches) {
eprintln!("Error running command: {}", e); eprintln!("Error running command: {e}");
process::exit(1) process::exit(1)
}; };
} }

View File

@ -479,7 +479,7 @@ fn start_vmm(cmd_arguments: ArgMatches) -> Result<Option<String>, Error> {
"log" => SeccompAction::Log, "log" => SeccompAction::Log,
_ => { _ => {
// The user providing an invalid value will be rejected by clap // The user providing an invalid value will be rejected by clap
panic!("Invalid parameter {} for \"--seccomp\" flag", seccomp_value); panic!("Invalid parameter {seccomp_value} for \"--seccomp\" flag");
} }
} }
} else { } else {
@ -499,7 +499,7 @@ fn start_vmm(cmd_arguments: ArgMatches) -> Result<Option<String>, Error> {
signal_hook::low_level::emulate_default_handler(SIGSYS).unwrap(); signal_hook::low_level::emulate_default_handler(SIGSYS).unwrap();
}) })
} }
.map_err(|e| eprintln!("Error adding SIGSYS signal handler: {}", e)) .map_err(|e| eprintln!("Error adding SIGSYS signal handler: {e}"))
.ok(); .ok();
} }
@ -508,13 +508,13 @@ fn start_vmm(cmd_arguments: ArgMatches) -> Result<Option<String>, Error> {
// dedicated signal handling thread we'll start in a bit. // dedicated signal handling thread we'll start in a bit.
for sig in &vmm::vm::Vm::HANDLED_SIGNALS { for sig in &vmm::vm::Vm::HANDLED_SIGNALS {
if let Err(e) = block_signal(*sig) { if let Err(e) = block_signal(*sig) {
eprintln!("Error blocking signals: {}", e); eprintln!("Error blocking signals: {e}");
} }
} }
for sig in &vmm::Vmm::HANDLED_SIGNALS { for sig in &vmm::Vmm::HANDLED_SIGNALS {
if let Err(e) = block_signal(*sig) { if let Err(e) = block_signal(*sig) {
eprintln!("Error blocking signals: {}", e); eprintln!("Error blocking signals: {e}");
} }
} }
@ -605,7 +605,7 @@ fn main() {
0 0
} }
Err(e) => { Err(e) => {
eprintln!("{}", e); eprintln!("{e}");
1 1
} }
}; };

View File

@ -148,13 +148,12 @@ impl GuestNetworkConfig {
let duration = start.elapsed(); let duration = start.elapsed();
eprintln!( eprintln!(
"\n\n==== Start 'wait_vm_boot' (FAILED) ====\n\n\ "\n\n==== Start 'wait_vm_boot' (FAILED) ====\n\n\
duration =\"{:?}, timeout = {}s\"\n\ duration =\"{duration:?}, timeout = {timeout}s\"\n\
listen_addr=\"{}\"\n\ listen_addr=\"{listen_addr}\"\n\
expected_guest_addr=\"{}\"\n\ expected_guest_addr=\"{expected_guest_addr}\"\n\
message=\"{}\"\n\ message=\"{s}\"\n\
error=\"{:?}\"\n\ error=\"{e:?}\"\n\
\n==== End 'wait_vm_boot' outout ====\n\n", \n==== End 'wait_vm_boot' outout ====\n\n"
duration, timeout, listen_addr, expected_guest_addr, s, e
); );
Err(e) Err(e)
@ -435,7 +434,7 @@ impl DiskConfig for WindowsDiskConfig {
.output() .output()
.expect("Expect device mapper nodes to be ready"); .expect("Expect device mapper nodes to be ready");
self.osdisk_path = format!("/dev/mapper/{}", windows_snapshot); self.osdisk_path = format!("/dev/mapper/{windows_snapshot}");
self.windows_snapshot_cow = windows_snapshot_cow; self.windows_snapshot_cow = windows_snapshot_cow;
self.windows_snapshot = windows_snapshot; self.windows_snapshot = windows_snapshot;
} }
@ -463,10 +462,7 @@ pub fn rate_limited_copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::
// Make sure there is at least 6 GiB of space // Make sure there is at least 6 GiB of space
if free_bytes < 6 << 30 { if free_bytes < 6 << 30 {
eprintln!( eprintln!("Not enough space on disk ({free_bytes}). Attempt {i} of 10. Sleeping.");
"Not enough space on disk ({}). Attempt {} of 10. Sleeping.",
free_bytes, i
);
thread::sleep(std::time::Duration::new(60, 0)); thread::sleep(std::time::Duration::new(60, 0));
continue; continue;
} }
@ -475,7 +471,7 @@ pub fn rate_limited_copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::
Err(e) => { Err(e) => {
if let Some(errno) = e.raw_os_error() { if let Some(errno) = e.raw_os_error() {
if errno == libc::ENOSPC { if errno == libc::ENOSPC {
eprintln!("Copy returned ENOSPC. Attempt {} of 10. Sleeping.", i); eprintln!("Copy returned ENOSPC. Attempt {i} of 10. Sleeping.");
thread::sleep(std::time::Duration::new(60, 0)); thread::sleep(std::time::Duration::new(60, 0));
continue; continue;
} }
@ -510,7 +506,7 @@ pub fn handle_child_output(
); );
} }
Some(code) => { Some(code) => {
eprintln!("\n\n==== child exit code: {} ====", code); eprintln!("\n\n==== child exit code: {code} ====");
} }
} }
@ -564,7 +560,7 @@ fn scp_to_guest_with_auth(
loop { loop {
match (|| -> Result<(), SshCommandError> { match (|| -> Result<(), SshCommandError> {
let tcp = let tcp =
TcpStream::connect(format!("{}:22", ip)).map_err(SshCommandError::Connection)?; TcpStream::connect(format!("{ip}:22")).map_err(SshCommandError::Connection)?;
let mut sess = Session::new().unwrap(); let mut sess = Session::new().unwrap();
sess.set_tcp_stream(tcp); sess.set_tcp_stream(tcp);
sess.handshake().map_err(SshCommandError::Handshake)?; sess.handshake().map_err(SshCommandError::Handshake)?;
@ -602,13 +598,12 @@ fn scp_to_guest_with_auth(
if counter >= retries { if counter >= retries {
eprintln!( eprintln!(
"\n\n==== Start scp command output (FAILED) ====\n\n\ "\n\n==== Start scp command output (FAILED) ====\n\n\
path =\"{:?}\"\n\ path =\"{path:?}\"\n\
remote_path =\"{:?}\"\n\ remote_path =\"{remote_path:?}\"\n\
auth=\"{:#?}\"\n\ auth=\"{auth:#?}\"\n\
ip=\"{}\"\n\ ip=\"{ip}\"\n\
error=\"{:?}\"\n\ error=\"{e:?}\"\n\
\n==== End scp command outout ====\n\n", \n==== End scp command outout ====\n\n"
path, remote_path, auth, ip, e
); );
return Err(e); return Err(e);
@ -653,7 +648,7 @@ pub fn ssh_command_ip_with_auth(
loop { loop {
match (|| -> Result<(), SshCommandError> { match (|| -> Result<(), SshCommandError> {
let tcp = let tcp =
TcpStream::connect(format!("{}:22", ip)).map_err(SshCommandError::Connection)?; TcpStream::connect(format!("{ip}:22")).map_err(SshCommandError::Connection)?;
let mut sess = Session::new().unwrap(); let mut sess = Session::new().unwrap();
sess.set_tcp_stream(tcp); sess.set_tcp_stream(tcp);
sess.handshake().map_err(SshCommandError::Handshake)?; sess.handshake().map_err(SshCommandError::Handshake)?;
@ -687,13 +682,12 @@ pub fn ssh_command_ip_with_auth(
if counter >= retries { if counter >= retries {
eprintln!( eprintln!(
"\n\n==== Start ssh command output (FAILED) ====\n\n\ "\n\n==== Start ssh command output (FAILED) ====\n\n\
command=\"{}\"\n\ command=\"{command}\"\n\
auth=\"{:#?}\"\n\ auth=\"{auth:#?}\"\n\
ip=\"{}\"\n\ ip=\"{ip}\"\n\
output=\"{}\"\n\ output=\"{s}\"\n\
error=\"{:?}\"\n\ error=\"{e:?}\"\n\
\n==== End ssh command outout ====\n\n", \n==== End ssh command outout ====\n\n"
command, auth, ip, s, e
); );
return Err(e); return Err(e);
@ -727,14 +721,14 @@ pub fn exec_host_command_status(command: &str) -> ExitStatus {
std::process::Command::new("bash") std::process::Command::new("bash")
.args(["-c", command]) .args(["-c", command])
.status() .status()
.unwrap_or_else(|_| panic!("Expected '{}' to run", command)) .unwrap_or_else(|_| panic!("Expected '{command}' to run"))
} }
pub fn exec_host_command_output(command: &str) -> Output { pub fn exec_host_command_output(command: &str) -> Output {
std::process::Command::new("bash") std::process::Command::new("bash")
.args(["-c", command]) .args(["-c", command])
.output() .output()
.unwrap_or_else(|_| panic!("Expected '{}' to run", command)) .unwrap_or_else(|_| panic!("Expected '{command}' to run"))
} }
pub const PIPE_SIZE: i32 = 32 << 20; pub const PIPE_SIZE: i32 = 32 << 20;
@ -755,15 +749,15 @@ impl Guest {
let tmp_dir = TempDir::new_with_prefix("/tmp/ch").unwrap(); let tmp_dir = TempDir::new_with_prefix("/tmp/ch").unwrap();
let network = GuestNetworkConfig { let network = GuestNetworkConfig {
guest_ip: format!("{}.{}.2", class, id), guest_ip: format!("{class}.{id}.2"),
l2_guest_ip1: format!("{}.{}.3", class, id), l2_guest_ip1: format!("{class}.{id}.3"),
l2_guest_ip2: format!("{}.{}.4", class, id), l2_guest_ip2: format!("{class}.{id}.4"),
l2_guest_ip3: format!("{}.{}.5", class, id), l2_guest_ip3: format!("{class}.{id}.5"),
host_ip: format!("{}.{}.1", class, id), host_ip: format!("{class}.{id}.1"),
guest_mac: format!("12:34:56:78:90:{:02x}", id), guest_mac: format!("12:34:56:78:90:{id:02x}"),
l2_guest_mac1: format!("de:ad:be:ef:12:{:02x}", id), l2_guest_mac1: format!("de:ad:be:ef:12:{id:02x}"),
l2_guest_mac2: format!("de:ad:be:ef:34:{:02x}", id), l2_guest_mac2: format!("de:ad:be:ef:34:{id:02x}"),
l2_guest_mac3: format!("de:ad:be:ef:56:{:02x}", id), l2_guest_mac3: format!("de:ad:be:ef:56:{id:02x}"),
tcp_listener_port: DEFAULT_TCP_LISTENER_PORT + id as u16, tcp_listener_port: DEFAULT_TCP_LISTENER_PORT + id as u16,
}; };
@ -900,9 +894,8 @@ impl Guest {
pub fn get_numa_node_memory(&self, node_id: usize) -> Result<u32, Error> { pub fn get_numa_node_memory(&self, node_id: usize) -> Result<u32, Error> {
self.ssh_command( self.ssh_command(
format!( format!(
"grep MemTotal /sys/devices/system/node/node{}/meminfo \ "grep MemTotal /sys/devices/system/node/node{node_id}/meminfo \
| cut -d \":\" -f 2 | grep -o \"[0-9]*\"", | cut -d \":\" -f 2 | grep -o \"[0-9]*\""
node_id
) )
.as_str(), .as_str(),
)? )?
@ -919,10 +912,7 @@ impl Guest {
pub fn check_numa_node_cpus(&self, node_id: usize, cpus: Vec<usize>) -> Result<(), Error> { pub fn check_numa_node_cpus(&self, node_id: usize, cpus: Vec<usize>) -> Result<(), Error> {
for cpu in cpus.iter() { for cpu in cpus.iter() {
let cmd = format!( let cmd = format!("[ -d \"/sys/devices/system/node/node{node_id}/cpu{cpu}\" ]");
"[ -d \"/sys/devices/system/node/node{}/cpu{}\" ]",
node_id, cpu
);
self.ssh_command(cmd.as_str())?; self.ssh_command(cmd.as_str())?;
} }
@ -934,7 +924,7 @@ impl Guest {
node_id: usize, node_id: usize,
distances: &str, distances: &str,
) -> Result<bool, Error> { ) -> Result<bool, Error> {
let cmd = format!("cat /sys/devices/system/node/node{}/distance", node_id); let cmd = format!("cat /sys/devices/system/node/node{node_id}/distance");
if self.ssh_command(cmd.as_str())?.trim() == distances { if self.ssh_command(cmd.as_str())?.trim() == distances {
Ok(true) Ok(true)
} else { } else {
@ -1047,8 +1037,7 @@ impl Guest {
// Write something to vsock from the host // Write something to vsock from the host
assert!(exec_host_command_status(&format!( assert!(exec_host_command_status(&format!(
"echo -e \"CONNECT 16\\nHelloWorld!\" | socat - UNIX-CONNECT:{}", "echo -e \"CONNECT 16\\nHelloWorld!\" | socat - UNIX-CONNECT:{socket}"
socket
)) ))
.success()); .success());
@ -1113,7 +1102,7 @@ impl Guest {
} }
// Check if the console is usable // Check if the console is usable
if let Some(console_text) = console_text { if let Some(console_text) = console_text {
let console_cmd = format!("echo {} | sudo tee /dev/hvc0", console_text); let console_cmd = format!("echo {console_text} | sudo tee /dev/hvc0");
self.ssh_command(&console_cmd).unwrap(); self.ssh_command(&console_cmd).unwrap();
} }
// The net device is 'automatically' exercised through the above 'ssh' commands // The net device is 'automatically' exercised through the above 'ssh' commands
@ -1121,13 +1110,11 @@ impl Guest {
// Check if the pmem device is usable // Check if the pmem device is usable
if let Some(pmem_path) = pmem_path { if let Some(pmem_path) = pmem_path {
assert_eq!( assert_eq!(
self.ssh_command(&format!("ls {}", pmem_path)) self.ssh_command(&format!("ls {pmem_path}")).unwrap().trim(),
.unwrap()
.trim(),
pmem_path pmem_path
); );
assert_eq!( assert_eq!(
self.ssh_command(&format!("sudo mount {} /mnt", pmem_path)) self.ssh_command(&format!("sudo mount {pmem_path} /mnt"))
.unwrap(), .unwrap(),
"" ""
); );
@ -1138,7 +1125,7 @@ impl Guest {
assert_eq!(self.ssh_command("ls /mnt").unwrap(), ""); assert_eq!(self.ssh_command("ls /mnt").unwrap(), "");
assert_eq!( assert_eq!(
self.ssh_command(&format!("sudo mount {} /mnt", pmem_path)) self.ssh_command(&format!("sudo mount {pmem_path} /mnt"))
.unwrap(), .unwrap(),
"" ""
); );
@ -1261,8 +1248,7 @@ impl<'a> GuestCommand<'a> {
Err(std::io::Error::new( Err(std::io::Error::new(
std::io::ErrorKind::Other, std::io::ErrorKind::Other,
format!( format!(
"resizing pipe w/ 'fnctl' failed: stdout pipesize {}, stderr pipesize {}", "resizing pipe w/ 'fnctl' failed: stdout pipesize {pipesize}, stderr pipesize {pipesize1}"
pipesize, pipesize1
), ),
)) ))
} }
@ -1320,8 +1306,8 @@ impl<'a> GuestCommand<'a> {
pub fn clh_command(cmd: &str) -> String { pub fn clh_command(cmd: &str) -> String {
env::var("BUILD_TARGET").map_or( env::var("BUILD_TARGET").map_or(
format!("target/x86_64-unknown-linux-gnu/release/{}", cmd), format!("target/x86_64-unknown-linux-gnu/release/{cmd}"),
|target| format!("target/{}/release/{}", target, cmd), |target| format!("target/{target}/release/{cmd}"),
) )
} }
@ -1422,8 +1408,7 @@ pub fn parse_fio_output(output: &str, fio_ops: &FioOps, num_jobs: u32) -> Result
}) })
.map_err(|_| { .map_err(|_| {
eprintln!( eprintln!(
"=============== Fio output ===============\n\n{}\n\n===========end============\n\n", "=============== Fio output ===============\n\n{output}\n\n===========end============\n\n"
output
); );
Error::FioOutputParse Error::FioOutputParse
}) })
@ -1478,8 +1463,7 @@ pub fn parse_fio_output_iops(output: &str, fio_ops: &FioOps, num_jobs: u32) -> R
}) })
.map_err(|_| { .map_err(|_| {
eprintln!( eprintln!(
"=============== Fio output ===============\n\n{}\n\n===========end============\n\n", "=============== Fio output ===============\n\n{output}\n\n===========end============\n\n"
output
); );
Error::FioOutputParse Error::FioOutputParse
}) })
@ -1532,7 +1516,7 @@ pub fn measure_virtio_net_throughput(
"-p", "-p",
&format!("{}", default_port + n), &format!("{}", default_port + n),
"-t", "-t",
&format!("{}", test_timeout), &format!("{test_timeout}"),
]); ]);
// For measuring the guest transmit throughput (as a sender), // For measuring the guest transmit throughput (as a sender),
// use reverse mode of the iperf3 client on the host // use reverse mode of the iperf3 client on the host
@ -1626,7 +1610,7 @@ pub fn measure_virtio_net_latency(guest: &Guest, test_timeout: u32) -> Result<Ve
)?; )?;
// Start the ethr server on the guest // Start the ethr server on the guest
guest.ssh_command(&format!("{} -s &> /dev/null &", ethr_remote_path))?; guest.ssh_command(&format!("{ethr_remote_path} -s &> /dev/null &"))?;
thread::sleep(Duration::new(10, 0)); thread::sleep(Duration::new(10, 0));
@ -1647,7 +1631,7 @@ pub fn measure_virtio_net_latency(guest: &Guest, test_timeout: u32) -> Result<Ve
"-o", "-o",
&log_file, // file output is JSON format &log_file, // file output is JSON format
"-d", "-d",
&format!("{}s", test_timeout), &format!("{test_timeout}s"),
]) ])
.stderr(Stdio::piped()) .stderr(Stdio::piped())
.stdout(Stdio::piped()) .stdout(Stdio::piped())

File diff suppressed because it is too large Load Diff

View File

@ -80,7 +80,7 @@ impl Tracer {
if let Some(depth) = self.thread_depths.get_mut(thread_name) { if let Some(depth) = self.thread_depths.get_mut(thread_name) {
depth.fetch_sub(1, Ordering::SeqCst); depth.fetch_sub(1, Ordering::SeqCst);
} else { } else {
panic!("Unmatched decreas for thread: {}", thread_name); panic!("Unmatched decreas for thread: {thread_name}");
} }
} }

View File

@ -105,8 +105,7 @@ impl Read for Vhdx {
std::io::Error::new( std::io::Error::new(
std::io::ErrorKind::Other, std::io::ErrorKind::Other,
format!( format!(
"Failed reading {} sectors from VHDx at index {}: {}", "Failed reading {sector_count} sectors from VHDx at index {sector_index}: {e}"
sector_count, sector_index, e
), ),
) )
}) })
@ -130,7 +129,7 @@ impl Write for Vhdx {
self.vhdx_header.update(&mut self.file).map_err(|e| { self.vhdx_header.update(&mut self.file).map_err(|e| {
std::io::Error::new( std::io::Error::new(
std::io::ErrorKind::Other, std::io::ErrorKind::Other,
format!("Failed to update VHDx header: {}", e), format!("Failed to update VHDx header: {e}"),
) )
})?; })?;
} }
@ -148,8 +147,7 @@ impl Write for Vhdx {
std::io::Error::new( std::io::Error::new(
std::io::ErrorKind::Other, std::io::ErrorKind::Other,
format!( format!(
"Failed writing {} sectors on VHDx at index {}: {}", "Failed writing {sector_count} sectors on VHDx at index {sector_index}: {e}"
sector_count, sector_index, e
), ),
) )
}) })

View File

@ -77,7 +77,7 @@ pub const SYNTAX: &str = "vhost-user-block backend parameters \
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "vhost_user_block_error: {:?}", self) write!(f, "vhost_user_block_error: {self:?}")
} }
} }
@ -502,7 +502,7 @@ pub fn start_block_backend(backend_command: &str) {
let backend_config = match VhostUserBlkBackendConfig::parse(backend_command) { let backend_config = match VhostUserBlkBackendConfig::parse(backend_command) {
Ok(config) => config, Ok(config) => config,
Err(e) => { Err(e) => {
println!("Failed parsing parameters {:?}", e); println!("Failed parsing parameters {e:?}");
process::exit(1); process::exit(1);
} }
}; };

View File

@ -62,7 +62,7 @@ num_queues=<number_of_queues>,queue_size=<size_of_each_queue>,tap=<if_name>\"";
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "vhost_user_net_error: {:?}", self) write!(f, "vhost_user_net_error: {self:?}")
} }
} }
@ -346,7 +346,7 @@ pub fn start_net_backend(backend_command: &str) {
let backend_config = match VhostUserNetBackendConfig::parse(backend_command) { let backend_config = match VhostUserNetBackendConfig::parse(backend_command) {
Ok(config) => config, Ok(config) => config,
Err(e) => { Err(e) => {
eprintln!("Failed parsing parameters {:?}", e); eprintln!("Failed parsing parameters {e:?}");
process::exit(1); process::exit(1);
} }
}; };

View File

@ -456,7 +456,7 @@ impl Block {
let disk_size = disk_image.size().map_err(|e| { let disk_size = disk_image.size().map_err(|e| {
io::Error::new( io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("Failed getting disk size: {}", e), format!("Failed getting disk size: {e}"),
) )
})?; })?;
if disk_size % SECTOR_SIZE != 0 { if disk_size % SECTOR_SIZE != 0 {

View File

@ -793,7 +793,7 @@ impl DmaRemapping for IommuMapping {
Err(io::Error::new( Err(io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("failed to translate GVA addr 0x{:x}", addr), format!("failed to translate GVA addr 0x{addr:x}"),
)) ))
} }
@ -821,7 +821,7 @@ impl DmaRemapping for IommuMapping {
Err(io::Error::new( Err(io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("failed to translate GPA addr 0x{:x}", addr), format!("failed to translate GPA addr 0x{addr:x}"),
)) ))
} }
} }

View File

@ -729,10 +729,7 @@ impl Mem {
if region_len != region_len / VIRTIO_MEM_ALIGN_SIZE * VIRTIO_MEM_ALIGN_SIZE { if region_len != region_len / VIRTIO_MEM_ALIGN_SIZE * VIRTIO_MEM_ALIGN_SIZE {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!( format!("Virtio-mem size is not aligned with {VIRTIO_MEM_ALIGN_SIZE}"),
"Virtio-mem size is not aligned with {}",
VIRTIO_MEM_ALIGN_SIZE
),
)); ));
} }
@ -763,8 +760,7 @@ impl Mem {
io::Error::new( io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!( format!(
"Failed to resize virtio-mem configuration to {}: {:?}", "Failed to resize virtio-mem configuration to {initial_size}: {e:?}"
initial_size, e
), ),
) )
})?; })?;
@ -780,7 +776,7 @@ impl Mem {
config.validate().map_err(|e| { config.validate().map_err(|e| {
io::Error::new( io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("Invalid virtio-mem configuration: {:?}", e), format!("Invalid virtio-mem configuration: {e:?}"),
) )
})?; })?;

View File

@ -548,9 +548,8 @@ impl<M: GuestAddressSpace + Sync + Send> ExternalDmaMapping for VdpaDmaMapping<M
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!( format!(
"failed to convert guest address 0x{:x} into \ "failed to convert guest address 0x{gpa:x} into \
host user virtual address", host user virtual address"
gpa
), ),
)); ));
}; };
@ -568,8 +567,7 @@ impl<M: GuestAddressSpace + Sync + Send> ExternalDmaMapping for VdpaDmaMapping<M
io::ErrorKind::Other, io::ErrorKind::Other,
format!( format!(
"failed to map memory for vDPA device, \ "failed to map memory for vDPA device, \
iova 0x{:x}, gpa 0x{:x}, size 0x{:x}: {:?}", iova 0x{iova:x}, gpa 0x{gpa:x}, size 0x{size:x}: {e:?}"
iova, gpa, size, e
), ),
) )
}) })
@ -586,8 +584,7 @@ impl<M: GuestAddressSpace + Sync + Send> ExternalDmaMapping for VdpaDmaMapping<M
io::ErrorKind::Other, io::ErrorKind::Other,
format!( format!(
"failed to unmap memory for vDPA device, \ "failed to unmap memory for vDPA device, \
iova 0x{:x}, size 0x{:x}: {:?}", iova 0x{iova:x}, size 0x{size:x}: {e:?}"
iova, size, e
), ),
) )
}) })

View File

@ -216,7 +216,7 @@ impl<S: VhostUserMasterReqHandler> VhostUserEpollHandler<S> {
.map_err(|e| { .map_err(|e| {
EpollHelperError::IoError(std::io::Error::new( EpollHelperError::IoError(std::io::Error::new(
std::io::ErrorKind::Other, std::io::ErrorKind::Other,
format!("failed connecting vhost-user backend {:?}", e), format!("failed connecting vhost-user backend {e:?}"),
)) ))
})?; })?;
@ -237,7 +237,7 @@ impl<S: VhostUserMasterReqHandler> VhostUserEpollHandler<S> {
.map_err(|e| { .map_err(|e| {
EpollHelperError::IoError(std::io::Error::new( EpollHelperError::IoError(std::io::Error::new(
std::io::ErrorKind::Other, std::io::ErrorKind::Other,
format!("failed reconnecting vhost-user backend{:?}", e), format!("failed reconnecting vhost-user backend{e:?}"),
)) ))
})?; })?;

View File

@ -853,7 +853,7 @@ mod tests {
assert_eq!(pkt.op(), uapi::VSOCK_OP_RESPONSE); assert_eq!(pkt.op(), uapi::VSOCK_OP_RESPONSE);
conn conn
} }
other => panic!("invalid ctx state: {:?}", other), other => panic!("invalid ctx state: {other:?}"),
}; };
assert_eq!(conn.state, conn_state); assert_eq!(conn.state, conn_state);
Self { Self {
@ -971,7 +971,7 @@ mod tests {
// There's no more data in the stream, so `recv_pkt` should yield `VsockError::NoData`. // There's no more data in the stream, so `recv_pkt` should yield `VsockError::NoData`.
match ctx.conn.recv_pkt(&mut ctx.pkt) { match ctx.conn.recv_pkt(&mut ctx.pkt) {
Err(VsockError::NoData) => (), Err(VsockError::NoData) => (),
other => panic!("{:?}", other), other => panic!("{other:?}"),
} }
// A recv attempt in an invalid state should yield an instant reset packet. // A recv attempt in an invalid state should yield an instant reset packet.

View File

@ -234,7 +234,7 @@ mod tests {
txbuf.push(tmp.as_slice()).unwrap(); txbuf.push(tmp.as_slice()).unwrap();
match txbuf.push(&[1, 2]) { match txbuf.push(&[1, 2]) {
Err(Error::TxBufFull) => (), Err(Error::TxBufFull) => (),
other => panic!("Unexpected result: {:?}", other), other => panic!("Unexpected result: {other:?}"),
} }
} }
@ -267,7 +267,7 @@ mod tests {
sink.set_err(io_err); sink.set_err(io_err);
match txbuf.flush_to(&mut sink) { match txbuf.flush_to(&mut sink) {
Err(Error::TxBufFlush(ref err)) if err.kind() == ErrorKind::PermissionDenied => (), Err(Error::TxBufFlush(ref err)) if err.kind() == ErrorKind::PermissionDenied => (),
other => panic!("Unexpected result: {:?}", other), other => panic!("Unexpected result: {other:?}"),
} }
} }
} }

View File

@ -598,7 +598,7 @@ mod tests {
.activate(memory.clone(), Arc::new(NoopVirtioInterrupt {}), Vec::new()); .activate(memory.clone(), Arc::new(NoopVirtioInterrupt {}), Vec::new());
match bad_activate { match bad_activate {
Err(ActivateError::BadActivate) => (), Err(ActivateError::BadActivate) => (),
other => panic!("{:?}", other), other => panic!("{other:?}"),
} }
// Test a correct activation. // Test a correct activation.

View File

@ -852,7 +852,7 @@ mod tests {
None, None,
) )
.unwrap(); .unwrap();
let uds_path = format!("test_vsock_{}.sock", name); let uds_path = format!("test_vsock_{name}.sock");
let muxer = VsockMuxer::new(PEER_CID, uds_path).unwrap(); let muxer = VsockMuxer::new(PEER_CID, uds_path).unwrap();
Self { Self {
@ -932,7 +932,7 @@ mod tests {
let (local_lsn_count, _) = self.count_epoll_listeners(); let (local_lsn_count, _) = self.count_epoll_listeners();
assert_eq!(local_lsn_count, init_local_lsn_count + 1); assert_eq!(local_lsn_count, init_local_lsn_count + 1);
let buf = format!("CONNECT {}\n", peer_port); let buf = format!("CONNECT {peer_port}\n");
stream.write_all(buf.as_bytes()).unwrap(); stream.write_all(buf.as_bytes()).unwrap();
// The muxer would now get notified that data is available for reading from the locally // The muxer would now get notified that data is available for reading from the locally
// initiated connection. // initiated connection.
@ -966,7 +966,7 @@ mod tests {
let mut buf = vec![0u8; 32]; let mut buf = vec![0u8; 32];
let len = stream.read(&mut buf[..]).unwrap(); let len = stream.read(&mut buf[..]).unwrap();
assert_eq!(&buf[..len], format!("OK {}\n", local_port).as_bytes()); assert_eq!(&buf[..len], format!("OK {local_port}\n").as_bytes());
(stream, local_port) (stream, local_port)
} }

View File

@ -40,7 +40,7 @@ pub type Result<T> = result::Result<T, Error>;
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "bus_error: {:?}", self) write!(f, "bus_error: {self:?}")
} }
} }
@ -275,7 +275,7 @@ mod tests {
let result = bus.insert(dummy.clone(), 0x0f, 0x10); let result = bus.insert(dummy.clone(), 0x0f, 0x10);
assert!(result.is_err()); assert!(result.is_err());
assert_eq!(format!("{:?}", result), "Err(Overlap)"); assert_eq!(format!("{result:?}"), "Err(Overlap)");
assert!(bus.insert(dummy.clone(), 0x10, 0x10).is_err()); assert!(bus.insert(dummy.clone(), 0x10, 0x10).is_err());
assert!(bus.insert(dummy.clone(), 0x10, 0x15).is_err()); assert!(bus.insert(dummy.clone(), 0x10, 0x15).is_err());

View File

@ -37,9 +37,8 @@ impl<M: GuestAddressSpace + Sync + Send> ExternalDmaMapping for VfioDmaMapping<M
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!( format!(
"failed to convert guest address 0x{:x} into \ "failed to convert guest address 0x{gpa:x} into \
host user virtual address", host user virtual address"
gpa
), ),
)); ));
}; };
@ -51,8 +50,7 @@ impl<M: GuestAddressSpace + Sync + Send> ExternalDmaMapping for VfioDmaMapping<M
io::ErrorKind::Other, io::ErrorKind::Other,
format!( format!(
"failed to map memory for VFIO container, \ "failed to map memory for VFIO container, \
iova 0x{:x}, gpa 0x{:x}, size 0x{:x}: {:?}", iova 0x{iova:x}, gpa 0x{gpa:x}, size 0x{size:x}: {e:?}"
iova, gpa, size, e
), ),
) )
}) })
@ -64,8 +62,7 @@ impl<M: GuestAddressSpace + Sync + Send> ExternalDmaMapping for VfioDmaMapping<M
io::ErrorKind::Other, io::ErrorKind::Other,
format!( format!(
"failed to unmap memory for VFIO container, \ "failed to unmap memory for VFIO container, \
iova 0x{:x}, size 0x{:x}: {:?}", iova 0x{iova:x}, size 0x{size:x}: {e:?}"
iova, size, e
), ),
) )
}) })

View File

@ -87,7 +87,7 @@ impl fmt::Display for VirtioDeviceType {
VirtioDeviceType::Watchdog => "watchdog", VirtioDeviceType::Watchdog => "watchdog",
VirtioDeviceType::Unknown => "UNKNOWN", VirtioDeviceType::Unknown => "UNKNOWN",
}; };
write!(f, "{}", output) write!(f, "{output}")
} }
} }

View File

@ -52,7 +52,7 @@ const HTTP_ROOT: &str = "/api/v1";
pub fn error_response(error: HttpError, status: StatusCode) -> Response { pub fn error_response(error: HttpError, status: StatusCode) -> Response {
let mut response = Response::new(Version::Http11, status); let mut response = Response::new(Version::Http11, status);
response.set_body(Body::new(format!("{:?}", error))); response.set_body(Body::new(format!("{error:?}")));
response response
} }

View File

@ -209,7 +209,7 @@ impl fmt::Display for ValidationError {
write!(f, "Huge page size specified but huge pages not enabled") write!(f, "Huge page size specified but huge pages not enabled")
} }
InvalidHugePageSize(s) => { InvalidHugePageSize(s) => {
write!(f, "Huge page size is not power of 2: {}", s) write!(f, "Huge page size is not power of 2: {s}")
} }
#[cfg(feature = "tdx")] #[cfg(feature = "tdx")]
TdxNoCpuHotplug => { TdxNoCpuHotplug => {
@ -231,56 +231,50 @@ impl fmt::Display for ValidationError {
MemoryZoneReused(s, u1, u2) => { MemoryZoneReused(s, u1, u2) => {
write!( write!(
f, f,
"Memory zone: {} belongs to multiple NUMA nodes {} and {}", "Memory zone: {s} belongs to multiple NUMA nodes {u1} and {u2}"
s, u1, u2
) )
} }
InvalidNumPciSegments(n) => { InvalidNumPciSegments(n) => {
write!( write!(
f, f,
"Number of PCI segments ({}) not in range of 1 to {}", "Number of PCI segments ({n}) not in range of 1 to {MAX_NUM_PCI_SEGMENTS}"
n, MAX_NUM_PCI_SEGMENTS
) )
} }
InvalidPciSegment(pci_segment) => { InvalidPciSegment(pci_segment) => {
write!(f, "Invalid PCI segment id: {}", pci_segment) write!(f, "Invalid PCI segment id: {pci_segment}")
} }
BalloonLargerThanRam(balloon_size, ram_size) => { BalloonLargerThanRam(balloon_size, ram_size) => {
write!( write!(
f, f,
"Ballon size ({}) greater than RAM ({})", "Ballon size ({balloon_size}) greater than RAM ({ram_size})"
balloon_size, ram_size
) )
} }
OnIommuSegment(pci_segment) => { OnIommuSegment(pci_segment) => {
write!( write!(
f, f,
"Device is on an IOMMU PCI segment ({}) but not placed behind IOMMU", "Device is on an IOMMU PCI segment ({pci_segment}) but not placed behind IOMMU"
pci_segment
) )
} }
IommuNotSupportedOnSegment(pci_segment) => { IommuNotSupportedOnSegment(pci_segment) => {
write!( write!(
f, f,
"Device is on an IOMMU PCI segment ({}) but does not support being placed behind IOMMU", "Device is on an IOMMU PCI segment ({pci_segment}) but does not support being placed behind IOMMU"
pci_segment
) )
} }
IdentifierNotUnique(s) => { IdentifierNotUnique(s) => {
write!(f, "Identifier {} is not unique", s) write!(f, "Identifier {s} is not unique")
} }
InvalidIdentifier(s) => { InvalidIdentifier(s) => {
write!(f, "Identifier {} is invalid", s) write!(f, "Identifier {s} is invalid")
} }
IommuNotSupported => { IommuNotSupported => {
write!(f, "Device does not support being placed behind IOMMU") write!(f, "Device does not support being placed behind IOMMU")
} }
DuplicateDevicePath(p) => write!(f, "Duplicated device path: {}", p), DuplicateDevicePath(p) => write!(f, "Duplicated device path: {p}"),
&InvalidMtu(mtu) => { &InvalidMtu(mtu) => {
write!( write!(
f, f,
"Provided MTU {} is lower than 1280 (expected by VIRTIO specification)", "Provided MTU {mtu} is lower than 1280 (expected by VIRTIO specification)"
mtu
) )
} }
} }
@ -291,51 +285,51 @@ impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::Error::*; use self::Error::*;
match self { match self {
ParseConsole(o) => write!(f, "Error parsing --console: {}", o), ParseConsole(o) => write!(f, "Error parsing --console: {o}"),
ParseConsoleInvalidModeGiven => { ParseConsoleInvalidModeGiven => {
write!(f, "Error parsing --console: invalid console mode given") write!(f, "Error parsing --console: invalid console mode given")
} }
ParseCpus(o) => write!(f, "Error parsing --cpus: {}", o), ParseCpus(o) => write!(f, "Error parsing --cpus: {o}"),
InvalidCpuFeatures(o) => write!(f, "Invalid feature in --cpus features list: {}", o), InvalidCpuFeatures(o) => write!(f, "Invalid feature in --cpus features list: {o}"),
ParseDevice(o) => write!(f, "Error parsing --device: {}", o), ParseDevice(o) => write!(f, "Error parsing --device: {o}"),
ParseDevicePathMissing => write!(f, "Error parsing --device: path missing"), ParseDevicePathMissing => write!(f, "Error parsing --device: path missing"),
ParseFileSystem(o) => write!(f, "Error parsing --fs: {}", o), ParseFileSystem(o) => write!(f, "Error parsing --fs: {o}"),
ParseFsSockMissing => write!(f, "Error parsing --fs: socket missing"), ParseFsSockMissing => write!(f, "Error parsing --fs: socket missing"),
ParseFsTagMissing => write!(f, "Error parsing --fs: tag missing"), ParseFsTagMissing => write!(f, "Error parsing --fs: tag missing"),
ParsePersistentMemory(o) => write!(f, "Error parsing --pmem: {}", o), ParsePersistentMemory(o) => write!(f, "Error parsing --pmem: {o}"),
ParsePmemFileMissing => write!(f, "Error parsing --pmem: file missing"), ParsePmemFileMissing => write!(f, "Error parsing --pmem: file missing"),
ParseVsock(o) => write!(f, "Error parsing --vsock: {}", o), ParseVsock(o) => write!(f, "Error parsing --vsock: {o}"),
ParseVsockCidMissing => write!(f, "Error parsing --vsock: cid missing"), ParseVsockCidMissing => write!(f, "Error parsing --vsock: cid missing"),
ParseVsockSockMissing => write!(f, "Error parsing --vsock: socket missing"), ParseVsockSockMissing => write!(f, "Error parsing --vsock: socket missing"),
ParseMemory(o) => write!(f, "Error parsing --memory: {}", o), ParseMemory(o) => write!(f, "Error parsing --memory: {o}"),
ParseMemoryZone(o) => write!(f, "Error parsing --memory-zone: {}", o), ParseMemoryZone(o) => write!(f, "Error parsing --memory-zone: {o}"),
ParseMemoryZoneIdMissing => write!(f, "Error parsing --memory-zone: id missing"), ParseMemoryZoneIdMissing => write!(f, "Error parsing --memory-zone: id missing"),
ParseNetwork(o) => write!(f, "Error parsing --net: {}", o), ParseNetwork(o) => write!(f, "Error parsing --net: {o}"),
ParseDisk(o) => write!(f, "Error parsing --disk: {}", o), ParseDisk(o) => write!(f, "Error parsing --disk: {o}"),
ParseRng(o) => write!(f, "Error parsing --rng: {}", o), ParseRng(o) => write!(f, "Error parsing --rng: {o}"),
ParseBalloon(o) => write!(f, "Error parsing --balloon: {}", o), ParseBalloon(o) => write!(f, "Error parsing --balloon: {o}"),
ParseRestore(o) => write!(f, "Error parsing --restore: {}", o), ParseRestore(o) => write!(f, "Error parsing --restore: {o}"),
#[cfg(target_arch = "x86_64")] #[cfg(target_arch = "x86_64")]
ParseSgxEpc(o) => write!(f, "Error parsing --sgx-epc: {}", o), ParseSgxEpc(o) => write!(f, "Error parsing --sgx-epc: {o}"),
#[cfg(target_arch = "x86_64")] #[cfg(target_arch = "x86_64")]
ParseSgxEpcIdMissing => write!(f, "Error parsing --sgx-epc: id missing"), ParseSgxEpcIdMissing => write!(f, "Error parsing --sgx-epc: id missing"),
ParseNuma(o) => write!(f, "Error parsing --numa: {}", o), ParseNuma(o) => write!(f, "Error parsing --numa: {o}"),
ParseRestoreSourceUrlMissing => { ParseRestoreSourceUrlMissing => {
write!(f, "Error parsing --restore: source_url missing") write!(f, "Error parsing --restore: source_url missing")
} }
ParseUserDeviceSocketMissing => { ParseUserDeviceSocketMissing => {
write!(f, "Error parsing --user-device: socket missing") write!(f, "Error parsing --user-device: socket missing")
} }
ParseUserDevice(o) => write!(f, "Error parsing --user-device: {}", o), ParseUserDevice(o) => write!(f, "Error parsing --user-device: {o}"),
Validation(v) => write!(f, "Error validating configuration: {}", v), Validation(v) => write!(f, "Error validating configuration: {v}"),
#[cfg(feature = "tdx")] #[cfg(feature = "tdx")]
ParseTdx(o) => write!(f, "Error parsing --tdx: {}", o), ParseTdx(o) => write!(f, "Error parsing --tdx: {o}"),
#[cfg(feature = "tdx")] #[cfg(feature = "tdx")]
FirmwarePathMissing => write!(f, "TDX firmware missing"), FirmwarePathMissing => write!(f, "TDX firmware missing"),
ParsePlatform(o) => write!(f, "Error parsing --platform: {}", o), ParsePlatform(o) => write!(f, "Error parsing --platform: {o}"),
ParseVdpa(o) => write!(f, "Error parsing --vdpa: {}", o), ParseVdpa(o) => write!(f, "Error parsing --vdpa: {o}"),
ParseVdpaPathMissing => write!(f, "Error parsing --vdpa: path missing"), ParseVdpaPathMissing => write!(f, "Error parsing --vdpa: path missing"),
ParseTpm(o) => write!(f, "Error parsing --tpm: {}", o), ParseTpm(o) => write!(f, "Error parsing --tpm: {o}"),
ParseTpmPathMissing => write!(f, "Error parsing --tpm: path missing"), ParseTpmPathMissing => write!(f, "Error parsing --tpm: path missing"),
} }
} }

View File

@ -848,7 +848,7 @@ impl CpuManager {
let handle = Some( let handle = Some(
thread::Builder::new() thread::Builder::new()
.name(format!("vcpu{}", vcpu_id)) .name(format!("vcpu{vcpu_id}"))
.spawn(move || { .spawn(move || {
// Schedule the thread to run on the expected CPU set // Schedule the thread to run on the expected CPU set
if let Some(cpuset) = cpuset.as_ref() { if let Some(cpuset) = cpuset.as_ref() {
@ -1589,8 +1589,7 @@ impl CpuManager {
6 => 52, 6 => 52,
_ => { _ => {
return Err(Error::TranslateVirtualAddress(anyhow!(format!( return Err(Error::TranslateVirtualAddress(anyhow!(format!(
"PA range not supported {}", "PA range not supported {pa_range}"
pa_range
)))) ))))
} }
}; };

View File

@ -517,7 +517,7 @@ pub fn create_pty() -> io::Result<(File, File, PathBuf)> {
return vmm_sys_util::errno::errno_result().map_err(|e| e.into()); return vmm_sys_util::errno::errno_result().map_err(|e| e.into());
} }
let proc_path = PathBuf::from(format!("/proc/self/fd/{}", sub_fd)); let proc_path = PathBuf::from(format!("/proc/self/fd/{sub_fd}"));
let path = read_link(proc_path)?; let path = read_link(proc_path)?;
// SAFETY: sub_fd is checked to be valid before being wrapped in File // SAFETY: sub_fd is checked to be valid before being wrapped in File
@ -665,15 +665,14 @@ impl DeviceRelocation for AddressManager {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!( format!(
"Couldn't find a resource with base 0x{:x} for device {}", "Couldn't find a resource with base 0x{old_base:x} for device {id}"
old_base, id
), ),
)); ));
} }
} else { } else {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("Couldn't find device {} from device tree", id), format!("Couldn't find device {id} from device tree"),
)); ));
} }
} }
@ -687,7 +686,7 @@ impl DeviceRelocation for AddressManager {
self.vm.unregister_ioevent(event, &io_addr).map_err(|e| { self.vm.unregister_ioevent(event, &io_addr).map_err(|e| {
io::Error::new( io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("failed to unregister ioevent: {:?}", e), format!("failed to unregister ioevent: {e:?}"),
) )
})?; })?;
} }
@ -698,7 +697,7 @@ impl DeviceRelocation for AddressManager {
.map_err(|e| { .map_err(|e| {
io::Error::new( io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("failed to register ioevent: {:?}", e), format!("failed to register ioevent: {e:?}"),
) )
})?; })?;
} }
@ -719,7 +718,7 @@ impl DeviceRelocation for AddressManager {
self.vm.remove_user_memory_region(mem_region).map_err(|e| { self.vm.remove_user_memory_region(mem_region).map_err(|e| {
io::Error::new( io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("failed to remove user memory region: {:?}", e), format!("failed to remove user memory region: {e:?}"),
) )
})?; })?;
@ -736,7 +735,7 @@ impl DeviceRelocation for AddressManager {
self.vm.create_user_memory_region(mem_region).map_err(|e| { self.vm.create_user_memory_region(mem_region).map_err(|e| {
io::Error::new( io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("failed to create user memory regions: {:?}", e), format!("failed to create user memory regions: {e:?}"),
) )
})?; })?;
@ -745,7 +744,7 @@ impl DeviceRelocation for AddressManager {
virtio_dev.set_shm_regions(shm_regions).map_err(|e| { virtio_dev.set_shm_regions(shm_regions).map_err(|e| {
io::Error::new( io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("failed to update shared memory regions: {:?}", e), format!("failed to update shared memory regions: {e:?}"),
) )
})?; })?;
} }
@ -3435,7 +3434,7 @@ impl DeviceManager {
pci_segment_id: u16, pci_segment_id: u16,
dma_handler: Option<Arc<dyn ExternalDmaMapping>>, dma_handler: Option<Arc<dyn ExternalDmaMapping>>,
) -> DeviceManagerResult<PciBdf> { ) -> DeviceManagerResult<PciBdf> {
let id = format!("{}-{}", VIRTIO_PCI_DEVICE_NAME_PREFIX, virtio_device_id); let id = format!("{VIRTIO_PCI_DEVICE_NAME_PREFIX}-{virtio_device_id}");
// Add the new virtio-pci node to the device tree. // Add the new virtio-pci node to the device tree.
let mut node = device_node!(id); let mut node = device_node!(id);
@ -4237,7 +4236,7 @@ impl Aml for DeviceManager {
let mut pci_scan_methods = Vec::new(); let mut pci_scan_methods = Vec::new();
for i in 0..self.pci_segments.len() { for i in 0..self.pci_segments.len() {
pci_scan_methods.push(aml::MethodCall::new( pci_scan_methods.push(aml::MethodCall::new(
format!("\\_SB_.PCI{:X}.PCNT", i).as_str().into(), format!("\\_SB_.PCI{i:X}.PCNT").as_str().into(),
vec![], vec![],
)); ));
} }

View File

@ -294,8 +294,8 @@ impl MultiThreadBase for GdbStub {
}); });
Ok(()) Ok(())
} }
Ok(s) => Err(format!("Unexpected response for ActiveVcpus: {:?}", s)), Ok(s) => Err(format!("Unexpected response for ActiveVcpus: {s:?}")),
Err(e) => Err(format!("Failed to request ActiveVcpus: {:?}", e)), Err(e) => Err(format!("Failed to request ActiveVcpus: {e:?}")),
} }
} }
@ -309,7 +309,7 @@ impl MultiThreadResume for GdbStub {
fn resume(&mut self) -> Result<(), Self::Error> { fn resume(&mut self) -> Result<(), Self::Error> {
match self.vm_request(GdbRequestPayload::Resume, 0) { match self.vm_request(GdbRequestPayload::Resume, 0) {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(e) => Err(format!("Failed to resume the target: {:?}", e)), Err(e) => Err(format!("Failed to resume the target: {e:?}")),
} }
} }
@ -320,7 +320,7 @@ impl MultiThreadResume for GdbStub {
self.single_step = false; self.single_step = false;
} }
Err(e) => { Err(e) => {
return Err(format!("Failed to request SetSingleStep: {:?}", e)); return Err(format!("Failed to request SetSingleStep: {e:?}"));
} }
} }
} }
@ -337,7 +337,7 @@ impl MultiThreadResume for GdbStub {
} }
match self.vm_request(GdbRequestPayload::Resume, tid_to_cpuid(tid)) { match self.vm_request(GdbRequestPayload::Resume, tid_to_cpuid(tid)) {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(e) => Err(format!("Failed to resume the target: {:?}", e)), Err(e) => Err(format!("Failed to resume the target: {e:?}")),
} }
} }
@ -363,13 +363,13 @@ impl MultiThreadSingleStep for GdbStub {
self.single_step = true; self.single_step = true;
} }
Err(e) => { Err(e) => {
return Err(format!("Failed to request SetSingleStep: {:?}", e)); return Err(format!("Failed to request SetSingleStep: {e:?}"));
} }
} }
} }
match self.vm_request(GdbRequestPayload::Resume, tid_to_cpuid(tid)) { match self.vm_request(GdbRequestPayload::Resume, tid_to_cpuid(tid)) {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(e) => Err(format!("Failed to resume the target: {:?}", e)), Err(e) => Err(format!("Failed to resume the target: {e:?}")),
} }
} }
} }

View File

@ -44,7 +44,7 @@ impl InterruptRoute {
vm.register_irqfd(&self.irq_fd, self.gsi).map_err(|e| { vm.register_irqfd(&self.irq_fd, self.gsi).map_err(|e| {
io::Error::new( io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("Failed registering irq_fd: {}", e), format!("Failed registering irq_fd: {e}"),
) )
})?; })?;
@ -60,7 +60,7 @@ impl InterruptRoute {
vm.unregister_irqfd(&self.irq_fd, self.gsi).map_err(|e| { vm.unregister_irqfd(&self.irq_fd, self.gsi).map_err(|e| {
io::Error::new( io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("Failed unregistering irq_fd: {}", e), format!("Failed unregistering irq_fd: {e}"),
) )
})?; })?;
@ -109,7 +109,7 @@ impl MsiInterruptGroup {
self.vm.set_gsi_routing(&entry_vec).map_err(|e| { self.vm.set_gsi_routing(&entry_vec).map_err(|e| {
io::Error::new( io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("Failed setting GSI routing: {}", e), format!("Failed setting GSI routing: {e}"),
) )
}) })
} }
@ -153,7 +153,7 @@ impl InterruptSourceGroup for MsiInterruptGroup {
Err(io::Error::new( Err(io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("trigger: Invalid interrupt index {}", index), format!("trigger: Invalid interrupt index {index}"),
)) ))
} }
@ -188,7 +188,7 @@ impl InterruptSourceGroup for MsiInterruptGroup {
Err(io::Error::new( Err(io::Error::new(
io::ErrorKind::Other, io::ErrorKind::Other,
format!("update: Invalid interrupt index {}", index), format!("update: Invalid interrupt index {index}"),
)) ))
} }
} }

View File

@ -109,8 +109,7 @@ fn sigwinch_listener_main(seccomp_filter: BpfProgram, tx: File, pty: File) -> !
let e = io::Error::last_os_error(); let e = io::Error::last_os_error();
assert!( assert!(
matches!(e.kind(), ErrorKind::Interrupted | ErrorKind::WouldBlock), matches!(e.kind(), ErrorKind::Interrupted | ErrorKind::WouldBlock),
"poll: {}", "poll: {e}"
e
); );
} }

View File

@ -862,9 +862,7 @@ impl Vm {
.map_err(|_| Error::InitramfsLoad)? .map_err(|_| Error::InitramfsLoad)?
.try_into() .try_into()
.unwrap(); .unwrap();
initramfs initramfs.rewind().map_err(|_| Error::InitramfsLoad)?;
.seek(SeekFrom::Start(0))
.map_err(|_| Error::InitramfsLoad)?;
let address = let address =
arch::initramfs_load_addr(guest_mem, size).map_err(|_| Error::InitramfsLoad)?; arch::initramfs_load_addr(guest_mem, size).map_err(|_| Error::InitramfsLoad)?;
@ -1829,9 +1827,7 @@ impl Vm {
return Err(Error::InvalidPayloadType); return Err(Error::InvalidPayloadType);
} }
payload_file payload_file.rewind().map_err(Error::LoadPayload)?;
.seek(SeekFrom::Start(0))
.map_err(Error::LoadPayload)?;
mem.read_from( mem.read_from(
GuestAddress(section.address), GuestAddress(section.address),
payload_file, payload_file,
@ -3174,7 +3170,7 @@ pub fn test_vm() {
println!("HLT"); println!("HLT");
break; break;
} }
r => panic!("unexpected exit reason: {:?}", r), r => panic!("unexpected exit reason: {r:?}"),
} }
} }
} }