diff --git a/Cargo.toml b/Cargo.toml index 18bab8d..c0ce766 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,4 +14,6 @@ rust-version = "1.71" [dependencies] bitflags = "2.4.2" +kvm-bindings = "0.7.0" kvm-ioctls = "0.16.0" +vmm-sys-util = "0.12.1" diff --git a/src/linux/mod.rs b/src/linux/mod.rs index dbcf918..e1f3120 100644 --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -5,6 +5,7 @@ pub enum CmdId { GetCapabilities = 0, InitVm = 1, + InitVcpu = 2, } /// Contains information for the sub-ioctl() command to be run. This is diff --git a/src/vcpu/linux/mod.rs b/src/vcpu/linux/mod.rs index cdc649a..7557906 100644 --- a/src/vcpu/linux/mod.rs +++ b/src/vcpu/linux/mod.rs @@ -1 +1,3 @@ // SPDX-License-Identifier: Apache-2.0 + +pub mod ioctl; diff --git a/src/vcpu/mod.rs b/src/vcpu/mod.rs index cdc649a..d32b5cd 100644 --- a/src/vcpu/mod.rs +++ b/src/vcpu/mod.rs @@ -1 +1,36 @@ // SPDX-License-Identifier: Apache-2.0 + +mod linux; + +use crate::linux::{Cmd, CmdId, TdxError}; +use kvm_bindings::*; +use vmm_sys_util::*; + +vmm_sys_util::ioctl_iowr_nr!(KVM_MEMORY_ENCRYPT_OP, KVMIO, 0xba, std::os::raw::c_ulong); + +pub struct TdxVcpu { + pub fd: kvm_ioctls::VcpuFd, +} + +impl TdxVcpu { + pub fn new(vm: &crate::vm::TdxVm, id: u64) -> Result { + let vcpufd = vm.fd.create_vcpu(id)?; + Ok(Self {fd: vcpufd}) + } + + /// TDX specific VCPU initialization using a TDVF HOB address + pub fn init_vcpu(&self, hob_addr: u64) -> Result<(), TdxError> { + let mut cmd = Cmd { + id: CmdId::InitVcpu as u32, + flags: 0, + data: hob_addr as *const u64 as _, + error: 0, + _unused: 0, + }; + let ret = unsafe { ioctl::ioctl_with_mut_ptr(&self.fd, KVM_MEMORY_ENCRYPT_OP(), &mut cmd) }; + if ret < 0 { + return Err(TdxError::from(ret)); + } + Ok(()) + } +} diff --git a/tests/launch.rs b/tests/launch.rs index 48785ee..0cb41c2 100644 --- a/tests/launch.rs +++ b/tests/launch.rs @@ -3,6 +3,7 @@ use kvm_ioctls::Kvm; use tdx::vm::TdxVm; +use tdx::vcpu::TdxVcpu; #[test] fn launch() { @@ -10,4 +11,6 @@ fn launch() { let tdx_vm = TdxVm::new(&kvm_fd).unwrap(); let caps = tdx_vm.get_capabilities().unwrap(); let _ = tdx_vm.init_vm(&kvm_fd, &caps).unwrap(); + let tdx_vcpu = TdxVcpu::new(&tdx_vm, 0).unwrap(); + let _ = tdx_vcpu.init_vcpu(0).unwrap(); }