Skip to content

feat: upgrade kvm-bindings to Rust edition 2024 #330

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions kvm-bindings/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
[package]
name = "kvm-bindings"
version = "0.12.0"
edition = "2024"
authors = ["Amazon firecracker team <[email protected]>"]
description = "Rust FFI bindings to KVM generated using bindgen."
repository = "https://github.com/rust-vmm/kvm"
Expand Down
21 changes: 17 additions & 4 deletions kvm-bindings/src/x86_64/bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,11 @@ impl<T> __IncompleteArrayField<T> {
}
#[inline]
pub unsafe fn as_slice(&self, len: usize) -> &[T] {
::std::slice::from_raw_parts(self.as_ptr(), len)
unsafe {::std::slice::from_raw_parts(self.as_ptr(), len)}
}
#[inline]
pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] {
::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len)
unsafe {::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len)}
}
}
impl<T> ::std::fmt::Debug for __IncompleteArrayField<T> {
Expand All @@ -127,11 +127,11 @@ impl<T> __BindgenUnionField<T> {
}
#[inline]
pub unsafe fn as_ref(&self) -> &T {
::std::mem::transmute(self)
unsafe {::std::mem::transmute(self)}
}
#[inline]
pub unsafe fn as_mut(&mut self) -> &mut T {
::std::mem::transmute(self)
unsafe {::std::mem::transmute(self)}
}
}
impl<T> ::std::default::Default for __BindgenUnionField<T> {
Expand Down Expand Up @@ -2022,6 +2022,10 @@ impl Default for kvm_vmx_nested_state_data {
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(zerocopy::IntoBytes, zerocopy::Immutable, zerocopy::FromBytes)
)]
pub struct kvm_vmx_nested_state_hdr {
pub vmxon_pa: __u64,
pub vmcs12_pa: __u64,
Expand All @@ -2032,6 +2036,10 @@ pub struct kvm_vmx_nested_state_hdr {
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(zerocopy::IntoBytes, zerocopy::Immutable, zerocopy::FromBytes)
)]
pub struct kvm_vmx_nested_state_hdr__bindgen_ty_1 {
pub flags: __u16,
}
Expand Down Expand Up @@ -2088,6 +2096,10 @@ impl Default for kvm_svm_nested_state_data {
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(zerocopy::IntoBytes, zerocopy::Immutable, zerocopy::FromBytes)
)]
pub struct kvm_svm_nested_state_hdr {
pub vmcb_pa: __u64,
}
Expand All @@ -2110,6 +2122,7 @@ pub struct kvm_nested_state {
}
#[repr(C)]
#[derive(Copy, Clone)]
#[cfg_attr(feature = "serde", derive(zerocopy::Immutable, zerocopy::FromBytes))]
pub union kvm_nested_state__bindgen_ty_1 {
pub vmx: kvm_vmx_nested_state_hdr,
pub svm: kvm_svm_nested_state_hdr,
Expand Down
4 changes: 2 additions & 2 deletions kvm-bindings/src/x86_64/fam_wrappers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use vmm_sys_util::fam::{FamStruct, FamStructWrapper};

use x86_64::bindings::*;
use crate::x86_64::bindings::*;

/// Maximum number of CPUID entries that can be returned by a call to KVM ioctls.
///
Expand Down Expand Up @@ -202,7 +202,7 @@ mod tests {
use crate::KvmIrqRouting;

use super::{CpuId, MsrList, Msrs, Xsave};
use x86_64::bindings::kvm_cpuid_entry2;
use crate::x86_64::bindings::kvm_cpuid_entry2;

use vmm_sys_util::fam::FamStruct;

Expand Down
2 changes: 2 additions & 0 deletions kvm-bindings/src/x86_64/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ pub mod bindings;
#[cfg(feature = "fam-wrappers")]
pub mod fam_wrappers;

pub mod nested;

#[cfg(feature = "serde")]
mod serialize;

Expand Down
117 changes: 117 additions & 0 deletions kvm-bindings/src/x86_64/nested.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
//! Higher-level abstractions for working with nested state.
//!
//! Getting and setting the nested KVM state is helpful if nested virtualization
//! is used and the state needs to be serialized, e.g., for live-migration or
//! state save/resume. See [`KvmNestedStateBuffer`].

use core::mem;
use crate::KVM_STATE_NESTED_SVM_VMCB_SIZE;
use crate::{kvm_nested_state__bindgen_ty_1, KVM_STATE_NESTED_VMX_VMCS_SIZE};

/// Non-zero variant of the bindgen data union.
///
/// Please note that on SVM, this type wastes one page as the VMX state is
/// larger.
#[derive(Clone, Copy)]
#[cfg_attr(feature = "serde", derive(zerocopy::Immutable, zerocopy::FromBytes))]
#[repr(C)]
pub union kvm_nested_state__data {
pub vmx: kvm_vmx_nested_state_data,
pub svm: kvm_svm_nested_state_data,
}

impl Default for kvm_nested_state__data {
fn default() -> Self {
// SAFETY: Every bit pattern is valid.
unsafe { mem::zeroed() }
}
}

#[derive(Clone, Copy)]
#[cfg_attr(
feature = "serde",
derive(zerocopy::IntoBytes, zerocopy::Immutable, zerocopy::FromBytes)
)]
#[repr(C)]
pub struct kvm_vmx_nested_state_data {
pub vmcs12: [u8; KVM_STATE_NESTED_VMX_VMCS_SIZE as usize],
pub shadow_vmcs12: [u8; KVM_STATE_NESTED_VMX_VMCS_SIZE as usize],
}

