Fix clippy errors and some warnings.

TEST=cargo test

Change-Id: I91afe78141c717a592eec5ec77acac2a500ba163
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/crosvm/+/2623941
Tested-by: kokoro <noreply+kokoro@google.com>
Tested-by: Keiichi Watanabe <keiichiw@chromium.org>
Reviewed-by: Andrew Walbran <qwandor@google.com>
Reviewed-by: Keiichi Watanabe <keiichiw@chromium.org>
Reviewed-by: Daniel Verkamp <dverkamp@chromium.org>
Commit-Queue: Andrew Walbran <qwandor@google.com>
This commit is contained in:
Andrew Walbran 2021-01-11 17:40:34 +00:00 committed by Commit Bot
parent 4223a41932
commit 9cfdbd9cc0
50 changed files with 320 additions and 338 deletions

View file

@ -333,16 +333,13 @@ impl SerialParameters {
pub fn add_bind_mounts(&self, jail: &mut Minijail) -> Result<(), minijail::Error> { pub fn add_bind_mounts(&self, jail: &mut Minijail) -> Result<(), minijail::Error> {
if let Some(path) = &self.path { if let Some(path) = &self.path {
match self.type_ { if let SerialType::UnixSocket = self.type_ {
SerialType::UnixSocket => { if let Some(parent) = path.as_path().parent() {
if let Some(parent) = path.as_path().parent() { if parent.exists() {
if parent.exists() { info!("Bind mounting dir {}", parent.display());
info!("Bind mounting dir {}", parent.display()); jail.mount_bind(parent, parent, true)?;
jail.mount_bind(parent, parent, true)?;
}
} }
} }
_ => {}
} }
} }
Ok(()) Ok(())

View file

@ -136,7 +136,7 @@ impl VecIoWrapper {
// iovecs are dropped because they borrow Self. Nothing can borrow the owned inner vec until self // iovecs are dropped because they borrow Self. Nothing can borrow the owned inner vec until self
// is consumed by `into`, which can't happen if there are outstanding mut borrows. // is consumed by `into`, which can't happen if there are outstanding mut borrows.
unsafe impl BackingMemory for VecIoWrapper { unsafe impl BackingMemory for VecIoWrapper {
fn get_iovec<'s>(&'s self, mem_range: MemRegion) -> Result<BorrowedIoVec<'s>> { fn get_iovec(&self, mem_range: MemRegion) -> Result<BorrowedIoVec<'_>> {
self.check_addrs(&mem_range)?; self.check_addrs(&mem_range)?;
// Safe because the mem_range range is valid in the backing memory as checked above. // Safe because the mem_range range is valid in the backing memory as checked above.
unsafe { unsafe {

View file

@ -86,7 +86,7 @@ impl BusDevice for ACPIPMResource {
return; return;
} }
let mut val_arr = u16::to_ne_bytes(0 as u16); let mut val_arr = u16::to_ne_bytes(0u16);
for i in 0..std::mem::size_of::<u16>() { for i in 0..std::mem::size_of::<u16>() {
if i < data.len() { if i < data.len() {
val_arr[i] = data[i]; val_arr[i] = data[i];

View file

@ -458,7 +458,7 @@ impl BusDevice for GoldfishBattery {
return; return;
} }
let mut val_arr = u32::to_ne_bytes(0 as u32); let mut val_arr = u32::to_ne_bytes(0u32);
val_arr.copy_from_slice(data); val_arr.copy_from_slice(data);
let val = u32::from_ne_bytes(val_arr); let val = u32::from_ne_bytes(val_arr);

View file

@ -77,7 +77,7 @@ impl BusDevice for Ioapic {
} }
fn read(&mut self, info: BusAccessInfo, data: &mut [u8]) { fn read(&mut self, info: BusAccessInfo, data: &mut [u8]) {
if data.len() > 8 || data.len() == 0 { if data.len() > 8 || data.is_empty() {
warn!("IOAPIC: Bad read size: {}", data.len()); warn!("IOAPIC: Bad read size: {}", data.len());
return; return;
} }
@ -102,7 +102,7 @@ impl BusDevice for Ioapic {
} }
fn write(&mut self, info: BusAccessInfo, data: &[u8]) { fn write(&mut self, info: BusAccessInfo, data: &[u8]) {
if data.len() > 8 || data.len() == 0 { if data.len() > 8 || data.is_empty() {
warn!("IOAPIC: Bad write size: {}", data.len()); warn!("IOAPIC: Bad write size: {}", data.len());
return; return;
} }
@ -172,7 +172,7 @@ impl Ioapic {
if self if self
.resample_events .resample_events
.get(i) .get(i)
.map_or(false, |events| events.len() > 0) .map_or(false, |events| !events.is_empty())
{ {
self.service_irq(i, false); self.service_irq(i, false);
} }
@ -328,7 +328,7 @@ impl Ioapic {
let gsi = if let Some(evt) = &self.out_events[index] { let gsi = if let Some(evt) = &self.out_events[index] {
evt.gsi evt.gsi
} else { } else {
let event = Event::new().map_err(|e| IoapicError::CreateEvent(e))?; let event = Event::new().map_err(IoapicError::CreateEvent)?;
let request = VmIrqRequest::AllocateOneMsi { let request = VmIrqRequest::AllocateOneMsi {
irqfd: MaybeOwnedDescriptor::Borrowed(event.as_raw_descriptor()), irqfd: MaybeOwnedDescriptor::Borrowed(event.as_raw_descriptor()),
}; };

View file

@ -372,7 +372,7 @@ impl IrqChip for KvmSplitIrqChip {
*current_routes = routes.to_vec(); *current_routes = routes.to_vec();
// We only call set_gsi_routing with the msi routes // We only call set_gsi_routing with the msi routes
let mut msi_routes = routes.to_vec().clone(); let mut msi_routes = routes.to_vec();
msi_routes.retain(|r| matches!(r.source, IrqSource::Msi { .. })); msi_routes.retain(|r| matches!(r.source, IrqSource::Msi { .. }));
self.vm.set_gsi_routing(&*msi_routes) self.vm.set_gsi_routing(&*msi_routes)

View file

@ -340,11 +340,7 @@ impl Pic {
fn get_irq(&self, pic_type: PicSelect) -> Option<u8> { fn get_irq(&self, pic_type: PicSelect) -> Option<u8> {
let pic = &self.pics[pic_type as usize]; let pic = &self.pics[pic_type as usize];
let mut irq_bitmap = pic.irr & !pic.imr; let mut irq_bitmap = pic.irr & !pic.imr;
let priority = if let Some(p) = Pic::get_priority(pic, irq_bitmap) { let priority = Pic::get_priority(pic, irq_bitmap)?;
p
} else {
return None;
};
// If the primary is in fully-nested mode, the IRQ coming from the secondary is not taken // If the primary is in fully-nested mode, the IRQ coming from the secondary is not taken
// into account for the priority computation below. // into account for the priority computation below.

View file

@ -144,7 +144,7 @@ impl Ac97Dev {
fn create_cras_audio_device(params: Ac97Parameters, mem: GuestMemory) -> Result<Self> { fn create_cras_audio_device(params: Ac97Parameters, mem: GuestMemory) -> Result<Self> {
let mut server = Box::new( let mut server = Box::new(
CrasClient::with_type(CrasSocketType::Unified) CrasClient::with_type(CrasSocketType::Unified)
.map_err(|e| pci_device::Error::CreateCrasClientFailed(e))?, .map_err(pci_device::Error::CreateCrasClientFailed)?,
); );
server.set_client_type(CrasClientType::CRAS_CLIENT_TYPE_CROSVM); server.set_client_type(CrasClientType::CRAS_CLIENT_TYPE_CROSVM);
if params.capture { if params.capture {

View file

@ -79,7 +79,7 @@ impl Ac97BusMasterRegs {
2 => 6, 2 => 6,
_ => { _ => {
warn!("unknown channel_count: 0x{:x}", val); warn!("unknown channel_count: 0x{:x}", val);
return 2; 2
} }
} }
} }
@ -559,7 +559,7 @@ impl Ac97BusMaster {
Ac97Function::Output => StreamDirection::Playback, Ac97Function::Output => StreamDirection::Playback,
}; };
let mut locked_regs = self.regs.lock(); let locked_regs = self.regs.lock();
let sample_rate = self.current_sample_rate(func, mixer); let sample_rate = self.current_sample_rate(func, mixer);
let buffer_samples = current_buffer_size(locked_regs.func_regs(func), &self.mem)?; let buffer_samples = current_buffer_size(locked_regs.func_regs(func), &self.mem)?;
let num_channels = locked_regs.channel_count(func); let num_channels = locked_regs.channel_count(func);
@ -569,10 +569,10 @@ impl Ac97BusMaster {
let starting_offsets = match direction { let starting_offsets = match direction {
StreamDirection::Capture => { StreamDirection::Capture => {
let mut offsets = [0, 0]; let mut offsets = [0, 0];
for i in 0..2 { for offset in &mut offsets {
let buffer = next_guest_buffer(&mut locked_regs, &self.mem, func, 0)? let buffer = next_guest_buffer(&locked_regs, &self.mem, func, 0)?
.ok_or(AudioError::NoBufferAvailable)?; .ok_or(AudioError::NoBufferAvailable)?;
offsets[i] = buffer.offset as u64; *offset = buffer.offset as u64;
pending_buffers.push_back(Some(buffer)); pending_buffers.push_back(Some(buffer));
} }
offsets offsets
@ -692,7 +692,7 @@ fn get_buffer_samples(
// This will return `None` if `civ + offset` is past LVI; if the DMA controlled // This will return `None` if `civ + offset` is past LVI; if the DMA controlled
// stopped bit is set, such as after an underrun where CIV hits LVI; or if // stopped bit is set, such as after an underrun where CIV hits LVI; or if
// `civ + offset == LVI and the CELV flag is set. // `civ + offset == LVI and the CELV flag is set.
fn next_guest_buffer<'a>( fn next_guest_buffer(
regs: &Ac97BusMasterRegs, regs: &Ac97BusMasterRegs,
mem: &GuestMemory, mem: &GuestMemory,
func: Ac97Function, func: Ac97Function,
@ -866,8 +866,7 @@ impl AudioWorker {
// Get a buffer to respond to our request. If there's no buffer // Get a buffer to respond to our request. If there's no buffer
// available, we'll wait one buffer interval and check again. // available, we'll wait one buffer interval and check again.
loop { loop {
if let Some(buffer) = if let Some(buffer) = next_guest_buffer(&locked_regs, &self.mem, func, offset)?
next_guest_buffer(&mut locked_regs, &self.mem, func, offset)?
{ {
break Some(buffer); break Some(buffer);
} }

View file

@ -167,14 +167,9 @@ impl VfioMsiCap {
} }
}; };
if index >= self.offset as u64 index >= self.offset as u64
&& index + len as u64 <= (self.offset + msi_len) as u64 && index + len as u64 <= (self.offset + msi_len) as u64
&& len as u32 <= msi_len && len as u32 <= msi_len
{
true
} else {
false
}
} }
fn write_msi_reg(&mut self, index: u64, data: &[u8]) -> Option<VfioMsiChange> { fn write_msi_reg(&mut self, index: u64, data: &[u8]) -> Option<VfioMsiChange> {
@ -343,11 +338,7 @@ impl VfioMsixCap {
let control_start = self.offset + PCI_MSIX_FLAGS; let control_start = self.offset + PCI_MSIX_FLAGS;
let control_end = control_start + 2; let control_end = control_start + 2;
if offset < control_end && offset + size > control_start { offset < control_end && offset + size > control_start
true
} else {
false
}
} }
fn read_msix_control(&self, data: &mut u32) { fn read_msix_control(&self, data: &mut u32) {
@ -372,14 +363,9 @@ impl VfioMsixCap {
fn is_msix_table(&self, bar_index: u32, offset: u64) -> bool { fn is_msix_table(&self, bar_index: u32, offset: u64) -> bool {
let table_size: u64 = (self.table_size * (MSIX_TABLE_ENTRIES_MODULO as u16)).into(); let table_size: u64 = (self.table_size * (MSIX_TABLE_ENTRIES_MODULO as u16)).into();
if bar_index != self.table_pci_bar bar_index == self.table_pci_bar
|| offset < self.table_offset && offset >= self.table_offset
|| offset >= self.table_offset + table_size && offset < self.table_offset + table_size
{
false
} else {
true
}
} }
fn read_table(&self, offset: u64, data: &mut [u8]) { fn read_table(&self, offset: u64, data: &mut [u8]) {
@ -396,14 +382,9 @@ impl VfioMsixCap {
let pba_size: u64 = (((self.table_size + BITS_PER_PBA_ENTRY as u16 - 1) let pba_size: u64 = (((self.table_size + BITS_PER_PBA_ENTRY as u16 - 1)
/ BITS_PER_PBA_ENTRY as u16) / BITS_PER_PBA_ENTRY as u16)
* MSIX_PBA_ENTRIES_MODULO as u16) as u64; * MSIX_PBA_ENTRIES_MODULO as u16) as u64;
if bar_index != self.pba_pci_bar bar_index == self.pba_pci_bar
|| offset < self.pba_offset && offset >= self.pba_offset
|| offset >= self.pba_offset + pba_size && offset < self.pba_offset + pba_size
{
false
} else {
true
}
} }
fn read_pba(&self, offset: u64, data: &mut [u8]) { fn read_pba(&self, offset: u64, data: &mut [u8]) {
@ -417,11 +398,7 @@ impl VfioMsixCap {
} }
fn is_msix_bar(&self, bar_index: u32) -> bool { fn is_msix_bar(&self, bar_index: u32) -> bool {
if bar_index == self.table_pci_bar || bar_index == self.pba_pci_bar { bar_index == self.table_pci_bar || bar_index == self.pba_pci_bar
true
} else {
false
}
} }
fn get_msix_irqfds(&self) -> Option<Vec<&Event>> { fn get_msix_irqfds(&self) -> Option<Vec<&Event>> {
@ -610,9 +587,8 @@ impl VfioPciDevice {
// Above disable_msi() or disable_msix() will enable intx again. // Above disable_msi() or disable_msix() will enable intx again.
// so disable_intx here again. // so disable_intx here again.
match self.irq_type { if let Some(VfioIrqType::Intx) = self.irq_type {
Some(VfioIrqType::Intx) => self.disable_intx(), self.disable_intx();
_ => (),
} }
} }

View file

@ -219,7 +219,7 @@ impl PortId {
} }
fn set(&self, value: u8) -> Result<()> { fn set(&self, value: u8) -> Result<()> {
if value < 1 || value > MAX_PORTS { if !(1..=MAX_PORTS).contains(&value) {
return Err(Error::BadPortId(value)); return Err(Error::BadPortId(value));
} }
*self.0.lock() = value; *self.0.lock() = value;

View file

@ -102,7 +102,7 @@ where
name: name.clone(), name: name.clone(),
state: Mutex::new(RingBufferState::Stopped), state: Mutex::new(RingBufferState::Stopped),
stop_callback: Mutex::new(Vec::new()), stop_callback: Mutex::new(Vec::new()),
ring_buffer: Mutex::new(RingBuffer::new(name.clone(), mem)), ring_buffer: Mutex::new(RingBuffer::new(name, mem)),
handler: Mutex::new(handler), handler: Mutex::new(handler),
event_loop: event_loop.clone(), event_loop: event_loop.clone(),
event: evt, event: evt,

View file

@ -106,13 +106,13 @@ impl Xhci {
let device_slots = DeviceSlots::new( let device_slots = DeviceSlots::new(
fail_handle.clone(), fail_handle.clone(),
regs.dcbaap.clone(), regs.dcbaap.clone(),
hub.clone(), hub,
interrupter.clone(), interrupter.clone(),
event_loop.clone(), event_loop.clone(),
mem.clone(), mem.clone(),
); );
let command_ring_controller = CommandRingController::new( let command_ring_controller = CommandRingController::new(
mem.clone(), mem,
event_loop.clone(), event_loop.clone(),
device_slots.clone(), device_slots.clone(),
interrupter.clone(), interrupter.clone(),

View file

@ -630,7 +630,7 @@ impl VfioDevice {
let areas = let areas =
unsafe { sparse_mmap.areas.as_slice(sparse_mmap.nr_areas as usize) }; unsafe { sparse_mmap.areas.as_slice(sparse_mmap.nr_areas as usize) };
for area in areas.iter() { for area in areas.iter() {
mmaps.push(area.clone()); mmaps.push(*area);
} }
} else if cap_header.id as u32 == VFIO_REGION_INFO_CAP_TYPE { } else if cap_header.id as u32 == VFIO_REGION_INFO_CAP_TYPE {
if offset + type_cap_sz > region_info_sz { if offset + type_cap_sz > region_info_sz {

View file

@ -115,7 +115,7 @@ impl Worker {
// The input thread runs in detached mode and will exit when channel is disconnected because // The input thread runs in detached mode and will exit when channel is disconnected because
// the console device has been dropped. // the console device has been dropped.
let res = thread::Builder::new() let res = thread::Builder::new()
.name(format!("console_input")) .name("console_input".to_string())
.spawn(move || { .spawn(move || {
loop { loop {
let mut rx_buf = vec![0u8; 1 << 12]; let mut rx_buf = vec![0u8; 1 << 12];
@ -402,7 +402,6 @@ impl VirtioDevice for Console {
match worker_result { match worker_result {
Err(e) => { Err(e) => {
error!("failed to spawn virtio_console worker: {}", e); error!("failed to spawn virtio_console worker: {}", e);
return;
} }
Ok(join_handle) => { Ok(join_handle) => {
self.worker_thread = Some(join_handle); self.worker_thread = Some(join_handle);

View file

@ -116,7 +116,7 @@ impl DescriptorChainRegions {
// Special case where the number of bytes to be copied is smaller than the `size()` of the // Special case where the number of bytes to be copied is smaller than the `size()` of the
// first regions. // first regions.
if region_count == 0 && regions.len() > 0 && count > 0 { if region_count == 0 && !regions.is_empty() && count > 0 {
debug_assert!(count < regions[0].len); debug_assert!(count < regions[0].len);
// Safe because we know that count is smaller than the length of the first slice. // Safe because we know that count is smaller than the length of the first slice.
Cow::Owned(vec![MemRegion { Cow::Owned(vec![MemRegion {
@ -291,7 +291,7 @@ impl Reader {
/// them as a collection. Returns an error if the size of the remaining data is indivisible by /// them as a collection. Returns an error if the size of the remaining data is indivisible by
/// the size of an object of type `T`. /// the size of an object of type `T`.
pub fn collect<C: FromIterator<io::Result<T>>, T: DataInit>(&mut self) -> C { pub fn collect<C: FromIterator<io::Result<T>>, T: DataInit>(&mut self) -> C {
C::from_iter(self.iter()) self.iter().collect()
} }
/// Creates an iterator for sequentially reading `DataInit` objects from the `Reader`. /// Creates an iterator for sequentially reading `DataInit` objects from the `Reader`.
@ -469,7 +469,7 @@ impl io::Read for Reader {
let mut rem = buf; let mut rem = buf;
let mut total = 0; let mut total = 0;
for b in self.regions.get_remaining(&self.mem) { for b in self.regions.get_remaining(&self.mem) {
if rem.len() == 0 { if rem.is_empty() {
break; break;
} }
@ -547,8 +547,11 @@ impl Writer {
/// this doesn't require the values to be stored in an intermediate collection first. It also /// this doesn't require the values to be stored in an intermediate collection first. It also
/// allows callers to choose which elements in a collection to write, for example by using the /// allows callers to choose which elements in a collection to write, for example by using the
/// `filter` or `take` methods of the `Iterator` trait. /// `filter` or `take` methods of the `Iterator` trait.
pub fn write_iter<T: DataInit, I: Iterator<Item = T>>(&mut self, iter: I) -> io::Result<()> { pub fn write_iter<T: DataInit, I: Iterator<Item = T>>(
iter.map(|v| self.write_obj(v)).collect() &mut self,
mut iter: I,
) -> io::Result<()> {
iter.try_for_each(|v| self.write_obj(v))
} }
/// Writes a collection of objects into the descriptor chain buffer. /// Writes a collection of objects into the descriptor chain buffer.
@ -699,7 +702,7 @@ impl io::Write for Writer {
let mut rem = buf; let mut rem = buf;
let mut total = 0; let mut total = 0;
for b in self.regions.get_remaining(&self.mem) { for b in self.regions.get_remaining(&self.mem) {
if rem.len() == 0 { if rem.is_empty() {
break; break;
} }

View file

@ -672,8 +672,8 @@ impl PassthroughFs {
inode, inode,
generation: 0, generation: 0,
attr: st, attr: st,
attr_timeout: self.cfg.attr_timeout.clone(), attr_timeout: self.cfg.attr_timeout,
entry_timeout: self.cfg.entry_timeout.clone(), entry_timeout: self.cfg.entry_timeout,
}) })
} }
@ -816,7 +816,7 @@ impl PassthroughFs {
fn do_getattr(&self, inode: &InodeData) -> io::Result<(libc::stat64, Duration)> { fn do_getattr(&self, inode: &InodeData) -> io::Result<(libc::stat64, Duration)> {
let st = stat(&inode.file)?; let st = stat(&inode.file)?;
Ok((st, self.cfg.attr_timeout.clone())) Ok((st, self.cfg.attr_timeout))
} }
fn do_unlink(&self, parent: &InodeData, name: &CStr, flags: libc::c_int) -> io::Result<()> { fn do_unlink(&self, parent: &InodeData, name: &CStr, flags: libc::c_int) -> io::Result<()> {
@ -1442,8 +1442,7 @@ impl FileSystem for PassthroughFs {
) -> io::Result<Self::DirIter> { ) -> io::Result<Self::DirIter> {
let data = self.find_handle(handle, inode)?; let data = self.find_handle(handle, inode)?;
let mut buf = Vec::with_capacity(size as usize); let buf = vec![0; size as usize];
buf.resize(size as usize, 0);
let dir = data.file.lock(); let dir = data.file.lock();
@ -1879,8 +1878,7 @@ impl FileSystem for PassthroughFs {
fn readlink(&self, _ctx: Context, inode: Inode) -> io::Result<Vec<u8>> { fn readlink(&self, _ctx: Context, inode: Inode) -> io::Result<Vec<u8>> {
let data = self.find_inode(inode)?; let data = self.find_inode(inode)?;
let mut buf = Vec::with_capacity(libc::PATH_MAX as usize); let mut buf = vec![0; libc::PATH_MAX as usize];
buf.resize(libc::PATH_MAX as usize, 0);
// Safe because this is a constant value and a valid C string. // Safe because this is a constant value and a valid C string.
let empty = unsafe { CStr::from_bytes_with_nul_unchecked(EMPTY_CSTR) }; let empty = unsafe { CStr::from_bytes_with_nul_unchecked(EMPTY_CSTR) };
@ -2350,7 +2348,6 @@ mod tests {
use std::env; use std::env;
use std::os::unix::ffi::OsStringExt; use std::os::unix::ffi::OsStringExt;
use std::path::PathBuf;
#[test] #[test]
fn create_temp_dir() { fn create_temp_dir() {
@ -2368,7 +2365,7 @@ mod tests {
let t = TempDir::new(&parent, 0o755).expect("Failed to create temporary directory"); let t = TempDir::new(&parent, 0o755).expect("Failed to create temporary directory");
let basename = t.basename().to_string_lossy(); let basename = t.basename().to_string_lossy();
let path = PathBuf::from(env::temp_dir()).join(&*basename); let path = env::temp_dir().join(&*basename);
assert!(path.exists()); assert!(path.exists());
assert!(path.is_dir()); assert!(path.is_dir());
} }
@ -2389,7 +2386,7 @@ mod tests {
let t = TempDir::new(&parent, 0o755).expect("Failed to create temporary directory"); let t = TempDir::new(&parent, 0o755).expect("Failed to create temporary directory");
let basename = t.basename().to_string_lossy(); let basename = t.basename().to_string_lossy();
let path = PathBuf::from(env::temp_dir()).join(&*basename); let path = env::temp_dir().join(&*basename);
mem::drop(t); mem::drop(t);
assert!(!path.exists()); assert!(!path.exists());
} }
@ -2411,14 +2408,16 @@ mod tests {
let (basename_cstr, _) = t.into_inner(); let (basename_cstr, _) = t.into_inner();
let basename = basename_cstr.to_string_lossy(); let basename = basename_cstr.to_string_lossy();
let path = PathBuf::from(env::temp_dir()).join(&*basename); let path = env::temp_dir().join(&*basename);
assert!(path.exists()); assert!(path.exists());
} }
#[test] #[test]
fn rewrite_xattr_names() { fn rewrite_xattr_names() {
let mut cfg = Config::default(); let cfg = Config {
cfg.rewrite_security_xattrs = true; rewrite_security_xattrs: true,
..Default::default()
};
let p = PassthroughFs::new(cfg).expect("Failed to create PassthroughFs"); let p = PassthroughFs::new(cfg).expect("Failed to create PassthroughFs");

View file

@ -544,7 +544,9 @@ impl Frontend {
} }
} }
} else { } else {
let likely_type = mem.read_obj_from_addr(desc.addr).unwrap_or(Le32::from(0)); let likely_type = mem
.read_obj_from_addr(desc.addr)
.unwrap_or_else(|_| Le32::from(0));
debug!( debug!(
"queue bad descriptor index = {} len = {} write = {} type = {}", "queue bad descriptor index = {} len = {} write = {} type = {}",
desc.index, desc.index,
@ -660,14 +662,14 @@ impl Frontend {
self.fence_descriptors.retain(|f_desc| { self.fence_descriptors.retain(|f_desc| {
for completed in &completed_fences { for completed in &completed_fences {
if fence_ctx_equal(&f_desc.desc_fence, completed) { if fence_ctx_equal(&f_desc.desc_fence, completed)
if f_desc.desc_fence.fence_id <= completed.fence_id { && f_desc.desc_fence.fence_id <= completed.fence_id
return_descs.push_back(ReturnDescriptor { {
index: f_desc.index, return_descs.push_back(ReturnDescriptor {
len: f_desc.len, index: f_desc.index,
}); len: f_desc.len,
return false; });
} return false;
} }
} }
true true

View file

@ -164,8 +164,9 @@ impl VirtioGpu {
let mut display = self.display.borrow_mut(); let mut display = self.display.borrow_mut();
let event_device_id = display.import_event_device(event_device)?; let event_device_id = display.import_event_device(event_device)?;
self.scanout_surface_id if let Some(s) = self.scanout_surface_id {
.map(|s| display.attach_event_device(s, event_device_id)); display.attach_event_device(s, event_device_id)
}
self.event_devices.insert(event_device_id, scanout); self.event_devices.insert(event_device_id, scanout);
Ok(OkNoData) Ok(OkNoData)
} }
@ -216,7 +217,7 @@ impl VirtioGpu {
let surface_id = let surface_id =
display.create_surface(None, self.display_width, self.display_height)?; display.create_surface(None, self.display_width, self.display_height)?;
self.scanout_surface_id = Some(surface_id); self.scanout_surface_id = Some(surface_id);
for (event_device_id, _) in &self.event_devices { for event_device_id in self.event_devices.keys() {
display.attach_event_device(surface_id, *event_device_id); display.attach_event_device(surface_id, *event_device_id);
} }
} }

View file

@ -28,9 +28,7 @@ struct evdev_buffer {
impl evdev_buffer { impl evdev_buffer {
fn new() -> evdev_buffer { fn new() -> evdev_buffer {
evdev_buffer { evdev_buffer { buffer: [0u8; 128] }
buffer: [0 as std::os::raw::c_uchar; 128],
}
} }
fn get(&self, bit: usize) -> bool { fn get(&self, bit: usize) -> bool {

View file

@ -441,7 +441,7 @@ where
mac_addr: MacAddress, mac_addr: MacAddress,
vq_pairs: u16, vq_pairs: u16,
) -> Result<Net<T>, NetError> { ) -> Result<Net<T>, NetError> {
let multi_queue = if vq_pairs > 1 { true } else { false }; let multi_queue = vq_pairs > 1;
let tap: T = T::new(true, multi_queue).map_err(NetError::TapOpen)?; let tap: T = T::new(true, multi_queue).map_err(NetError::TapOpen)?;
tap.set_ip_addr(ip_addr).map_err(NetError::TapSetIp)?; tap.set_ip_addr(ip_addr).map_err(NetError::TapSetIp)?;
tap.set_netmask(netmask).map_err(NetError::TapSetNetmask)?; tap.set_netmask(netmask).map_err(NetError::TapSetNetmask)?;
@ -747,6 +747,6 @@ where
} }
} }
return true; true
} }
} }

View file

@ -91,15 +91,10 @@ impl DescriptorChain {
return None; return None;
} }
let desc_head = match mem.checked_offset(desc_table, (index as u64) * 16) { let desc_head = mem.checked_offset(desc_table, (index as u64) * 16)?;
Some(a) => a,
None => return None,
};
// These reads can't fail unless Guest memory is hopelessly broken. // These reads can't fail unless Guest memory is hopelessly broken.
let addr = GuestAddress(mem.read_obj_from_addr::<u64>(desc_head).unwrap() as u64); let addr = GuestAddress(mem.read_obj_from_addr::<u64>(desc_head).unwrap() as u64);
if mem.checked_offset(desc_head, 16).is_none() { mem.checked_offset(desc_head, 16)?;
return None;
}
let len: u32 = mem.read_obj_from_addr(desc_head.unchecked_add(8)).unwrap(); let len: u32 = mem.read_obj_from_addr(desc_head.unchecked_add(8)).unwrap();
let flags: u16 = mem.read_obj_from_addr(desc_head.unchecked_add(12)).unwrap(); let flags: u16 = mem.read_obj_from_addr(desc_head.unchecked_add(12)).unwrap();
let next: u16 = mem.read_obj_from_addr(desc_head.unchecked_add(14)).unwrap(); let next: u16 = mem.read_obj_from_addr(desc_head.unchecked_add(14)).unwrap();
@ -122,7 +117,7 @@ impl DescriptorChain {
} }
} }
#[allow(clippy::if_same_then_else)] #[allow(clippy::if_same_then_else, clippy::needless_bool)]
fn is_valid(&self) -> bool { fn is_valid(&self) -> bool {
if self.len > 0 if self.len > 0
&& self && self

View file

@ -358,7 +358,7 @@ pub mod tests {
fn create_guest_memory() -> result::Result<GuestMemory, GuestMemoryError> { fn create_guest_memory() -> result::Result<GuestMemory, GuestMemoryError> {
let start_addr1 = GuestAddress(0x0); let start_addr1 = GuestAddress(0x0);
let start_addr2 = GuestAddress(0x1000); let start_addr2 = GuestAddress(0x1000);
GuestMemory::new(&vec![(start_addr1, 0x1000), (start_addr2, 0x4000)]) GuestMemory::new(&[(start_addr1, 0x1000), (start_addr2, 0x4000)])
} }
fn create_net_common() -> Net<FakeTap, FakeNet<FakeTap>> { fn create_net_common() -> Net<FakeTap, FakeNet<FakeTap>> {
@ -383,7 +383,7 @@ pub mod tests {
fn keep_rds() { fn keep_rds() {
let net = create_net_common(); let net = create_net_common();
let fds = net.keep_rds(); let fds = net.keep_rds();
assert!(fds.len() >= 1, "We should have gotten at least one fd"); assert!(!fds.is_empty(), "We should have gotten at least one fd");
} }
#[test] #[test]

View file

@ -252,7 +252,7 @@ mod tests {
let cid = 0xfca9a559fdcb9756; let cid = 0xfca9a559fdcb9756;
let vsock = Vsock::new_for_testing(cid, 0); let vsock = Vsock::new_for_testing(cid, 0);
let mut buf = [0 as u8; 8]; let mut buf = [0u8; 8];
vsock.read_config(0, &mut buf); vsock.read_config(0, &mut buf);
assert_eq!(cid, u64::from_le_bytes(buf)); assert_eq!(cid, u64::from_le_bytes(buf));

View file

@ -1052,7 +1052,7 @@ impl WlState {
fn process_wait_context(&mut self) { fn process_wait_context(&mut self) {
let events = match self.wait_ctx.wait_timeout(Duration::from_secs(0)) { let events = match self.wait_ctx.wait_timeout(Duration::from_secs(0)) {
Ok(v) => v.to_owned(), Ok(v) => v,
Err(e) => { Err(e) => {
error!("failed polling for vfd evens: {}", e); error!("failed polling for vfd evens: {}", e);
return; return;
@ -1547,16 +1547,16 @@ impl Worker {
let min_in_desc_len = (size_of::<CtrlVfdRecv>() let min_in_desc_len = (size_of::<CtrlVfdRecv>()
+ size_of::<Le32>() * VIRTWL_SEND_MAX_ALLOCS) + size_of::<Le32>() * VIRTWL_SEND_MAX_ALLOCS)
as u32; as u32;
in_desc_chains.extend(self.in_queue.iter(&self.mem).filter_map(|d| { in_desc_chains.extend(self.in_queue.iter(&self.mem).filter(|d| {
if d.len >= min_in_desc_len && d.is_write_only() { if d.len >= min_in_desc_len && d.is_write_only() {
Some(d) true
} else { } else {
// Can not use queue.add_used directly because it's being borrowed // Can not use queue.add_used directly because it's being borrowed
// for the iterator chain, so we buffer the descriptor index in // for the iterator chain, so we buffer the descriptor index in
// rejects. // rejects.
rejects[rejects_len] = d.index; rejects[rejects_len] = d.index;
rejects_len += 1; rejects_len += 1;
None false
} }
})); }));
for &reject in &rejects[..rejects_len] { for &reject in &rejects[..rejects_len] {

View file

@ -125,9 +125,9 @@ fn parse_chunk<T: Read + Seek>(
} }
CHUNK_TYPE_FILL => { CHUNK_TYPE_FILL => {
if chunk_header.total_sz == chunk_hdr_size as u32 { if chunk_header.total_sz == chunk_hdr_size as u32 {
return Err(Error::InvalidSpecification(format!( return Err(Error::InvalidSpecification(
"Fill chunk did not have any data to fill" "Fill chunk did not have any data to fill".to_string(),
))); ));
} }
let fill_size = chunk_header.total_sz.to_native() as u64 - chunk_hdr_size as u64; let fill_size = chunk_header.total_sz.to_native() as u64 - chunk_hdr_size as u64;
let mut fill_bytes = vec![0u8; fill_size as usize]; let mut fill_bytes = vec![0u8; fill_size as usize];

View file

@ -320,7 +320,7 @@ impl QcowHeader {
autoclear_features: 0, autoclear_features: 0,
refcount_order: DEFAULT_REFCOUNT_ORDER, refcount_order: DEFAULT_REFCOUNT_ORDER,
header_size: V3_BARE_HEADER_SIZE, header_size: V3_BARE_HEADER_SIZE,
backing_file_path: backing_file.map(|x| String::from(x)), backing_file_path: backing_file.map(String::from),
}) })
} }

View file

@ -184,8 +184,7 @@ impl<F: FileSystem + Sync> Server<F> {
.checked_sub(size_of::<InHeader>()) .checked_sub(size_of::<InHeader>())
.ok_or(Error::InvalidHeaderLength)?; .ok_or(Error::InvalidHeaderLength)?;
let mut buf = Vec::with_capacity(namelen); let mut buf = vec![0; namelen];
buf.resize(namelen, 0);
r.read_exact(&mut buf).map_err(Error::DecodeMessage)?; r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
@ -296,8 +295,7 @@ impl<F: FileSystem + Sync> Server<F> {
let len = (in_header.len as usize) let len = (in_header.len as usize)
.checked_sub(size_of::<InHeader>()) .checked_sub(size_of::<InHeader>())
.ok_or(Error::InvalidHeaderLength)?; .ok_or(Error::InvalidHeaderLength)?;
let mut buf = Vec::with_capacity(len); let mut buf = vec![0; len];
buf.resize(len, 0);
r.read_exact(&mut buf).map_err(Error::DecodeMessage)?; r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
@ -337,8 +335,7 @@ impl<F: FileSystem + Sync> Server<F> {
.checked_sub(size_of::<InHeader>()) .checked_sub(size_of::<InHeader>())
.and_then(|l| l.checked_sub(size_of::<MknodIn>())) .and_then(|l| l.checked_sub(size_of::<MknodIn>()))
.ok_or(Error::InvalidHeaderLength)?; .ok_or(Error::InvalidHeaderLength)?;
let mut buf = Vec::with_capacity(buflen); let mut buf = vec![0; buflen];
buf.resize(buflen, 0);
r.read_exact(&mut buf).map_err(Error::DecodeMessage)?; r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
@ -374,8 +371,7 @@ impl<F: FileSystem + Sync> Server<F> {
.checked_sub(size_of::<InHeader>()) .checked_sub(size_of::<InHeader>())
.and_then(|l| l.checked_sub(size_of::<MkdirIn>())) .and_then(|l| l.checked_sub(size_of::<MkdirIn>()))
.ok_or(Error::InvalidHeaderLength)?; .ok_or(Error::InvalidHeaderLength)?;
let mut buf = Vec::with_capacity(buflen); let mut buf = vec![0; buflen];
buf.resize(buflen, 0);
r.read_exact(&mut buf).map_err(Error::DecodeMessage)?; r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
@ -445,8 +441,7 @@ impl<F: FileSystem + Sync> Server<F> {
let namelen = (in_header.len as usize) let namelen = (in_header.len as usize)
.checked_sub(size_of::<InHeader>()) .checked_sub(size_of::<InHeader>())
.ok_or(Error::InvalidHeaderLength)?; .ok_or(Error::InvalidHeaderLength)?;
let mut name = Vec::with_capacity(namelen); let mut name = vec![0; namelen];
name.resize(namelen, 0);
r.read_exact(&mut name).map_err(Error::DecodeMessage)?; r.read_exact(&mut name).map_err(Error::DecodeMessage)?;
@ -464,8 +459,7 @@ impl<F: FileSystem + Sync> Server<F> {
let namelen = (in_header.len as usize) let namelen = (in_header.len as usize)
.checked_sub(size_of::<InHeader>()) .checked_sub(size_of::<InHeader>())
.ok_or(Error::InvalidHeaderLength)?; .ok_or(Error::InvalidHeaderLength)?;
let mut name = Vec::with_capacity(namelen); let mut name = vec![0; namelen];
name.resize(namelen, 0);
r.read_exact(&mut name).map_err(Error::DecodeMessage)?; r.read_exact(&mut name).map_err(Error::DecodeMessage)?;
@ -492,8 +486,7 @@ impl<F: FileSystem + Sync> Server<F> {
.checked_sub(size_of::<InHeader>()) .checked_sub(size_of::<InHeader>())
.and_then(|l| l.checked_sub(msg_size)) .and_then(|l| l.checked_sub(msg_size))
.ok_or(Error::InvalidHeaderLength)?; .ok_or(Error::InvalidHeaderLength)?;
let mut buf = Vec::with_capacity(buflen); let mut buf = vec![0; buflen];
buf.resize(buflen, 0);
r.read_exact(&mut buf).map_err(Error::DecodeMessage)?; r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
@ -541,8 +534,7 @@ impl<F: FileSystem + Sync> Server<F> {
.checked_sub(size_of::<InHeader>()) .checked_sub(size_of::<InHeader>())
.and_then(|l| l.checked_sub(size_of::<LinkIn>())) .and_then(|l| l.checked_sub(size_of::<LinkIn>()))
.ok_or(Error::InvalidHeaderLength)?; .ok_or(Error::InvalidHeaderLength)?;
let mut name = Vec::with_capacity(namelen); let mut name = vec![0; namelen];
name.resize(namelen, 0);
r.read_exact(&mut name).map_err(Error::DecodeMessage)?; r.read_exact(&mut name).map_err(Error::DecodeMessage)?;
@ -762,8 +754,7 @@ impl<F: FileSystem + Sync> Server<F> {
.checked_sub(size_of::<InHeader>()) .checked_sub(size_of::<InHeader>())
.and_then(|l| l.checked_sub(size_of::<SetxattrIn>())) .and_then(|l| l.checked_sub(size_of::<SetxattrIn>()))
.ok_or(Error::InvalidHeaderLength)?; .ok_or(Error::InvalidHeaderLength)?;
let mut buf = Vec::with_capacity(len); let mut buf = vec![0; len];
buf.resize(len, 0);
r.read_exact(&mut buf).map_err(Error::DecodeMessage)?; r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
@ -800,8 +791,7 @@ impl<F: FileSystem + Sync> Server<F> {
.checked_sub(size_of::<InHeader>()) .checked_sub(size_of::<InHeader>())
.and_then(|l| l.checked_sub(size_of::<GetxattrIn>())) .and_then(|l| l.checked_sub(size_of::<GetxattrIn>()))
.ok_or(Error::InvalidHeaderLength)?; .ok_or(Error::InvalidHeaderLength)?;
let mut name = Vec::with_capacity(namelen); let mut name = vec![0; namelen];
name.resize(namelen, 0);
r.read_exact(&mut name).map_err(Error::DecodeMessage)?; r.read_exact(&mut name).map_err(Error::DecodeMessage)?;
@ -876,8 +866,7 @@ impl<F: FileSystem + Sync> Server<F> {
.checked_sub(size_of::<InHeader>()) .checked_sub(size_of::<InHeader>())
.ok_or(Error::InvalidHeaderLength)?; .ok_or(Error::InvalidHeaderLength)?;
let mut buf = Vec::with_capacity(namelen); let mut buf = vec![0; namelen];
buf.resize(namelen, 0);
r.read_exact(&mut buf).map_err(Error::DecodeMessage)?; r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;
@ -1276,8 +1265,7 @@ impl<F: FileSystem + Sync> Server<F> {
.and_then(|l| l.checked_sub(size_of::<CreateIn>())) .and_then(|l| l.checked_sub(size_of::<CreateIn>()))
.ok_or(Error::InvalidHeaderLength)?; .ok_or(Error::InvalidHeaderLength)?;
let mut buf = Vec::with_capacity(buflen); let mut buf = vec![0; buflen];
buf.resize(buflen, 0);
r.read_exact(&mut buf).map_err(Error::DecodeMessage)?; r.read_exact(&mut buf).map_err(Error::DecodeMessage)?;

View file

@ -32,8 +32,8 @@ fn scan_path<P: AsRef<Path>, O: AsRef<OsStr>>(path: P, name: O) -> Option<PathBu
// Searches for the given protocol in both the system wide and bundles protocols path. // Searches for the given protocol in both the system wide and bundles protocols path.
fn find_protocol(name: &str) -> PathBuf { fn find_protocol(name: &str) -> PathBuf {
let protocols_path = let protocols_path = env::var("WAYLAND_PROTOCOLS_PATH")
env::var("WAYLAND_PROTOCOLS_PATH").unwrap_or("/usr/share/wayland-protocols".to_owned()); .unwrap_or_else(|_| "/usr/share/wayland-protocols".to_owned());
let protocol_file_name = PathBuf::from(format!("{}.xml", name)); let protocol_file_name = PathBuf::from(format!("{}.xml", name));
// Prioritize the systems wayland protocols before using the bundled ones. // Prioritize the systems wayland protocols before using the bundled ones.

View file

@ -7,10 +7,10 @@ fn main() {
let mem = disp.framebuffer(surface_id).unwrap(); let mem = disp.framebuffer(surface_id).unwrap();
for y in 0..1024 { for y in 0..1024 {
let mut row = [0u32; 1280]; let mut row = [0u32; 1280];
for x in 0..1280 { for (x, item) in row.iter_mut().enumerate() {
let b = ((x as f32 / 1280.0) * 256.0) as u32; let b = ((x as f32 / 1280.0) * 256.0) as u32;
let g = ((y as f32 / 1024.0) * 256.0) as u32; let g = ((y as f32 / 1024.0) * 256.0) as u32;
row[x] = b | (g << 8); *item = b | (g << 8);
} }
mem.as_volatile_slice() mem.as_volatile_slice()
.offset(1280 * 4 * y) .offset(1280 * 4 * y)

View file

@ -30,11 +30,11 @@ impl Buffer {
} }
fn stride(&self) -> usize { fn stride(&self) -> usize {
return (self.bytes_per_pixel as usize) * (self.width as usize); (self.bytes_per_pixel as usize) * (self.width as usize)
} }
fn bytes_per_pixel(&self) -> usize { fn bytes_per_pixel(&self) -> usize {
return self.bytes_per_pixel as usize; self.bytes_per_pixel as usize
} }
} }

View file

@ -572,7 +572,7 @@ impl Vm for KvmVm {
prot: Protection, prot: Protection,
) -> Result<()> { ) -> Result<()> {
let mut regions = self.mem_regions.lock(); let mut regions = self.mem_regions.lock();
let region = regions.get_mut(&slot).ok_or(Error::new(EINVAL))?; let region = regions.get_mut(&slot).ok_or_else(|| Error::new(EINVAL))?;
match region.add_fd_mapping(offset, size, fd, fd_offset, prot) { match region.add_fd_mapping(offset, size, fd, fd_offset, prot) {
Ok(()) => Ok(()), Ok(()) => Ok(()),
@ -583,7 +583,7 @@ impl Vm for KvmVm {
fn remove_mapping(&mut self, slot: u32, offset: usize, size: usize) -> Result<()> { fn remove_mapping(&mut self, slot: u32, offset: usize, size: usize) -> Result<()> {
let mut regions = self.mem_regions.lock(); let mut regions = self.mem_regions.lock();
let region = regions.get_mut(&slot).ok_or(Error::new(EINVAL))?; let region = regions.get_mut(&slot).ok_or_else(|| Error::new(EINVAL))?;
match region.remove_mapping(offset, size) { match region.remove_mapping(offset, size) {
Ok(()) => Ok(()), Ok(()) => Ok(()),
@ -792,7 +792,7 @@ impl Vcpu for KvmVcpu {
// kvm_sigmask.len = size_of::<sigset_t>() as u32; // kvm_sigmask.len = size_of::<sigset_t>() as u32;
kvm_sigmask[0].len = 8; kvm_sigmask[0].len = 8;
// Ensure the length is not too big. // Ensure the length is not too big.
const _ASSERT: usize = size_of::<sigset_t>() - 8 as usize; const _ASSERT: usize = size_of::<sigset_t>() - 8usize;
// Safe as we allocated exactly the needed space // Safe as we allocated exactly the needed space
unsafe { unsafe {

View file

@ -153,8 +153,10 @@ impl KvmVm {
/// ///
/// Note that this call can only succeed after a call to `Vm::create_irq_chip`. /// Note that this call can only succeed after a call to `Vm::create_irq_chip`.
pub fn get_pic_state(&self, id: PicSelect) -> Result<kvm_pic_state> { pub fn get_pic_state(&self, id: PicSelect) -> Result<kvm_pic_state> {
let mut irqchip_state = kvm_irqchip::default(); let mut irqchip_state = kvm_irqchip {
irqchip_state.chip_id = id as u32; chip_id: id as u32,
..Default::default()
};
let ret = unsafe { let ret = unsafe {
// Safe because we know our file is a VM fd, we know the kernel will only write // Safe because we know our file is a VM fd, we know the kernel will only write
// correct amount of memory to our pointer, and we verify the return result. // correct amount of memory to our pointer, and we verify the return result.
@ -175,8 +177,10 @@ impl KvmVm {
/// ///
/// Note that this call can only succeed after a call to `Vm::create_irq_chip`. /// Note that this call can only succeed after a call to `Vm::create_irq_chip`.
pub fn set_pic_state(&self, id: PicSelect, state: &kvm_pic_state) -> Result<()> { pub fn set_pic_state(&self, id: PicSelect, state: &kvm_pic_state) -> Result<()> {
let mut irqchip_state = kvm_irqchip::default(); let mut irqchip_state = kvm_irqchip {
irqchip_state.chip_id = id as u32; chip_id: id as u32,
..Default::default()
};
irqchip_state.chip.pic = *state; irqchip_state.chip.pic = *state;
// Safe because we know that our file is a VM fd, we know the kernel will only read // Safe because we know that our file is a VM fd, we know the kernel will only read
// correct amount of memory from our pointer, and we verify the return result. // correct amount of memory from our pointer, and we verify the return result.
@ -192,8 +196,10 @@ impl KvmVm {
/// ///
/// Note that this call can only succeed after a call to `Vm::create_irq_chip`. /// Note that this call can only succeed after a call to `Vm::create_irq_chip`.
pub fn get_ioapic_state(&self) -> Result<kvm_ioapic_state> { pub fn get_ioapic_state(&self) -> Result<kvm_ioapic_state> {
let mut irqchip_state = kvm_irqchip::default(); let mut irqchip_state = kvm_irqchip {
irqchip_state.chip_id = 2; chip_id: 2,
..Default::default()
};
let ret = unsafe { let ret = unsafe {
// Safe because we know our file is a VM fd, we know the kernel will only write // Safe because we know our file is a VM fd, we know the kernel will only write
// correct amount of memory to our pointer, and we verify the return result. // correct amount of memory to our pointer, and we verify the return result.
@ -214,8 +220,10 @@ impl KvmVm {
/// ///
/// Note that this call can only succeed after a call to `Vm::create_irq_chip`. /// Note that this call can only succeed after a call to `Vm::create_irq_chip`.
pub fn set_ioapic_state(&self, state: &kvm_ioapic_state) -> Result<()> { pub fn set_ioapic_state(&self, state: &kvm_ioapic_state) -> Result<()> {
let mut irqchip_state = kvm_irqchip::default(); let mut irqchip_state = kvm_irqchip {
irqchip_state.chip_id = 2; chip_id: 2,
..Default::default()
};
irqchip_state.chip.ioapic = *state; irqchip_state.chip.ioapic = *state;
// Safe because we know that our file is a VM fd, we know the kernel will only read // Safe because we know that our file is a VM fd, we know the kernel will only read
// correct amount of memory from our pointer, and we verify the return result. // correct amount of memory from our pointer, and we verify the return result.
@ -273,8 +281,10 @@ impl KvmVm {
/// Enable support for split-irqchip. /// Enable support for split-irqchip.
pub fn enable_split_irqchip(&self) -> Result<()> { pub fn enable_split_irqchip(&self) -> Result<()> {
let mut cap: kvm_enable_cap = Default::default(); let mut cap = kvm_enable_cap {
cap.cap = KVM_CAP_SPLIT_IRQCHIP; cap: KVM_CAP_SPLIT_IRQCHIP,
..Default::default()
};
cap.args[0] = NUM_IOAPIC_PINS as u64; cap.args[0] = NUM_IOAPIC_PINS as u64;
// safe becuase we allocated the struct and we know the kernel will read // safe becuase we allocated the struct and we know the kernel will read
// exactly the size of the struct // exactly the size of the struct
@ -587,8 +597,8 @@ impl VcpuX86_64 for KvmVcpu {
// bit 10: always 1. // bit 10: always 1.
dbg.arch.debugreg[7] = 0x0600; dbg.arch.debugreg[7] = 0x0600;
for i in 0..addrs.len() { for (i, addr) in addrs.iter().enumerate() {
dbg.arch.debugreg[i] = addrs[i].0; dbg.arch.debugreg[i] = addr.0;
// Set global breakpoint enable flag // Set global breakpoint enable flag
dbg.arch.debugreg[7] |= 2 << (i * 2); dbg.arch.debugreg[7] |= 2 << (i * 2);
} }

View file

@ -494,9 +494,7 @@ impl URingContext {
/// completed operations. `wait` blocks until at least one completion is ready. If called /// completed operations. `wait` blocks until at least one completion is ready. If called
/// without any new events added, this simply waits for any existing events to complete and /// without any new events added, this simply waits for any existing events to complete and
/// returns as soon an one or more is ready. /// returns as soon an one or more is ready.
pub fn wait<'a>( pub fn wait(&mut self) -> Result<impl Iterator<Item = (UserData, std::io::Result<u32>)> + '_> {
&'a mut self,
) -> Result<impl Iterator<Item = (UserData, std::io::Result<u32>)> + 'a> {
let completed = self.complete_ring.num_completed(); let completed = self.complete_ring.num_completed();
self.stats.total_complete = self.stats.total_complete.wrapping_add(completed as u64); self.stats.total_complete = self.stats.total_complete.wrapping_add(completed as u64);
self.in_flight -= completed; self.in_flight -= completed;
@ -903,7 +901,7 @@ mod tests {
.add_write(buf.as_mut_ptr(), buf.len(), f.as_raw_fd(), 0, 55) .add_write(buf.as_mut_ptr(), buf.len(), f.as_raw_fd(), 0, 55)
.unwrap(); .unwrap();
let (user_data, res) = uring.wait().unwrap().next().unwrap(); let (user_data, res) = uring.wait().unwrap().next().unwrap();
assert_eq!(user_data, 55 as UserData); assert_eq!(user_data, 55_u64);
assert_eq!(res.unwrap(), buf.len() as u32); assert_eq!(res.unwrap(), buf.len() as u32);
} }
} }
@ -934,7 +932,7 @@ mod tests {
let event = events.iter_readable().next().unwrap(); let event = events.iter_readable().next().unwrap();
assert_eq!(event.token(), 1); assert_eq!(event.token(), 1);
let (user_data, res) = uring.wait().unwrap().next().unwrap(); let (user_data, res) = uring.wait().unwrap().next().unwrap();
assert_eq!(user_data, 55 as UserData); assert_eq!(user_data, 55_u64);
assert_eq!(res.unwrap(), buf.len() as u32); assert_eq!(res.unwrap(), buf.len() as u32);
} }
} }
@ -1009,7 +1007,7 @@ mod tests {
.add_fallocate(f.as_raw_fd(), 0, set_size as u64, 0, 66) .add_fallocate(f.as_raw_fd(), 0, set_size as u64, 0, 66)
.unwrap(); .unwrap();
let (user_data, res) = uring.wait().unwrap().next().unwrap(); let (user_data, res) = uring.wait().unwrap().next().unwrap();
assert_eq!(user_data, 66 as UserData); assert_eq!(user_data, 66_u64);
match res { match res {
Err(e) => { Err(e) => {
if e.kind() == std::io::ErrorKind::InvalidInput { if e.kind() == std::io::ErrorKind::InvalidInput {
@ -1018,7 +1016,7 @@ mod tests {
} }
panic!("Unexpected fallocate error: {}", e); panic!("Unexpected fallocate error: {}", e);
} }
Ok(val) => assert_eq!(val, 0 as u32), Ok(val) => assert_eq!(val, 0_u32),
} }
// Add a few writes and then fsync // Add a few writes and then fsync
@ -1064,8 +1062,8 @@ mod tests {
) )
.unwrap(); .unwrap();
let (user_data, res) = uring.wait().unwrap().next().unwrap(); let (user_data, res) = uring.wait().unwrap().next().unwrap();
assert_eq!(user_data, 68 as UserData); assert_eq!(user_data, 68_u64);
assert_eq!(res.unwrap(), 0 as u32); assert_eq!(res.unwrap(), 0_u32);
drop(f); // Close to ensure directory entires for metadata are updated. drop(f); // Close to ensure directory entires for metadata are updated.
@ -1081,8 +1079,8 @@ mod tests {
.add_poll_fd(f.as_raw_fd(), &WatchingEvents::empty().set_read(), 454) .add_poll_fd(f.as_raw_fd(), &WatchingEvents::empty().set_read(), 454)
.unwrap(); .unwrap();
let (user_data, res) = uring.wait().unwrap().next().unwrap(); let (user_data, res) = uring.wait().unwrap().next().unwrap();
assert_eq!(user_data, 454 as UserData); assert_eq!(user_data, 454_u64);
assert_eq!(res.unwrap(), 1 as u32); assert_eq!(res.unwrap(), 1_u32);
} }
#[test] #[test]
@ -1116,14 +1114,14 @@ mod tests {
{ {
let mut results = uring.wait().unwrap(); let mut results = uring.wait().unwrap();
for _i in 0..num_entries * 2 { for _i in 0..num_entries * 2 {
assert_eq!(results.next().unwrap().1.unwrap(), 1 as u32); assert_eq!(results.next().unwrap().1.unwrap(), 1_u32);
} }
assert!(results.next().is_none()); assert!(results.next().is_none());
} }
// The second will finish submitting any more sqes and return the rest. // The second will finish submitting any more sqes and return the rest.
let mut results = uring.wait().unwrap(); let mut results = uring.wait().unwrap();
for _i in 0..num_entries + 1 { for _i in 0..num_entries + 1 {
assert_eq!(results.next().unwrap().1.unwrap(), 1 as u32); assert_eq!(results.next().unwrap().1.unwrap(), 1_u32);
} }
assert!(results.next().is_none()); assert!(results.next().is_none());
} }

View file

@ -494,8 +494,10 @@ impl Vm {
/// Note that this call can only succeed after a call to `Vm::create_irq_chip`. /// Note that this call can only succeed after a call to `Vm::create_irq_chip`.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn get_pic_state(&self, id: PicId) -> Result<kvm_pic_state> { pub fn get_pic_state(&self, id: PicId) -> Result<kvm_pic_state> {
let mut irqchip_state = kvm_irqchip::default(); let mut irqchip_state = kvm_irqchip {
irqchip_state.chip_id = id as u32; chip_id: id as u32,
..Default::default()
};
let ret = unsafe { let ret = unsafe {
// Safe because we know our file is a VM fd, we know the kernel will only write // Safe because we know our file is a VM fd, we know the kernel will only write
// correct amount of memory to our pointer, and we verify the return result. // correct amount of memory to our pointer, and we verify the return result.
@ -517,8 +519,10 @@ impl Vm {
/// Note that this call can only succeed after a call to `Vm::create_irq_chip`. /// Note that this call can only succeed after a call to `Vm::create_irq_chip`.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn set_pic_state(&self, id: PicId, state: &kvm_pic_state) -> Result<()> { pub fn set_pic_state(&self, id: PicId, state: &kvm_pic_state) -> Result<()> {
let mut irqchip_state = kvm_irqchip::default(); let mut irqchip_state = kvm_irqchip {
irqchip_state.chip_id = id as u32; chip_id: id as u32,
..Default::default()
};
irqchip_state.chip.pic = *state; irqchip_state.chip.pic = *state;
// Safe because we know that our file is a VM fd, we know the kernel will only read // Safe because we know that our file is a VM fd, we know the kernel will only read
// correct amount of memory from our pointer, and we verify the return result. // correct amount of memory from our pointer, and we verify the return result.
@ -535,8 +539,10 @@ impl Vm {
/// Note that this call can only succeed after a call to `Vm::create_irq_chip`. /// Note that this call can only succeed after a call to `Vm::create_irq_chip`.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn get_ioapic_state(&self) -> Result<kvm_ioapic_state> { pub fn get_ioapic_state(&self) -> Result<kvm_ioapic_state> {
let mut irqchip_state = kvm_irqchip::default(); let mut irqchip_state = kvm_irqchip {
irqchip_state.chip_id = 2; chip_id: 2,
..Default::default()
};
let ret = unsafe { let ret = unsafe {
// Safe because we know our file is a VM fd, we know the kernel will only write // Safe because we know our file is a VM fd, we know the kernel will only write
// correct amount of memory to our pointer, and we verify the return result. // correct amount of memory to our pointer, and we verify the return result.
@ -558,8 +564,10 @@ impl Vm {
/// Note that this call can only succeed after a call to `Vm::create_irq_chip`. /// Note that this call can only succeed after a call to `Vm::create_irq_chip`.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn set_ioapic_state(&self, state: &kvm_ioapic_state) -> Result<()> { pub fn set_ioapic_state(&self, state: &kvm_ioapic_state) -> Result<()> {
let mut irqchip_state = kvm_irqchip::default(); let mut irqchip_state = kvm_irqchip {
irqchip_state.chip_id = 2; chip_id: 2,
..Default::default()
};
irqchip_state.chip.ioapic = *state; irqchip_state.chip.ioapic = *state;
// Safe because we know that our file is a VM fd, we know the kernel will only read // Safe because we know that our file is a VM fd, we know the kernel will only read
// correct amount of memory from our pointer, and we verify the return result. // correct amount of memory from our pointer, and we verify the return result.
@ -1418,7 +1426,7 @@ impl Vcpu {
// kvm_sigmask.len = size_of::<sigset_t>() as u32; // kvm_sigmask.len = size_of::<sigset_t>() as u32;
kvm_sigmask[0].len = 8; kvm_sigmask[0].len = 8;
// Ensure the length is not too big. // Ensure the length is not too big.
const _ASSERT: usize = size_of::<sigset_t>() - 8 as usize; const _ASSERT: usize = size_of::<sigset_t>() - 8usize;
// Safe as we allocated exactly the needed space // Safe as we allocated exactly the needed space
unsafe { unsafe {

View file

@ -167,7 +167,7 @@ pub trait MsgReceiver: AsRef<UnixSeqpacket> {
} }
}; };
if msg_buffer.len() == 0 && Self::M::fixed_size() != Some(0) { if msg_buffer.is_empty() && Self::M::fixed_size() != Some(0) {
return Err(MsgError::RecvZero); return Err(MsgError::RecvZero);
} }

View file

@ -230,10 +230,10 @@ impl AddressAllocator {
let end = address.checked_add(size).ok_or(Error::OutOfBounds)?; let end = address.checked_add(size).ok_or(Error::OutOfBounds)?;
match (range.contains(&address), range.contains(&end)) { match (range.contains(&address), range.contains(&end)) {
(true, true) => Ok(address), (true, true) => Ok(address),
_ => return Err(Error::OutOfBounds), _ => Err(Error::OutOfBounds),
} }
} }
None => return Err(Error::InvalidAlloc(alloc)), None => Err(Error::InvalidAlloc(alloc)),
} }
} }
} }

View file

@ -68,7 +68,7 @@ pub fn transfer_2d<'a, S: Iterator<Item = VolatileSlice<'a>>>(
checked_range!(checked_arithmetic!(rect_x + rect_w)?; <= resource_w)?; checked_range!(checked_arithmetic!(rect_x + rect_w)?; <= resource_w)?;
checked_range!(checked_arithmetic!(rect_y + rect_h)?; <= resource_h)?; checked_range!(checked_arithmetic!(rect_y + rect_h)?; <= resource_h)?;
let bytes_per_pixel = 4 as u64; let bytes_per_pixel = 4u64;
let rect_x = rect_x as u64; let rect_x = rect_x as u64;
let rect_y = rect_y as u64; let rect_y = rect_y as u64;
@ -85,11 +85,11 @@ pub fn transfer_2d<'a, S: Iterator<Item = VolatileSlice<'a>>>(
let mut next_src; let mut next_src;
let mut next_line; let mut next_line;
let mut current_height = 0 as u64; let mut current_height = 0u64;
let mut src_opt = srcs.next(); let mut src_opt = srcs.next();
// Cumulative start offset of the current src. // Cumulative start offset of the current src.
let mut src_start_offset = 0 as u64; let mut src_start_offset = 0u64;
while let Some(src) = src_opt { while let Some(src) = src_opt {
if current_height >= rect_h { if current_height >= rect_h {
break; break;
@ -117,10 +117,7 @@ pub fn transfer_2d<'a, S: Iterator<Item = VolatileSlice<'a>>>(
let copyable_size = let copyable_size =
checked_arithmetic!(src_copyable_end_offset - src_copyable_start_offset)?; checked_arithmetic!(src_copyable_end_offset - src_copyable_start_offset)?;
let offset_within_src = match src_copyable_start_offset.checked_sub(src_start_offset) { let offset_within_src = src_copyable_start_offset.saturating_sub(src_start_offset);
Some(difference) => difference,
None => 0,
};
if src_line_end_offset > src_end_offset { if src_line_end_offset > src_end_offset {
next_src = true; next_src = true;
@ -135,7 +132,7 @@ pub fn transfer_2d<'a, S: Iterator<Item = VolatileSlice<'a>>>(
let src_subslice = src let src_subslice = src
.get_slice(offset_within_src as usize, copyable_size as usize) .get_slice(offset_within_src as usize, copyable_size as usize)
.map_err(|e| RutabagaError::MemCopy(e))?; .map_err(RutabagaError::MemCopy)?;
let dst_line_vertical_offset = checked_arithmetic!(current_height * dst_stride)?; let dst_line_vertical_offset = checked_arithmetic!(current_height * dst_stride)?;
let dst_line_horizontal_offset = let dst_line_horizontal_offset =
@ -146,7 +143,7 @@ pub fn transfer_2d<'a, S: Iterator<Item = VolatileSlice<'a>>>(
let dst_subslice = dst let dst_subslice = dst
.get_slice(dst_start_offset as usize, copyable_size as usize) .get_slice(dst_start_offset as usize, copyable_size as usize)
.map_err(|e| RutabagaError::MemCopy(e))?; .map_err(RutabagaError::MemCopy)?;
src_subslice.copy_to_volatile_slice(dst_subslice); src_subslice.copy_to_volatile_slice(dst_subslice);
} else { } else {

View file

@ -270,9 +270,8 @@ impl Rutabaga {
/// Forces context zero for the default rutabaga component. /// Forces context zero for the default rutabaga component.
pub fn force_ctx_0(&self) { pub fn force_ctx_0(&self) {
match self.components.get(&self.default_component) { if let Some(component) = self.components.get(&self.default_component) {
Some(component) => component.force_ctx_0(), component.force_ctx_0();
None => (),
} }
} }
@ -319,10 +318,9 @@ impl Rutabaga {
fence_ctx_idx: 0, fence_ctx_idx: 0,
}); });
for (_ctx_id, ctx) in &mut self.contexts { for ctx in self.contexts.values_mut() {
match ctx.context_poll() { if let Some(ref mut ctx_completed_fences) = ctx.context_poll() {
Some(ref mut ctx_completed_fences) => completed_fences.append(ctx_completed_fences), completed_fences.append(ctx_completed_fences);
None => (),
} }
} }
completed_fences completed_fences

View file

@ -2533,7 +2533,7 @@ impl BalloonPolicy {
} }
return Ok(result); return Ok(result);
} }
return Ok(0); Ok(0)
} }
} }
@ -2644,7 +2644,7 @@ fn run_control<V: VmArch + 'static, Vcpu: VcpuArch + 'static, I: IrqChipArch + '
setup_vcpu_signal_handler::<Vcpu>(use_hypervisor_signals)?; setup_vcpu_signal_handler::<Vcpu>(use_hypervisor_signals)?;
let vcpus: Vec<Option<_>> = match linux.vcpus.take() { let vcpus: Vec<Option<_>> = match linux.vcpus.take() {
Some(vec) => vec.into_iter().map(|vcpu| Some(vcpu)).collect(), Some(vec) => vec.into_iter().map(Some).collect(),
None => iter::repeat_with(|| None).take(linux.vcpu_count).collect(), None => iter::repeat_with(|| None).take(linux.vcpu_count).collect(),
}; };
for (cpu_id, vcpu) in vcpus.into_iter().enumerate() { for (cpu_id, vcpu) in vcpus.into_iter().enumerate() {

View file

@ -598,8 +598,8 @@ fn parse_battery_options(s: Option<&str>) -> argument::Result<BatteryType> {
if let Some(s) = s { if let Some(s) = s {
let opts = s let opts = s
.split(",") .split(',')
.map(|frag| frag.split("=")) .map(|frag| frag.split('='))
.map(|mut kv| (kv.next().unwrap_or(""), kv.next().unwrap_or(""))); .map(|mut kv| (kv.next().unwrap_or(""), kv.next().unwrap_or("")));
for (k, v) in opts { for (k, v) in opts {
@ -759,7 +759,7 @@ fn set_argument(cfg: &mut Config, name: &str, value: Option<&str>) -> argument::
SerialHardware::Serial => {} SerialHardware::Serial => {}
_ => { _ => {
return Err(argument::Error::InvalidValue { return Err(argument::Error::InvalidValue {
value: serial_params.hardware.to_string().to_owned(), value: serial_params.hardware.to_string(),
expected: String::from("earlycon not supported for hardware"), expected: String::from("earlycon not supported for hardware"),
}); });
} }
@ -1187,7 +1187,7 @@ fn set_argument(cfg: &mut Config, name: &str, value: Option<&str>) -> argument::
})?; })?;
let dur = Duration::from_secs(seconds); let dur = Duration::from_secs(seconds);
shared_dir.fs_cfg.entry_timeout = dur.clone(); shared_dir.fs_cfg.entry_timeout = dur;
shared_dir.fs_cfg.attr_timeout = dur; shared_dir.fs_cfg.attr_timeout = dur;
} }
"cache" => { "cache" => {

View file

@ -145,7 +145,7 @@ impl UnixSeqpacket {
/// Gets the number of bytes that can be read from this socket without blocking. /// Gets the number of bytes that can be read from this socket without blocking.
pub fn get_readable_bytes(&self) -> io::Result<usize> { pub fn get_readable_bytes(&self) -> io::Result<usize> {
let mut byte_count = 0 as libc::c_int; let mut byte_count = 0i32;
let ret = unsafe { libc::ioctl(self.fd, libc::FIONREAD, &mut byte_count) }; let ret = unsafe { libc::ioctl(self.fd, libc::FIONREAD, &mut byte_count) };
if ret < 0 { if ret < 0 {
Err(io::Error::last_os_error()) Err(io::Error::last_os_error())

View file

@ -671,10 +671,10 @@ impl GuestMemory {
// It is safe to implement BackingMemory because GuestMemory can be mutated any time already. // It is safe to implement BackingMemory because GuestMemory can be mutated any time already.
unsafe impl BackingMemory for GuestMemory { unsafe impl BackingMemory for GuestMemory {
fn get_iovec<'s>( fn get_iovec(
&'s self, &self,
mem_range: cros_async::MemRegion, mem_range: cros_async::MemRegion,
) -> uring_mem::Result<uring_mem::BorrowedIoVec<'s>> { ) -> uring_mem::Result<uring_mem::BorrowedIoVec<'_>> {
let vs = self let vs = self
.get_slice_at_addr(GuestAddress(mem_range.offset as u64), mem_range.len) .get_slice_at_addr(GuestAddress(mem_range.offset as u64), mem_range.len)
.map_err(|_| uring_mem::Error::InvalidOffset(mem_range.offset, mem_range.len))?; .map_err(|_| uring_mem::Error::InvalidOffset(mem_range.offset, mem_range.len))?;

View file

@ -82,7 +82,7 @@ fn create_dsdt_table(amls: Vec<u8>) -> SDT {
OEM_REVISION, OEM_REVISION,
); );
if amls.len() != 0 { if !amls.is_empty() {
dsdt.append_slice(amls.as_slice()); dsdt.append_slice(amls.as_slice());
} }

View file

@ -58,10 +58,11 @@ pub fn create_fdt(
mem::size_of::<setup_data>(), mem::size_of::<setup_data>(),
mem::size_of::<setup_data_hdr>() mem::size_of::<setup_data_hdr>()
); );
let mut hdr: setup_data_hdr = Default::default(); let hdr = setup_data_hdr {
hdr.next = 0; next: 0,
hdr.type_ = SETUP_DTB; type_: SETUP_DTB,
hdr.len = fdt_data_size as u32; len: fdt_data_size as u32,
};
assert!(fdt_data_size as u64 <= X86_64_FDT_MAX_SIZE); assert!(fdt_data_size as u64 <= X86_64_FDT_MAX_SIZE);

View file

@ -405,7 +405,7 @@ impl arch::LinuxArch for X8664arch {
let mut io_bus = Self::setup_io_bus( let mut io_bus = Self::setup_io_bus(
irq_chip.pit_uses_speaker_port(), irq_chip.pit_uses_speaker_port(),
exit_evt.try_clone().map_err(Error::CloneEvent)?, exit_evt.try_clone().map_err(Error::CloneEvent)?,
Some(pci_bus.clone()), Some(pci_bus),
components.memory_size, components.memory_size,
)?; )?;
@ -1014,7 +1014,7 @@ impl X8664arch {
io_bus.insert(pci_root, 0xcf8, 0x8).unwrap(); io_bus.insert(pci_root, 0xcf8, 0x8).unwrap();
} else { } else {
// ignore pci. // ignore pci.
io_bus.insert(nul_device.clone(), 0xcf8, 0x8).unwrap(); io_bus.insert(nul_device, 0xcf8, 0x8).unwrap();
} }
Ok(io_bus) Ok(io_bus)

View file

@ -166,18 +166,20 @@ pub fn setup_mptable(
for cpu_id in 0..num_cpus { for cpu_id in 0..num_cpus {
let size = mem::size_of::<mpc_cpu>(); let size = mem::size_of::<mpc_cpu>();
let mut mpc_cpu = mpc_cpu::default(); let mpc_cpu = mpc_cpu {
mpc_cpu.type_ = MP_PROCESSOR as u8; type_: MP_PROCESSOR as u8,
mpc_cpu.apicid = cpu_id; apicid: cpu_id,
mpc_cpu.apicver = APIC_VERSION; apicver: APIC_VERSION,
mpc_cpu.cpuflag = CPU_ENABLED as u8 cpuflag: CPU_ENABLED as u8
| if cpu_id == 0 { | if cpu_id == 0 {
CPU_BOOTPROCESSOR as u8 CPU_BOOTPROCESSOR as u8
} else { } else {
0 0
}; },
mpc_cpu.cpufeature = CPU_STEPPING; cpufeature: CPU_STEPPING,
mpc_cpu.featureflag = CPU_FEATURE_APIC | CPU_FEATURE_FPU; featureflag: CPU_FEATURE_APIC | CPU_FEATURE_FPU,
..Default::default()
};
mem.write_obj_at_addr(mpc_cpu, base_mp) mem.write_obj_at_addr(mpc_cpu, base_mp)
.map_err(|_| Error::WriteMpcCpu)?; .map_err(|_| Error::WriteMpcCpu)?;
base_mp = base_mp.unchecked_add(size as u64); base_mp = base_mp.unchecked_add(size as u64);
@ -185,12 +187,13 @@ pub fn setup_mptable(
} }
{ {
let size = mem::size_of::<mpc_ioapic>(); let size = mem::size_of::<mpc_ioapic>();
let mut mpc_ioapic = mpc_ioapic::default(); let mpc_ioapic = mpc_ioapic {
mpc_ioapic.type_ = MP_IOAPIC as u8; type_: MP_IOAPIC as u8,
mpc_ioapic.apicid = ioapicid; apicid: ioapicid,
mpc_ioapic.apicver = APIC_VERSION; apicver: APIC_VERSION,
mpc_ioapic.flags = MPC_APIC_USABLE as u8; flags: MPC_APIC_USABLE as u8,
mpc_ioapic.apicaddr = IO_APIC_DEFAULT_PHYS_BASE; apicaddr: IO_APIC_DEFAULT_PHYS_BASE,
};
mem.write_obj_at_addr(mpc_ioapic, base_mp) mem.write_obj_at_addr(mpc_ioapic, base_mp)
.map_err(|_| Error::WriteMpcIoapic)?; .map_err(|_| Error::WriteMpcIoapic)?;
base_mp = base_mp.unchecked_add(size as u64); base_mp = base_mp.unchecked_add(size as u64);
@ -198,10 +201,11 @@ pub fn setup_mptable(
} }
for pci_bus_id in 0..isa_bus_id { for pci_bus_id in 0..isa_bus_id {
let size = mem::size_of::<mpc_bus>(); let size = mem::size_of::<mpc_bus>();
let mut mpc_bus = mpc_bus::default(); let mpc_bus = mpc_bus {
mpc_bus.type_ = MP_BUS as u8; type_: MP_BUS as u8,
mpc_bus.busid = pci_bus_id; busid: pci_bus_id,
mpc_bus.bustype = BUS_TYPE_PCI; bustype: BUS_TYPE_PCI,
};
mem.write_obj_at_addr(mpc_bus, base_mp) mem.write_obj_at_addr(mpc_bus, base_mp)
.map_err(|_| Error::WriteMpcBus)?; .map_err(|_| Error::WriteMpcBus)?;
base_mp = base_mp.unchecked_add(size as u64); base_mp = base_mp.unchecked_add(size as u64);
@ -209,10 +213,11 @@ pub fn setup_mptable(
} }
{ {
let size = mem::size_of::<mpc_bus>(); let size = mem::size_of::<mpc_bus>();
let mut mpc_bus = mpc_bus::default(); let mpc_bus = mpc_bus {
mpc_bus.type_ = MP_BUS as u8; type_: MP_BUS as u8,
mpc_bus.busid = isa_bus_id; busid: isa_bus_id,
mpc_bus.bustype = BUS_TYPE_ISA; bustype: BUS_TYPE_ISA,
};
mem.write_obj_at_addr(mpc_bus, base_mp) mem.write_obj_at_addr(mpc_bus, base_mp)
.map_err(|_| Error::WriteMpcBus)?; .map_err(|_| Error::WriteMpcBus)?;
base_mp = base_mp.unchecked_add(size as u64); base_mp = base_mp.unchecked_add(size as u64);
@ -220,14 +225,15 @@ pub fn setup_mptable(
} }
{ {
let size = mem::size_of::<mpc_intsrc>(); let size = mem::size_of::<mpc_intsrc>();
let mut mpc_intsrc = mpc_intsrc::default(); let mpc_intsrc = mpc_intsrc {
mpc_intsrc.type_ = MP_INTSRC as u8; type_: MP_INTSRC as u8,
mpc_intsrc.irqtype = mp_irq_source_types_mp_INT as u8; irqtype: mp_irq_source_types_mp_INT as u8,
mpc_intsrc.irqflag = MP_IRQDIR_DEFAULT as u16; irqflag: MP_IRQDIR_DEFAULT as u16,
mpc_intsrc.srcbus = isa_bus_id; srcbus: isa_bus_id,
mpc_intsrc.srcbusirq = 0; srcbusirq: 0,
mpc_intsrc.dstapic = 0; dstapic: 0,
mpc_intsrc.dstirq = 0; dstirq: 0,
};
mem.write_obj_at_addr(mpc_intsrc, base_mp) mem.write_obj_at_addr(mpc_intsrc, base_mp)
.map_err(|_| Error::WriteMpcIntsrc)?; .map_err(|_| Error::WriteMpcIntsrc)?;
base_mp = base_mp.unchecked_add(size as u64); base_mp = base_mp.unchecked_add(size as u64);
@ -237,14 +243,15 @@ pub fn setup_mptable(
// Per kvm_setup_default_irq_routing() in kernel // Per kvm_setup_default_irq_routing() in kernel
for i in 0..sci_irq { for i in 0..sci_irq {
let size = mem::size_of::<mpc_intsrc>(); let size = mem::size_of::<mpc_intsrc>();
let mut mpc_intsrc = mpc_intsrc::default(); let mpc_intsrc = mpc_intsrc {
mpc_intsrc.type_ = MP_INTSRC as u8; type_: MP_INTSRC as u8,
mpc_intsrc.irqtype = mp_irq_source_types_mp_INT as u8; irqtype: mp_irq_source_types_mp_INT as u8,
mpc_intsrc.irqflag = MP_IRQDIR_DEFAULT as u16; irqflag: MP_IRQDIR_DEFAULT as u16,
mpc_intsrc.srcbus = isa_bus_id; srcbus: isa_bus_id,
mpc_intsrc.srcbusirq = i; srcbusirq: i,
mpc_intsrc.dstapic = ioapicid; dstapic: ioapicid,
mpc_intsrc.dstirq = i; dstirq: i,
};
mem.write_obj_at_addr(mpc_intsrc, base_mp) mem.write_obj_at_addr(mpc_intsrc, base_mp)
.map_err(|_| Error::WriteMpcIntsrc)?; .map_err(|_| Error::WriteMpcIntsrc)?;
base_mp = base_mp.unchecked_add(size as u64); base_mp = base_mp.unchecked_add(size as u64);
@ -255,14 +262,15 @@ pub fn setup_mptable(
// This setting can be changed in future if necessary. // This setting can be changed in future if necessary.
{ {
let size = mem::size_of::<mpc_intsrc>(); let size = mem::size_of::<mpc_intsrc>();
let mut mpc_intsrc = mpc_intsrc::default(); let mpc_intsrc = mpc_intsrc {
mpc_intsrc.type_ = MP_INTSRC as u8; type_: MP_INTSRC as u8,
mpc_intsrc.irqtype = mp_irq_source_types_mp_INT as u8; irqtype: mp_irq_source_types_mp_INT as u8,
mpc_intsrc.irqflag = (MP_IRQDIR_HIGH | MP_LEVEL_TRIGGER) as u16; irqflag: (MP_IRQDIR_HIGH | MP_LEVEL_TRIGGER) as u16,
mpc_intsrc.srcbus = isa_bus_id; srcbus: isa_bus_id,
mpc_intsrc.srcbusirq = sci_irq; srcbusirq: sci_irq,
mpc_intsrc.dstapic = ioapicid; dstapic: ioapicid,
mpc_intsrc.dstirq = sci_irq; dstirq: sci_irq,
};
mem.write_obj_at_addr(mpc_intsrc, base_mp) mem.write_obj_at_addr(mpc_intsrc, base_mp)
.map_err(|_| Error::WriteMpcIntsrc)?; .map_err(|_| Error::WriteMpcIntsrc)?;
base_mp = base_mp.unchecked_add(size as u64); base_mp = base_mp.unchecked_add(size as u64);
@ -272,14 +280,15 @@ pub fn setup_mptable(
// Insert PCI interrupts after platform IRQs. // Insert PCI interrupts after platform IRQs.
for (address, irq_num, irq_pin) in pci_irqs.iter() { for (address, irq_num, irq_pin) in pci_irqs.iter() {
let size = mem::size_of::<mpc_intsrc>(); let size = mem::size_of::<mpc_intsrc>();
let mut mpc_intsrc = mpc_intsrc::default(); let mpc_intsrc = mpc_intsrc {
mpc_intsrc.type_ = MP_INTSRC as u8; type_: MP_INTSRC as u8,
mpc_intsrc.irqtype = mp_irq_source_types_mp_INT as u8; irqtype: mp_irq_source_types_mp_INT as u8,
mpc_intsrc.irqflag = MP_IRQDIR_DEFAULT as u16; irqflag: MP_IRQDIR_DEFAULT as u16,
mpc_intsrc.srcbus = address.bus; srcbus: address.bus,
mpc_intsrc.srcbusirq = address.dev << 2 | irq_pin.to_mask() as u8; srcbusirq: address.dev << 2 | irq_pin.to_mask() as u8,
mpc_intsrc.dstapic = ioapicid; dstapic: ioapicid,
mpc_intsrc.dstirq = u8::try_from(*irq_num).map_err(|_| Error::WriteMpcIntsrc)?; dstirq: u8::try_from(*irq_num).map_err(|_| Error::WriteMpcIntsrc)?,
};
mem.write_obj_at_addr(mpc_intsrc, base_mp) mem.write_obj_at_addr(mpc_intsrc, base_mp)
.map_err(|_| Error::WriteMpcIntsrc)?; .map_err(|_| Error::WriteMpcIntsrc)?;
base_mp = base_mp.unchecked_add(size as u64); base_mp = base_mp.unchecked_add(size as u64);
@ -294,14 +303,15 @@ pub fn setup_mptable(
// Finally insert ISA interrupts. // Finally insert ISA interrupts.
for i in starting_isa_irq_num..16 { for i in starting_isa_irq_num..16 {
let size = mem::size_of::<mpc_intsrc>(); let size = mem::size_of::<mpc_intsrc>();
let mut mpc_intsrc = mpc_intsrc::default(); let mpc_intsrc = mpc_intsrc {
mpc_intsrc.type_ = MP_INTSRC as u8; type_: MP_INTSRC as u8,
mpc_intsrc.irqtype = mp_irq_source_types_mp_INT as u8; irqtype: mp_irq_source_types_mp_INT as u8,
mpc_intsrc.irqflag = MP_IRQDIR_DEFAULT as u16; irqflag: MP_IRQDIR_DEFAULT as u16,
mpc_intsrc.srcbus = isa_bus_id; srcbus: isa_bus_id,
mpc_intsrc.srcbusirq = i as u8; srcbusirq: i as u8,
mpc_intsrc.dstapic = ioapicid; dstapic: ioapicid,
mpc_intsrc.dstirq = i as u8; dstirq: i as u8,
};
mem.write_obj_at_addr(mpc_intsrc, base_mp) mem.write_obj_at_addr(mpc_intsrc, base_mp)
.map_err(|_| Error::WriteMpcIntsrc)?; .map_err(|_| Error::WriteMpcIntsrc)?;
base_mp = base_mp.unchecked_add(size as u64); base_mp = base_mp.unchecked_add(size as u64);
@ -309,14 +319,15 @@ pub fn setup_mptable(
} }
{ {
let size = mem::size_of::<mpc_lintsrc>(); let size = mem::size_of::<mpc_lintsrc>();
let mut mpc_lintsrc = mpc_lintsrc::default(); let mpc_lintsrc = mpc_lintsrc {
mpc_lintsrc.type_ = MP_LINTSRC as u8; type_: MP_LINTSRC as u8,
mpc_lintsrc.irqtype = mp_irq_source_types_mp_ExtINT as u8; irqtype: mp_irq_source_types_mp_ExtINT as u8,
mpc_lintsrc.irqflag = MP_IRQDIR_DEFAULT as u16; irqflag: MP_IRQDIR_DEFAULT as u16,
mpc_lintsrc.srcbusid = isa_bus_id; srcbusid: isa_bus_id,
mpc_lintsrc.srcbusirq = 0; srcbusirq: 0,
mpc_lintsrc.destapic = 0; destapic: 0,
mpc_lintsrc.destapiclint = 0; destapiclint: 0,
};
mem.write_obj_at_addr(mpc_lintsrc, base_mp) mem.write_obj_at_addr(mpc_lintsrc, base_mp)
.map_err(|_| Error::WriteMpcLintsrc)?; .map_err(|_| Error::WriteMpcLintsrc)?;
base_mp = base_mp.unchecked_add(size as u64); base_mp = base_mp.unchecked_add(size as u64);
@ -324,14 +335,15 @@ pub fn setup_mptable(
} }
{ {
let size = mem::size_of::<mpc_lintsrc>(); let size = mem::size_of::<mpc_lintsrc>();
let mut mpc_lintsrc = mpc_lintsrc::default(); let mpc_lintsrc = mpc_lintsrc {
mpc_lintsrc.type_ = MP_LINTSRC as u8; type_: MP_LINTSRC as u8,
mpc_lintsrc.irqtype = mp_irq_source_types_mp_NMI as u8; irqtype: mp_irq_source_types_mp_NMI as u8,
mpc_lintsrc.irqflag = MP_IRQDIR_DEFAULT as u16; irqflag: MP_IRQDIR_DEFAULT as u16,
mpc_lintsrc.srcbusid = isa_bus_id; srcbusid: isa_bus_id,
mpc_lintsrc.srcbusirq = 0; srcbusirq: 0,
mpc_lintsrc.destapic = 0xFF; // Per SeaBIOS destapic: 0xFF, // Per SeaBIOS
mpc_lintsrc.destapiclint = 1; destapiclint: 1,
};
mem.write_obj_at_addr(mpc_lintsrc, base_mp) mem.write_obj_at_addr(mpc_lintsrc, base_mp)
.map_err(|_| Error::WriteMpcLintsrc)?; .map_err(|_| Error::WriteMpcLintsrc)?;
base_mp = base_mp.unchecked_add(size as u64); base_mp = base_mp.unchecked_add(size as u64);
@ -342,13 +354,15 @@ pub fn setup_mptable(
let table_end = base_mp; let table_end = base_mp;
{ {
let mut mpc_table = mpc_table::default(); let mut mpc_table = mpc_table {
mpc_table.signature = MPC_SIGNATURE; signature: MPC_SIGNATURE,
mpc_table.length = table_end.offset_from(table_base) as u16; length: table_end.offset_from(table_base) as u16,
mpc_table.spec = MPC_SPEC; spec: MPC_SPEC,
mpc_table.oem = MPC_OEM; oem: MPC_OEM,
mpc_table.productid = MPC_PRODUCT_ID; productid: MPC_PRODUCT_ID,
mpc_table.lapic = APIC_DEFAULT_PHYS_BASE; lapic: APIC_DEFAULT_PHYS_BASE,
..Default::default()
};
checksum = checksum.wrapping_add(compute_checksum(&mpc_table)); checksum = checksum.wrapping_add(compute_checksum(&mpc_table));
mpc_table.checksum = (!checksum).wrapping_add(1) as i8; mpc_table.checksum = (!checksum).wrapping_add(1) as i8;
mem.write_obj_at_addr(mpc_table, table_base) mem.write_obj_at_addr(mpc_table, table_base)

View file

@ -360,7 +360,7 @@ mod tests {
use vm_memory::{GuestAddress, GuestMemory}; use vm_memory::{GuestAddress, GuestMemory};
fn create_guest_mem() -> GuestMemory { fn create_guest_mem() -> GuestMemory {
GuestMemory::new(&vec![(GuestAddress(0), 0x10000)]).unwrap() GuestMemory::new(&[(GuestAddress(0), 0x10000)]).unwrap()
} }
fn read_u64(gm: &GuestMemory, offset: u64) -> u64 { fn read_u64(gm: &GuestMemory, offset: u64) -> u64 {

View file

@ -150,7 +150,7 @@ fn write_string(mem: &GuestMemory, val: &str, mut curptr: GuestAddress) -> Resul
for c in val.as_bytes().iter() { for c in val.as_bytes().iter() {
curptr = write_and_incr(mem, *c, curptr)?; curptr = write_and_incr(mem, *c, curptr)?;
} }
curptr = write_and_incr(mem, 0 as u8, curptr)?; curptr = write_and_incr(mem, 0_u8, curptr)?;
Ok(curptr) Ok(curptr)
} }
@ -163,32 +163,36 @@ pub fn setup_smbios(mem: &GuestMemory) -> Result<()> {
{ {
handle += 1; handle += 1;
let mut smbios_biosinfo = SmbiosBiosInfo::default(); let smbios_biosinfo = SmbiosBiosInfo {
smbios_biosinfo.typ = BIOS_INFORMATION; typ: BIOS_INFORMATION,
smbios_biosinfo.length = mem::size_of::<SmbiosBiosInfo>() as u8; length: mem::size_of::<SmbiosBiosInfo>() as u8,
smbios_biosinfo.handle = handle; handle,
smbios_biosinfo.vendor = 1; // First string written in this section vendor: 1, // First string written in this section
smbios_biosinfo.version = 2; // Second string written in this section version: 2, // Second string written in this section
smbios_biosinfo.characteristics = PCI_SUPPORTED; characteristics: PCI_SUPPORTED,
smbios_biosinfo.characteristics_ext2 = IS_VIRTUAL_MACHINE; characteristics_ext2: IS_VIRTUAL_MACHINE,
..Default::default()
};
curptr = write_and_incr(mem, smbios_biosinfo, curptr)?; curptr = write_and_incr(mem, smbios_biosinfo, curptr)?;
curptr = write_string(mem, "crosvm", curptr)?; curptr = write_string(mem, "crosvm", curptr)?;
curptr = write_string(mem, "0", curptr)?; curptr = write_string(mem, "0", curptr)?;
curptr = write_and_incr(mem, 0 as u8, curptr)?; curptr = write_and_incr(mem, 0_u8, curptr)?;
} }
{ {
handle += 1; handle += 1;
let mut smbios_sysinfo = SmbiosSysInfo::default(); let smbios_sysinfo = SmbiosSysInfo {
smbios_sysinfo.typ = SYSTEM_INFORMATION; typ: SYSTEM_INFORMATION,
smbios_sysinfo.length = mem::size_of::<SmbiosSysInfo>() as u8; length: mem::size_of::<SmbiosSysInfo>() as u8,
smbios_sysinfo.handle = handle; handle,
smbios_sysinfo.manufacturer = 1; // First string written in this section manufacturer: 1, // First string written in this section
smbios_sysinfo.product_name = 2; // Second string written in this section product_name: 2, // Second string written in this section
..Default::default()
};
curptr = write_and_incr(mem, smbios_sysinfo, curptr)?; curptr = write_and_incr(mem, smbios_sysinfo, curptr)?;
curptr = write_string(mem, "ChromiumOS", curptr)?; curptr = write_string(mem, "ChromiumOS", curptr)?;
curptr = write_string(mem, "crosvm", curptr)?; curptr = write_string(mem, "crosvm", curptr)?;
curptr = write_and_incr(mem, 0 as u8, curptr)?; curptr = write_and_incr(mem, 0u8, curptr)?;
} }
{ {

View file

@ -6,7 +6,6 @@
use devices::IrqChipX86_64; use devices::IrqChipX86_64;
use hypervisor::{HypervisorX86_64, VcpuExit, VcpuX86_64, VmX86_64}; use hypervisor::{HypervisorX86_64, VcpuExit, VcpuX86_64, VmX86_64};
use msg_socket;
use vm_memory::{GuestAddress, GuestMemory}; use vm_memory::{GuestAddress, GuestMemory};
use super::cpuid::setup_cpuid; use super::cpuid::setup_cpuid;