kvm_rs/vm.rs
1// SPDX-License-Identifier: MIT
2//
3// Copyright (c) 2021, Johannes Stoelp <dev@memzero.de>
4
5//! VM system ioctls.
6
7use std::fs;
8use std::io;
9use std::os::unix::io::FromRawFd;
10
11use crate::vcpu::Vcpu;
12use crate::{ioctl, kvm_sys, KvmRun, PhysAddr, UserMem};
13
14/// Wrapper for VM ioctls.
15///
16/// Representation of the file descriptor obtained by the [`KVM_CREATE_VM`][kvm-create-vm] ioctl.
17/// This wrapper provides access to the `VM ioctls` as described in [KVM API][kvm].
18///
19/// [kvm]: https://www.kernel.org/doc/html/latest/virt/kvm/api.html#general-description
20/// [kvm-create-vm]: https://www.kernel.org/doc/html/latest/virt/kvm/api.html#kvm-create-vm
21pub struct Vm {
22 vm: fs::File,
23 vcpu_mmap_size: usize,
24}
25
26impl Vm {
27 pub(crate) fn new(vm: fs::File, vcpu_mmap_size: usize) -> Vm {
28 Vm { vm, vcpu_mmap_size }
29 }
30
31 /// Map memory from userspace into the VM as `guest physical` memory starting at address
32 /// `phys_addr`.
33 /// The underlying operation is the [`KVM_SET_USER_MEMORY_REGION`][kvm-set-user-memory-region]
34 /// ioctl.
35 ///
36 /// # Safety
37 ///
38 /// The `mem: &UserMem` argument passed to this function must at least live as long the `Vcpu`
39 /// instance.
40 ///
41 /// [kvm-set-user-memory-region]: https://www.kernel.org/doc/html/latest/virt/kvm/api.html#kvm-set-user-memory-region
42 pub unsafe fn set_user_memory_region(
43 &self,
44 phys_addr: PhysAddr,
45 mem: &UserMem,
46 ) -> io::Result<()> {
47 // Create guest physical memory mapping for `slot : 0` at guest `phys_addr`.
48 let mut kvm_mem = kvm_sys::kvm_userspace_memory_region::default();
49 kvm_mem.userspace_addr = mem.ptr as u64;
50 kvm_mem.memory_size = mem.len as u64;
51 kvm_mem.guest_phys_addr = phys_addr.0;
52
53 ioctl(
54 &self.vm,
55 kvm_sys::KVM_SET_USER_MEMORY_REGION,
56 &kvm_mem as *const _ as u64,
57 )
58 .map(|_| ())
59 }
60
61 /// Create a new virtual cpu with the [`KVM_CREATE_VCPU`][kvm-create-vcpu] ioctl.
62 /// Returns a wrapper [`vcpu::Vcpu`][crate::vcpu::Vcpu] representing the VCPU.
63 ///
64 /// [kvm-create-vcpu]: https://www.kernel.org/doc/html/latest/virt/kvm/api.html#kvm-create-vcpu
65 pub fn create_vpcu(&self, id: u64) -> io::Result<Vcpu> {
66 let vcpu = ioctl(&self.vm, kvm_sys::KVM_CREATE_VCPU, id)
67 .map(|fd| unsafe { fs::File::from_raw_fd(fd) })?;
68
69 let kvm_run = KvmRun::new(&vcpu, self.vcpu_mmap_size)?;
70
71 Ok(Vcpu::new(vcpu, kvm_run))
72 }
73}