Skip to content

Commit 72d929e

Browse files
committed
refactor: simplify max memslot checks
It is reasonable to assume that we will not have more than u32::MAX memory slots since kernel only returns i32 from a query syscall. Enforce this with `.expect` calls and change the type of `max_memslots` to u32. Signed-off-by: Egor Lazarchuk <[email protected]>
1 parent e36e774 commit 72d929e

File tree

2 files changed

+15
-10
lines changed

2 files changed

+15
-10
lines changed

src/vmm/src/vstate/kvm.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,11 @@ impl Kvm {
8080
}
8181

8282
/// Returns the maximal number of memslots allowed in a [`Vm`]
83-
pub fn max_nr_memslots(&self) -> usize {
84-
self.fd.get_nr_memslots()
83+
pub fn max_nr_memslots(&self) -> u32 {
84+
self.fd
85+
.get_nr_memslots()
86+
.try_into()
87+
.expect("Number of vcpus reported by KVM exceeds u32::MAX")
8588
}
8689
}
8790

src/vmm/src/vstate/vm.rs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ use crate::{DirtyBitmap, Vcpu, mem_size_mib};
3131
pub struct VmCommon {
3232
/// The KVM file descriptor used to access this Vm.
3333
pub fd: VmFd,
34-
max_memslots: usize,
34+
max_memslots: u32,
3535
/// The guest memory of this Vm.
3636
pub guest_memory: GuestMemoryMmap,
3737
}
@@ -51,8 +51,8 @@ pub enum VmError {
5151
EventFd(std::io::Error),
5252
/// Failed to create vcpu: {0}
5353
CreateVcpu(VcpuError),
54-
/// The number of configured slots is bigger than the maximum reported by KVM
55-
NotEnoughMemorySlots,
54+
/// The number of configured slots is bigger than the maximum reported by KVM: {0}
55+
NotEnoughMemorySlots(u32),
5656
/// Memory Error: {0}
5757
VmMemory(#[from] vm_memory::Error),
5858
}
@@ -142,9 +142,9 @@ impl Vm {
142142
.guest_memory()
143143
.num_regions()
144144
.try_into()
145-
.map_err(|_| VmError::NotEnoughMemorySlots)?;
146-
if next_slot as usize >= self.common.max_memslots {
147-
return Err(VmError::NotEnoughMemorySlots);
145+
.expect("Number of existing memory regions exceeds u32::MAX");
146+
if self.common.max_memslots <= next_slot {
147+
return Err(VmError::NotEnoughMemorySlots(self.common.max_memslots));
148148
}
149149

150150
let flags = if region.bitmap().is_some() {
@@ -362,9 +362,11 @@ pub(crate) mod tests {
362362

363363
let res = vm.register_memory_region(region);
364364

365-
if i >= max_nr_regions {
365+
// For some reason max_nr_regions is considered unused here
366+
#[allow(unused_variables)]
367+
if max_nr_regions <= i {
366368
assert!(
367-
matches!(res, Err(VmError::NotEnoughMemorySlots)),
369+
matches!(res, Err(VmError::NotEnoughMemorySlots(max_nr_regions))),
368370
"{:?} at iteration {} - max_nr_memslots: {}",
369371
res,
370372
i,

0 commit comments

Comments
 (0)