clippy: Address the issue 'needless-borrow'

Issue from beta verion of clippy:

Error:    --> vm-virtio/src/queue.rs:700:59
    |
700 |             if let Some(used_event) = self.get_used_event(&mem) {
    |                                                           ^^^^ help: change this to: `mem`
    |
    = note: `-D clippy::needless-borrow` implied by `-D warnings`
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow

Signed-off-by: Bo Chen <chen.bo@intel.com>
This commit is contained in:
Bo Chen 2021-06-23 13:42:17 -07:00 committed by Sebastien Boeuf
parent 585269ecb9
commit 5825ab2dd4
30 changed files with 74 additions and 74 deletions

View File

@ -36,7 +36,7 @@ impl Rsdp {
};
rsdp.checksum = super::generate_checksum(&rsdp.as_slice()[0..19]);
rsdp.extended_checksum = super::generate_checksum(&rsdp.as_slice());
rsdp.extended_checksum = super::generate_checksum(rsdp.as_slice());
rsdp
}

View File

@ -75,7 +75,7 @@ impl Sdt {
}
pub fn as_slice(&self) -> &[u8] {
&self.data.as_slice()
self.data.as_slice()
}
pub fn append<T>(&mut self, value: T) {

View File

@ -196,7 +196,7 @@ fn create_gic_node(fdt: &mut FdtWriter, gic_device: &dyn GicDevice) -> FdtWriter
// interrupt source. The type shall be a <u32> and the value shall be 3 if no PPI affinity description
// is required.
fdt.property_u32("#interrupt-cells", 3)?;
fdt.property_array_u64("reg", &gic_reg_prop)?;
fdt.property_array_u64("reg", gic_reg_prop)?;
fdt.property_u32("phandle", GIC_PHANDLE)?;
fdt.property_u32("#address-cells", 2)?;
fdt.property_u32("#size-cells", 2)?;
@ -215,7 +215,7 @@ fn create_gic_node(fdt: &mut FdtWriter, gic_device: &dyn GicDevice) -> FdtWriter
fdt.property_null("msi-controller")?;
fdt.property_u32("phandle", MSI_PHANDLE)?;
let msi_reg_prop = gic_device.msi_properties();
fdt.property_array_u64("reg", &msi_reg_prop)?;
fdt.property_array_u64("reg", msi_reg_prop)?;
fdt.end_node(msic_node)?;
}

View File