#[derive(Clone, Copy)]
#[cfg_attr(
feature = "serde",
derive(zerocopy::IntoBytes, zerocopy::Immutable, zerocopy::FromBytes)
)]
#[repr(C)]
pub struct kvm_svm_nested_state_data {
pub vmcb12: [u8; KVM_STATE_NESTED_SVM_VMCB_SIZE as usize],
}

/// A stack-allocated buffer for nested KVM state including the mandatory
/// header with meta-information.
///
/// KVM uses a dynamically sized buffer structure (with a header reporting the
/// size of the buffer/state). This helper type makes working with
/// `get_nested_state()` and `set_nested_state`() significantly more convenient
/// at the cost of a slightly higher memory footprint in some cases.
///
/// # Type Size
///
/// On Intel VMX, the actual state requires `128 + 8192 == 8320` bytes, on
/// AMD SVM, the actual state requires `128 + 4096 == 4224` bytes. This type
/// doesn't make a differentiation and unifies the required memory. By
/// sacrificing a few more bytes on VMX, this type is generally convenient to
/// use.
#[derive(Clone, Copy)]
#[cfg_attr(
feature = "serde",
derive(zerocopy::IntoBytes, zerocopy::Immutable, zerocopy::FromBytes)
)]
#[repr(C)]
#[non_exhaustive] // Prevent constructor bypass in public API.
pub struct KvmNestedStateBuffer {
pub flags: u16,
pub format: u16,
pub size: u32,
pub hdr: kvm_nested_state__bindgen_ty_1,
pub data: kvm_nested_state__data,
}

impl KvmNestedStateBuffer {
/// Creates a new empty buffer, ready for nested state to be stored in by KVM.
///
/// The `size` property will report the size of the buffer to KVM.
pub fn empty() -> Self {
// SAFETY: Every bit pattern is valid.
let mut this: KvmNestedStateBuffer = unsafe { mem::zeroed() };
// This way, KVM knows the size of the buffer to store state into.
// See: https://elixir.bootlin.com/linux/v6.12/source/arch/x86/kvm/x86.c#L6193
this.size = size_of::<Self>() as u32;
this
}
}

impl Default for KvmNestedStateBuffer {
fn default() -> Self {
Self::empty()
}
}

#[cfg(test)]
mod tests {
use super::*;

use crate::kvm_nested_state as kvm_nested_state_raw_binding;

#[test]
fn test_layout() {
assert_eq!(
align_of::<kvm_nested_state_raw_binding>(),
align_of::<KvmNestedStateBuffer>()
);
assert!(size_of::<KvmNestedStateBuffer>() > size_of::<kvm_nested_state_raw_binding>());
// When this fails/changes, we should re-evaluate the overall types and API
assert_eq!(size_of::<KvmNestedStateBuffer>(), 8320);
}
}
31 changes: 30 additions & 1 deletion kvm-bindings/src/x86_64/serialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use bindings::{
kvm_xcr, kvm_xcrs, kvm_xsave,
};
use fam_wrappers::kvm_xsave2;
use kvm_nested_state__bindgen_ty_1;
use nested::{kvm_nested_state__data, KvmNestedStateBuffer};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use zerocopy::{transmute, FromBytes, FromZeros, Immutable, IntoBytes};

Expand All @@ -35,7 +37,8 @@ serde_impls!(
kvm_xsave2,
kvm_irqchip,
kvm_irq_routing,
kvm_irq_routing_entry
kvm_irq_routing_entry,
KvmNestedStateBuffer
);

// SAFETY: zerocopy's derives explicitly disallow deriving for unions where
Expand Down Expand Up @@ -122,6 +125,30 @@ unsafe impl IntoBytes for kvm_irq_routing_entry__bindgen_ty_1 {
}
}

// SAFETY: zerocopy's derives explicitly disallow deriving for unions where
// the fields have different sizes, due to the smaller fields having padding.
// Miri however does not complain about these implementations (e.g. about
// reading the "padding" for one union field as valid data for a bigger one)
unsafe impl IntoBytes for kvm_nested_state__bindgen_ty_1 {
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized,
{
}
}

// SAFETY: zerocopy's derives explicitly disallow deriving for unions where
// the fields have different sizes, due to the smaller fields having padding.
// Miri however does not complain about these implementations (e.g. about
// reading the "padding" for one union field as valid data for a bigger one)
unsafe impl IntoBytes for kvm_nested_state__data {
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized,
{
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -182,6 +209,7 @@ mod tests {
is_serde::<kvm_mp_state>();
is_serde::<kvm_irq_routing>();
is_serde::<kvm_irq_routing_entry>();
is_serde::<KvmNestedStateBuffer>();
}

fn is_serde_json<T: Serialize + for<'de> Deserialize<'de> + Default>() {
Expand Down Expand Up @@ -216,5 +244,6 @@ mod tests {
is_serde_json::<kvm_mp_state>();
is_serde_json::<kvm_irq_routing>();
is_serde_json::<kvm_irq_routing_entry>();
is_serde_json::<KvmNestedStateBuffer>();
}
}
2 changes: 2 additions & 0 deletions kvm-ioctls/src/cap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,4 +165,6 @@ pub enum Cap {
UserMemory2 = KVM_CAP_USER_MEMORY2,
GuestMemfd = KVM_CAP_GUEST_MEMFD,
MemoryAttributes = KVM_CAP_MEMORY_ATTRIBUTES,
#[cfg(target_arch = "x86_64")]
NestedState = KVM_CAP_NESTED_STATE,
}
Loading