@ -152,7 +152,7 @@ pub fn set_dist_regs(gic: &Arc<dyn hypervisor::Device>, state: &[u32]) -> Result
for dreg in VGIC_DIST_REGS {
let mut base = dreg.base + REG_SIZE as u32 * dreg.bpi as u32;
let end = compute_reg_len(gic, &dreg, base)?;
let end = compute_reg_len(gic, dreg, base)?;
while base < end {
let val = state[idx];
@ -169,7 +169,7 @@ pub fn get_dist_regs(gic: &Arc<dyn hypervisor::Device>) -> Result<Vec<u32>> {
for dreg in VGIC_DIST_REGS {
let mut base = dreg.base + REG_SIZE as u32 * dreg.bpi as u32;
let end = compute_reg_len(gic, &dreg, base)?;
let end = compute_reg_len(gic, dreg, base)?;
while base < end {
let val: u32 = 0;

View File

@ -107,19 +107,19 @@ pub mod kvm {
/// Save the state of GIC.
fn state(&self, gicr_typers: &[u64]) -> Result<Gicv3State> {
// Flush redistributors pending tables to guest RAM.
save_pending_tables(&self.device()).map_err(Error::SavePendingTables)?;
save_pending_tables(self.device()).map_err(Error::SavePendingTables)?;
let gicd_ctlr =
read_ctlr(&self.device()).map_err(Error::SaveDistributorCtrlRegisters)?;
read_ctlr(self.device()).map_err(Error::SaveDistributorCtrlRegisters)?;
let dist_state =
get_dist_regs(&self.device()).map_err(Error::SaveDistributorRegisters)?;
get_dist_regs(self.device()).map_err(Error::SaveDistributorRegisters)?;
let rdist_state = get_redist_regs(&self.device(), &gicr_typers)
let rdist_state = get_redist_regs(self.device(), gicr_typers)
.map_err(Error::SaveRedistributorRegisters)?;
let icc_state =
get_icc_regs(&self.device(), &gicr_typers).map_err(Error::SaveIccRegisters)?;
get_icc_regs(self.device(), gicr_typers).map_err(Error::SaveIccRegisters)?;
Ok(Gicv3State {
dist: dist_state,
@ -131,16 +131,16 @@ pub mod kvm {
/// Restore the state of GIC.
fn set_state(&mut self, gicr_typers: &[u64], state: &Gicv3State) -> Result<()> {
write_ctlr(&self.device(), state.gicd_ctlr)
write_ctlr(self.device(), state.gicd_ctlr)
.map_err(Error::RestoreDistributorCtrlRegisters)?;
set_dist_regs(&self.device(), &state.dist)
set_dist_regs(self.device(), &state.dist)
.map_err(Error::RestoreDistributorRegisters)?;
set_redist_regs(&self.device(), gicr_typers, &state.rdist)
set_redist_regs(self.device(), gicr_typers, &state.rdist)
.map_err(Error::RestoreRedistributorRegisters)?;
set_icc_regs(&self.device(), &gicr_typers, &state.icc)
set_icc_regs(self.device(), gicr_typers, &state.icc)
.map_err(Error::RestoreIccRegisters)?;
Ok(())

View File

@ -142,14 +142,14 @@ pub fn get_redist_regs(gic: &Arc<dyn hypervisor::Device>, gicr_typer: &[u64]) ->
let mut idx: usize = 0;
access_redists_aux(
gic,
&gicr_typer,
gicr_typer,
&mut state,
VGIC_RDIST_REGS,
&mut idx,
false,
)?;
access_redists_aux(gic, &gicr_typer, &mut state, VGIC_SGI_REGS, &mut idx, false)?;
access_redists_aux(gic, gicr_typer, &mut state, VGIC_SGI_REGS, &mut idx, false)?;
Ok(state)
}

View File

@ -187,8 +187,8 @@ impl Request {
}
let mut req = Request {
request_type: request_type(&mem, avail_desc.addr)?,
sector: sector(&mem, avail_desc.addr)?,
request_type: request_type(mem, avail_desc.addr)?,
sector: sector(mem, avail_desc.addr)?,
data_descriptors: Vec::new(),
status_addr: GuestAddress(0),
writeback: true,
@ -288,7 +288,7 @@ impl Request {
if (*data_len as usize) < disk_id.len() {
return Err(ExecuteError::BadRequest(Error::InvalidOffset));
}
mem.write_slice(&disk_id.as_slice(), *data_addr)
mem.write_slice(disk_id.as_slice(), *data_addr)
.map_err(ExecuteError::Write)?;
}
RequestType::Unsupported(t) => return Err(ExecuteError::Unsupported(t)),

View File

@ -175,7 +175,7 @@ mod tests {
let mut disk_file: File = TempFile::new().unwrap().into_file();
disk_file.set_len(0x1000_0200).unwrap();
disk_file.seek(SeekFrom::Start(0x1000_0000)).unwrap();
disk_file.write_all(&footer).unwrap();
disk_file.write_all(footer).unwrap();
testfn(disk_file); // File closed when the function exits.
}

View File

@ -297,7 +297,7 @@ impl BusDevice for Gpio {
fn write(&mut self, _base: u64, offset: u64, data: &[u8]) -> Option<Arc<Barrier>> {
if data.len() <= 4 {
let value = read_le_u32(&data);
let value = read_le_u32(data);
if let Err(e) = self.handle_write(offset, value) {
warn!("Failed to write to GPIO PL061 device: {}", e);
}

View File

@ -328,7 +328,7 @@ impl BusDevice for Rtc {
fn write(&mut self, _base: u64, offset: u64, data: &[u8]) -> Option<Arc<Barrier>> {
if data.len() <= 4 {
let v = read_le_u32(&data);
let v = read_le_u32(data);
if let Err(e) = self.handle_write(offset, v) {
warn!("Failed to write to RTC PL031 device: {}", e);
}

View File

@ -341,7 +341,7 @@ impl BusDevice for Pl011 {
fn write(&mut self, _base: u64, offset: u64, data: &[u8]) -> Option<Arc<Barrier>> {
if data.len() <= 4 {
let v = read_le_u32(&data);
let v = read_le_u32(data);
if let Err(e) = self.handle_write(offset, v) {
warn!("Failed to write to PL011 device: {}", e);
}

View File

@ -678,7 +678,7 @@ mod mock_vmm {
};
if let Some(mem) = memory {
vmm.write_memory(mem.0, &mem.1).unwrap();
vmm.write_memory(mem.0, mem.1).unwrap();
}
vmm
@ -693,7 +693,7 @@ mod mock_vmm {
let ip = self.cpu_state(cpu_id).unwrap().ip();
let mut emulator = Emulator::new(self);
let new_state = emulator.emulate_insn_stream(cpu_id, &insn, num_insn)?;
let new_state = emulator.emulate_insn_stream(cpu_id, insn, num_insn)?;
if num_insn.is_none() {
assert_eq!(ip + insn.len() as u64, new_state.ip());
}

View File

@ -226,7 +226,7 @@ impl vm::Vm for KvmVm {
unsafe {
let entries_slice: &mut [kvm_irq_routing_entry] =
irq_routing[0].entries.as_mut_slice(entries.len());
entries_slice.copy_from_slice(&entries);
entries_slice.copy_from_slice(entries);
}
self.fd
@ -801,7 +801,7 @@ impl cpu::Vcpu for KvmVcpu {
///
fn set_xcrs(&self, xcrs: &ExtendedControlRegisters) -> cpu::Result<()> {
self.fd
.set_xcrs(&xcrs)
.set_xcrs(xcrs)
.map_err(|e| cpu::HypervisorCpuError::SetXcsr(e.into()))
}
///

View File

@ -235,7 +235,7 @@ impl cpu::Vcpu for MshvVcpu {
///
fn set_xcrs(&self, xcrs: &ExtendedControlRegisters) -> cpu::Result<()> {
self.fd
.set_xcrs(&xcrs)
.set_xcrs(xcrs)
.map_err(|e| cpu::HypervisorCpuError::SetXcsr(e.into()))
}
#[cfg(target_arch = "x86_64")]
@ -708,7 +708,7 @@ impl vm::Vm for MshvVm {
debug!("register_irqfd fd {} gsi {}", fd.as_raw_fd(), gsi);
self.fd
.register_irqfd(&fd, gsi)
.register_irqfd(fd, gsi)
.map_err(|e| vm::HypervisorVmError::RegisterIrqFd(e.into()))?;
Ok(())
@ -720,7 +720,7 @@ impl vm::Vm for MshvVm {
debug!("unregister_irqfd fd {} gsi {}", fd.as_raw_fd(), gsi);
self.fd
.unregister_irqfd(&fd, gsi)
.unregister_irqfd(fd, gsi)
.map_err(|e| vm::HypervisorVmError::UnregisterIrqFd(e.into()))?;
Ok(())
@ -833,7 +833,7 @@ impl vm::Vm for MshvVm {
unsafe {
let entries_slice: &mut [mshv_msi_routing_entry] =
msi_routing[0].entries.as_mut_slice(entries.len());
entries_slice.copy_from_slice(&entries);
entries_slice.copy_from_slice(entries);
}
self.fd

View File

@ -47,7 +47,7 @@ impl CtrlQueue {
pub fn process(&mut self, mem: &GuestMemoryMmap, queue: &mut Queue) -> Result<bool> {
let mut used_desc_heads = Vec::new();
for avail_desc in queue.iter(&mem) {
for avail_desc in queue.iter(mem) {
let ctrl_hdr: ControlHeader =
mem.read_obj(avail_desc.addr).map_err(Error::GuestMemory)?;
let data_desc = avail_desc
@ -111,8 +111,8 @@ impl CtrlQueue {
}
for (desc_index, len) in used_desc_heads.iter() {
queue.add_used(&mem, *desc_index, *len);
queue.update_avail_event(&mem);
queue.add_used(mem, *desc_index, *len);
queue.update_avail_event(mem);
}
Ok(!used_desc_heads.is_empty())

View File

@ -57,7 +57,7 @@ impl MacAddr {
// TODO: using something like std::mem::uninitialized could avoid the extra initialization,
// if this ever becomes a performance bottleneck.
let mut bytes = [0u8; MAC_ADDR_LEN];
bytes[..].copy_from_slice(&src);
bytes[..].copy_from_slice(src);
MacAddr { bytes }
}

View File

@ -40,7 +40,7 @@ impl TxVirtio {
queue: &mut Queue,
rate_limiter: &mut Option<RateLimiter>,
) -> Result<(), NetQueuePairError> {
while let Some(avail_desc) = queue.iter(&mem).next() {
while let Some(avail_desc) = queue.iter(mem).next() {
let head_index = avail_desc.index;
let mut next_desc = Some(avail_desc);
@ -108,8 +108,8 @@ impl TxVirtio {
self.counter_frames += Wrapping(1);
}
queue.add_used(&mem, head_index, 0);
queue.update_avail_event(&mem);
queue.add_used(mem, head_index, 0);
queue.update_avail_event(mem);
}
Ok(())
@ -146,7 +146,7 @@ impl RxVirtio {
let mut exhausted_descs = true;
let mut rate_limit_reached = false;
while let Some(avail_desc) = queue.iter(&mem).next() {
while let Some(avail_desc) = queue.iter(mem).next() {
if rate_limit_reached {
exhausted_descs = false;
queue.go_to_previous_position();
@ -208,8 +208,8 @@ impl RxVirtio {
0
};
queue.add_used(&mem, head_index, len);
queue.update_avail_event(&mem);
queue.add_used(mem, head_index, len);
queue.update_avail_event(mem);
// For the sake of simplicity (keeping the handling of RX_QUEUE_EVENT and
// RX_TAP_EVENT totally asynchronous), we always let the 'last' descriptor

View File

@ -384,7 +384,7 @@ impl Read for Tap {
impl Write for Tap {
fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
self.tap_file.write(&buf)
self.tap_file.write(buf)
}
fn flush(&mut self) -> IoResult<()> {

View File

@ -576,7 +576,7 @@ impl QcowFile {
/// Returns the L1 lookup table for this file. This is only useful for debugging.
pub fn l1_table(&self) -> &[u64] {
&self.l1_table.get_values()
self.l1_table.get_values()
}
/// Returns an L2_table of cluster addresses, only used for debugging.
@ -613,7 +613,7 @@ impl QcowFile {
/// Returns the refcount table for this file. This is only useful for debugging.
pub fn ref_table(&self) -> &[u64] {
&self.refcounts.ref_table()
self.refcounts.ref_table()
}
/// Returns the `index`th refcount block from the file.
@ -831,7 +831,7 @@ impl QcowFile {
// Rewrite the top-level refcount table.
raw_file
.write_pointer_table(header.refcount_table_offset, &ref_table, 0)
.write_pointer_table(header.refcount_table_offset, ref_table, 0)
.map_err(Error::WritingHeader)?;
// Rewrite the header again, now with lazy refcounts disabled.
@ -1379,7 +1379,7 @@ impl QcowFile {
let mut sync_required = if self.l1_table.dirty() {
self.raw_file.write_pointer_table(
self.header.l1_table_offset,
&self.l1_table.get_values(),
self.l1_table.get_values(),
0,
)?;
self.l1_table.mark_clean();
@ -1783,7 +1783,7 @@ mod tests {
F: FnMut(RawFile),
{
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.seek(SeekFrom::Start(0)).unwrap();

View File

@ -171,7 +171,7 @@ impl RefCount {
if self.ref_table.dirty() {
raw_file.write_pointer_table(
self.refcount_table_offset,
&self.ref_table.get_values(),
self.ref_table.get_values(),
0,
)?;
self.ref_table.mark_clean();
@ -210,7 +210,7 @@ impl RefCount {
/// Returns the refcount table for this file. This is only useful for debugging.
pub fn ref_table(&self) -> &[u64] {
&self.ref_table.get_values()
self.ref_table.get_values()
}
/// Returns the refcounts stored in the given block.

View File

@ -150,7 +150,7 @@ fn create_app<'a, 'b>(
topology=<threads_per_core>:<cores_per_die>:<dies_per_package>:<packages>,\
kvm_hyperv=on|off,max_phys_bits=<maximum_number_of_physical_bits>",
)
.default_value(&default_vcpus)
.default_value(default_vcpus)
.group("vm-config"),
)
.arg(
@ -164,7 +164,7 @@ fn create_app<'a, 'b>(
hotplug_size=<hotpluggable_memory_size>,\
hotplugged_size=<hotplugged_memory_size>\"",
)
.default_value(&default_memory)
.default_value(default_memory)
.group("vm-config"),
)
.arg(
@ -229,7 +229,7 @@ fn create_app<'a, 'b>(
.help(
"Random number generator parameters \"src=<entropy_source_path>,iommu=on|off\"",
)
.default_value(&default_rng)
.default_value(default_rng)
.group("vm-config"),
)
.arg(

View File

@ -1765,7 +1765,7 @@ mod tests {
fn get_counters(api_socket: &str) -> Counters {
// Get counters
let (cmd_success, cmd_output) = remote_command_w_output(&api_socket, "counters", None);
let (cmd_success, cmd_output) = remote_command_w_output(api_socket, "counters", None);
assert!(cmd_success);
let counters: HashMap<&str, HashMap<&str, u64>> =
@ -1813,7 +1813,7 @@ mod tests {
}
fn get_pty_path(api_socket: &str, pty_type: &str) -> PathBuf {
let (cmd_success, cmd_output) = remote_command_w_output(&api_socket, "info", None);
let (cmd_success, cmd_output) = remote_command_w_output(api_socket, "info", None);
assert!(cmd_success);
let info: serde_json::Value = serde_json::from_slice(&cmd_output).unwrap_or_default();
assert_eq!("Pty", info["config"][pty_type]["mode"]);
@ -1859,7 +1859,7 @@ mod tests {
}
fn balloon_size(api_socket: &str) -> u64 {
let (cmd_success, cmd_output) = remote_command_w_output(&api_socket, "info", None);
let (cmd_success, cmd_output) = remote_command_w_output(api_socket, "info", None);
assert!(cmd_success);
let info: serde_json::Value = serde_json::from_slice(&cmd_output).unwrap_or_default();
@ -5433,7 +5433,7 @@ mod tests {
"create",
"-f",
"raw",
&img.to_str().unwrap(),
img.to_str().unwrap(),
format!("{}m", sz).as_str(),
])
.output()
@ -5443,7 +5443,7 @@ mod tests {
// Associate image to a loop device
let out = Command::new("losetup")
.args(&["--show", "-f", &img.to_str().unwrap()])
.args(&["--show", "-f", img.to_str().unwrap()])
.output()
.expect("failed to create loop device")
.stdout;
@ -5467,7 +5467,7 @@ mod tests {
// Disengage the loop device
let out = Command::new("losetup")
.args(&["-d", &loop_dev])
.args(&["-d", loop_dev])
.output()
.expect("loop device not found")
.stdout;
@ -5480,7 +5480,7 @@ mod tests {
"--offset",
(512 * 2048).to_string().as_str(),
"-f",
&img.to_str().unwrap(),
img.to_str().unwrap(),
])
.output()
.expect("failed to create loop device")
@ -5504,7 +5504,7 @@ mod tests {
// Disengage the loop device
let out = Command::new("losetup")
.args(&["-d", &loop_dev])
.args(&["-d", loop_dev])
.output()
.unwrap_or_else(|_| panic!("loop device '{}' not found", loop_dev))
.stdout;

View File

@ -154,7 +154,7 @@ impl VhostUserBlkThread {
if self.event_idx {
let queue = vring.mut_queue();
if let Some(used_idx) = queue.add_used(mem, head.index, len) {
if queue.needs_notification(&mem, Wrapping(used_idx)) {
if queue.needs_notification(mem, Wrapping(used_idx)) {
debug!("signalling queue");
vring.signal_used_queue().unwrap();
} else {
@ -391,7 +391,7 @@ impl VhostUserBackend for VhostUserBlkBackend {
return Err(io::Error::from_raw_os_error(libc::EINVAL));
}
let (_, right) = config_slice.split_at_mut(offset as usize);
right.copy_from_slice(&data);
right.copy_from_slice(data);
self.update_writeback();
Ok(())
}

View File

@ -652,7 +652,7 @@ impl VirtioPciDevice {
if offset < std::mem::size_of::<VirtioPciCap>() {
let (_, right) = cap_slice.split_at_mut(offset);
right[..data_len].copy_from_slice(&data);
right[..data_len].copy_from_slice(data);
None
} else {
// Safe since we know self.cap_pci_cfg_info.cap.cap.offset is 32bits long.

View File

@ -302,7 +302,7 @@ impl Fs {
let num_queues = NUM_QUEUE_OFFSET + req_num_queues;
// Connect to the vhost-user socket.
let mut vhost_user_fs = connect_vhost_user(false, &path, num_queues as u64, false)?;
let mut vhost_user_fs = connect_vhost_user(false, path, num_queues as u64, false)?;
// Filling device and vring features VMM supports.
let avail_features = DEFAULT_VIRTIO_FEATURES;

View File

@ -234,7 +234,7 @@ impl VsockChannel for VsockMuxer {
// connection requests.
if pkt.op() == uapi::VSOCK_OP_REQUEST {
// Oh, this is a connection request!
self.handle_peer_request_pkt(&pkt);
self.handle_peer_request_pkt(pkt);
} else {
// Send back an RST, to let the drive know we weren't expecting this packet.
self.enq_rst(pkt.dst_port(), pkt.src_port());

View File

@ -697,7 +697,7 @@ impl Queue {
let mut notify = true;
if let Some(old_idx) = self.signalled_used {
if let Some(used_event) = self.get_used_event(&mem) {
if let Some(used_event) = self.get_used_event(mem) {
debug!(
"used_event = {:?} used_idx = {:?} old_idx = {:?}",
used_event, used_idx, old_idx

View File

@ -241,7 +241,7 @@ fn handle_http_request(
let path = request.uri().get_abs_path().to_string();
let mut response = match HTTP_ROUTES.routes.get(&path) {
Some(route) => match api_notifier.try_clone() {
Ok(notifier) => route.handle_request(&request, notifier, api_sender.clone()),
Ok(notifier) => route.handle_request(request, notifier, api_sender.clone()),
Err(_) => error_response(
HttpError::InternalServerError,
StatusCode::InternalServerError,

View File

@ -3159,7 +3159,7 @@ impl DeviceManager {
device_cfg: &mut DeviceConfig,
) -> DeviceManagerResult<PciDeviceInfo> {
let pci = if let Some(pci_bus) = &self.pci_bus {
Arc::clone(&pci_bus)
Arc::clone(pci_bus)
} else {
return Err(DeviceManagerError::NoPciBus);
};
@ -3235,7 +3235,7 @@ impl DeviceManager {
pub fn eject_device(&mut self, device_id: u8) -> DeviceManagerResult<()> {
// Retrieve the PCI bus.
let pci = if let Some(pci_bus) = &self.pci_bus {
Arc::clone(&pci_bus)
Arc::clone(pci_bus)
} else {
return Err(DeviceManagerError::NoPciBus);
};
@ -3382,7 +3382,7 @@ impl DeviceManager {
}
let pci = if let Some(pci_bus) = &self.pci_bus {
Arc::clone(&pci_bus)
Arc::clone(pci_bus)
} else {
return Err(DeviceManagerError::NoPciBus);
};
@ -4049,7 +4049,7 @@ impl BusDevice for DeviceManager {
B0EJ_FIELD_OFFSET => {
assert!(data.len() == B0EJ_FIELD_SIZE);
let mut data_array: [u8; 4] = [0, 0, 0, 0];
data_array.copy_from_slice(&data);
data_array.copy_from_slice(data);
let device_bitmap = u32::from_le_bytes(data_array);
for device_id in 0..32 {

View File

@ -1186,7 +1186,7 @@ impl Vm {
self.device_manager
.lock()
.unwrap()
.update_memory(&new_region)
.update_memory(new_region)
.map_err(Error::DeviceManager)?;
match memory_config.hotplug_method {
@ -2580,7 +2580,7 @@ pub fn test_vm() {
println!(
"IO out -- addr: {:#x} data [{:?}]",
addr,
str::from_utf8(&data).unwrap()
str::from_utf8(data).unwrap()
);
}
VmExit::Reset => {